From 633b97d21c248b0f3498d4b4b15f52b346fa6a22 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 12 Nov 2026 04:47:02 +0100 Subject: [PATCH 001/136] test(scenarios): cases on a mission of a scenery, slow and xfail marks, --seed A case can now run one of the base scenery's own missions among its traffic: - vehicle: the train under test is a vehicle of the base scenery (with strip_trainsets false), the fragment becomes optional, - replace: literal replacements in the base scenery, e.g. another locomotive on a mission, - physicslog false: no physicslogs and no black box, for a scenery with dozens of AI trains; the case then has the result of the test mode and the log checks only, - on such a case the runner doesn't wait for physicslog rows nor give up on a bad vehicle of the scenery, and removes the physicslogs the other trains wrote; with file.binary.terrain no in ini it leaves no geometry cache behind, - slow: skipped by the default sweep, run by name or with --slow, - xfail: a known, reported failure is XFAIL and keeps the run green, a pass is XPASS and fails it, - --seed: the seed of the simulator's random numbers for a run, for bugs that show up sometimes. The couples check takes vehicle names in any case (the simulator reads them in lower case), and the physicslog is no longer read four times a second once it has rows. --- tests/scenarios/README.md | 85 ++++++++++++++++++++++++++--- tests/scenarios/run.py | 111 +++++++++++++++++++++++++++++--------- 2 files changed, 166 insertions(+), 30 deletions(-) diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index ea5ebc89b..736e8639a 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -135,13 +135,23 @@ Python 3.10+, no extra packages. Options: `cmake-build-*/bin/Release/eu07*.exe`. The build needs the `--test` and `-ini` command line options. - name one or more cases to run only those, e.g. `run.py ... eu07_td_timetable`. -- `-j N` runs N cases at once. Each case prints its results when it is done. All 19 cases - take about 30 s with `-j 4`, loading included. +- `-j N` runs N cases at once. Each case prints its results when it is done. The 19 cases + that aren't `slow` take about 30 s with `-j 4` and 2 minutes one at a time, loading included. - `--watch` runs a case the old way, in a visible window in real time (or faster with `--timespeed N`), closed after the case's `duration`; the exit code isn't checked then. For watching what a case does. +- `--slow` runs the cases marked `slow` too. Without it, and with no cases named, they are + skipped (and listed): each is a whole mission on a big scenery and takes many minutes. A + slow case named on the command line always runs. Run them one at a time (`-j 1`): each + simulator loads a whole scenery, and the ones with physicslog on collect every physicslog + written in the game dir meanwhile. +- `--seed N` (a number or a word) runs the cases with another seed of the simulator's random + numbers (`randomseed`) than the fixed one of the test mode, for a bug that shows up only + sometimes: run the case with a few seeds. -Exit code is 0 when every case passed. Logs of each run (`log.txt`, `errors.txt`, +Exit code is 0 when every case passed, or failed as its `xfail` mark says it does (`XFAIL` in +the summary); a case marked `xfail` that passes (`XPASS`) fails the run, so that the mark gets +removed. Logs of each run (`log.txt`, `errors.txt`, `stdout.txt`, the physicslogs of the vehicle and of other trains of the case, the black box as `autotest_.blackbox`) are moved to `tests/scenarios/out//`. @@ -171,7 +181,17 @@ The lead vehicle is named `autotest_`, so every case has its own physicslo files and cases can run in parallel. The `autotest_*` sceneries (and the simulator's `.sbt` geometry cache of them) stay in the game's `scenery/` dir; the cache is dropped when the base scenery is newer, and after a run cut short (`wall_timeout`, `error`, a crash, or killed by run.py), -which could have been writing it. +which could have been writing it. A case with `file.binary.terrain no` in its `ini` has no cache +written, and one left by an earlier run is removed. + +A case with `vehicle` runs a train of the base scenery under its own name: its physicslog is +`physicslog/.dat` (one of that name already in the game dir is replaced), and with the +physicslogs on, every train of the scenery writes one, over any of the same name; those written +during the run are deleted after it. Don't run such a case along with another one in the same game dir. + +Apart from these the game dir loses its `log.txt` and `errors.txt`, those of the last game +session: the simulator deletes them at every start, before it knows that the run's log goes +to `logs/`. ## Writing a case @@ -180,13 +200,18 @@ which could have been writing it. | key | meaning | | --- | --- | | `base_scenery` | scenery file in the game's `scenery/` dir | -| `strip_trainsets` | drop the base scenery's trainsets (default `true`) | +| `strip_trainsets` | drop the base scenery's trainsets (default `true`); `false` keeps them, for a case on one of the scenery's own missions (below) | +| `vehicle` | the train under test is this vehicle of the base scenery (its node name), instead of the `autotest_` one of the fragment: `test.vehicle`, the physicslog checked and `{{vehicle}}` are this one. With `strip_trainsets` `false` | +| `replace` | literal replacements in the text of the base scenery, a list of `[old, new]`, e.g. to put another locomotive on a mission; an `old` the scenery doesn't have is an error | +| `physicslog` | `false` turns the physicslogs (and the black box) off for the run: on a scenery with dozens of AI trains each of them would write 3-4 kB per second of simulation into the game dir. Such a case has the result of the test mode and the log checks only (default `true`) | +| `slow` | `true` marks a case that takes many minutes: skipped unless named or run with `--slow` | +| `xfail` | marks a case that fails because of a known, reported bug, with the reference and the reason as its text, e.g. `"eu07/maszyna#524: the AI never couples"`. Its failure is reported as `XFAIL` and doesn't fail the run; when it passes (`XPASS`) the run fails until the mark is removed | | `time` | replace the scenery start time, `HH:MM` | | `track_friction` | set the friction of every track of the base scenery (default in the sceneries is 0.15), e.g. for slippery rail | | `track_events` | lines added to tracks of the base scenery, by track name, e.g. `{ "tor1k": "event0 test_pass" }`; only tracks in the scenery file itself, not in its includes | | `test_config` | lines of a `config` block added to the scenery, e.g. `["test.timeout 90"]`; the block always has `test.vehicle` with the case's lead vehicle, so only its train counts for the pass and the standstill | | `ini` | extra `eu07.ini` lines for the run, after the common ones of the runner's `-ini` file, e.g. `["crashdamage yes"]` | -| `fragment` | `.scn` file in `cases/` added to the scenery: trainsets after `FirstInit` (before it they derail on unlinked track), the rest before it (launchers read after it never fire) | +| `fragment` | `.scn` file in `cases/` added to the scenery: trainsets after `FirstInit` (before it they derail on unlinked track), the rest before it (launchers read after it never fire). Optional when the case keeps the scenery's trainsets | | `vars` | values for `{{name}}` in the fragment; a list becomes one line per item | | `expect` | the result the test mode should end with: `pass`, `fail`, `signal_passed_at_danger`, `timeout`, `standstill` or `error`, or `wall_timeout` for the timeout of the real time watchdog (the timeout code with a verdict saying it was the real time; a case expecting `timeout` fails on it). Default `timeout` for a case with `duration`, else `pass` | | `duration` | seconds of simulation to record: the test timeout of the run (`--test-timeout`) | @@ -230,6 +255,54 @@ couple and neither shows up: the black box has to have the last car of the stand writes nothing to the log when couplers catch). Nothing reports a result, so both end on the 60 s test timeout. +### Cases on a mission of a scenery + +The cases made from players' reports (eu07/maszyna#421, #506, #524, #525) run a whole mission +of a scenery of the game, among its own traffic: `strip_trainsets` `false`, `vehicle` the +mission's own locomotive or unit, every train driven by AI as always in the test mode. They are +`slow`, have `physicslog` `false` unless a check needs the black box, and `file.binary.terrain no` +in `ini`, so that no geometry cache of the copied scenery (hundreds of MB for these) is written +into the game dir. What they add to the scenery: + +- nothing, when standing too long is the bug: `test.standstill` is set above the longest wait + the mission has, and the run ends with `duration` (`baltyk_skm1_*`), +- `mission_state_probe.scn`: these sceneries steer each station with a state cell per train + (text and two values, e.g. `deb_tme222158_stat` = `a 6 *`: the route of step 6 is set). The + probe is a loop of two events that looks at the cell `vars.cell` every 5 s and reports the + pass once it holds `vars.state` (a `memcompare`: `* 6 *`, `d * *`), with `vars.reason` as the + text. No fail event: a train that never gets there ends the test with the standstill or the + timeout. A periodic event launcher wouldn't do, the simulator polls those near the camera only, +- events named `:event0`, `:event1`, `:event2` or `:eventall1`...: the simulator binds an + event with such a name to the track by itself, so a fragment can hang events on tracks that + live in the scenery's includes, where `track_events` doesn't reach (`wrzosy_pxe336080_couple.scn`). + The name must not be one the scenery has already: a second event of the same name replaces the first. + +A train whose trainset has velocity 0 has a driver that sleeps in `Wait_for_orders` when nobody +is in the cab: the player would drive it, so the fragment has to give the orders the player's +hands stand for, with `PutValues` from an event the vehicle itself sets off (`event0` of the +track it stands on). The first of them must not be the one to couple (`Shunt -2 -3`): a driver +whose first order is `Connect` never releases the hand brake a cold locomotive starts with. The +mission trains of velocity 0.1 wait for their signal and need nothing. + +The cases and what they showed on master of 2026-11-11: + +| case | report | result | +| --- | --- | --- | +| `wrzosy_pxe336080_couples` | #524 | passes: ordered to, the locomotive couples to the rake (`couples`, 262 s) and takes it out of the depot (696 s). The scenery itself gives no such order | +| `baltyk_skm1_roj55324_shunting_signal` | #525 | passes, with four seeds: the unit on the siding is let into the platforms 4 minutes after the start, once the shunter beside it has done its first moves, and leaves at 10:42 | +| `baltyk_skm1_roj55321_departure` | #525 | passes, with three seeds: the unit in the platform leaves at 10:34 | +| `l053_poranek_tme222158_debica` | #421 | `xfail`: the train is never let into Debica, the station jams 4 minutes after the start: the AI of EP07-338'16 passes the shunting signal Tm4 at stop at 29 km/h and stops 20 m beyond the checkpoint the station waits for it at | +| `l053_poranek_tme222158_debica_et21` | #421 | `xfail`: with an ET21, as in the report, the locomotive stops for good at Debica Towarowa: running round the wagons it stands on the headshunt 20 m past the end of the overhead wire, and its driver never gets out of `Prepare_engine` | +| `l053_poludnie_roj32134_debica` | #506 | passes: both trains run and the unit ends at Debica after 6134 s; no train in its way | + +In the L053 sceneries the test mode logs a signal passed at danger for several shunting +locomotives within minutes, so these cases have `test.fail_if_stop_overran no`. + +The simulation ran at 15 times real time on Baltyk and at 5-8 times on L053 (with another +build going on on the machine) with the physicslogs off, and at 3-4 times on Wrzosy with them +on (250 drivers, the road vehicles included: 740 MB of physicslogs in 900 s), after 30-150 s of +loading. + Checks (speeds in km/h, times in seconds of physicslog time, distances in metres). Most use the physicslog Velocity column, which is the wheel speed: it stays at 0 while the wheels are locked in a skid. The ones marked *vehicle speed* use the vehicle speed column at the end of diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py index 51fdc3c66..cd05866ec 100644 --- a/tests/scenarios/run.py +++ b/tests/scenarios/run.py @@ -77,7 +77,7 @@ width 1280 height 720 inactivepause no soundenabled no -physicslog yes +physicslog {physicslog} multiplelogs yes timespeed {timespeed} """ @@ -156,7 +156,12 @@ def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> s text = set_track_friction(text, case["track_friction"]) if "track_events" in case: text = add_track_events(text, case["track_events"]) - fragment = (CASES_DIR / case["fragment"]).read_bytes().decode("latin-1") + for old, new in case.get("replace", []): + if old not in text: + sys.exit(f"replace: the base scenery has no {old!r}") + text = text.replace(old, new) + # a case on a mission of the base scenery may have nothing to add but its test_config + fragment = (CASES_DIR / case["fragment"]).read_bytes().decode("latin-1") if "fragment" in case else "" # vars first: {{vehicle}} inside a var's value gets filled in the second pass fragment = fill_vars(fragment, case.get("vars", {}), keep={"vehicle"}) fragment = fill_vars(fragment, {"vehicle": vehicle}) @@ -328,7 +333,7 @@ class RunResult: def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog: Path, - duration: float | None, timeout: float, watch: bool, say) -> RunResult: + duration: float | None, timeout: float, watch: bool, say, expect_rows: bool = True) -> RunResult: """Runs the simulator on the scenery. In test mode it quits by itself and the exit code is the result; with watch it runs in a window and gets closed after `duration`.""" physicslog.unlink(missing_ok=True) @@ -351,7 +356,9 @@ def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog while True: time.sleep(0.25) # at timespeed 20 that is 5 s of simulation wall = time.monotonic() - started - result.rows = read_physicslog(physicslog) + # the whole file is read each time: in test mode, once there are rows, only for the progress line + if watch or not result.rows or wall - last_report >= 15: + result.rows = read_physicslog(physicslog) sim_t = result.rows[-1][COL_TIME] if result.rows else 0.0 if wall - last_report >= 15: v = result.rows[-1][COL_VELOCITY] if result.rows else 0.0 @@ -366,7 +373,10 @@ def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog if wall > timeout + (0 if watch else KILL_GRACE): result.failure = f"timed out after {wall:.0f}s before {duration}s of simulation" break - if not result.rows: + # not for a case with physicslog off, which has no rows to wait for, nor for one on a mission of the + # base scenery: a big scenery loads for minutes, and a bad vehicle among its decorations isn't the + # case's (a missing test vehicle ends the test mode with `error` by itself) + if expect_rows and not result.rows: result.logs = find_logs(game_dir, scenery, since) fatal = [l.strip() for l in read_text(result.logs.get("errors")).splitlines() if any(k in l for k in FATAL_LOG_LINES)] @@ -579,11 +589,12 @@ LOG_CHECKS = { def check_couples(box, vehicle, other): """The two vehicles couple in the run and stay coupled to its end; coupled from the start doesn't count.""" - numbers = {name: number for number, name in box.vehicles.items()} - unknown = [name for name in (vehicle, other) if name not in numbers] + # the simulator reads the names of a scenery in lower case, whatever the scenery (or the case) writes + 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], numbers[other]} + pair = {numbers[vehicle.lower()], numbers[other.lower()]} # of the two vehicles of a coupling the one with the lower number tells it, each change of that coupler # under the same vehicle and side: the record which coupled the two, for as long as they stay coupled made, parted = {}, None @@ -637,21 +648,51 @@ def describe_exit(code: int | None) -> str: return f"{code} ({name})" if name else f"{code} (0x{code & 0xFFFFFFFF:08X}, a crash?)" -def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool, say) -> bool: - case = json.loads((CASES_DIR / f"{name}.json").read_text(encoding="utf-8")) +def load_case(name: str) -> dict: + return json.loads((CASES_DIR / f"{name}.json").read_text(encoding="utf-8")) + + +def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool, say, seed: str | None = None) -> str: + """Runs the case and returns PASS or FAIL; for a case marked `xfail` (a known, reported bug) XFAIL + when it fails as expected, and XPASS when it passes, which means the mark has to go.""" + case = load_case(name) + ok = _run_case(name, case, exe, game_dir, timespeed, watch, say, seed) + if "xfail" not in case or watch: + return "PASS" if ok else "FAIL" + if ok: + say(f" XPASS the case passes although it is marked xfail ({case['xfail']}): remove the mark") + return "XPASS" + say(f" XFAIL fails as expected: {case['xfail']}") + return "XFAIL" + + +def _run_case(name: str, case: dict, exe: Path, game_dir: Path, timespeed: float, watch: bool, say, + seed: str | None = None) -> bool: say(f"\n=== {name}: {case.get('description', '')}") out = OUT_DIR / name shutil.rmtree(out, ignore_errors=True) out.mkdir(parents=True) - # the lead vehicle is named after the case, so parallel runs never share a physicslog - vehicle = f"autotest_{name}" + # the lead vehicle is named after the case, so parallel runs never share a physicslog. a case on a + # mission of the base scenery (strip_trainsets false) names one of the scenery's own vehicles instead + own_vehicle = "vehicle" in case + vehicle = case.get("vehicle", f"autotest_{name}") + # a long run on a scenery with dozens of AI trains would write a physicslog for each of them into the + # game dir (3-4 kB per second of simulation and train); such a case turns them off and relies on the + # result of the test mode and on the log + with_physicslog = case.get("physicslog", True) + needs_physicslog = [c["type"] for c in case.get("checks", []) if c["type"] not in LOG_CHECKS] + if not with_physicslog and (watch or needs_physicslog): + sys.exit(f"{name}: with physicslog off a case can have log checks only ({', '.join(LOG_CHECKS)}), " + "and can't run with --watch") scenery = build_scenery(case, game_dir, name, vehicle) ini = out / "autotest.ini" - # the case's own settings go last, over the common ones - ini.write_text(TEST_INI.format(timespeed=timespeed) + "".join(line + "\n" for line in case.get("ini", [])), - encoding="ascii") + # the case's own settings go last, over the common ones; then the seed of this run of the suite, if any + settings = [*case.get("ini", []), *([f"randomseed {seed}"] if seed else [])] + ini.write_text(TEST_INI.format(timespeed=timespeed, physicslog="yes" if with_physicslog else "no") + + "".join(line + "\n" for line in settings), encoding="ascii") physicslog = game_dir / "physicslog" / f"{vehicle}.dat" + started = time.time() - 1 duration = float(case["duration"]) if "duration" in case else None # a case that only records `duration` seconds ends on the test timeout; one that says @@ -662,7 +703,11 @@ def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool if watch and duration is None: sys.exit(f"{name}: --watch needs a case with duration") result = run_simulator(exe, game_dir, scenery, ini, physicslog, - duration, float(case.get("timeout", 600)), watch, say) + duration, float(case.get("timeout", 600)), watch, say, + expect_rows=with_physicslog and not own_vehicle) + # a case that asked for no geometry cache (file.binary.terrain no) leaves none of an earlier run behind + if any(line.split()[:2] == ["file.binary.terrain", "no"] for line in case.get("ini", [])): + scenery_cache(game_dir, name).unlink(missing_ok=True) # the logs are ours alone (named after the case scenery), move them out of the game dir for kind, path in result.logs.items(): @@ -672,6 +717,13 @@ def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool # other trains of the case with a driver, named _, log too for other in physicslog.parent.glob(f"*_{vehicle}.dat"): shutil.move(other, out / other.name) + # on a mission of the base scenery every train with a driver logs under its own name, the road vehicles + # too (250 files and 740 MB after 900 s of Wrzosy): the ones written in this run are removed, nothing + # checks them (so such a case can't share the game dir with another run at the time) + if own_vehicle and with_physicslog: + for other in physicslog.parent.glob("*.dat"): + if other.stat().st_mtime >= started: + other.unlink() # the black box is named after the case scenery too if result.blackbox: result.blackbox = Path(shutil.move(result.blackbox, out / f"{vehicle}.blackbox")) @@ -701,7 +753,7 @@ def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool if result.failure: say(f" FAIL {result.failure}") ok = False - if not result.rows and case.get("checks"): + if not result.rows and needs_physicslog: if not result.failure: say(f" FAIL no physicslog for '{vehicle}'") return False @@ -751,6 +803,10 @@ def main() -> int: help="with --watch: simulation time multiplier, the simulator offers 1, 5, 20 and 60 (default 1)") ap.add_argument("-j", "--jobs", type=int, default=1, help="cases run at once, each in a simulator of its own (default 1)") + ap.add_argument("--seed", help="seed of the simulator's random numbers for this run (randomseed), a number or a " + "word; the default is the fixed one of the test mode. For bugs that show up only sometimes") + ap.add_argument("--slow", action="store_true", + help="with no cases named: run the ones marked slow too (they are skipped otherwise)") args = ap.parse_args() if not args.game_dir: @@ -763,6 +819,12 @@ def main() -> int: missing = [n for n in names if not (CASES_DIR / f"{n}.json").exists()] if missing: sys.exit("no such case: " + ", ".join(missing)) + # a case marked slow (a whole mission on a big scenery, many minutes) runs when named, or with --slow + if not args.cases and not args.slow: + slow = [n for n in names if load_case(n).get("slow")] + if slow: + names = [n for n in names if n not in slow] + print(f"skipped {len(slow)} slow case(s), run them by name or with --slow: {', '.join(slow)}") started = time.monotonic() results = {} @@ -770,7 +832,7 @@ def main() -> int: def say(line, progress=False): print(line, flush=True) for n in names: - results[n] = run_case(n, exe, game_dir, args.timespeed, args.watch, say) + results[n] = run_case(n, exe, game_dir, args.timespeed, args.watch, say, args.seed) else: # each case prints its block when it is done, so parallel output does not interleave def job(n): @@ -778,20 +840,21 @@ def main() -> int: def say(line, progress=False): if not progress: lines.append(line) - ok = run_case(n, exe, game_dir, args.timespeed, args.watch, say) - return n, ok, lines + status = run_case(n, exe, game_dir, args.timespeed, args.watch, say, args.seed) + return n, status, lines with ThreadPoolExecutor(max_workers=args.jobs) as pool: for n in names: print(f"started {n}", flush=True) for fut in as_completed([pool.submit(job, n) for n in names]): - n, ok, lines = fut.result() + n, status, lines = fut.result() print("\n".join(lines), flush=True) - results[n] = ok + results[n] = status print(f"\n=== summary ({time.monotonic() - started:.0f}s)") for n in names: - print(f" {'PASS' if results[n] else 'FAIL'} {n}") - return 0 if all(results.values()) else 1 + print(f" {results[n]:5} {n}") + # a known failure keeps the suite green; one that stopped failing doesn't, so that its mark gets removed + return 0 if all(status in ("PASS", "XFAIL") for status in results.values()) else 1 if __name__ == "__main__": From ca23831bb2b783ec9c2eb7178a3bc90f60d1eb16 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 12 Nov 2026 04:47:03 +0100 Subject: [PATCH 002/136] test(scenarios): cases from the reports eu07/maszyna#421, #506, #524, #525 Six slow cases, each a mission of a scenery of the game with every train driven by AI: - wrzosy_pxe336080_couples (#524): the locomotive, given the orders the player's hands stand for, couples to the rake in the Wolica depot and takes it out. Passes. - baltyk_skm1_roj55324_shunting_signal, baltyk_skm1_roj55321_departure (#525): the unit on the siding gets its shunting signal once the shunter beside it has moved, the one in the platform leaves on time. Pass, with 4 and 3 seeds. - l053_poranek_tme222158_debica (#421): xfail, the train is never let into Debica: the AI of another locomotive passes the shunting signal Tm4 at stop and the station waits for it for good. - l053_poranek_tme222158_debica_et21 (#421, with the ET21 of the report): xfail, the ET21 stops past the end of the overhead wire at Debica Towarowa and its driver never restarts it. - l053_poludnie_roj32134_debica (#506): both trains of the mission run and end at Debica. Passes. --- .../cases/baltyk_skm1_roj55321_departure.json | 18 +++++++++ .../baltyk_skm1_roj55324_shunting_signal.json | 18 +++++++++ .../cases/l053_poludnie_roj32134_debica.json | 24 ++++++++++++ .../cases/l053_poranek_tme222158_debica.json | 31 +++++++++++++++ .../l053_poranek_tme222158_debica_et21.json | 37 ++++++++++++++++++ tests/scenarios/cases/mission_state_probe.scn | 13 +++++++ .../cases/wrzosy_pxe336080_couple.scn | 39 +++++++++++++++++++ .../cases/wrzosy_pxe336080_couples.json | 26 +++++++++++++ 8 files changed, 206 insertions(+) create mode 100644 tests/scenarios/cases/baltyk_skm1_roj55321_departure.json create mode 100644 tests/scenarios/cases/baltyk_skm1_roj55324_shunting_signal.json create mode 100644 tests/scenarios/cases/l053_poludnie_roj32134_debica.json create mode 100644 tests/scenarios/cases/l053_poranek_tme222158_debica.json create mode 100644 tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json create mode 100644 tests/scenarios/cases/mission_state_probe.scn create mode 100644 tests/scenarios/cases/wrzosy_pxe336080_couple.scn create mode 100644 tests/scenarios/cases/wrzosy_pxe336080_couples.json diff --git a/tests/scenarios/cases/baltyk_skm1_roj55321_departure.json b/tests/scenarios/cases/baltyk_skm1_roj55321_departure.json new file mode 100644 index 000000000..98b9c8119 --- /dev/null +++ b/tests/scenarios/cases/baltyk_skm1_roj55321_departure.json @@ -0,0 +1,18 @@ +{ + "description": "eu07/maszyna#525, Baltyk skm1, the mission that starts in the platform of Baltyk Glowny (EN71-014ra, ROJ55321, departure 10:34): the exit signal has to clear and the unit has to leave. Standing for 10 minutes ends the test as standstill.", + "base_scenery": "baltyk_skm1.scn", + "strip_trainsets": false, + "vehicle": "EN71-014ra", + "slow": true, + "physicslog": false, + "ini": [ + "file.binary.terrain no" + ], + "test_config": [ + "test.standstill 600", + "test.fail_if_stop_overran no" + ], + "duration": 900, + "expect": "timeout", + "timeout": 900 +} diff --git a/tests/scenarios/cases/baltyk_skm1_roj55324_shunting_signal.json b/tests/scenarios/cases/baltyk_skm1_roj55324_shunting_signal.json new file mode 100644 index 000000000..a8fa0e7cc --- /dev/null +++ b/tests/scenarios/cases/baltyk_skm1_roj55324_shunting_signal.json @@ -0,0 +1,18 @@ +{ + "description": "eu07/maszyna#525, Baltyk skm1, the mission that starts on the siding of Baltyk Towarowy next to the shunter (EN90-009A, ROJ55324): the station lets the unit into the platforms once its shunter 6Dg-1244, on the track beside it, has done its first moves (4 minutes after the start), and out to Alakowice at 10:42. A shunter that gets stuck leaves the unit at the shunting signal for good: standing for 15 minutes ends the test as standstill.", + "base_scenery": "baltyk_skm1.scn", + "strip_trainsets": false, + "vehicle": "EN90-009A", + "slow": true, + "physicslog": false, + "ini": [ + "file.binary.terrain no" + ], + "test_config": [ + "test.standstill 900", + "test.fail_if_stop_overran no" + ], + "duration": 1800, + "expect": "timeout", + "timeout": 900 +} diff --git a/tests/scenarios/cases/l053_poludnie_roj32134_debica.json b/tests/scenarios/cases/l053_poludnie_roj32134_debica.json new file mode 100644 index 000000000..7ed64bf96 --- /dev/null +++ b/tests/scenarios/cases/l053_poludnie_roj32134_debica.json @@ -0,0 +1,24 @@ +{ + "description": "eu07/maszyna#506, L053 poludnie, ROJ23133 Debica - Rudawa and ROJ32134 back (EN57-1797ra): the unit runs both trains among the scenery's traffic and ends at Debica (the station's state cell of ROJ32134 says done).", + "base_scenery": "l053_poludnie.scn", + "strip_trainsets": false, + "vehicle": "EN57-1797ra", + "fragment": "mission_state_probe.scn", + "vars": { + "cell": "deb_roj32134_stat", + "state": "d * *", + "reason": "roj32134_ended_at_debica" + }, + "slow": true, + "physicslog": false, + "ini": [ + "file.binary.terrain no" + ], + "test_config": [ + "test.timeout 7200", + "test.standstill 1500", + "test.fail_if_stop_overran no" + ], + "expect": "pass", + "timeout": 3600 +} diff --git a/tests/scenarios/cases/l053_poranek_tme222158_debica.json b/tests/scenarios/cases/l053_poranek_tme222158_debica.json new file mode 100644 index 000000000..bad10aee4 --- /dev/null +++ b/tests/scenarios/cases/l053_poranek_tme222158_debica.json @@ -0,0 +1,31 @@ +{ + "description": "eu07/maszyna#421, L053 poranek, TME222158: the locomotive brings the wagons with steel coils from Debica Towarowa to Debica, uncouples (Shunt 0 0 from the scenery), shunts on the Ms2 signals while the station's SM42 takes the wagons away, couples to its next train and gets the exit signal to Sandomierz (step 6 of the station's state cell).", + "base_scenery": "l053_poranek.scn", + "strip_trainsets": false, + "vehicle": "ET22-654", + "fragment": "mission_state_probe.scn", + "vars": { + "cell": "deb_tme222158_stat", + "state": "* 6 *", + "reason": "tme222158_got_the_exit_signal_at_debica" + }, + "slow": true, + "xfail": "eu07/maszyna#421 is not reached: with every train driven by AI Debica jams 4 minutes after the start, the AI of EP07-338'16 passes the shunting signal Tm4 at stop at 29 km/h and stops 20 m beyond the checkpoint before it (tor1834:event0), so RPE23113 never reports there and TME222158 is never let into the station", + "physicslog": false, + "ini": [ + "file.binary.terrain no" + ], + "test_config": [ + "test.timeout 6000", + "test.standstill 2100", + "test.fail_if_stop_overran no" + ], + "expect": "pass", + "timeout": 3600, + "checks": [ + { + "type": "log_contains", + "pattern": "Uncoupling \\[ET22-654\\]: uncoupled" + } + ] +} diff --git a/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json b/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json new file mode 100644 index 000000000..49c1ba3c2 --- /dev/null +++ b/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json @@ -0,0 +1,37 @@ +{ + "description": "eu07/maszyna#421 as reported in 2021, with an ET21 on TME222158 (the scenery has an ET22 there now): the same run as l053_poranek_tme222158_debica, the locomotive of the mission replaced.", + "base_scenery": "l053_poranek.scn", + "strip_trainsets": false, + "replace": [ + [ + "node -1 0 ET22-654 dynamic pkp\\et22_v3 201E-654 201E -1 headdriver 3 0 enddynamic", + "node -1 0 ET21-367 dynamic pkp\\et21_v2 ET21-367 3e2 -1 headdriver 3 0 enddynamic" + ] + ], + "vehicle": "ET21-367", + "fragment": "mission_state_probe.scn", + "vars": { + "cell": "deb_tme222158_stat", + "state": "* 6 *", + "reason": "tme222158_got_the_exit_signal_at_debica" + }, + "slow": true, + "xfail": "eu07/maszyna#421: the ET21 stands for good at Debica Towarowa with the shunting signal at Ms2. Running round the wagons it stops on the headshunt 20 m past the end of the overhead wire (the wire ends at z 4804 over tor2466, the locomotive stands at z 4786), loses power, and its driver never gets out of Prepare_engine; the ET22 the scenery has there now gets through", + "physicslog": false, + "ini": [ + "file.binary.terrain no" + ], + "test_config": [ + "test.timeout 6000", + "test.standstill 2100", + "test.fail_if_stop_overran no" + ], + "expect": "pass", + "timeout": 3600, + "checks": [ + { + "type": "log_contains", + "pattern": "Uncoupling \\[ET21-367\\]: uncoupled" + } + ] +} diff --git a/tests/scenarios/cases/mission_state_probe.scn b/tests/scenarios/cases/mission_state_probe.scn new file mode 100644 index 000000000..fd158dab3 --- /dev/null +++ b/tests/scenarios/cases/mission_state_probe.scn @@ -0,0 +1,13 @@ +// added by tests/scenarios/run.py to a scenery that keeps its own trainsets (strip_trainsets false): the +// case tests one of the scenery's missions, with every train driven by AI. +// the sceneries of this kind steer their stations with state cells, one per train (text and two values, +// e.g. "a 6 *": the route of step 6 is set for the train, "d * *": the train is done at this station). +// the probe looks at the cell {{cell}} every 5 s from the start on and reports the pass once it holds +// {{state}}. no fail event: a train that never gets there ends the test with the standstill or the +// timeout of the test mode. +// the two events calling each other are the loop these sceneries use themselves (e.g. bal_obsluga_stacji); +// an event with "onstart" in its name is queued when the scenery starts. +event onstart_autotest_probe multiple 30 none autotest_probe endevent +event autotest_probe multiple 0 {{cell}} autotest_pass else autotest_probe_wait condition memcompare {{state}} endevent +event autotest_probe_wait multiple 5 none autotest_probe endevent +event autotest_pass UpdateValues 0 __test.result {{reason}} 1 * endevent diff --git a/tests/scenarios/cases/wrzosy_pxe336080_couple.scn b/tests/scenarios/cases/wrzosy_pxe336080_couple.scn new file mode 100644 index 000000000..c0d504d57 --- /dev/null +++ b/tests/scenarios/cases/wrzosy_pxe336080_couple.scn @@ -0,0 +1,39 @@ +// added by tests/scenarios/run.py to wrzosy_pxe336080.scn, which keeps its own trainsets: the mission of +// eu07/maszyna#524. EU07-234 runs light from final_2t839 through the Wolica depot to the rake of 12 coaches +// pxe_1 .. pxe_12 (linia053_wrzosy/pxe336080_dekoracje.scm, "trainset none woa_odst009 304 0"), has to +// couple to it and take it out of the depot. +// +// the scenery gives the locomotive no order at all: its trainset has velocity 0, so with nobody in the cab +// its driver sleeps in Wait_for_orders, and nothing in the scenery tells it to couple, the player does that +// by hand. the two orders the player's hands stand for are given here. +// +// 1. a minute after the start (the scenery sets the way and the shunting signals at 50-55 s): shunt, as +// the signals say (Shunt -1 0). PutValues goes to the vehicle that set the event off, so it hangs on +// event0 of the track the locomotive stands on (the three its 16 m may reach); event0 comes again and +// again while it stands there, the cell lets the order through once. +// the first order is not the one to couple, on purpose: a driver whose first order is Connect never +// releases the hand brake the locomotive starts with, and pulls against it for good (CheckVehicles() +// leaves AutoRewident() out for Connect). +node -1 0 autotest_ordered memcell 0 0 0 ordered 0 0 none endmemcell +event final_2t838:event0 multiple 60 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event final_2t839:event0 multiple 60 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event final_2t840:event0 multiple 60 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event autotest_order PutValues 0 none 0 0 0 Shunt -1 0 endevent +event autotest_order_given UpdateValues 0 autotest_ordered * 1 * endevent + +// 2. on the last track before the rake, in the direction the locomotive comes from (event2 of +// woa_lokom007, some 35-45 m short of the first coach): couple to the consist standing ahead with the +// coupler and the brake hose (3), turn round and wait for the shunting signal. it is the order these +// sceneries give their AI shunters (dos_sm42_przypnij). +event woa_lokom007:event2 PutValues 0 none 0 0 0 Shunt -2 -3 endevent + +// 330 s after the locomotive ran over lok_woa005 towards the rake the scenery sets the way out +// (lok_woa005:event2 -> PXE_gotowy -> pxe_manewry_ruszaj), coupled or not. it leads back over lok_woa005, +// towards its point 1. every vehicle going that way is counted (eventall1); the locomotive alone makes 1, +// so the second vehicle is a coach of the rake, coupled and pulled. the test ends there, with the train +// still moving (test.no_movement_before_pass no). +node -1 0 autotest_left memcell 0 0 0 left 0 0 none endmemcell +event lok_woa005:eventall1 multiple 0 none autotest_count autotest_judge endevent +event autotest_count AddValues 0 autotest_left * 1 0 endevent +event autotest_judge multiple 0 autotest_left autotest_pass condition memcompare * 2 * endevent +event autotest_pass UpdateValues 0 __test.result the_rake_left_the_depot_behind_the_locomotive 1 * endevent diff --git a/tests/scenarios/cases/wrzosy_pxe336080_couples.json b/tests/scenarios/cases/wrzosy_pxe336080_couples.json new file mode 100644 index 000000000..11d385871 --- /dev/null +++ b/tests/scenarios/cases/wrzosy_pxe336080_couples.json @@ -0,0 +1,26 @@ +{ + "description": "eu07/maszyna#524, Wrzosy PXE336080: EU07-234 runs light to the rake of 12 coaches in the Wolica depot, gets the order to couple (the player's hand, the scenery gives none), has to couple to the first coach and leave the depot with the rake behind it.", + "base_scenery": "wrzosy_pxe336080.scn", + "strip_trainsets": false, + "vehicle": "EU07-234", + "fragment": "wrzosy_pxe336080_couple.scn", + "slow": true, + "ini": [ + "file.binary.terrain no" + ], + "test_config": [ + "test.timeout 1800", + "test.standstill 900", + "test.fail_if_stop_overran no", + "test.no_movement_before_pass no" + ], + "expect": "pass", + "timeout": 1200, + "checks": [ + { + "type": "couples", + "vehicle": "EU07-234", + "other": "pxe_1" + } + ] +} From c5676629132eed0358c5f95fe5ef3f83ea79b641 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 12 Nov 2026 05:26:57 +0100 Subject: [PATCH 003/136] fix(ai): release the hand brake when the first order is Connect CheckVehicles() ran the inspector (AutoRewident(), which also releases the hand and spring brakes of the AI's train) only under Shunt, Loose_shunt, Obey_train and Bank. A locomotive loaded cold (trainset velocity 0) starts with its hand brake on; when the first order it drives under is Connect (Shunt x,y with a coupler, e.g. Shunt -2 -3 after Prepare_engine), it pulled against the hand brake for good and never reached the wagons. The inspector now also runs under Connect, except for the look the AI takes at the moment it couples (CheckVehicles(Connect)): the wagons just coupled keep their hand brakes until the order after the coupling looks at the new train, as before, so those to be left standing again (Shunt x,-y) stay braked. Wagons not yet coupled are never touched: AutoRewident() goes over the vehicles coupled to the AI's train only. The rule is brake_setting::inspects_train(), with a unit test. --- tests/unit/test_brake_setting.cpp | 23 +++++++++++++++++++++++ vehicle/Driver.cpp | 2 +- vehicle/brakesetting.cpp | 4 ++++ vehicle/brakesetting.h | 9 +++++++++ 4 files changed, 37 insertions(+), 1 deletion(-) diff --git a/tests/unit/test_brake_setting.cpp b/tests/unit/test_brake_setting.cpp index 5034bf3c5..39b0e2117 100644 --- a/tests/unit/test_brake_setting.cpp +++ b/tests/unit/test_brake_setting.cpp @@ -474,6 +474,29 @@ TEST_CASE("brake setting: a bank engine's run counts as a train, shunting doesn' CHECK(false == brake_setting::is_cut_out(car.mover())); } +TEST_CASE("brake setting: the AI looks at its train under the orders it drives it under, Connect included") { + CHECK(brake_setting::inspects_train(Shunt, false)); + CHECK(brake_setting::inspects_train(Loose_shunt, false)); + CHECK(brake_setting::inspects_train(Obey_train, false)); + CHECK(brake_setting::inspects_train(Bank, false)); + // the run up to the wagons: a locomotive standing cold has its hand brake to release first + CHECK(brake_setting::inspects_train(Connect, false)); + CHECK(brake_setting::inspects_train(Connect | Change_direction, false)); + // but not at the coupling: the wagons just coupled wait for the next order, which may leave some of them + CHECK(false == brake_setting::inspects_train(Connect, true)); + CHECK(false == brake_setting::inspects_train(Connect | Change_direction, true)); + // a train run with a coupling on it is still a train run + CHECK(brake_setting::inspects_train(Obey_train | Connect, true)); + CHECK(brake_setting::inspects_train(Shunt, true)); + // standing, starting or stopping the engine, turning round, uncoupling: nothing to look at + CHECK(false == brake_setting::inspects_train(Wait_for_orders, false)); + CHECK(false == brake_setting::inspects_train(Prepare_engine, false)); + CHECK(false == brake_setting::inspects_train(Release_engine, false)); + CHECK(false == brake_setting::inspects_train(Change_direction, false)); + CHECK(false == brake_setting::inspects_train(Disconnect, false)); + CHECK(false == brake_setting::inspects_train(Jump_to_first_order, false)); +} + TEST_CASE("brake setting: R+Mg brakes as hard as R at speed, the rapid stage of an LSt kept") { // the inspector sets R+Mg (Cw-1 §18.2), the bits of R and Mg together: the valves test the bit of R, not // the whole setting, so the high stage of R at speed stays on with Mg. the EU07's LSt given an Mg here diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index eb74344bf..ce41ee780 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -2876,7 +2876,7 @@ bool TController::CheckVehicles(TOrders user) = 0; } - if( OrderCurrentGet() & ( Shunt | Loose_shunt | Obey_train | Bank ) ) { + if( brake_setting::inspects_train( OrderCurrentGet(), user == Connect ) ) { // nastawianie hamulca do jazdy pociągowej AutoRewident(); /* diff --git a/vehicle/brakesetting.cpp b/vehicle/brakesetting.cpp index ceffe3180..918da3d02 100644 --- a/vehicle/brakesetting.cpp +++ b/vehicle/brakesetting.cpp @@ -177,6 +177,10 @@ bool runs_as_train(int const Orders) { return (Orders & (Obey_train | Bank)) != 0; } +bool inspects_train(int const Orders, bool const Coupled) { + return (Orders & (Shunt | Loose_shunt | Obey_train | Bank)) != 0 || ((Orders & Connect) != 0 && false == Coupled); +} + bool at_standstill(double const Velocity) { return std::abs(Velocity) < EU07_AI_MOVEMENT; } diff --git a/vehicle/brakesetting.h b/vehicle/brakesetting.h index cb7ad5225..e3e5b4974 100644 --- a/vehicle/brakesetting.h +++ b/vehicle/brakesetting.h @@ -65,6 +65,15 @@ std::vector choose(std::vector const &Consist, bool Train); // train run too (with the braking of a train). Orders is the order of the AI (TOrders) bool runs_as_train(int Orders); +// the AI has the inspector look at its train (TController::AutoRewident(): the brake settings, and the hand and +// spring brakes of the train released) under the orders it drives the train under: shunting, loose shunting, the +// train run, banking, and the run up to the wagons to couple to (Connect), which a locomotive left standing cold, +// with its hand brake on, would make pulling against it. Coupled: the look the AI takes at the moment it couples +// (CheckVehicles(Connect)); Connect doesn't count for it, so the wagons just coupled keep their hand brakes until +// the order after the coupling looks at the new train, as before: those of them to be left standing again +// (Shunt x,-y) stay braked. Orders is the order of the AI (TOrders) +bool inspects_train(int Orders, bool Coupled); + // the train stands for the inspector: slower than the AI takes for a deliberate movement (EU07_AI_MOVEMENT). // the AI looks at the train while it still creeps to a stop (at a W4, or switching from shunting to the train // run), so a stricter threshold would miss those checks; a train really on the run (an order changed mid-run) From ea4409042b47743a1a876f21066cadd7c80226ba Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 12 Nov 2026 05:26:57 +0100 Subject: [PATCH 004/136] test(scenarios): a cold EU07 couples to coaches as its first order eu07_td_cold_connect: an EU07 with a hand brake (4E-ZEZ_GREY) stands cold on td.scn with two coaches 45 m ahead; event0 of its track gives it Shunt -1 3 once. It has to start the engine, couple (Connect is the first order it drives under) and push the coaches onto tor1k. Before the fix it stands pulling against its hand brake and the case ends as a standstill. --- tests/scenarios/README.md | 9 ++++++ .../scenarios/cases/eu07_td_cold_connect.json | 28 +++++++++++++++++++ tests/scenarios/cases/td_cold_connect.scn | 28 +++++++++++++++++++ 3 files changed, 65 insertions(+) create mode 100644 tests/scenarios/cases/eu07_td_cold_connect.json create mode 100644 tests/scenarios/cases/td_cold_connect.scn diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index ea5ebc89b..71c29cbd8 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -230,6 +230,15 @@ couple and neither shows up: the black box has to have the last car of the stand writes nothing to the log when couplers catch). Nothing reports a result, so both end on the 60 s test timeout. +`eu07_td_cold_connect` (fragment `td_cold_connect.scn`) has an EU07 with a hand brake +(`4E-ZEZ_GREY`; the plain `4e` has none) standing cold on track 1 of Stacja1 (trainset velocity 0, +so it starts with the hand brake on) and two coaches standing 45 m ahead of it. Its driver sleeps +until `event0` of its track gives it, once, `Shunt -1 3`: start the engine, couple to the consist +ahead (Connect, the first order it drives under), go on shunting. It passes when the first coach, +pushed, runs onto `tor1k` (`eventall2`), with the train still moving, and the black box has the +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. + Checks (speeds in km/h, times in seconds of physicslog time, distances in metres). Most use the physicslog Velocity column, which is the wheel speed: it stays at 0 while the wheels are locked in a skid. The ones marked *vehicle speed* use the vehicle speed column at the end of diff --git a/tests/scenarios/cases/eu07_td_cold_connect.json b/tests/scenarios/cases/eu07_td_cold_connect.json new file mode 100644 index 000000000..26c975861 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_cold_connect.json @@ -0,0 +1,28 @@ +{ + "description": "EU07 with a hand brake (4E-ZEZ_GREY) on td.scn, standing cold with the hand brake on, gets the order to couple to the two coaches standing 45 m ahead (Shunt -1 3): after starting the engine it has to release its hand brake, run up to the coaches, couple and push them on. Connect is the first order the AI drives under.", + "base_scenery": "td.scn", + "fragment": "td_cold_connect.scn", + "vars": { + "locomotive": "pkp\\4e_v1 4E-ZEZ-234 4E-ZEZ_GREY", + "rake": [ + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 0 0 enddynamic" + ] + }, + "track_events": { + "tdo_n1725": "event0 autotest_wake", + "tor1k": "eventall2 autotest_pass" + }, + "test_config": [ + "test.timeout 900", + "test.standstill 300", + "test.no_movement_before_pass no" + ], + "expect": "pass", + "timeout": 900, + "checks": [ + { "type": "couples", "vehicle": "{{vehicle}}", "other": "{{vehicle}}_c2" }, + { "type": "log_lacks", "pattern": "derailed" }, + { "type": "log_lacks", "pattern": "collided" } + ] +} diff --git a/tests/scenarios/cases/td_cold_connect.scn b/tests/scenarios/cases/td_cold_connect.scn new file mode 100644 index 000000000..3ea9306c6 --- /dev/null +++ b/tests/scenarios/cases/td_cold_connect.scn @@ -0,0 +1,28 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// on the straight track 1 of Stacja1: a locomotive with an AI driver stands cold (trainset velocity 0, so +// it starts "Braked": hand brake on, battery off, pantographs down) on tdo_n1725, its front 60 m past +// point 1 of the track, facing point 2; the rake (vars.rake) stands, braked as well and with nobody in it, +// on tdo_n1734 ahead of it, its front 60 m past point 1 of that track, some 45 m in front of the +// locomotive (two coaches of 26.4 m). +trainset none tdo_n1725 60.0 0.0 +node -1 0 {{vehicle}} dynamic {{locomotive}} 0 headdriver 0 0 enddynamic +endtrainset + +trainset none tdo_n1734 60.0 0.0 +{{rake}} +endtrainset + +// a driver of a standing trainset sleeps on Wait_for_orders until something wakes it. event0 of the +// locomotive's track (the case's track_events) runs while it stands there and gives it, once (the memory +// cell), the order a scenery gives a shunter to couple: Shunt -1 3, couple to the consist standing ahead +// with the coupler and the brake hose and go on shunting. the engine is cold, so the AI starts it +// first: its orders are Prepare_engine, Connect, Shunt, and Connect is the first one it drives under. +node -1 0 autotest_ordered memcell 0 0 0 ordered 0 0 none endmemcell +event autotest_wake multiple 0 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event autotest_order PutValues 0 none 0 0 0 Shunt -1 3 endevent +event autotest_order_given UpdateValues 0 autotest_ordered * 1 * endevent + +// the rake, pushed by the locomotive, runs onto tor1k (40 m ahead of its first coach) towards its +// point 2: eventall2 of tor1k (the case's track_events) passes the test, which ends there with the train +// still moving (test.no_movement_before_pass no), 100 m short of the exit signal at the end of tor1k. +event autotest_pass UpdateValues 0 __test.result the_rake_was_coupled_and_pushed 1 * endevent From 2cd646dbb6ed4552b8c161d35b4b430b2edd6e9e Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 12 Nov 2026 06:59:56 +0100 Subject: [PATCH 005/136] test(scenarios): the L053 poranek cases look for the uncoupling under the lower-case name the log writes --- tests/scenarios/cases/l053_poranek_tme222158_debica.json | 2 +- tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/scenarios/cases/l053_poranek_tme222158_debica.json b/tests/scenarios/cases/l053_poranek_tme222158_debica.json index bad10aee4..6fbc141e7 100644 --- a/tests/scenarios/cases/l053_poranek_tme222158_debica.json +++ b/tests/scenarios/cases/l053_poranek_tme222158_debica.json @@ -25,7 +25,7 @@ "checks": [ { "type": "log_contains", - "pattern": "Uncoupling \\[ET22-654\\]: uncoupled" + "pattern": "Uncoupling \\[et22-654\\]: uncoupled" } ] } diff --git a/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json b/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json index 49c1ba3c2..4f169fea7 100644 --- a/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json +++ b/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json @@ -31,7 +31,7 @@ "checks": [ { "type": "log_contains", - "pattern": "Uncoupling \\[ET21-367\\]: uncoupled" + "pattern": "Uncoupling \\[et21-367\\]: uncoupled" } ] } From 1bd7187db7166b998cb61b6a24294a8a8dcfe9a2 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 13 Nov 2026 14:25:18 +0100 Subject: [PATCH 006/136] fix(scripting): close the small holes in the script screen sandbox - Lua: once the instruction budget of a call is spent, the count hook runs at every instruction and raises again, so pcall, nested pcall and coroutine.resume can't swallow the limit; xpcall is rebuilt on pcall so its handler runs after the error left f, while the hook works - Lua: the metatables of eu07.image/font/sprite are locked (__metatable = false); __gc destroys only an object of its own type, once - Lua: read_png checks the size with stbi_info before decoding - Lua: string.rep makes no string over 1 MiB - Lua and WASM: at most 64 commands per call, names up to 64 bytes, 32 log lines per call cut at 1024 bytes; the drops are logged once - fonts: a glyph wider than 4096 is skipped; more than 4096 glyphs, 8192 columns or an image side over 4096 refuse the font; cut_glyph reads only the columns inside the image - the script path from the .mmd (cab screens, destination signs, make: textures) must stay inside the game folder; the files a screen reads, its script and its module must be regular files of 16 MiB at most Tests for each in test_script_screen_host.cpp, test_script_screen_drawing.cpp and test_script_screens.cpp; the test stubs can capture the log. --- scripting/luaprogram.cpp | 145 +++++++-- scripting/scriptscreendrawing.cpp | 21 +- scripting/scriptscreendrawing.h | 9 +- scripting/scriptscreenprogram.h | 35 ++ scripting/scriptscreenrules.cpp | 11 + scripting/scriptscreenrules.h | 6 + scripting/scriptscreens.cpp | 67 +++- scripting/wasmprogram.cpp | 29 +- tests/unit/engine_stubs.cpp | 34 ++ tests/unit/test_script_screen_drawing.cpp | 39 +++ tests/unit/test_script_screen_host.cpp | 369 +++++++++++++++++++++- tests/unit/test_script_screens.cpp | 16 + vehicle/DynObj.cpp | 14 +- vehicle/Train.cpp | 9 +- 14 files changed, 750 insertions(+), 54 deletions(-) diff --git a/scripting/luaprogram.cpp b/scripting/luaprogram.cpp index 36d95d271..4e3c0eea4 100644 --- a/scripting/luaprogram.cpp +++ b/scripting/luaprogram.cpp @@ -29,8 +29,6 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include -#include #include #include #include @@ -43,20 +41,28 @@ namespace { constexpr int hook_interval{1000}; -constexpr char const *image_metatable{"eu07.image"}; -constexpr char const *font_metatable{"eu07.font"}; -constexpr char const *sprite_metatable{"eu07.sprite"}; +// the longest string string.rep makes +constexpr double max_repeat{1024 * 1024}; +// arrays, to be arguments of collect<> +constexpr char image_metatable[]{"eu07.image"}; +constexpr char font_metatable[]{"eu07.font"}; +constexpr char sprite_metatable[]{"eu07.sprite"}; // the address is the key of the program in the registry of its state constexpr char program_key{0}; class lua_program final : public program { public: - lua_program(std::string const &Script, script_screen_kind const Kind) : kind{Kind}, script{Script}, folder{substr_path(Script)} {} + lua_program(std::string const &Script, script_screen_kind const Kind) + : kind{Kind}, script{Script}, folder{substr_path(Script)}, output{std::format("Lua screen \"{}\"", Script)} + { + } ~lua_program() override { if (m_state != nullptr) { + // the finalizers lua_close runs aren't counted: the budget of the last call may be spent + lua_sethook(m_state, nullptr, 0, 0); lua_close(m_state); } } @@ -71,6 +77,7 @@ class lua_program final : public program std::string const folder; render_call *call{nullptr}; // the refresh in progress bool commands_ignored{false}; // a screen outside the cab tried to send a command, and it was logged + output_limits output; std::int64_t budget{0}; // instructions left to the call in progress private: @@ -102,6 +109,11 @@ void count_hook(lua_State *L, lua_Debug * /*Debug*/) self->budget -= hook_interval; if (self->budget < 0) { + // from now on the hook runs at every instruction, and raises the error again. a script that catches it (pcall, + // xpcall, coroutine.resume) gets it again at its next instruction, so the error comes out of every level of the + // script in turn, and the call ends. run() sets the interval back for the next call. the hook is the state's, + // shared by its coroutines + lua_sethook(L, count_hook, LUA_MASKCOUNT, 1); luaL_error(L, "instruction limit exceeded"); } } @@ -120,12 +132,6 @@ template std::remove_cvref_t *push_object(lua_State *L, return object; } -template int collect(lua_State *L) -{ - static_cast(lua_touserdata(L, 1))->~Type_(); - return 0; -} - // the object at the index when it has the metatable, otherwise nullptr template Type_ *test_object(lua_State *L, int const Index, char const *Metatable) { @@ -140,6 +146,19 @@ template Type_ *test_object(lua_State *L, int const Index, char return matches ? static_cast(object) : nullptr; } +// __gc. the metatables are locked (make_metatable), so only the collector calls it; all the same it destroys only an +// object of its own type, and once: the object loses its metatable, which its methods check for +template int collect(lua_State *L) +{ + if (auto *object{test_object(L, 1, Metatable_)}; object != nullptr) + { + object->~Type_(); + lua_pushnil(L); + lua_setmetatable(L, 1); + } + return 0; +} + template Type_ &check_object(lua_State *L, int const Index, char const *Metatable) { auto *object{test_object(L, Index, Metatable)}; @@ -262,6 +281,12 @@ std::optional read_png(std::string const &Folder, std::string_vie int width{0}; int height{0}; int channels{0}; + // the size first: a small file may declare an image of gigabytes + if (0 == stbi_info_from_memory(reinterpret_cast(file->data()), static_cast(file->size()), &width, &height, &channels) || + false == valid_image_side(width) || false == valid_image_side(height)) + { + return std::nullopt; + } // the texture loader turns every image bottom row first, for all threads (model/Texture.cpp): fonts and sprites are // read top row first, as led_util reads them stbi_set_flip_vertically_on_load_thread(0); @@ -362,9 +387,13 @@ int api_log(lua_State *L) { lua_concat(L, count * 2 - 1); } - auto const *self{program_of(L)}; - auto const *text{lua_tostring(L, -1)}; - WriteLog(std::format("Lua screen \"{}\": {}", self->script, text != nullptr ? text : "")); + auto *self{program_of(L)}; + std::size_t length{0}; + auto const *text{lua_tolstring(L, -1, &length)}; + if (auto const line{self->output.take_log(text != nullptr ? std::string_view{text, length} : std::string_view{})}; line.has_value()) + { + WriteLog(*line); + } return 0; } @@ -388,7 +417,10 @@ int api_command(lua_State *L) } return 0; } - self->call->commands.emplace_back(std::string{name}, param1, param2, self->call->vehicle); + if (self->output.take_command(*self->call, name)) + { + self->call->commands.emplace_back(std::string{name}, param1, param2, self->call->vehicle); + } return 0; } @@ -663,6 +695,58 @@ constexpr std::array api_functions{ luaL_Reg{nullptr, nullptr}, }; +// string.rep, which makes no string longer than max_repeat. a separator (a third argument, where LuaJIT takes one) +// is counted as well +int api_repeat(lua_State *L) +{ + std::size_t length{0}; + luaL_checklstring(L, 1, &length); + auto const count{luaL_checknumber(L, 2)}; + std::size_t separator{0}; + luaL_optlstring(L, 3, "", &separator); + // as a double: no overflow for any count, and a count of NaN fails both comparisons + if (false == (count <= 0) && false == (static_cast(length) * count + static_cast(separator) * (count - 1) <= max_repeat)) + { + return luaL_error(L, "string.rep: the result would be over %d bytes", static_cast(max_repeat)); + } + lua_pushvalue(L, lua_upvalueindex(1)); + lua_insert(L, 1); + lua_call(L, lua_gettop(L) - 1, 1); + return 1; +} + +// xpcall(f, handler, ...). LuaJIT calls the handler where the error was raised, before the stack unwinds: for the error +// of the instruction hook that is while the hook still runs, when no hook is called, so a handler that loops would never +// be stopped. here f runs under pcall (the upvalue), and the handler is called, under pcall as well, once the error +// has left f. a script has no debug library to look at the stack with, so the handler gets what it got before +int api_xpcall(lua_State *L) +{ + auto const arguments{lua_gettop(L)}; + luaL_checkany(L, 2); + lua_pushvalue(L, lua_upvalueindex(1)); + lua_pushvalue(L, 1); + for (int idx = 3; idx <= arguments; ++idx) + { + lua_pushvalue(L, idx); + } + lua_call(L, arguments - 1, LUA_MULTRET); + if (lua_toboolean(L, arguments + 1) != 0) + { + // true and the results of f + return lua_gettop(L) - arguments; + } + // false and what the handler made of the error + auto const error{lua_gettop(L)}; + lua_pushboolean(L, 0); + lua_pushvalue(L, lua_upvalueindex(1)); + lua_pushvalue(L, 2); + lua_pushvalue(L, error); + lua_call(L, 2, 2); + // pcall(handler, error) gave true and the handler's value, or false and the handler's own error + lua_remove(L, -2); + return 2; +} + template void make_metatable(lua_State *L, char const *Name, std::array const &Methods, lua_CFunction Collect) { luaL_newmetatable(L, Name); @@ -679,6 +763,9 @@ template void make_metatable(lua_State *L, char const *Name, lua_setfield(L, -2, "__index"); lua_pushcfunction(L, Collect); lua_setfield(L, -2, "__gc"); + // getmetatable() of an object gives this instead of the table + lua_pushboolean(L, 0); + lua_setfield(L, -2, "__metatable"); lua_pop(L, 1); } @@ -747,7 +834,15 @@ void lua_program::open_libraries() lua_getglobal(m_state, LUA_STRLIBNAME); lua_pushnil(m_state); lua_setfield(m_state, -2, "dump"); + // string.rep with a cap on the length, around the library's own. strings share the table as their methods + lua_getfield(m_state, -1, "rep"); + lua_pushcclosure(m_state, api_repeat, 1); + lua_setfield(m_state, -2, "rep"); lua_pop(m_state, 1); + // xpcall made of pcall, see api_xpcall + lua_getglobal(m_state, "pcall"); + lua_pushcclosure(m_state, api_xpcall, 1); + lua_setglobal(m_state, "xpcall"); } void lua_program::register_api() @@ -757,9 +852,9 @@ void lua_program::register_api() lua_pushlightuserdata(L, this); lua_rawset(L, LUA_REGISTRYINDEX); - make_metatable(L, image_metatable, image_methods, collect); - make_metatable(L, font_metatable, font_methods, collect); - make_metatable(L, sprite_metatable, sprite_methods, collect); + make_metatable(L, image_metatable, image_methods, collect); + make_metatable(L, font_metatable, font_methods, collect); + make_metatable(L, sprite_metatable, sprite_methods, collect); lua_newtable(L); for (auto const &function : api_functions) @@ -780,6 +875,9 @@ void lua_program::register_api() bool lua_program::run(int const Arguments, int const Results, std::string_view const What) { budget = instruction_limit; + // the interval, which the hook shortens once the budget of a call is spent + lua_sethook(m_state, count_hook, LUA_MASKCOUNT, hook_interval); + output.start_call(); if (0 == lua_pcall(m_state, Arguments, Results, 0)) { return true; @@ -804,14 +902,13 @@ bool lua_program::start() register_api(); lua_sethook(m_state, count_hook, LUA_MASKCOUNT, hook_interval); - std::ifstream file{script, std::ios::binary}; - if (false == file.is_open()) + auto const code{read_regular_file(script)}; + if (false == code.has_value()) { - ErrorLog(std::format("Lua screen \"{}\": file not found", script)); + ErrorLog(std::format("Lua screen \"{}\": file not found, or larger than {} bytes", script, max_screen_file)); return false; } - std::string const code{std::istreambuf_iterator{file}, std::istreambuf_iterator{}}; - if (false == load_chunk(m_state, code, script)) + if (false == load_chunk(m_state, *code, script)) { ErrorLog(std::format("Lua screen \"{}\": {}", script, lua_tostring(m_state, -1))); return false; diff --git a/scripting/scriptscreendrawing.cpp b/scripting/scriptscreendrawing.cpp index f738d9292..870b5b8a3 100644 --- a/scripting/scriptscreendrawing.cpp +++ b/scripting/scriptscreendrawing.cpp @@ -64,13 +64,11 @@ bool lit_pixel(std::span const Rgba, int const Width, int co glyph cut_glyph(std::span const Rgba, int const Width, int const Height, int const First, int const Count) { std::vector lit(static_cast(Count) * Height, false); - for (auto column = 0; column < Count; ++column) + // only the columns inside the image are read + auto const last{static_cast(std::min(static_cast(First) + Count, Width))}; + for (auto x = std::max(First, 0); x < last; ++x) { - auto const x{First + column}; - if (x < 0 || x >= Width) - { - continue; - } + auto const column{x - First}; for (auto y = 0; y < Height; ++y) { lit[static_cast(column) * Height + y] = lit_pixel(Rgba, Width, x, y); @@ -128,14 +126,15 @@ std::u32string decode_utf8(std::string_view const Text) std::optional bitmap_font::parse(std::span const Rgba, int const Width, int const Height, std::string_view const Description) { - if (Width <= 0 || Height <= 0 || Rgba.size() < static_cast(Width) * Height * 4) + if (Width <= 0 || Height <= 0 || Width > max_font_image_side || Height > max_font_image_side || Rgba.size() < static_cast(Width) * Height * 4) { return std::nullopt; } bitmap_font font; font.m_height = Height; auto const all{lines(Description)}; - auto x{0}; + auto x{0}; // where the glyph starts: at most max_font_columns + auto glyphs{0}; // the first line is a comment for (std::size_t line = 1; line < all.size(); ++line) { @@ -157,10 +156,14 @@ std::optional bitmap_font::parse(std::span cons digits.remove_suffix(1); } auto width{0}; - if (std::from_chars(digits.data(), digits.data() + digits.size(), width).ec != std::errc{} || width < 0) + if (std::from_chars(digits.data(), digits.data() + digits.size(), width).ec != std::errc{} || width < 0 || width > max_font_image_side) { continue; } + if (++glyphs > max_font_glyphs || x + width > max_font_columns) + { + return std::nullopt; + } auto cut{cut_glyph(Rgba, Width, Height, x, width)}; if (font.m_glyphs.empty()) { diff --git a/scripting/scriptscreendrawing.h b/scripting/scriptscreendrawing.h index 215f2bf73..5b8166efa 100644 --- a/scripting/scriptscreendrawing.h +++ b/scripting/scriptscreendrawing.h @@ -57,12 +57,19 @@ class glyph std::vector m_lit; }; +// what a font may be: an image no larger than a screen image, a glyph no wider; no more glyphs, nor columns of them +// side by side, than a font can use. a glyph past the image's edge is unlit there, as with led_util +constexpr int max_font_image_side{4096}; +constexpr int max_font_glyphs{4096}; +constexpr int max_font_columns{2 * max_font_image_side}; + class bitmap_font { public: // a font as led_util.load_font() reads it: Rgba (Width x Height) has the glyphs side by side, a column apart; // Description has a comment line, then a line per glyph: the character and its width. a pixel is lit unless it is - // opaque white. nothing for a description without glyphs + // opaque white. a glyph wider than max_font_image_side is skipped. nothing for a description without glyphs, or + // beyond the limits above static std::optional parse(std::span Rgba, int Width, int Height, std::string_view Description); // a sprite as led_util.load_spr() reads it: the whole image as one glyph static glyph sprite(std::span Rgba, int Width, int Height); diff --git a/scripting/scriptscreenprogram.h b/scripting/scriptscreenprogram.h index 6b0d1b70b..86e59859b 100644 --- a/scripting/scriptscreenprogram.h +++ b/scripting/scriptscreenprogram.h @@ -14,11 +14,13 @@ http://mozilla.org/MPL/2.0/. #include "scripting/scriptscreens.h" +#include #include #include #include #include #include +#include #include namespace script_screens @@ -28,6 +30,14 @@ namespace script_screens constexpr int max_image_side{4096}; // the most instructions one call into a screen may run, so that a script stuck in a loop can't hang the worker constexpr std::int64_t instruction_limit{200'000'000}; +// what one call into a screen may send and log; the rest is dropped, which the log tells once per screen. the longest +// name of a command the engine knows is under 40 characters +constexpr std::size_t max_commands_per_call{64}; +constexpr std::size_t max_command_name{64}; +constexpr int max_log_lines_per_call{32}; +constexpr std::size_t max_log_line{1024}; // bytes of the text, a longer one is cut +// the largest file a screen reads: its script or module, a file below its folder +constexpr std::uintmax_t max_screen_file{16 * 1024 * 1024}; struct pending_command { @@ -86,6 +96,31 @@ std::unique_ptr make_wasm_runtime(); std::string utf8_text(std::string const &Text); // a file of the screen's folder or below; nothing for a path leading outside, or no such file std::optional read_screen_file(std::string const &Folder, std::string_view Path); +// the file, when it is a regular file of at most max_screen_file bytes: not a folder, a device or anything larger +std::optional read_regular_file(std::string const &Path); + +// what a screen sends and logs, held to the limits of one call. Name: how the log names the screen +class output_limits +{ + public: + explicit output_limits(std::string Name) : m_name{std::move(Name)} {} + + // a new call into the screen + void start_call() + { + m_log_lines = 0; + } + // true when the command may go with the call; a command over the limits is dropped + bool take_command(render_call const &Call, std::string_view Name); + // the line to log, cut to max_log_line; nothing when the call logged enough + std::optional take_log(std::string_view Text); + + private: + std::string m_name; + int m_log_lines{0}; + bool m_commands_dropped{false}; // logged once + bool m_logs_dropped{false}; // logged once +}; // seconds of a steady clock, the same for every screen, for animations that don't depend on how often the screen is // refreshed double screen_time(); diff --git a/scripting/scriptscreenrules.cpp b/scripting/scriptscreenrules.cpp index 58c69efde..6f47565ef 100644 --- a/scripting/scriptscreenrules.cpp +++ b/scripting/scriptscreenrules.cpp @@ -123,4 +123,15 @@ bool is_safe_relative_path(std::string_view const Path) return true; } +std::optional screen_script_path(std::string const &Folder, std::string const &Script) +{ + // as substr_path() tells a folder + auto path{Script.find('/') == std::string::npos ? Folder + Script : Script}; + if (false == is_safe_relative_path(path)) + { + return std::nullopt; + } + return path; +} + } // namespace script_screens diff --git a/scripting/scriptscreenrules.h b/scripting/scriptscreenrules.h index d7d753841..37cf0bd83 100644 --- a/scripting/scriptscreenrules.h +++ b/scripting/scriptscreenrules.h @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #pragma once #include +#include #include #include @@ -72,4 +73,9 @@ class frame_schedule // drive or a leading separator bool is_safe_relative_path(std::string_view Path); +// the path the game opens the script of a screen by: a name without a folder is in the vehicle's folder (Folder), a +// path is from the game's folder. nothing for a path that leads outside the game's folder (as for the files a screen +// reads: absolute, with a drive, or with ".."), since the script's folder is the one the screen then reads files from +std::optional screen_script_path(std::string const &Folder, std::string const &Script); + } // namespace script_screens diff --git a/scripting/scriptscreens.cpp b/scripting/scriptscreens.cpp index 08314932e..224a2f27e 100644 --- a/scripting/scriptscreens.cpp +++ b/scripting/scriptscreens.cpp @@ -26,6 +26,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include #include @@ -34,6 +35,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include #include @@ -99,12 +101,73 @@ std::optional read_screen_file(std::string const &Folder, std::stri { return std::nullopt; } - std::ifstream file{Folder + std::string{Path}, std::ios::binary}; + return read_regular_file(Folder + std::string{Path}); +} + +std::optional read_regular_file(std::string const &Path) +{ + // a folder or a device (CON, NUL, COM1...) isn't a regular file + std::error_code error; + // in the code page of the system, as the game opens its files + std::filesystem::path const path{Path}; + if (false == std::filesystem::is_regular_file(path, error)) + { + return std::nullopt; + } + auto const size{std::filesystem::file_size(path, error)}; + if (error || size > max_screen_file) + { + return std::nullopt; + } + std::ifstream file{path, std::ios::binary}; if (false == file.is_open()) { return std::nullopt; } - return std::string{std::istreambuf_iterator{file}, std::istreambuf_iterator{}}; + std::string contents(static_cast(size), '\0'); + file.read(contents.data(), static_cast(contents.size())); + // what was read, should the file have shrunk meanwhile + contents.resize(static_cast(file.gcount())); + return contents; +} + +bool output_limits::take_command(render_call const &Call, std::string_view const Name) +{ + if (Call.commands.size() < max_commands_per_call && Name.size() <= max_command_name) + { + return true; + } + if (false == m_commands_dropped) + { + m_commands_dropped = true; + ErrorLog(std::format("{}: commands over {} in a refresh, or with names over {} characters, are dropped", m_name, max_commands_per_call, max_command_name)); + } + return false; +} + +std::optional output_limits::take_log(std::string_view Text) +{ + if (m_log_lines >= max_log_lines_per_call) + { + if (false == m_logs_dropped) + { + m_logs_dropped = true; + ErrorLog(std::format("{}: log lines over {} in a call are dropped", m_name, max_log_lines_per_call)); + } + return std::nullopt; + } + ++m_log_lines; + if (Text.size() <= max_log_line) + { + return std::format("{}: {}", m_name, Text); + } + // cut on the start of a UTF-8 character + auto end{max_log_line}; + while (end > 0 && (static_cast(Text[end]) & 0xC0) == 0x80) + { + --end; + } + return std::format("{}: {} [cut at {} of {} bytes]", m_name, Text.substr(0, end), end, Text.size()); } double screen_time() diff --git a/scripting/wasmprogram.cpp b/scripting/wasmprogram.cpp index d2f914cf0..422ce70dc 100644 --- a/scripting/wasmprogram.cpp +++ b/scripting/wasmprogram.cpp @@ -25,8 +25,6 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include -#include #include #include #include @@ -117,7 +115,10 @@ std::int32_t to_int32(std::size_t const Value) class wasm_program final : public program { public: - wasm_program(std::string const &Script, script_screen_kind const Kind) : kind{Kind}, script{Script}, folder{substr_path(Script)} {} + wasm_program(std::string const &Script, script_screen_kind const Kind) + : kind{Kind}, script{Script}, folder{substr_path(Script)}, output{std::format("WASM screen \"{}\"", Script)} + { + } ~wasm_program() override { if (exec_env != nullptr) @@ -142,6 +143,7 @@ class wasm_program final : public program input_view const *input{nullptr}; render_call *call{nullptr}; bool commands_ignored{false}; // a screen outside the cab tried to send a command, and it was logged + output_limits output; private: bool call_i32(wasm_function_inst_t Function, std::string_view Name, std::int32_t &Result); @@ -300,17 +302,23 @@ void native_command(wasm_exec_env_t Env, char const *Name, std::uint32_t const L } return; } - screen->call->commands.emplace_back(std::string{Name, Length}, Param1, Param2, screen->call->vehicle); + if (screen->output.take_command(*screen->call, std::string_view{Name, Length})) + { + screen->call->commands.emplace_back(std::string{Name, Length}, Param1, Param2, screen->call->vehicle); + } } void native_log(wasm_exec_env_t Env, char const *Text, std::uint32_t const Length) { - auto const *screen{program_of(Env)}; + auto *screen{program_of(Env)}; if (screen == nullptr || Text == nullptr) { return; } - WriteLog(std::format("WASM screen \"{}\": {}", screen->script, std::string_view{Text, Length})); + if (auto const line{screen->output.take_log(std::string_view{Text, Length})}; line.has_value()) + { + WriteLog(*line); + } } // reads a file from the screen's folder into the buffer. returns the size of the whole file, which may be more @@ -436,6 +444,7 @@ bool wasm_program::instantiate(wasm_module_t const Module) bool wasm_program::call_i32(wasm_function_inst_t Function, std::string_view const Name, std::int32_t &Result) { wasm_runtime_set_instruction_count_limit(exec_env, static_cast(instruction_limit)); + output.start_call(); std::array cells{}; if (false == wasm_runtime_call_wasm(exec_env, Function, 0, cells.data())) { @@ -579,13 +588,13 @@ wasm_module_t wasm_runtime_host::load_module(std::string const &Script) } // a failure is kept as well, so the module isn't tried again for every screen using it auto &entry{m_modules[Script]}; - std::ifstream file{Script, std::ios::binary}; - if (false == file.is_open()) + auto const file{read_regular_file(Script)}; + if (false == file.has_value()) { - ErrorLog(std::format("WASM screen \"{}\": file not found", Script)); + ErrorLog(std::format("WASM screen \"{}\": file not found, or larger than {} bytes", Script, max_screen_file)); return nullptr; } - entry.bytes.assign(std::istreambuf_iterator{file}, std::istreambuf_iterator{}); + entry.bytes.assign(file->begin(), file->end()); if (entry.bytes.empty() || entry.bytes.size() > std::numeric_limits::max()) { ErrorLog(std::format("WASM screen \"{}\": invalid module size", Script)); diff --git a/tests/unit/engine_stubs.cpp b/tests/unit/engine_stubs.cpp index 20cd008a1..d3ea80892 100644 --- a/tests/unit/engine_stubs.cpp +++ b/tests/unit/engine_stubs.cpp @@ -11,6 +11,10 @@ #include #include +#include +#include +#include +#include // settings --------------------------------------------------------------------------------------- @@ -27,9 +31,39 @@ bool log_enabled() { static bool const enabled{std::getenv("EU07_UNIT_TESTS_LOG") != nullptr}; return enabled; } + +// the lines kept for a test that checks what goes to the log, from any thread; see unit_tests_log_capture() +std::mutex &captured_mutex() { + static std::mutex mutex; + return mutex; +} + +std::optional> &captured_lines() { + static std::optional> lines; + return lines; +} + } // namespace +// for the tests: keeps every line logged from now on (true), or stops keeping them and forgets them (false) +void unit_tests_log_capture(bool const Enabled) { + std::scoped_lock lock{captured_mutex()}; + captured_lines() = Enabled ? std::make_optional>() : std::nullopt; +} + +// for the tests: the lines kept so far +std::vector unit_tests_logged_lines() { + std::scoped_lock lock{captured_mutex()}; + return captured_lines().value_or(std::vector{}); +} + void WriteLog(const char *str, logtype const, bool const isError) { + if (str != nullptr) { + std::scoped_lock lock{captured_mutex()}; + if (captured_lines().has_value()) { + captured_lines()->emplace_back(str); + } + } if (log_enabled() && str != nullptr) { (isError ? std::cerr : std::cout) << str << "\n"; } diff --git a/tests/unit/test_script_screen_drawing.cpp b/tests/unit/test_script_screen_drawing.cpp index ff822b02d..a68857ebe 100644 --- a/tests/unit/test_script_screen_drawing.cpp +++ b/tests/unit/test_script_screen_drawing.cpp @@ -5,6 +5,7 @@ #include #include +#include #include // the drawing the Lua screens get from the game: fonts read as scripts/led_util.py reads them, text and images @@ -85,6 +86,44 @@ TEST_CASE("script screen drawing: a description without glyphs, or one wider tha CHECK_FALSE(font->find(U'w').lit(4, 0)); } +TEST_CASE("script screen drawing: a glyph wider than the largest image is skipped") { + auto const pixels{image(2, 1, {})}; + auto const font{bitmap_font::parse(pixels, 2, 1, "//\nw5000\nv1\nx2147483647\n")}; + REQUIRE(font.has_value()); + // not in the font: the fallback, its first glyph + CHECK(font->find(U'w').width() == 1); + CHECK(font->find(U'x').width() == 1); + CHECK(font->find(U'v').width() == 1); + // the largest one is taken + auto const widest{bitmap_font::parse(pixels, 2, 1, "//\nw4096\n")}; + REQUIRE(widest.has_value()); + CHECK(widest->find(U'w').width() == 4096); +} + +TEST_CASE("script screen drawing: a font of too many glyphs, too many columns or too large an image is refused") { + auto const pixels{image(2, 1, {})}; + // more glyphs than any font has + std::string many{"//\n"}; + for (char32_t character = 0x100; character < 0x100 + 5000; ++character) { + // the character in UTF-8 (two bytes up to 0x7FF, three above), then its width + if (character < 0x800) { + many += static_cast(0xC0 | (character >> 6)); + } + else { + many += static_cast(0xE0 | (character >> 12)); + many += static_cast(0x80 | ((character >> 6) & 0x3F)); + } + many += static_cast(0x80 | (character & 0x3F)); + many += "0\n"; + } + CHECK_FALSE(bitmap_font::parse(pixels, 2, 1, many).has_value()); + // glyphs side by side much wider than the largest image + CHECK_FALSE(bitmap_font::parse(pixels, 2, 1, "//\na4000\nb4000\nc4000\n").has_value()); + // an image taller than the largest one + std::vector const tall(static_cast(1) * 5000 * 4, 255); + CHECK_FALSE(bitmap_font::parse(tall, 1, 5000, "//\na1\n").has_value()); +} + 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")}; diff --git a/tests/unit/test_script_screen_host.cpp b/tests/unit/test_script_screen_host.cpp index 355b9b9e8..697175c35 100644 --- a/tests/unit/test_script_screen_host.cpp +++ b/tests/unit/test_script_screen_host.cpp @@ -2,9 +2,9 @@ #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 +// image that goes to the screen's texture, bottom row first, and sends a command; a script stuck in a loop is stopped, +// even when it catches the error; a Lua script can't reach files, the system, precompiled code or the metatables of the +// api; what a call may send, log, read or make is capped. the Lua cases need WITH_LUA, the WebAssembly ones WITH_WASM #include "scripting/scriptscreens.h" #include "input/command.h" @@ -12,13 +12,16 @@ #include "utilities/Globals.h" #include "utilities/dictionary.h" +#include #include #include #include #include #include #include +#include #include +#include #include #include #include @@ -142,6 +145,47 @@ void refresh(script_screen_queue &Queue, std::shared_ptr const &S Queue.submit(Screen, std::move(Input), Vehicle); } +// runs frames for a while: long enough for the worker to load and run a screen that was submitted +void run_frames(script_screen_queue &Queue) { + for (int frame = 0; frame < 40; ++frame) { + Queue.update(); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } +} + +// the limits of the sandbox (scripting/scriptscreenprogram.h), as the tests expect them +constexpr std::size_t commands_per_call{64}; +constexpr std::size_t log_lines_per_call{32}; +constexpr std::size_t log_line_length{1024}; +constexpr std::size_t screen_file_size{16 * 1024 * 1024}; + +} // namespace + +// the lines logged while the object lives, kept by the engine stubs (engine_stubs.cpp) +void unit_tests_log_capture(bool Enabled); +std::vector unit_tests_logged_lines(); + +namespace { + +class log_capture { + public: + log_capture() { unit_tests_log_capture(true); } + ~log_capture() { unit_tests_log_capture(false); } + log_capture(log_capture const &) = delete; + log_capture &operator=(log_capture const &) = delete; + + // the lines logged so far with the text in them + std::vector lines_with(std::string_view const Text) const { + std::vector result; + for (auto &line : unit_tests_logged_lines()) { + if (line.find(Text) != std::string::npos) { + result.push_back(std::move(line)); + } + } + return result; + } +}; + } // namespace TEST_CASE("script screens: a language that doesn't run gets no screens") { @@ -202,6 +246,39 @@ constexpr std::array spin_module{ 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}; +// "flood": screen_render sends the command "cmdtest" 1000 times (with the parameters (i, 0)), then logs a line of +// 4000 'a' 100 times, and returns 0: +// (import "eu07" "command" (func $command (param i32 i32 i32 i32))) +// (import "eu07" "log" (func $log (param i32 i32))) +// (memory (export "memory") 1) +// (data (i32.const 0) "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 $i i32) +// ;; for i in 0..1000: (call $command (i32.const 0) (i32.const 7) (local.get $i) (i32.const 0)) +// ;; for i in 0..4000: (i32.store8 (i32.add (local.get $i) (i32.const 64)) (i32.const 97)) +// ;; for i in 0..100: (call $log (i32.const 64) (i32.const 4000)) +// (i32.const 0)) +constexpr std::array flood_module{ + 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x11, 0x03, 0x60, 0x04, 0x7f, 0x7f, 0x7f, + 0x7f, 0x00, 0x60, 0x02, 0x7f, 0x7f, 0x00, 0x60, 0x00, 0x01, 0x7f, 0x02, 0x1b, 0x02, 0x04, 0x65, + 0x75, 0x30, 0x37, 0x07, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x00, 0x00, 0x04, 0x65, 0x75, + 0x30, 0x37, 0x03, 0x6c, 0x6f, 0x67, 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, 0x81, + 0x01, 0x03, 0x04, 0x00, 0x41, 0x02, 0x0b, 0x04, 0x00, 0x41, 0x02, 0x0b, 0x75, 0x01, 0x01, 0x7f, + 0x41, 0x00, 0x21, 0x00, 0x02, 0x40, 0x03, 0x40, 0x20, 0x00, 0x41, 0xe8, 0x07, 0x4e, 0x0d, 0x01, + 0x41, 0x00, 0x41, 0x07, 0x20, 0x00, 0x41, 0x00, 0x10, 0x00, 0x20, 0x00, 0x41, 0x01, 0x6a, 0x21, + 0x00, 0x0c, 0x00, 0x0b, 0x0b, 0x41, 0x00, 0x21, 0x00, 0x02, 0x40, 0x03, 0x40, 0x20, 0x00, 0x41, + 0xa0, 0x1f, 0x4e, 0x0d, 0x01, 0x20, 0x00, 0x41, 0xc0, 0x00, 0x6a, 0x41, 0xe1, 0x00, 0x3a, 0x00, + 0x00, 0x20, 0x00, 0x41, 0x01, 0x6a, 0x21, 0x00, 0x0c, 0x00, 0x0b, 0x0b, 0x41, 0x00, 0x21, 0x00, + 0x02, 0x40, 0x03, 0x40, 0x20, 0x00, 0x41, 0xe4, 0x00, 0x4e, 0x0d, 0x01, 0x41, 0xc0, 0x00, 0x41, + 0xa0, 0x1f, 0x10, 0x01, 0x20, 0x00, 0x41, 0x01, 0x6a, 0x21, 0x00, 0x0c, 0x00, 0x0b, 0x0b, 0x41, + 0x00, 0x0b, 0x0b, 0x0d, 0x01, 0x00, 0x41, 0x00, 0x0b, 0x07, 0x63, 0x6d, 0x64, 0x74, 0x65, 0x73, + 0x74}; + } // namespace TEST_CASE("wasm screens: a cab screen draws from its input and sends commands to its vehicle") { @@ -325,6 +402,60 @@ TEST_CASE("wasm screens: the screens outlive the queue without harm") { screen.reset(); } +TEST_CASE("wasm screens: the commands and the log lines of one call are capped") { + sent_commands().clear(); + log_capture const log; + script_folder const folder{"wasm_flood"}; + auto const module{folder.write("flood.wasm", flood_module)}; + script_screen_queue queue; + REQUIRE(queue.init()); + + recording_texture texture; + auto const screen{queue.acquire(request(script_language::wasm, module, "flood", &texture))}; + refresh(queue, screen, speed(0.0), 3); + REQUIRE(run_until(queue, [] { return false == sent_commands().empty(); })); + queue.update(); + // the first ones go, the rest is dropped + CHECK(sent_commands().size() == commands_per_call); + CHECK(sent_commands().back().first.param1 == static_cast(commands_per_call - 1)); + + auto const lines{log.lines_with("aaaaaaaaaa")}; + REQUIRE(false == lines.empty()); + CHECK(lines.size() <= log_lines_per_call); + auto const longest{std::ranges::max(lines, {}, [](std::string const &Line) { return Line.size(); })}; + CHECK(longest.size() < module.size() + log_line_length + 100); + queue.exit(); +} + +TEST_CASE("wasm screens: a module larger than the limit isn't loaded") { + // the screen of "paint", with a custom section that makes the file larger than a screen may read + std::vector bytes(paint_module.begin(), paint_module.end()); + auto const payload{screen_file_size}; + auto size{static_cast(payload + 2)}; // the name: its length and one letter + bytes.push_back(0x00); + do { + auto const low{static_cast(size & 0x7f)}; + size >>= 7; + bytes.push_back(size != 0 ? static_cast(low | 0x80) : low); + } while (size != 0); + bytes.push_back(0x01); + bytes.push_back('x'); + bytes.resize(bytes.size() + payload, 0); + + script_folder const folder{"wasm_large"}; + auto const module{folder.write("large.wasm", bytes)}; + script_screen_queue queue; + REQUIRE(queue.init()); + + recording_texture texture; + auto const screen{queue.acquire(request(script_language::wasm, module, "large", &texture))}; + refresh(queue, screen, speed(1.0), 1); + run_frames(queue); + CHECK_FALSE(queue.due(*screen)); + CHECK(texture.uploads == 0); + queue.exit(); +} + #endif #ifdef WITH_LUA @@ -750,4 +881,236 @@ TEST_CASE("lua screens: an image read after led_post has its post-processing don queue.exit(); } +namespace { + +// scripts that catch the error of the instruction limit and go on looping +constexpr std::string_view pcall_spin_script{R"( +local function spin() while true do end end +return { render = function(state) while true do pcall(spin) end end } +)"}; + +constexpr std::string_view nested_pcall_spin_script{R"( +local function spin() while true do end end +return { render = function(state) while true do pcall(function() while true do pcall(spin) end end) end end } +)"}; + +constexpr std::string_view xpcall_spin_script{R"( +local function spin() while true do end end +local function handler() while true do end end +return { render = function(state) while true do xpcall(spin, handler) end end } +)"}; + +constexpr std::string_view coroutine_spin_script{R"( +local function spin() while true do end end +return { render = function(state) while true do coroutine.resume(coroutine.create(spin)) end end } +)"}; + +// white when the metatable of an image can't be reached, and its __gc can't be called +constexpr std::string_view metatable_script{R"( +local image = eu07.image(1, 1) +local metatable = getmetatable(image) +local locked = type(metatable) ~= "table" +-- only where the metatable is locked: an unlocked one would destroy the image twice +local collected = locked and pcall(function() return metatable.__gc(image) end) +local usable = image:width() == 1 +return { + render = function(state) + return eu07.image(1, 1, (locked and not collected and usable) and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// white when string.rep refuses a result over the limit and makes the ones under it +constexpr std::string_view repeat_script{R"( +local huge = pcall(string.rep, "x", 64 * 1024 * 1024) +local method = pcall(function() return ("ab"):rep(16 * 1024 * 1024) end) +local endless = pcall(string.rep, "x", 1e300) +local fits = #string.rep("x", 1024 * 1024) == 1024 * 1024 and ("ab"):rep(3) == "ababab" and ("x"):rep(0) == "" and ("x"):rep(-1) == "" +return { + render = function(state) + return eu07.image(1, 1, (not huge and not method and not endless and fits) and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// white when an image larger than a screen can be isn't decoded, and a small one is +constexpr std::string_view large_png_script{R"( +local sprite = pcall(eu07.sprite, "large") +local font = pcall(eu07.font, "large") +local small = pcall(eu07.sprite, "small") +return { + render = function(state) + return eu07.image(1, 1, (not sprite and not font and small) and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// a long command name first, then too many commands and log lines for one call +constexpr std::string_view flood_script{R"( +return { + render = function(state) + eu07.command("cmdtest" .. ("q"):rep(100), 1, 0) + for i = 0, 999 do eu07.command("cmdtest", i, 0) end + for i = 1, 100 do eu07.log(("y"):rep(5000)) end + return eu07.image(1, 1) + end +} +)"}; + +// white when a file larger than a screen may read, and a folder, read as nothing +constexpr std::string_view large_file_script{R"( +local large = eu07.read_file("large.bin") +local folder = eu07.read_file("data") +local small = eu07.read_file("data/small.txt") +return { + render = function(state) + return eu07.image(1, 1, (large == nil and folder == nil and small == "small") and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// a white image of the size, as a .png +std::vector white_png(int const Width, int const Height) { + std::vector const pixels(static_cast(Width) * Height * 4, 255); + std::vector result; + auto const append{[](void *Target, void *Data, int const Size) { + auto *bytes{static_cast(Data)}; + static_cast *>(Target)->insert(static_cast *>(Target)->end(), bytes, bytes + Size); + }}; + stbi_write_png_to_func(append, &result, Width, Height, 4, pixels.data(), Width * 4); + return result; +} + +// runs the script of a screen once; the first pixel of what it drew, or -1 when it drew nothing (after a wait) +int first_pixel(std::string const &Script, std::string const &Key) { + script_screen_queue queue; + REQUIRE(queue.init()); + recording_texture texture; + auto const screen{queue.acquire(request(script_language::lua, Script, Key, &texture))}; + refresh(queue, screen, speed(0.0), 1); + auto const drawn{run_until(queue, [&texture] { return texture.uploads > 0; })}; + queue.exit(); + return drawn && false == texture.pixels.empty() ? texture.pixels[0] : -1; +} + +} // namespace + +TEST_CASE("lua screens: a script catching the instruction limit with pcall, xpcall or a coroutine is stopped all the same") { + script_folder const folder{"lua_pcall_spin"}; + auto const painting{folder.write("paint.lua", paint_script)}; + for (auto const &[name, code] : {std::pair{"pcall.lua", pcall_spin_script}, std::pair{"nested.lua", nested_pcall_spin_script}, + std::pair{"xpcall.lua", xpcall_spin_script}, std::pair{"coroutine.lua", coroutine_spin_script}}) { + CAPTURE(name); + auto const spinning{folder.write(name, code)}; + // a worker stuck for good would keep the queue's destructor waiting: such a queue is left behind, so the test + // fails instead of hanging the run + auto *queue{new script_screen_queue}; // NOSONAR see above + 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); + + auto const stopped{run_until(*queue, [&working] { return working.uploads > 0; })}; + CHECK(stopped); + if (false == stopped) { + // the stuck worker doesn't touch the textures, and nothing uploads to them any more + continue; + } + CHECK(stuck.uploads == 0); + CHECK_FALSE(queue->due(*first)); + queue->exit(); + delete queue; // NOSONAR see above + } +} + +TEST_CASE("lua screens: xpcall passes the arguments, and the error to its handler") { + script_folder const folder{"lua_xpcall"}; + constexpr std::string_view script{R"( +local ok1, sum = xpcall(function(a, b) return a + b end, function(e) return "handled" end, 2, 3) +local ok2, handled = xpcall(function() error("boom") end, function(e) return "handled: " .. tostring(e) end) +local ok3 = xpcall(function() error("boom") end, function(e) error("again") end) +local good = ok1 and sum == 5 and not ok2 and handled:find("handled: .*boom") ~= nil and not ok3 +return { + render = function(state) + return eu07.image(1, 1, good and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + CHECK(first_pixel(folder.write("xpcall.lua", script), "xpcall") == 255); +} + +TEST_CASE("lua screens: the metatables of the api objects can't be reached from a script") { + script_folder const folder{"lua_metatable"}; + CHECK(first_pixel(folder.write("metatable.lua", metatable_script), "metatable") == 255); +} + +TEST_CASE("lua screens: string.rep makes no string over the limit") { + script_folder const folder{"lua_rep"}; + CHECK(first_pixel(folder.write("rep.lua", repeat_script), "rep") == 255); +} + +TEST_CASE("lua screens: a .png larger than a screen image isn't decoded") { + script_folder const folder{"lua_large_png"}; + folder.write("large.png", white_png(5000, 1)); + folder.write("large.txt", std::string_view{"//\na1\n"}); + folder.write("small.png", white_png(2, 2)); + CHECK(first_pixel(folder.write("png.lua", large_png_script), "png") == 255); +} + +TEST_CASE("lua screens: the commands and the log lines of one call are capped") { + sent_commands().clear(); + log_capture const log; + script_folder const folder{"lua_flood"}; + auto const script{folder.write("flood.lua", flood_script)}; + script_screen_queue queue; + REQUIRE(queue.init()); + + recording_texture texture; + auto const screen{queue.acquire(request(script_language::lua, script, "flood", &texture))}; + refresh(queue, screen, speed(0.0), 3); + REQUIRE(run_until(queue, [] { return false == sent_commands().empty(); })); + queue.update(); + // the long name is dropped, of the rest the first ones go + CHECK(sent_commands().size() == commands_per_call); + CHECK(sent_commands().front().first.param1 == 0.0); + CHECK(sent_commands().back().first.param1 == static_cast(commands_per_call - 1)); + // the command of the long name didn't get as far as the engine's command names + CHECK(log.lines_with("not found").empty()); + + auto const lines{log.lines_with("yyyyyyyyyy")}; + REQUIRE(false == lines.empty()); + CHECK(lines.size() <= log_lines_per_call); + auto const longest{std::ranges::max(lines, {}, [](std::string const &Line) { return Line.size(); })}; + CHECK(longest.size() < script.size() + log_line_length + 100); + queue.exit(); +} + +TEST_CASE("lua screens: a file larger than the limit, or a folder, reads as nothing") { + script_folder const folder{"lua_large_file"}; + folder.write("large.bin", std::string(screen_file_size + 1, 'x')); + folder.write("data/small.txt", std::string_view{"small"}); + CHECK(first_pixel(folder.write("file.lua", large_file_script), "file") == 255); +} + +TEST_CASE("lua screens: a script larger than the limit isn't loaded") { + script_folder const folder{"lua_large_script"}; + std::string code{"return { render = function(state) return eu07.image(1, 1, { 255, 255, 255 }) end }\n--"}; + code.append(screen_file_size, 'x'); + auto const script{folder.write("large.lua", code)}; + script_screen_queue queue; + REQUIRE(queue.init()); + + recording_texture texture; + auto const screen{queue.acquire(request(script_language::lua, script, "large", &texture))}; + refresh(queue, screen, speed(0.0), 1); + run_frames(queue); + CHECK_FALSE(queue.due(*screen)); + CHECK(texture.uploads == 0); + queue.exit(); +} + #endif diff --git a/tests/unit/test_script_screens.cpp b/tests/unit/test_script_screens.cpp index 9e0bb7a92..4fc688928 100644 --- a/tests/unit/test_script_screens.cpp +++ b/tests/unit/test_script_screens.cpp @@ -101,3 +101,19 @@ TEST_CASE("script screens: a screen reads files only below its own folder") { CHECK_FALSE(script_screens::is_safe_relative_path("\\windows")); CHECK_FALSE(script_screens::is_safe_relative_path("c:/windows/win.ini")); } + +TEST_CASE("script screens: the script of a screen is in the vehicle's folder, or from the game's, and not outside it") { + using script_screens::screen_script_path; + std::string const vehicle{"dynamic/pkp/ep07_v1/"}; + CHECK(screen_script_path(vehicle, "screen.lua") == "dynamic/pkp/ep07_v1/screen.lua"); + CHECK(screen_script_path(vehicle, "scripts/screen.lua") == "scripts/screen.lua"); + // a backslash isn't a folder to the game (substr_path), so the name goes in the vehicle's folder + CHECK(screen_script_path(vehicle, "lua\\screen.lua") == "dynamic/pkp/ep07_v1/lua\\screen.lua"); + + CHECK_FALSE(screen_script_path(vehicle, "../../../screen.lua").has_value()); + CHECK_FALSE(screen_script_path(vehicle, "scripts/../../screen.lua").has_value()); + CHECK_FALSE(screen_script_path(vehicle, "..\\..\\screen.lua").has_value()); + CHECK_FALSE(screen_script_path(vehicle, "/screen.lua").has_value()); + CHECK_FALSE(screen_script_path(vehicle, "c:/games/screen.lua").has_value()); + CHECK_FALSE(screen_script_path("../outside/", "screen.lua").has_value()); +} diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 24810a2e7..002a03196 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -317,9 +317,13 @@ namespace { void deserialize_script_sign( cParser &Parser, script_screens::screen_config &Sign, std::string const &Folder ) { Sign.deserialize( Parser ); - if( false == Sign.script.empty() - && substr_path( Sign.script ).empty() ) { - Sign.script = Folder + Sign.script; + if( Sign.script.empty() ) { return; } + if( auto path { script_screens::screen_script_path( Folder, Sign.script ) }; path.has_value() ) { + Sign.script = std::move( *path ); + } + else { + ErrorLog( "Bad script sign: \"" + Sign.script + "\" leads outside the game's folder" ); + Sign.script.clear(); } } @@ -8096,6 +8100,10 @@ std::shared_ptr TDynamicObject::draw_script_texture( std::string auto const script { Name.substr( 5, query == std::string::npos ? std::string::npos : query - 5 ) }; auto const language { script_language_of( script ) }; if( false == language.has_value() ) { return nullptr; } // a python texture, made by the texture itself + if( false == script_screens::screen_script_path( "", script ).has_value() ) { + ErrorLog( "Bad script texture: \"" + script + "\" leads outside the game's folder" ); + return nullptr; + } auto &queue { Application.screens() }; auto &texture { GfxRenderer->Texture( GfxRenderer->Material( Material )->GetTexture( 0 ) ) }; diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 50659934c..f0324e85b 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -10625,9 +10625,14 @@ void TTrain::load_script_screen(cParser &Parser, script_language const Language) { return; } - if (substr_path(entry.config.script).empty()) + if (auto path{script_screens::screen_script_path(DynamicObject->asBaseDir, entry.config.script)}; path.has_value()) { - entry.config.script = DynamicObject->asBaseDir + entry.config.script; + entry.config.script = std::move(*path); + } + else + { + ErrorLog(std::format("Bad script screen: \"{}\" leads outside the game's folder", entry.config.script)); + return; } TSubModel *submodel{nullptr}; From acda6562cd798c05275699d14ff546cfbcaed46d Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 13 Nov 2026 15:23:01 +0100 Subject: [PATCH 007/136] fix(scripting): sandbox the scenery Lua scripts like the Lua screens The scenery scripts (lua in the .scn) ran in a state with all of LuaJIT's libraries (io, os, ffi, debug, require, load*), loaded with luaL_dofile from any path, '..' and absolute ones included, and their errors in event handlers went through an unprotected lua_call. - scripting/luasandbox.{h,cpp}: what the Lua states share: the safe library set (moved from lua_program::open_libraries), loading a text-only chunk (moved from load_chunk), reading a script from a folder through the screens' path check (regular file, at most 16 MB), running it under pcall, and a clock-only os table (time, clock, difftime, date with the C89 conversions; MSVC's strftime ends the program on an unknown one). - lua.cpp: the scenery state gets the safe set and the clock; interpret() takes the scenery folder and the file and logs a refused or failing script with its file name; event handlers run under pcall and are logged with the event name; the scriptapi functions check their string argument (luaL_checkstring) instead of making a std::string from NULL; a memcell table without str updates the text to "" instead of from NULL. - luaprogram.cpp: calls the shared helpers, no change for the screens. - eu07.ini lua.fulllibraries (default no) gives trusted sceneries all libraries back. Documented in script_screens_doc.md. - tests/unit/test_lua_sandbox.cpp: 8 cases for the shared sandbox. --- CMakeLists.txt | 3 +- script_screens_doc.md | 22 +++ scripting/lua.cpp | 64 ++++--- scripting/lua.h | 5 +- scripting/luaprogram.cpp | 32 +--- scripting/luasandbox.cpp | 167 +++++++++++++++++ scripting/luasandbox.h | 49 +++++ simulation/simulationstateserializer.cpp | 3 +- tests/unit/CMakeLists.txt | 2 +- tests/unit/test_lua_sandbox.cpp | 218 +++++++++++++++++++++++ utilities/Globals.cpp | 9 + utilities/Globals.h | 1 + 12 files changed, 520 insertions(+), 55 deletions(-) create mode 100644 scripting/luasandbox.cpp create mode 100644 scripting/luasandbox.h create mode 100644 tests/unit/test_lua_sandbox.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index e97e41d03..1b73b0805 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -384,7 +384,8 @@ endif() if (WITH_LUA) set(DEFINITIONS ${DEFINITIONS} "WITH_LUA") - set(SOURCES ${SOURCES} "scripting/lua.cpp") + # the scenery scripts (lua.cpp) and the Lua screens (luaprogram.cpp) share the sandbox of luasandbox.cpp + set(SOURCES ${SOURCES} "scripting/lua.cpp" "scripting/luasandbox.cpp") endif() # the script screens (scripting/scriptscreens.cpp), with the Lua and the WebAssembly runtime when they're built diff --git a/script_screens_doc.md b/script_screens_doc.md index 52ccc9ced..09a4c2638 100644 --- a/script_screens_doc.md +++ b/script_screens_doc.md @@ -208,3 +208,25 @@ clang --target=wasm32 -O2 -nostdlib -Wl,--no-entry -o ekran.wasm ekran.c Any language that compiles to WebAssembly works the same way (Rust `wasm32-unknown-unknown`, Zig, AssemblyScript), as long as the module imports nothing but the `eu07` functions above. + +## Scenery scripts + +A scenery runs a Lua script with `lua ` in its `.scn`, while the scenery loads. The script registers events +and works with memcells, tracks and vehicles through the table `eu07.events` (`event_create`, `event_dispatch`, +`memcell_update`, `writelog` and the rest, see `scripting/lua.cpp`). It shares the sandbox of the Lua screens: + +- the file is a path relative to the scenery folder (`scenery/`), and stays inside it: no `..`, no drive, no leading + `/`. It is text, of at most 16 MB; precompiled code is not loaded; +- the script gets the base library, `table`, `string`, `math` and `bit`, and of `os` only the clock: `os.time`, + `os.clock`, `os.difftime` and `os.date` (with the C89 conversions only, `%Y`, `%d`, `%H` and so on). It gets no + `io`, the rest of `os`, `ffi`, `debug`, `jit`, `package`, `require`, `dofile`, `load`, `loadfile` or `loadstring`; +- a script that fails stops there, the error goes to the log with the file name and line, and the scenery goes on + loading. An event handler that fails is logged with the name of the event, and the simulation goes on. + +A script written for the earlier full libraries stops at the first call to one of them (`attempt to index global +'io' (a nil value)` in the log). For a scenery you trust, `eu07.ini` can give the scripts all of LuaJIT's libraries +again: + +| key | default | meaning | +|---------------------|---------|------------------------------------------------------------------------------------------| +| `lua.fulllibraries` | no | yes: the scenery scripts get all of LuaJIT's libraries (`io`, `os`, `ffi`, `require`...), and with them the files and programs of the computer. The Lua screens stay sandboxed | diff --git a/scripting/lua.cpp b/scripting/lua.cpp index 14ecbb75d..0854579d9 100644 --- a/scripting/lua.cpp +++ b/scripting/lua.cpp @@ -5,6 +5,7 @@ #include "world/MemCell.h" #include "vehicle/Driver.h" #include "simulation/simulation.h" +#include "scripting/luasandbox.h" lua::lua() { @@ -12,7 +13,10 @@ lua::lua() if (!state) throw std::runtime_error("cannot create lua state"); lua_atpanic(state, atpanic); - luaL_openlibs(state); + // sandboxed as the script screens are: no io, ffi, debug, require or load*, and of os only the clock. + // lua.fulllibraries in eu07.ini opens the rest when the scenery loads its first script (interpret()) + lua_sandbox::open_safe_libraries(state); + lua_sandbox::open_clock_library(state); static constexpr luaL_Reg api[] = { @@ -51,21 +55,29 @@ lua::~lua() std::string lua::get_error() const { - return lua_tostring(state, -1); + auto const *error = lua_tostring(state, -1); + return error ? error : "unknown error"; } -void lua::interpret(const std::string& file) const +void lua::interpret(const std::string &folder, const std::string &file) { - if (luaL_dofile(state, file.c_str())) { - std::string str = lua_tostring(state, -1); - ErrorLog("lua: Runtime error: " + str, logtype::lua); + if (Global.lua_fulllibraries && !full_libraries) { + // all of LuaJIT's libraries, as before the sandbox: the scripts may then reach files, programs and ffi + luaL_openlibs(state); + full_libraries = true; + WriteLog("lua: lua.fulllibraries is on, the scenery scripts run with all libraries (io, os, ffi, require...)", logtype::lua); + } + // a relative path inside the scenery folder, a file of text, run in protected mode: a script that fails stops + // there, and the scenery goes on loading + if (auto const error = lua_sandbox::run_script_file(state, folder, file)) { + ErrorLog("lua: " + *error, logtype::lua); } } int lua::atpanic(lua_State *s) { - std::string err = lua_tostring(s, -1); - ErrorLog("lua: Runtime error: " + err, logtype::lua); + auto const *err = lua_tostring(s, -1); + ErrorLog(std::string("lua: Runtime error: ") + (err ? err : "unknown error"), logtype::lua); return 0; } @@ -81,7 +93,12 @@ void lua::dispatch_event(lua_State *L, const int handler, basic_event *event, co lua_rawgeti(L, LUA_REGISTRYINDEX, handler); lua_pushlightuserdata(L, event); lua_pushlightuserdata(L, const_cast(activator)); - lua_call(L, 2, 0); + // in protected mode: a handler that fails is logged, and the simulation goes on + if (lua_pcall(L, 2, 0, 0) != 0) { + auto const *error = lua_tostring(L, -1); + ErrorLog("lua: event " + (event ? event->m_name : std::string("?")) + ": " + (error ? error : "unknown error"), logtype::lua); + lua_pop(L, 1); + } } void lua::push_memcell_values(lua_State *L, const TMemCell *mc) @@ -103,7 +120,8 @@ memcell_values lua::get_memcell_values(lua_State *L, int idx) // For negative indices, we need to account for the extra item that is the key name/value extracted from the table. if (idx < 0) idx--; - memcell_values mc{nullptr, 0.0, 0.0}; + // no text in the table is an empty one: the memcell and the vehicle take the text as a string + memcell_values mc{"", 0.0, 0.0}; lua_pushstring(L, "str"); lua_gettable(L, idx); if (lua_isstring(L, -1)) @@ -124,7 +142,7 @@ memcell_values lua::get_memcell_values(lua_State *L, int idx) int lua::scriptapi_event_create(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); double delay = lua_tonumber(L, 2); double randomdelay = lua_tonumber(L, 3); lua_pushvalue(L, 4); @@ -144,7 +162,7 @@ int lua::scriptapi_event_create(lua_State *L) int lua::scriptapi_event_find(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); basic_event *foundevent = simulation::Events.FindEvent(name); if (foundevent) { @@ -157,7 +175,7 @@ int lua::scriptapi_event_find(lua_State *L) int lua::scriptapi_event_exists(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); basic_event *foundevent = simulation::Events.FindEvent(name); lua_pushboolean(L, foundevent != nullptr); return 1; @@ -186,7 +204,7 @@ int lua::scriptapi_event_dispatch(lua_State *L) int lua::scriptapi_event_dispatch_n(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); auto *activator = static_cast(lua_touserdata(L, 2)); double delay = lua_tonumber(L, 3); basic_event *foundevent = simulation::Events.FindEvent(name); @@ -199,7 +217,7 @@ int lua::scriptapi_event_dispatch_n(lua_State *L) int lua::scriptapi_track_find(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); TTrack *track = simulation::Paths.find(name); if (track) { @@ -223,7 +241,7 @@ int lua::scriptapi_track_isoccupied(lua_State *L) int lua::scriptapi_track_isoccupied_n(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); TTrack *track = simulation::Paths.find(name); if (track) { @@ -236,7 +254,7 @@ int lua::scriptapi_track_isoccupied_n(lua_State *L) int lua::scriptapi_isolated_find(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); TIsolated *isolated = TIsolated::Find(name); if (isolated) { @@ -260,7 +278,7 @@ int lua::scriptapi_isolated_isoccupied(lua_State *L) int lua::scriptapi_isolated_isoccupied_n(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); TIsolated *isolated = TIsolated::Find(name); if (isolated) { @@ -298,7 +316,7 @@ int lua::scriptapi_dynobj_putvalues(lua_State *L) int lua::scriptapi_memcell_find(lua_State *L) { - std::string str = lua_tostring(L, 1); + std::string str = luaL_checkstring(L, 1); TMemCell *mc = simulation::Memory.find(str); if (mc) { @@ -318,7 +336,7 @@ int lua::scriptapi_memcell_read(lua_State *L) int lua::scriptapi_memcell_read_n(lua_State *L) { - std::string str = lua_tostring(L, 1); + std::string str = luaL_checkstring(L, 1); TMemCell *mc = simulation::Memory.find(str); push_memcell_values(L, mc); if (!mc) @@ -338,7 +356,7 @@ int lua::scriptapi_memcell_update(lua_State *L) int lua::scriptapi_memcell_update_n(lua_State *L) { - std::string mstr = lua_tostring(L, 1); + std::string mstr = luaL_checkstring(L, 1); auto [str, num1, num2] = get_memcell_values(L, 2); TMemCell *mc = simulation::Memory.find(mstr); if (mc) @@ -359,14 +377,14 @@ int lua::scriptapi_random(lua_State *L) int lua::scriptapi_writelog(lua_State *L) { - std::string txt = lua_tostring(L, 1); + std::string txt = luaL_checkstring(L, 1); WriteLog("lua: log: " + txt, logtype::lua); return 0; } int lua::scriptapi_writeerrorlog(lua_State *L) { - std::string txt = lua_tostring(L, 1); + std::string txt = luaL_checkstring(L, 1); ErrorLog("lua: log: " + txt, logtype::lua); return 0; } diff --git a/scripting/lua.h b/scripting/lua.h index 07d729264..8663103df 100644 --- a/scripting/lua.h +++ b/scripting/lua.h @@ -10,6 +10,7 @@ struct memcell_values { const char *str; double num1; double num2; }; class lua { lua_State *state; + bool full_libraries = false; // lua.fulllibraries: all of LuaJIT's libraries opened static int atpanic(lua_State *s); @@ -41,7 +42,9 @@ public: ~lua(); std::string get_error() const; - void interpret(const std::string& file) const; + // runs the script file, a relative path inside folder (the scenery folder), sandboxed (scripting/luasandbox.h). + // a script that can't be read or fails is logged + void interpret(const std::string &folder, const std::string &file); static void unref(lua_State *L, int ref); static void dispatch_event(lua_State *L, int handler, basic_event *event, const TDynamicObject *activator); static void push_memcell_values(lua_State *L, const TMemCell *mc); diff --git a/scripting/luaprogram.cpp b/scripting/luaprogram.cpp index 36d95d271..07fe89a4b 100644 --- a/scripting/luaprogram.cpp +++ b/scripting/luaprogram.cpp @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "scripting/scriptscreenprogram.h" #include "scripting/scriptscreendrawing.h" #include "scripting/scriptscreenkernels.h" +#include "scripting/luasandbox.h" #include "utilities/Logs.h" #include "utilities/dictionary.h" @@ -411,12 +412,7 @@ int api_read_file(lua_State *L) // loads a script as text: precompiled code is refused. leaves the chunk, or an error message, on the stack bool load_chunk(lua_State *L, std::string_view const Code, std::string const &Name) { - if (false == Code.empty() && Code.front() == '\x1b') - { - lua_pushfstring(L, "%s: precompiled scripts aren't loaded", Name.c_str()); - return false; - } - return 0 == luaL_loadbufferx(L, Code.data(), Code.size(), ("@" + Name).c_str(), "t"); + return lua_sandbox::load_text_chunk(L, Code, Name); } // eu07.include(path): runs another script below the script's folder and returns what it returns @@ -724,30 +720,10 @@ void push_state(lua_State *L, dictionary_source const &Input) } } -void open_library(lua_State *L, lua_CFunction Open, char const *Name) -{ - lua_pushcfunction(L, Open); - lua_pushstring(L, Name); - lua_call(L, 1, 0); -} - void lua_program::open_libraries() { - open_library(m_state, luaopen_base, ""); - open_library(m_state, luaopen_table, LUA_TABLIBNAME); - open_library(m_state, luaopen_string, LUA_STRLIBNAME); - open_library(m_state, luaopen_math, LUA_MATHLIBNAME); - open_library(m_state, luaopen_bit, LUA_BITLIBNAME); - // what reaches files or loads code - for (auto const *name : {"dofile", "loadfile", "load", "loadstring", "module", "require"}) - { - lua_pushnil(m_state); - lua_setglobal(m_state, name); - } - lua_getglobal(m_state, LUA_STRLIBNAME); - lua_pushnil(m_state); - lua_setfield(m_state, -2, "dump"); - lua_pop(m_state, 1); + // base, table, string, math and bit, without what reaches files or loads code + lua_sandbox::open_safe_libraries(m_state); } void lua_program::register_api() diff --git a/scripting/luasandbox.cpp b/scripting/luasandbox.cpp new file mode 100644 index 000000000..8d80cdebf --- /dev/null +++ b/scripting/luasandbox.cpp @@ -0,0 +1,167 @@ +/* +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 "scripting/luasandbox.h" + +#include "scripting/scriptscreenrules.h" + +#include +#include +#include + +namespace lua_sandbox +{ + +namespace +{ + +void open_library(lua_State *L, lua_CFunction Open, char const *Name) +{ + lua_pushcfunction(L, Open); + lua_pushstring(L, Name); + lua_call(L, 1, 0); +} + +// the conversions of strftime in C89, which every C library knows. LuaJIT hands each one to strftime on its own +constexpr std::string_view date_conversions{"aAbBcdHIjmMpSUwWxXyYZ%"}; + +// os.date(format, time), the library's own (the upvalue) for a format of known conversions only: the Microsoft +// C library ends the program on one it doesn't know ("%Q", "%#") +int api_date(lua_State *L) +{ + std::size_t length{0}; + auto const *format{luaL_optlstring(L, 1, "%c", &length)}; + std::string_view const text{format, length}; + for (std::size_t idx = 0; idx + 1 < text.size(); ++idx) + { + if (text[idx] != '%') + { + continue; + } + ++idx; + if (date_conversions.find(text[idx]) == std::string_view::npos) + { + return luaL_error(L, "os.date: unknown conversion '%%%c'", text[idx]); + } + } + lua_pushvalue(L, lua_upvalueindex(1)); + lua_insert(L, 1); + lua_call(L, lua_gettop(L) - 1, LUA_MULTRET); + return lua_gettop(L); +} + +} // namespace + +void open_safe_libraries(lua_State *L) +{ + open_library(L, luaopen_base, ""); + open_library(L, luaopen_table, LUA_TABLIBNAME); + open_library(L, luaopen_string, LUA_STRLIBNAME); + open_library(L, luaopen_math, LUA_MATHLIBNAME); + open_library(L, luaopen_bit, LUA_BITLIBNAME); + // what reaches files or loads code + for (auto const *name : {"dofile", "loadfile", "load", "loadstring", "module", "require"}) + { + lua_pushnil(L); + lua_setglobal(L, name); + } + lua_getglobal(L, LUA_STRLIBNAME); + lua_pushnil(L); + lua_setfield(L, -2, "dump"); + lua_pop(L, 1); +} + +void open_clock_library(lua_State *L) +{ + // the whole library, of which a new table takes what only reads the clock + open_library(L, luaopen_os, LUA_OSLIBNAME); + lua_getglobal(L, LUA_OSLIBNAME); + lua_newtable(L); + for (auto const *name : {"time", "clock", "difftime"}) + { + lua_getfield(L, -2, name); + lua_setfield(L, -2, name); + } + lua_getfield(L, -2, "date"); + lua_pushcclosure(L, api_date, 1); + lua_setfield(L, -2, "date"); + // the new table in place of the library: the global, and the one the libraries know as loaded, which + // luaL_openlibs fills up again rather than make a new global + lua_pushvalue(L, -1); + lua_setglobal(L, LUA_OSLIBNAME); + lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); + lua_pushvalue(L, -2); + lua_setfield(L, -2, LUA_OSLIBNAME); + // _LOADED, the new table, the library + lua_pop(L, 3); +} + +bool load_text_chunk(lua_State *L, std::string_view const Code, std::string const &Name) +{ + if (false == Code.empty() && Code.front() == '\x1b') + { + lua_pushfstring(L, "%s: precompiled scripts aren't loaded", Name.c_str()); + return false; + } + return 0 == luaL_loadbufferx(L, Code.data(), Code.size(), ("@" + Name).c_str(), "t"); +} + +std::optional read_script_file(std::string const &Folder, std::string_view const Path) +{ + if (false == script_screens::is_safe_relative_path(Path)) + { + return std::nullopt; + } + // a folder or a device (CON, NUL, COM1...) isn't a regular file. in the code page of the system, as the game opens + // its files + std::filesystem::path const path{Folder + std::string{Path}}; + std::error_code error; + if (false == std::filesystem::is_regular_file(path, error)) + { + return std::nullopt; + } + auto const size{std::filesystem::file_size(path, error)}; + if (error || size > max_script_file) + { + return std::nullopt; + } + std::ifstream file{path, std::ios::binary}; + if (false == file.is_open()) + { + return std::nullopt; + } + std::string contents(static_cast(size), '\0'); + file.read(contents.data(), static_cast(contents.size())); + // what was read, should the file have shrunk meanwhile + contents.resize(static_cast(file.gcount())); + return contents; +} + +std::optional run_script_file(lua_State *L, std::string const &Folder, std::string_view const Path) +{ + auto const name{Folder + std::string{Path}}; + auto const code{read_script_file(Folder, Path)}; + if (false == code.has_value()) + { + return name + ": not found, not a file, larger than " + std::to_string(max_script_file) + + " bytes, or outside the folder (an absolute path, a drive or '..')"; + } + if (false == load_text_chunk(L, *code, name) || 0 != lua_pcall(L, 0, 0, 0)) + { + std::size_t length{0}; + auto const *message{lua_tolstring(L, -1, &length)}; + std::string result{message != nullptr ? std::string{message, length} : name + ": unknown error"}; + lua_pop(L, 1); + return result; + } + return std::nullopt; +} + +} // namespace lua_sandbox diff --git a/scripting/luasandbox.h b/scripting/luasandbox.h new file mode 100644 index 000000000..abdd21933 --- /dev/null +++ b/scripting/luasandbox.h @@ -0,0 +1,49 @@ +/* +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 + +// what the Lua states of the game share to run scripts sandboxed: the scenery scripts (scripting/lua.cpp, lua in the +// .scn) and the script screens (scripting/luaprogram.cpp). a sandboxed script reaches no files, no other programs, no +// ffi and no debug library, and loads no code of its own: no require, dofile, load or precompiled chunks + +#include + +#include +#include +#include +#include + +namespace lua_sandbox +{ + +// the largest script file a scenery loads +constexpr std::uintmax_t max_script_file{16 * 1024 * 1024}; + +// the libraries a sandboxed script gets: base, table, string, math and bit, without dofile, loadfile, load, +// loadstring, module, require and string.dump +void open_safe_libraries(lua_State *L); + +// the os table with only what reads the clock: os.time, os.clock, os.difftime and os.date, the last refusing the +// conversions the C library doesn't know (the Microsoft one ends the program on them) +void open_clock_library(lua_State *L); + +// loads Code as text, under the name Name: precompiled code is refused. leaves the chunk, or an error message, on the +// stack +bool load_text_chunk(lua_State *L, std::string_view Code, std::string const &Name); + +// the file Path of Folder, when Path is a relative path inside Folder (no '..', no drive, no leading separator) and +// names a regular file of at most max_script_file bytes. nothing otherwise +std::optional read_script_file(std::string const &Folder, std::string_view Path); + +// reads the script Path of Folder (as read_script_file), loads it as text and runs it in protected mode. nothing when +// it ran, otherwise why it didn't +std::optional run_script_file(lua_State *L, std::string const &Folder, std::string_view Path); + +} // namespace lua_sandbox diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index 9d1e94869..c39870600 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -405,7 +405,8 @@ void state_serializer::deserialize_lua( cParser &Input, scene::scratch_data &Scr std::string file; Input >> file; #ifdef WITH_LUA - simulation::Lua.interpret(Global.asCurrentSceneryPath + file); + // the file is relative to the scenery folder, and stays inside it + simulation::Lua.interpret(Global.asCurrentSceneryPath, file); #else ErrorLog(file + ": lua scripts not supported in this build."); #endif diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index c1ad98f35..e24db024f 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -39,7 +39,7 @@ 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") + target_sources(${UNIT_TESTS_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/scripting/luaprogram.cpp" "${CMAKE_SOURCE_DIR}/scripting/luasandbox.cpp" "${CMAKE_SOURCE_DIR}/stb/stb_image.c") endif() if (WITH_WASM) target_sources(${UNIT_TESTS_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/scripting/wasmprogram.cpp") diff --git a/tests/unit/test_lua_sandbox.cpp b/tests/unit/test_lua_sandbox.cpp new file mode 100644 index 000000000..f23cb0406 --- /dev/null +++ b/tests/unit/test_lua_sandbox.cpp @@ -0,0 +1,218 @@ +#include "stdafx.h" +#include "doctest.h" + +// the sandbox the Lua states of the game share (scripting/luasandbox.cpp): the scenery scripts (lua in the .scn, +// scripting/lua.cpp) and the script screens (scripting/luaprogram.cpp, tested with the screens in +// test_script_screen_host.cpp). a script gets base, table, string, math and bit, and of os only the clock; it reaches +// no files, no programs, no ffi, loads no code of its own and no precompiled chunk, and a scenery reads its scripts +// only from its own folder + +#ifdef WITH_LUA + +#include "scripting/luasandbox.h" +#include "scratch.h" + +#include +#include +#include +#include + +namespace { + +// a state with the libraries of the scenery scripts +class sandboxed_state { + public: + sandboxed_state() : m_state{luaL_newstate()} { + lua_sandbox::open_safe_libraries(m_state); + lua_sandbox::open_clock_library(m_state); + } + ~sandboxed_state() { lua_close(m_state); } + sandboxed_state(sandboxed_state const &) = delete; + sandboxed_state &operator=(sandboxed_state const &) = delete; + + lua_State *get() const { return m_state; } + + // runs the code, which returns one value, and gives that value as text ("nil", "true", a number, a string), or + // "error: " and the message + std::string run(std::string_view const Code) const { + auto const top{lua_gettop(m_state)}; + std::string result; + if (false == lua_sandbox::load_text_chunk(m_state, Code, "test") || 0 != lua_pcall(m_state, 0, 1, 0)) { + result = std::string{"error: "} + lua_tostring(m_state, -1); + } else if (lua_isnil(m_state, -1)) { + result = "nil"; + } else if (lua_isboolean(m_state, -1)) { + result = lua_toboolean(m_state, -1) ? "true" : "false"; + } else { + auto const *text{lua_tostring(m_state, -1)}; + result = text != nullptr ? text : "?"; + } + lua_settop(m_state, top); + return result; + } + + private: + lua_State *m_state; +}; + +bool contains(std::string_view const Text, std::string_view const Part) { + return Text.find(Part) != std::string_view::npos; +} + +} // namespace + +TEST_CASE("lua sandbox: no library that reaches files, programs, ffi or the debugger, and nothing that loads code") { + sandboxed_state const lua; + for (auto const *name : {"io", "ffi", "debug", "package", "jit", "require", "module", "dofile", "loadfile", "load", "loadstring", + "string.dump", "os.execute", "os.exit", "os.remove", "os.rename", "os.getenv", "os.tmpname", + "os.setlocale"}) { + CAPTURE(name); + CHECK(lua.run(std::format("return {}", name)) == "nil"); + } + // what the scripts did with them fails, as a Lua error + CHECK(contains(lua.run("return io.open('eu07.ini')"), "attempt to index global 'io' (a nil value)")); + CHECK(contains(lua.run("return os.execute('cmd')"), "attempt to call field 'execute' (a nil value)")); + CHECK(contains(lua.run("return require('ffi')"), "attempt to call global 'require' (a nil value)")); +} + +TEST_CASE("lua sandbox: the libraries a script gets work") { + sandboxed_state const lua; + CHECK(lua.run("return math.floor(2.5) + #string.rep('a', 3) + bit.band(7, 4) + #table.concat({ 'a', 'b' })") == "11"); + CHECK(lua.run("return ('%d-%s'):format(7, 'x')") == "7-x"); + CHECK(lua.run("local ok, error = pcall(function() error('boom') end) return (not ok) and error:find('boom') ~= nil") == "true"); + CHECK(lua.run("local n = 0 for _, v in ipairs({ 1, 2, 3 }) do n = n + v end return n") == "6"); + CHECK(lua.run("return tostring(tonumber('12') + select('#', 1, 2))") == "14"); +} + +TEST_CASE("lua sandbox: os reads the clock, and nothing else") { + sandboxed_state const lua; + CHECK(lua.run("return type(os.time()) == 'number' and os.time() > 0") == "true"); + CHECK(lua.run("return type(os.clock()) == 'number'") == "true"); + CHECK(lua.run("return os.difftime(10, 4)") == "6"); + CHECK(lua.run("return os.time({ year = 2020, month = 1, day = 2, hour = 12 }) > 0") == "true"); + CHECK(lua.run("return os.date('!%Y-%m-%d', 0)") == "1970-01-01"); + CHECK(lua.run("return os.date('!*t', 86400 * 365).year") == "1971"); + CHECK(lua.run("return #os.date()") != "0"); + // a lone % at the end and %% are text + CHECK(lua.run("return os.date('!100%%', 0)") == "100%"); + CHECK(lua.run("return os.date('!100%', 0)") == "100%"); + // conversions the Microsoft C library doesn't know end the program there: refused before + CHECK(contains(lua.run("return os.date('%Q')"), "os.date: unknown conversion '%Q'")); + CHECK(contains(lua.run("return os.date('%#c')"), "os.date: unknown conversion '%#'")); + CHECK(contains(lua.run("return os.date('%Ey')"), "os.date: unknown conversion '%E'")); + // the table holds only the clock + CHECK(lua.run("local n = 0 for _ in pairs(os) do n = n + 1 end return n") == "4"); +} + +TEST_CASE("lua sandbox: all libraries opened over the sandbox are whole again (lua.fulllibraries)") { + sandboxed_state const lua; + luaL_openlibs(lua.get()); + for (auto const *name : {"io.open", "os.execute", "os.getenv", "os.date", "require", "loadstring", "dofile", "string.dump", "debug.traceback"}) { + CAPTURE(name); + CHECK(lua.run(std::format("return type({})", name)) == "function"); + } + CHECK(lua.run("return type(require('ffi'))") == "table"); + CHECK(lua.run("return rawequal(os, package.loaded.os)") == "true"); +} + +TEST_CASE("lua sandbox: precompiled code isn't loaded") { + // real LuaJIT bytecode, from a state with all libraries + auto *full{luaL_newstate()}; + luaL_openlibs(full); + // luaL_dostring is a || of two calls, a bool in C++ + REQUIRE_FALSE(luaL_dostring(full, "return string.dump(function() return 42 end)")); + std::size_t length{0}; + auto const *bytes{lua_tolstring(full, -1, &length)}; + std::string const bytecode{bytes, length}; + lua_close(full); + REQUIRE(false == bytecode.empty()); + CHECK(bytecode.front() == '\x1b'); + + sandboxed_state const lua; + auto const top{lua_gettop(lua.get())}; + CHECK_FALSE(lua_sandbox::load_text_chunk(lua.get(), bytecode, "compiled.lua")); + CHECK(contains(lua_tostring(lua.get(), -1), "compiled.lua: precompiled scripts aren't loaded")); + lua_settop(lua.get(), top); + // nor in a text that only starts with the marker + CHECK_FALSE(lua_sandbox::load_text_chunk(lua.get(), std::string_view{"\x1bLJ\x02 return 1"}, "fake.lua")); + lua_settop(lua.get(), top); +} + +TEST_CASE("lua sandbox: a scenery reads its scripts only from its own folder") { + test::scratch_folder const root{"lua_sandbox_paths"}; + root.write("outside.lua", "return 1"); + root.write("scenery/test.lua", "return 2"); + root.write("scenery/scripts/module.lua", "return 3"); + root.write("scenery/folder.lua/inner.lua", "return 4"); + auto const folder{root.path("scenery") + "/"}; + + CHECK(lua_sandbox::read_script_file(folder, "test.lua") == std::optional{"return 2"}); + CHECK(lua_sandbox::read_script_file(folder, "scripts/module.lua") == std::optional{"return 3"}); + CHECK(lua_sandbox::read_script_file(folder, "scripts\\module.lua") == std::optional{"return 3"}); + for (auto const &path : {std::string{"../outside.lua"}, std::string{"scripts/../../outside.lua"}, std::string{"..\\outside.lua"}, + root.path("outside.lua"), std::string{"/outside.lua"}, std::string{"\\outside.lua"}, std::string{"C:outside.lua"}, + std::string{"missing.lua"}, std::string{"folder.lua"}, std::string{"scripts"}, std::string{}}) { + CAPTURE(path); + CHECK_FALSE(lua_sandbox::read_script_file(folder, path).has_value()); + } +} + +TEST_CASE("lua sandbox: a script larger than the limit isn't read") { + test::scratch_folder const root{"lua_sandbox_size"}; + root.write("scenery/limit.lua", std::string(static_cast(lua_sandbox::max_script_file), ' ')); + root.write("scenery/over.lua", std::string(static_cast(lua_sandbox::max_script_file) + 1, ' ')); + auto const folder{root.path("scenery") + "/"}; + CHECK(lua_sandbox::read_script_file(folder, "limit.lua").has_value()); + CHECK_FALSE(lua_sandbox::read_script_file(folder, "over.lua").has_value()); +} + +TEST_CASE("lua sandbox: a scenery script runs in protected mode, and its errors name the file") { + test::scratch_folder const root{"lua_sandbox_run"}; + root.write("scenery/good.lua", "ran = (ran or 0) + 1"); + root.write("scenery/fails.lua", "ran = 10\nlocal x = nil\nx.field = 1\nran = 20"); + root.write("scenery/files.lua", "local f = io.open('eu07.ini')"); + root.write("scenery/system.lua", "os.execute('cmd /c echo pwned')"); + root.write("scenery/syntax.lua", "this is not lua"); + root.write("scenery/compiled.lua", std::string_view{"\x1bLJ\x02 bytes"}); + auto const folder{root.path("scenery") + "/"}; + + sandboxed_state const lua; + auto *L{lua.get()}; + auto const top{lua_gettop(L)}; + + CHECK_FALSE(lua_sandbox::run_script_file(L, folder, "good.lua").has_value()); + CHECK(lua.run("return ran") == "1"); + + auto const fails{lua_sandbox::run_script_file(L, folder, "fails.lua")}; + REQUIRE(fails.has_value()); + CHECK(contains(*fails, "fails.lua:3:")); + // it stopped at the error + CHECK(lua.run("return ran") == "10"); + + auto const files{lua_sandbox::run_script_file(L, folder, "files.lua")}; + REQUIRE(files.has_value()); + CHECK(contains(*files, "files.lua:1: attempt to index global 'io' (a nil value)")); + + auto const system{lua_sandbox::run_script_file(L, folder, "system.lua")}; + REQUIRE(system.has_value()); + CHECK(contains(*system, "system.lua:1: attempt to call field 'execute' (a nil value)")); + + auto const syntax{lua_sandbox::run_script_file(L, folder, "syntax.lua")}; + REQUIRE(syntax.has_value()); + CHECK(contains(*syntax, "syntax.lua:1:")); + + auto const compiled{lua_sandbox::run_script_file(L, folder, "compiled.lua")}; + REQUIRE(compiled.has_value()); + CHECK(contains(*compiled, "compiled.lua: precompiled scripts aren't loaded")); + + auto const outside{lua_sandbox::run_script_file(L, folder, "../good.lua")}; + REQUIRE(outside.has_value()); + CHECK(contains(*outside, "outside the folder")); + + // nothing left on the stack, and the state still works + CHECK(lua_gettop(L) == top); + CHECK_FALSE(lua_sandbox::run_script_file(L, folder, "good.lua").has_value()); + CHECK(lua.run("return ran") == "11"); +} + +#endif diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index a2cb6f59d..2b5684dab 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -956,6 +956,14 @@ bool global_settings::ConfigParseScriptScreens(cParser& Parser, std::string_view return true; } + // the scenery scripts (lua in the .scn) with all of LuaJIT's libraries, for a scenery that needs io, ffi or + // require: they then reach files and programs as the player does + if (token == "lua.fulllibraries") + { + ParseOne(Parser, lua_fulllibraries, 1); + return true; + } + if (token == "wasm.enabled") { ParseOne(Parser, wasm_enabled, 1); @@ -1962,6 +1970,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "python.uploadmain", python_uploadmain ); export_as_text( Output, "python.mipmaps", python_mipmaps ); export_as_text( Output, "luascreens.enabled", luascreens_enabled ); + export_as_text( Output, "lua.fulllibraries", lua_fulllibraries ); export_as_text( Output, "wasm.enabled", wasm_enabled ); export_as_text( Output, "screens.cabframes", screens_cabframes ); export_as_text( Output, "screens.externalframes", screens_externalframes ); diff --git a/utilities/Globals.h b/utilities/Globals.h index 8d32a463c..25c7872c8 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -312,6 +312,7 @@ struct global_settings { bool python_uploadmain = true; std::chrono::duration python_minframetime {0.01f}; bool luascreens_enabled{true}; // screens drawn by Lua scripts (luascreen:, luadestinationsign: in the .mmd) + bool lua_fulllibraries{false}; // the scenery scripts (lua in the .scn) get all of LuaJIT's libraries (io, os, ffi, require...), not only the sandboxed ones bool wasm_enabled{true}; // screens drawn by WebAssembly modules (wasmscreen:, wasmdestinationsign: in the .mmd) int screens_cabframes{4}; // the script screens in the cab are refreshed every so many rendered frames int screens_externalframes{30}; // the script screens outside the cab (destination signs) are refreshed every so many rendered frames From cae152c96e8c79241ad337fbc34df8b6045abfac Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 13 Nov 2026 16:23:57 +0100 Subject: [PATCH 008/136] feat(ui): driving aid shows the ED braking and hides a local brake the cab lacks The driving aid panel works out its throttle and brakes numbers in a new pure helper, vehicle/drivingaid.{h,cpp} (in CORE_SOURCES, unit tested). - EIM vehicles: the brakes line gets " ED brake: N%" while the ED braking demand (-eimic_real) is at least 1%, except where the integrated universal controller already shows it as the brake number (eu07/maszyna#558). - SplitEDPneumaticBrake (Vectron): the ED lever off zero shows in the throttle line as the negative step the cab's joint controller shows. - The local brake setting ("+N") shows only when the cab has a localbrake: lever or a jointctrl: whose braking range is the local brake, or when the local brake is applied. The Elf cabs have neither (eu07/maszyna#555). Vehicles without an EIM controller and with a local brake control show what they did. The existing msgids stay; two new ones show in English until the game data's lang/*.po (SVN) have them: "Brakes: %5.1f%c%s" (pl "Hamulce: %5.1f%c%s") and " ED brake: %d%%%%" (pl " Hamowanie ED: %d%%%%"). Adds the Vectron (vectron_v1/wariant_7w) to the real definitions of the unit tests. --- CMakeLists.txt | 1 + application/driveruipanels.cpp | 48 +++-- tests/unit/data/fiz/README.md | 3 +- .../unit/data/fiz/vectron_v1/wariant_7w.json | 72 +++++++ tests/unit/test_drivingaid.cpp | 176 ++++++++++++++++++ vehicle/drivingaid.cpp | 79 ++++++++ vehicle/drivingaid.h | 68 +++++++ 7 files changed, 434 insertions(+), 13 deletions(-) create mode 100644 tests/unit/data/fiz/vectron_v1/wariant_7w.json create mode 100644 tests/unit/test_drivingaid.cpp create mode 100644 vehicle/drivingaid.cpp create mode 100644 vehicle/drivingaid.h diff --git a/CMakeLists.txt b/CMakeLists.txt index e97e41d03..a88a88424 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -548,6 +548,7 @@ set(CORE_SOURCES "vehicle/blackbox.cpp" "vehicle/enginestart.cpp" "vehicle/brakesetting.cpp" +"vehicle/drivingaid.cpp" "vehicle/handover.cpp" "vehicle/horn.cpp" "vehicle/linebreaker.cpp" diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index ba8e7556d..c598842d7 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -23,6 +23,7 @@ http://mozilla.org/MPL/2.0/. #include "world/mtable.h" #include "vehicle/Train.h" #include "vehicle/Driver.h" +#include "vehicle/drivingaid.h" #include "model/AnimModel.h" #include "vehicle/DynObj.h" #include "model/Model3d.h" @@ -76,6 +77,13 @@ drivingaid_panel::update() { auto const *mover = controlled->MoverParameters; auto const *vehicledriver = controlled->Mechanik; auto const *owner = controlled->ctOwner != nullptr ? controlled->ctOwner : controlled->Mechanik; + // the numbers of the throttle and brakes lines, with the controls of the cab the driver is in + auto const readout { drivingaid::compute( drivingaid::from_movers( + *mover, + *vehicledriver->Controlling(), + drivingaid::cab_controls { + train->ggLocalBrake.SubModel != nullptr, + train->ggJointCtrl.SubModel != nullptr } ) ) }; { // throttle, velocity, speed limits and grade std::string expandedtext; @@ -116,8 +124,8 @@ drivingaid_panel::update() { std::snprintf( m_buffer.data(), m_buffer.size(), STR_C("Throttle: %3d+%d %c%s"), - mover->EIMCtrlType > 0 ? std::max(0, static_cast(100.4 * mover->eimic_real)) : vehicledriver->Controlling()->MainCtrlPos, - mover->EIMCtrlType > 0 ? vehicledriver->Controlling()->MainCtrlPos : vehicledriver->Controlling()->ScndCtrlPos, + readout.throttle_first, + readout.throttle_second, mover->SpeedCtrlUnit.IsActive ? 'T' : mover->DirActive > 0 ? 'D' : mover->DirActive < 0 ? 'R' : @@ -137,16 +145,32 @@ drivingaid_panel::update() { mover->PipePress * 100 ); expandedtext = m_buffer.data(); } - auto const basicbraking { mover->fBrakeCtrlPos }; - auto const eimicbraking { std::max( 0.0, -100.0 * mover->eimic_real ) }; - std::snprintf( - m_buffer.data(), m_buffer.size(), - STR_C("Brakes: %5.1f+%-2.0f%c%s"), -// ( mover->EIMCtrlType == 0 ? basicbraking : mover->EIMCtrlType == 3 ? ( mover->UniCtrlIntegratedBrakeCtrl ? eimicbraking : basicbraking ) : eimicbraking ), - mover->UniCtrlIntegratedBrakeCtrl ? eimicbraking : basicbraking, - mover->LocalBrakePosA * LocalBrakePosNo, - mover->SlippingWheels ? '!' : ' ', - expandedtext.c_str() ); + if( readout.ed_percent ) { + // the ED braking demand, ahead of the expanded data (eu07/maszyna#558) + std::snprintf( + m_buffer.data(), m_buffer.size(), + STR_C(" ED brake: %d%%%%"), + *readout.ed_percent ); + expandedtext.insert( 0, m_buffer.data() ); + } + if( readout.show_local_brake ) { + std::snprintf( + m_buffer.data(), m_buffer.size(), + STR_C("Brakes: %5.1f+%-2.0f%c%s"), + readout.brake_first, + readout.local_brake, + mover->SlippingWheels ? '!' : ' ', + expandedtext.c_str() ); + } + else { + // the cab has no local brake control: its setting is left out (eu07/maszyna#555) + std::snprintf( + m_buffer.data(), m_buffer.size(), + STR_C("Brakes: %5.1f%c%s"), + readout.brake_first, + mover->SlippingWheels ? '!' : ' ', + expandedtext.c_str() ); + } text_lines.emplace_back( m_buffer.data(), Global.UITextColor ); } diff --git a/tests/unit/data/fiz/README.md b/tests/unit/data/fiz/README.md index 514fb6287..eb5650edb 100644 --- a/tests/unit/data/fiz/README.md +++ b/tests/unit/data/fiz/README.md @@ -59,8 +59,9 @@ Every `.json` here is a vehicle picked up by `test_fiz.cpp`: record the paramete | `su45_v2/301d.fiz` | SU45 | DumbDE | LSt | FV4a | PneumaticBrake | Screw | | `su46_v2/303d.fiz` | SU46 | DumbDE | LSt | FV4a | PneumaticBrake | Screw | | `tem2_v2/tem2a.fiz` | TEM2 | DieselElectric | LSt | M394 | PneumaticBrake | Screw | +| `vectron_v1/wariant_7w.fiz` | VECTRON | ElectricInductionMotor | EStED | MHZ_K8P | PneumaticBrake | Screw | | `wm15_v1/wm15.fiz` | WM15 | Dumb | LSt | FV4a | PneumaticBrake | Screw | | `wmb10_v1/wmb10.fiz` | WMB10 | DieselEngine | LSt | FV4a | PneumaticBrake | Screw | | `z1_v2/152a.fiz` | Z1 | - | KE | - | ManualBrake | Screw | -The paths are those of the game's `.fiz` files. `elf_v1/inverter.fiz` is a part the Elf units include, not a vehicle. The 218M (V2NList), the SA134 (HTCList) and the 22WEc (ffBrakeList) are there for lists the others lack, the EP05 for its camshaft. The 214MA stands for the 214M railbus, whose own file repeats a section (TurboPos and MotorParamTable twice), which the definitions here can't hold. +The paths are those of the game's `.fiz` files. `elf_v1/inverter.fiz` is a part the Elf units include, not a vehicle. The 218M (V2NList), the SA134 (HTCList) and the 22WEc (ffBrakeList) are there for lists the others lack, the EP05 for its camshaft, the Vectron for its ED brake lever of its own (SplitEDPneumaticBrake). The 214MA stands for the 214M railbus, whose own file repeats a section (TurboPos and MotorParamTable twice), which the definitions here can't hold. diff --git a/tests/unit/data/fiz/vectron_v1/wariant_7w.json b/tests/unit/data/fiz/vectron_v1/wariant_7w.json new file mode 100644 index 000000000..777f4a78b --- /dev/null +++ b/tests/unit/data/fiz/vectron_v1/wariant_7w.json @@ -0,0 +1,72 @@ +{ + "_source": "pkp/vectron_v1/wariant_7w.fiz", + "_comment": "converted by test_fiz.cpp from the game's definition with the files it includes, keeping what the game's loader reads", + "Param": {"Category": "train", "M": "90000", "Mred": "12000", "Vmax": "200", "PWR": "6400", "SandCap": "700"}, + "Load": {"MaxLoad": "7", "LoadQ": "pieces", "LoadAccepted": "pantstate", "LoadSpeed": "1", "UnLoadSpeed": "0.1"}, + "Dimensions": {"L": "18.925", "H": "3.95", "W": "2.95", "Cx": "0.1"}, + "Wheels": {"D": "1.250", "AIM": "4000", "Tw": "1.435", "Axle": "Bo'Bo'", "Ad": "3", "Bd": "9.5", "Rmin": "80"}, + "Brake": {"BrakeValve": "EStED", "NBpA": "4", "MBF": "50", "MaxBP": "3.7", "MaxLBP": "3.7", "BCN": "8", "RM": "0.81", "BCR": "0.127", "BCD": "0.04", "BCM": "2.7", "BCS": "0.8", "BSA": "0", "BM": "Disk2", "BVV": "125", "Vv": "0.8", "CompressorSpeed": "0.06", "CompressorPower": "Main", "MinCP": "8.5", "MaxCP": "9.9", "UBB1": "8", "UBB2": "2", "LPOn": "3.0", "LPOff": "4.5", "HandlePipeUnlockPos": "-1", "EmergencyCutsOffHandle": "Yes"}, + "SpringBrake": {"Volume": "10", "MBF": "8", "MaxSP": "5.5", "ResetP": "4.0", "MinFP": "3.5", "PressOff": "4.5", "PressOn": "3.5", "ValveOnArea": "0.0002", "ValveOffArea": "0.0002", "ValvePNBArea": "0.002", "MTC": "4"}, + "BuffCoupl": {"CType": "Screw", "kB": "9200", "DmaxB": "0.15", "FmaxB": "740", "kC": "4800", "DmaxC": "0.15", "FmaxC": "780", "beta": "0.58", "AllowedFlag": "103"}, + "Cntrl": {"BrakeSystem": "Pneumatic", "BrakeOpModes": "PN", "BCPN": "4", "BDelay1": "15", "BDelay2": "4", "BDelay3": "35", "BDelay4": "25", "ASB": "Automatic", "LocalBrake": "PneumaticBrake", "MCPN": "15", "SCPN": "40", "SpeedCtrlDelay": "0.5", "AutoRelay": "No", "MainInitTime": "10", "MainStart": "Manual", "IniCDelay": "0.5", "SCDelay": "0.1", "BrakeDelays": "GPR", "BrakeHandle": "MHZ_K8P", "LocBrakeHandle": "FD1", "ScndS": "Yes", "SBD": "0", "ConverterStart": "Automatic", "ConverterStartDelay": "10", "PantCompressorStart": "Automatic", "PantAutoValve": "Yes", "EIMCtrlType": "0", "HAO": "No", "HMO": "No", "HGDP1": "0.1", "OMP": "0.4", "DirChangeMaxPos": "0", "LocalBrakeTraxx": "No", "PantEPValveStart": "Manual", "PantEPValveSpring": "No", "HideDirStatusWhenMoving": "Yes", "HideDirStatusSpeed": "5", "AutomaticCabActivation": "No", "InactiveCabFlag": "161", "DCMB": "Yes", "DCDPP": "1.0", "IBTB": "Yes", "SBBBH": "Yes", "BBHT": "2.0", "MotorBlowersStart": "Converter", "SplitEDPneumaticBrake": "Yes", "DBPN": "15", "rows": [ + ["-1","0.8","-1","20","Pneumatic"], + ["0","0.5","-1","2","Pneumatic"], + ["1","0.46","-1","2","Pneumatic"], + ["2","0.42","-1","2","Pneumatic"], + ["3","0.38","-1","2","Pneumatic"], + ["4","0.34","-1","2","Pneumatic"], + ["5","0.29","-1","2","Pneumatic"], + ["6","0","-1","40","Pneumatic"], + ["LampRed=255","LampGreen=255","LampBlue=228"] + ]}, + "Security": {"AwareSystem": "Active,CabSignal,SeparateAcknowledge", "AwareDelay": "30", "SoundSignalDelay": "0", "MaxHoldTime": "1.0", "EmergencyBrakeDelay": "5", "RadioStop": "Yes"}, + "Light": {"Light": "Generator", "LGeneratorEngine": "ElectricSeriesMotor", "LMaxVoltage": "24", "LMaxCurrent": "155"}, + "Clima": {"Heating": "Main"}, + "Power": {"EnginePower": "CurrentCollector", "CollectorsNo": "2", "MaxVoltage": "4200", "MaxCurrent": "2000", "MinH": "0.38", "MinV": "1900", "MaxH": "2.4", "CSW": "1.4", "PhysicalLayout": "3", "PantType": "WBL85"}, + "Engine": {"EngineType": "ElectricInductionMotor", "Trans": "10:47", "dfic": "931", "dfmax": "1.67", "p": "2", "cfu": "29", "cim": "8.86", "icif": "0.642", "Uzmax": "2216", "Uzh": "2216", "DU": "20", "I0": "20", "fcfu": "30", "F0": "340", "a1": "0.35", "Pmax": "6400", "Fh": "150", "Ph": "5200", "Vh0": "5", "Vh1": "10", "Imax": "2500", "Flat": "Yes", "abed": "1", "edep": "1.5", "Imaxrpc": "500", "BRVto": "15", "MotorBlowersSustainTime": "30", "MotorBlowersStartVelocity": "0.1", "MotorBlowersSpeed": "-10"}, + "SpeedControl": {"SpeedCtrl": "Yes", "OverrideManual": "No", "InitPwr": "1.0", "MaxPwrVel": "-1", "StartVel": "-1", "VelStep": "5", "PwrStep": "0.01", "MinPwr": "0.0", "MaxPwr": "1.0", "MinVel": "0", "MaxVel": "200", "Offset": "0", "kPpos": "0.1", "kPneg": "0.2", "kIpos": "0.03", "kIneg": "0.03", "BrakeIntervention": "No", "SpeedCtrlType": "Time", "SpeedCtrlDelay": "0.5"}, + "Doors": {"OpenCtrl": "Mixed", "CloseCtrl": "Mixed", "DoorOpenWithPermit": "1", "DoorMaxShiftL": "2", "DoorsPermitLightBlinking": "0"}, + "Switches": {"Pantograph": "Impulse", "PantographPresets": "2|1|3|2", "PantographPresetDefault": "1", "ModernDimmer": "Yes"}, + "DimmerList": {"Size": "5", "Cycle": "no", "DefaultPos": "3", "rows": [ + ["yes","no","no"], + ["yes","yes","no"], + ["no","no","yes"], + ["no","no","no"], + ["no","yes","no"] + ]}, + "ffList": {"Size": "8", "rows": [ + ["0","0.2"], + ["1","0.2"], + ["9.2","0.6"], + ["24.6","0.8"], + ["30.0","0.8"], + ["30.0","1.74"], + ["35.2","2.07"], + ["35.2","2.44"], + ["49.8","3.388"] + ]}, + "LightsList": {"Size": "16", "Wrap": "Yes", "Default": "1", "rows": [ + ["0","0"], + ["17","0"], + ["4","0"], + ["16","1"], + ["1","16"], + ["21","34"], + ["34","0"], + ["21","0"], + ["37","0"], + ["33","0"], + ["22","34"], + ["36","0"], + ["21","0"], + ["21","0"], + ["38","34"], + ["38","0"] + ]}, + "WiperList": {"Size": "4", "Angle": "58", "rows": [ + ["0","0.7","0.0","0.5"], + ["3","0.7","7.0","0.5"], + ["3","0.7","0.7","0.0"], + ["3","0.5","0.5","0.0"] + ]} +} diff --git a/tests/unit/test_drivingaid.cpp b/tests/unit/test_drivingaid.cpp new file mode 100644 index 000000000..b6ae1cc9d --- /dev/null +++ b/tests/unit/test_drivingaid.cpp @@ -0,0 +1,176 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "real_vehicles.h" + +#include "vehicle/drivingaid.h" +#include "McZapkie/hamulce.h" + +#include +#include +#include + +// the numbers of the driving aid panel's throttle and brakes lines: the ED braking shows (eu07/maszyna#558) and +// the local brake is left out where the cab has no control of it (eu07/maszyna#555) + +using test::definition; +using test::vehicle; + +namespace { + +// the cab controls of the vehicles here, as their cab definitions (.mmd) have them: the Vectron has a local brake +// lever and a joint controller whose braking range is its ED lever, the Traxx and the EU07 a local brake lever, +// the SM42 a joint controller whose braking range is the local brake, none of the 45 Elf cabs either of them +constexpr drivingaid::cab_controls vectron_cab{true, true}; +constexpr drivingaid::cab_controls lever_cab{true, false}; +constexpr drivingaid::cab_controls jointctrl_cab{false, true}; +constexpr drivingaid::cab_controls elf_cab{false, false}; + +drivingaid::readout read(vehicle &Vehicle, drivingaid::cab_controls const &Cab) { + return drivingaid::compute(drivingaid::from_movers(Vehicle.mover(), Vehicle.mover(), Cab)); +} + +// what the panel showed before: the throttle and brakes numbers, and the local brake always +drivingaid::readout before(TMoverParameters const &Mover) { + drivingaid::readout result; + result.throttle_first = Mover.EIMCtrlType > 0 ? std::max(0, static_cast(100.4 * Mover.eimic_real)) : Mover.MainCtrlPos; + result.throttle_second = Mover.EIMCtrlType > 0 ? Mover.MainCtrlPos : Mover.ScndCtrlPos; + result.brake_first = Mover.UniCtrlIntegratedBrakeCtrl ? std::max(0.0, -100.0 * Mover.eimic_real) : Mover.fBrakeCtrlPos; + result.local_brake = Mover.LocalBrakePosA * LocalBrakePosNo; + return result; +} + +test::track const line{0.15, 0.0, test::catenary_3kv}; + +} // namespace + +TEST_CASE("driving aid: the Vectron's ED lever shows as a negative throttle step, and its ED braking") { + vehicle vectron{definition::fiz("vectron_v1/wariant_7w"), 80.0 /* km/h */, "vectron", 1}; + REQUIRE(vectron->SplitEDPneumaticBrake); + REQUIRE(vectron->DynamicBrakeCtrlPosNo == 15); + REQUIRE(vectron->EIMCtrlType == 0); + + // lever at zero: the master controller, as before, and no ED braking + auto const idle{read(vectron, vectron_cab)}; + CHECK(idle.throttle_first == vectron->MainCtrlPos); + CHECK_FALSE(idle.ed_percent.has_value()); + CHECK(idle.show_local_brake); + + // six steps of the ED lever, as the cab's joint controller shows them + for (int step = 0; step < 6; ++step) { + REQUIRE(vectron->IncDynamicBrakeLevel(1.f)); + } + vectron.run(1.0, line); + REQUIRE(vectron->Vel > 15.0); // above Vh1, where the ED brake has its full demand + auto const braking{read(vectron, vectron_cab)}; + CHECK(braking.throttle_first == -6); + REQUIRE(vectron->eimic_real == doctest::Approx(-0.4)); + REQUIRE(braking.ed_percent.has_value()); + CHECK(*braking.ed_percent == 40); + // the train brake handle and the local brake, as before + CHECK(braking.brake_first == doctest::Approx(vectron->fBrakeCtrlPos)); + CHECK(braking.show_local_brake); + CHECK(braking.local_brake == doctest::Approx(0.0)); + + // the joint controller's braking range is the ED lever, so it isn't a local brake control + CHECK_FALSE(read(vectron, jointctrl_cab).show_local_brake); +} + +TEST_CASE("driving aid: the Traxx's ED braking from its master controller") { + vehicle traxx{definition::fiz("e186_v2/eu47"), 80.0 /* km/h */, "traxx", 1}; + REQUIRE(traxx->EIMCtrlType == 1); + REQUIRE_FALSE(traxx->SplitEDPneumaticBrake); + + CHECK_FALSE(read(traxx, lever_cab).ed_percent.has_value()); + // B+: the braking demand ramps towards full + traxx->MainCtrlPos = 0; + traxx.run(3.0, line); + REQUIRE(traxx->eimic_real < -0.2); + auto const braking{read(traxx, lever_cab)}; + REQUIRE(braking.ed_percent.has_value()); + CHECK(*braking.ed_percent == std::lround(-100.0 * traxx->eimic_real)); + // the drive demand stays at zero while braking, with the controller position next to it, as before + CHECK(braking.throttle_first == 0); + CHECK(braking.throttle_second == 0); + CHECK(braking.show_local_brake); +} + +TEST_CASE("driving aid: the Elf leaves out the local brake it has no control of, and shows its ED braking") { + vehicle elf{definition::fiz("elf_v1/21we-a"), 60.0 /* km/h */, "elf", 1}; + REQUIRE(elf->EIMCtrlType == 2); + // the definition has a local brake (LocalBrake=PneumaticBrake, LocBrakeHandle=FD1), the cab no control of it + REQUIRE(elf->LocalBrake == TLocalBrake::PneumaticBrake); + + auto const idle{read(elf, elf_cab)}; + CHECK_FALSE(idle.show_local_brake); + CHECK_FALSE(idle.ed_percent.has_value()); + + // the controller at its lowest braking position: the demand ramps towards full braking + elf->MainCtrlPos = 0; + elf.run(2.0, line); + REQUIRE(elf->eimic_real < -0.1); + auto const braking{read(elf, elf_cab)}; + REQUIRE(braking.ed_percent.has_value()); + CHECK(*braking.ed_percent == std::lround(-100.0 * elf->eimic_real)); + CHECK(braking.throttle_first == 0); + CHECK(braking.throttle_second == 0); + CHECK_FALSE(braking.show_local_brake); + + // applied after all (the AI, or the keys), it shows + elf->LocalBrakePosA = 0.3; + auto const applied{read(elf, elf_cab)}; + CHECK(applied.show_local_brake); + CHECK(applied.local_brake == doctest::Approx(3.0)); +} + +TEST_CASE("driving aid: a vehicle without an EIM controller shows what it did") { + vehicle eu07{definition::fiz("4e_v1/4e"), 60.0 /* km/h */, "eu07", 1}; + eu07->MainCtrlPos = 5; + eu07->LocalBrakePosA = 0.2; + auto const readout{read(eu07, lever_cab)}; + CHECK(readout.throttle_first == 5); + CHECK(readout.throttle_second == eu07->ScndCtrlPos); + CHECK(readout.local_brake == doctest::Approx(2.0)); + CHECK(readout.show_local_brake); + CHECK_FALSE(readout.ed_percent.has_value()); + + // the SM42's local brake is the braking range of its joint controller + vehicle sm42{definition::fiz("sm42_v1/6d1"), 0.0, "sm42", 1}; + CHECK(read(sm42, jointctrl_cab).show_local_brake); + CHECK_FALSE(read(sm42, elf_cab).show_local_brake); +} + +TEST_CASE("driving aid: the integrated universal controller shows the ED demand as its brake number, once") { + drivingaid::input input; + input.eim = true; + input.eimctrltype = 3; + input.integratedbrake = true; + input.eimic_real = -0.35; + input.brakectrlpos = 2.0; + auto const readout{drivingaid::compute(input)}; + CHECK(readout.brake_first == doctest::Approx(35.0)); + CHECK_FALSE(readout.ed_percent.has_value()); + CHECK(readout.throttle_first == 0); +} + +TEST_CASE("driving aid: every real vehicle with a local brake control shows the numbers it showed before") { + // with the ED lever of a split ED brake at zero, the change only adds the ED part and leaves out the local brake + // of a cab without a control of it + for (auto const &path : test::real_vehicles()) { + CAPTURE(path); + test::reseed_random(); + vehicle real{definition::fiz(path), 40.0 /* km/h */, "real", 1}; + for (auto const &[mainctrl, localbrake, eimic] : {std::tuple{0, 0.0, 0.0}, std::tuple{1, 0.4, -0.25}, std::tuple{1, 0.0, 0.6}}) { + real->MainCtrlPos = std::min(mainctrl, real->MainCtrlPosNo); + real->LocalBrakePosA = localbrake; + real->eimic_real = eimic; + auto const now{read(real, lever_cab)}; + auto const was{before(real.mover())}; + CHECK(now.throttle_first == was.throttle_first); + CHECK(now.throttle_second == was.throttle_second); + CHECK(now.brake_first == doctest::Approx(was.brake_first)); + CHECK(now.local_brake == doctest::Approx(was.local_brake)); + CHECK(now.show_local_brake); + } + } +} diff --git a/vehicle/drivingaid.cpp b/vehicle/drivingaid.cpp new file mode 100644 index 000000000..df8fc37a7 --- /dev/null +++ b/vehicle/drivingaid.cpp @@ -0,0 +1,79 @@ +/* +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/drivingaid.h" + +#include "McZapkie/MOVER.h" +#include "McZapkie/hamulce.h" + +#include +#include + +namespace drivingaid { + +namespace { + +// the first throttle number: the drive demand in percent with an EIM controller, else the master controller. +// a separate ED lever off its zero shows as the negative step the cab's joint controller is at +int throttle_first(input const &Input) { + if (Input.splited && Input.dynamicbrakepos > 0.0) { + return -static_cast(std::lround(Input.dynamicbrakepos * Input.dynamicbrakeposno)); + } + if (Input.eimctrltype > 0) { + return std::max(0, static_cast(100.4 * Input.eimic_real)); + } + return Input.mainctrlpos; +} + +// the cab has a control of the local brake: its own lever, or the braking range of the joint controller +// unless that range is the separate ED lever +bool has_local_brake_control(input const &Input) { + return Input.cab.localbrake || (Input.cab.jointctrl && false == Input.splited); +} + +} // namespace + +readout compute(input const &Input) { + readout result; + result.throttle_first = throttle_first(Input); + result.throttle_second = Input.eimctrltype > 0 ? Input.mainctrlpos : Input.scndctrlpos; + + auto const edbraking{std::max(0.0, -100.0 * Input.eimic_real)}; + result.brake_first = Input.integratedbrake ? edbraking : Input.brakectrlpos; + result.local_brake = Input.localbrakepos * LocalBrakePosNo; + // without a control in the cab the local brake is left out, unless it is applied after all (the AI or a key) + result.show_local_brake = has_local_brake_control(Input) || Input.localbrakepos > 0.0; + // the integrated universal controller shows the ED demand as its brake number already + if (Input.eim && false == Input.integratedbrake) { + if (auto const percent{static_cast(std::lround(edbraking))}; percent > 0) { + result.ed_percent = percent; + } + } + return result; +} + +input from_movers(TMoverParameters const &Vehicle, TMoverParameters const &Controlling, cab_controls const &Cab) { + input result; + result.eim = Vehicle.EngineType == TEngineType::ElectricInductionMotor || Vehicle.EIMCtrlType > 0; + result.eimctrltype = Vehicle.EIMCtrlType; + result.splited = Controlling.SplitEDPneumaticBrake; + result.integratedbrake = Vehicle.UniCtrlIntegratedBrakeCtrl; + result.eimic_real = Vehicle.eimic_real; + result.dynamicbrakepos = Controlling.DynamicBrakeCtrlPos; + result.dynamicbrakeposno = Controlling.DynamicBrakeCtrlPosNo; + result.mainctrlpos = Controlling.MainCtrlPos; + result.scndctrlpos = Controlling.ScndCtrlPos; + result.brakectrlpos = Vehicle.fBrakeCtrlPos; + result.localbrakepos = Vehicle.LocalBrakePosA; + result.cab = Cab; + return result; +} + +} // namespace drivingaid diff --git a/vehicle/drivingaid.h b/vehicle/drivingaid.h new file mode 100644 index 000000000..8cec257da --- /dev/null +++ b/vehicle/drivingaid.h @@ -0,0 +1,68 @@ +/* +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 + +class TMoverParameters; + +// what the driving aid panel shows of the controls and of the braking: the numbers of its throttle and +// brakes lines, worked out from the vehicle state (eu07/maszyna#558, eu07/maszyna#555) +namespace drivingaid { + +// the cab controls the panel needs to know of, which the cab definition (.mmd) has or lacks +struct cab_controls { + // a lever of the local (auxiliary) brake: localbrake: + bool localbrake{true}; + // a joint controller, jointctrl:, whose braking range is the local brake, or the ED lever with + // SplitEDPneumaticBrake + bool jointctrl{false}; +}; + +struct input { + // the vehicle works out the integrated drive and brake demand (eimic): an induction motor vehicle, + // or a diesel one with an EIM controller + bool eim{false}; + int eimctrltype{0}; + // the ED brake has a lever of its own (SplitEDPneumaticBrake), with dynamicbrakeposno steps + bool splited{false}; + // the universal controller brakes with the ED brake, so the brake handle number is the ED demand already + bool integratedbrake{false}; + // the demand in use, -1..1, negative braking + double eimic_real{0.0}; + double dynamicbrakepos{0.0}; // 0..1 + int dynamicbrakeposno{10}; + int mainctrlpos{0}; + int scndctrlpos{0}; + double brakectrlpos{0.0}; // the train brake handle + double localbrakepos{0.0}; // 0..1 + cab_controls cab; +}; + +struct readout { + // "Throttle: first+second" + int throttle_first{0}; + int throttle_second{0}; + // "Brakes: first+local" + double brake_first{0.0}; + double local_brake{0.0}; + bool show_local_brake{true}; + // the ED braking demand in percent, while there is some + std::optional ed_percent; +}; + +// the panel's numbers from the vehicle state +readout compute(input const &Input); + +// the state the panel reads: Vehicle is the one the driver sits in, Controlling the one whose controllers +// the driver moves (TController::Controlling()) +input from_movers(TMoverParameters const &Vehicle, TMoverParameters const &Controlling, cab_controls const &Cab); + +} // namespace drivingaid From 57c723a72e929bb389c055dbc62ebdf8ad2df027 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 13 Nov 2026 17:56:09 +0100 Subject: [PATCH 009/136] refactor: reentrant localtime and no goto in the cross switch lookup (Sonar S1912, S1909) The date of the scenery wizard's .scn header and the stamp of the editor's terrain backups use local_tm() (localtime_s/localtime_r) instead of std::localtime. The goto out of the loop over the four tracks of a cross switch, into the continue of the failed "ac" assignment, becomes a std::all_of check which continues the outer node loop, as the goto did. --- launcher/scenery_wizard.cpp | 4 +++- scene/scenelayerssave.cpp | 3 ++- scene/scenenodegroups.cpp | 8 ++++---- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/launcher/scenery_wizard.cpp b/launcher/scenery_wizard.cpp index 339a2871c..7038415d6 100644 --- a/launcher/scenery_wizard.cpp +++ b/launcher/scenery_wizard.cpp @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Globals.h" #include "utilities/Logs.h" #include "utilities/translation.h" +#include "utilities/utilities.h" #include #include @@ -400,7 +401,8 @@ bool ui::scenerywizard_panel::create_scenery() } auto const now{std::time(nullptr)}; char date[32]; - std::strftime(date, sizeof(date), "%Y-%m-%d", std::localtime(&now)); + std::tm const local{local_tm(now)}; + std::strftime(date, sizeof(date), "%Y-%m-%d", &local); char reference[96]; std::snprintf(reference, sizeof(reference), "//$g PUWG1992 %.3f %.3f", m_map.point().x / 1000.0, m_map.point().y / 1000.0); auto const area{range()}; diff --git a/scene/scenelayerssave.cpp b/scene/scenelayerssave.cpp index d85d43ac4..8321c1844 100644 --- a/scene/scenelayerssave.cpp +++ b/scene/scenelayerssave.cpp @@ -1668,7 +1668,8 @@ save_result node_layers::save(std::vector const &Rootstatements, st { auto const now{std::time(nullptr)}; char stamp[32]; - std::strftime(stamp, sizeof(stamp), "%Y%m%d-%H%M%S", std::localtime(&now)); + std::tm const local{local_tm(now)}; + std::strftime(stamp, sizeof(stamp), "%Y%m%d-%H%M%S", &local); for (auto const output : written) { auto const filepath{path(output)}; diff --git a/scene/scenenodegroups.cpp b/scene/scenenodegroups.cpp index 781287806..dd10fc143 100644 --- a/scene/scenenodegroups.cpp +++ b/scene/scenenodegroups.cpp @@ -207,12 +207,12 @@ node_groups::update_map() continue; last_switch->track[lastc - 'a'] = track; - for (auto trk : last_switch->track) - if (!trk) - goto skip_e; + // all four tracks of the cross switch have to be known before it's assigned + if (!std::all_of(last_switch->track.begin(), last_switch->track.end(), [](TTrack const *Track) { return Track != nullptr; })) + continue; if (!assign_cross_switch(*last_switch, sw_name, "ac", 0)) - skip_e: continue; + continue; if (!assign_cross_switch(*last_switch, sw_name, "ad", 1)) continue; if (!assign_cross_switch(*last_switch, sw_name, "bc", 2)) From 8467eab8b49d87c0ff3cfdccd1444cda9ad8df49 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 13 Nov 2026 18:35:47 +0100 Subject: [PATCH 010/136] fix(scripting): read '\' as a folder separator in scenery script paths on Linux too The unit test reading "scripts\module.lua" failed on Linux/GCC: there '\' is part of a file name, not a separator. The game already reads '\' in its data paths as '/' (replace_slashes, the model and texture names, the parser's include tokens), and sceneries made on Windows often name their folders with it, so the scenery scripts do the same: read_script_file turns '\' into '/' (lua_sandbox::with_forward_slashes) after the path check. is_safe_relative_path splits on both separators on every system, so '..\' and 'a\..\..\' stay refused; the test now checks those too. --- script_screens_doc.md | 2 +- scripting/luasandbox.cpp | 10 +++++++++- scripting/luasandbox.h | 7 ++++++- tests/unit/test_lua_sandbox.cpp | 3 +++ 4 files changed, 19 insertions(+), 3 deletions(-) diff --git a/script_screens_doc.md b/script_screens_doc.md index 09a4c2638..4cdc5badd 100644 --- a/script_screens_doc.md +++ b/script_screens_doc.md @@ -216,7 +216,7 @@ and works with memcells, tracks and vehicles through the table `eu07.events` (`e `memcell_update`, `writelog` and the rest, see `scripting/lua.cpp`). It shares the sandbox of the Lua screens: - the file is a path relative to the scenery folder (`scenery/`), and stays inside it: no `..`, no drive, no leading - `/`. It is text, of at most 16 MB; precompiled code is not loaded; + `/`. `/` and `\` both separate folders, on Linux too. It is text, of at most 16 MB; precompiled code is not loaded; - the script gets the base library, `table`, `string`, `math` and `bit`, and of `os` only the clock: `os.time`, `os.clock`, `os.difftime` and `os.date` (with the C89 conversions only, `%Y`, `%d`, `%H` and so on). It gets no `io`, the rest of `os`, `ffi`, `debug`, `jit`, `package`, `require`, `dofile`, `load`, `loadfile` or `loadstring`; diff --git a/scripting/luasandbox.cpp b/scripting/luasandbox.cpp index 8d80cdebf..ea5f98a88 100644 --- a/scripting/luasandbox.cpp +++ b/scripting/luasandbox.cpp @@ -12,6 +12,7 @@ http://mozilla.org/MPL/2.0/. #include "scripting/scriptscreenrules.h" +#include #include #include #include @@ -59,6 +60,13 @@ int api_date(lua_State *L) } // namespace +std::string with_forward_slashes(std::string_view const Path) +{ + std::string result{Path}; + std::ranges::replace(result, '\\', '/'); + return result; +} + void open_safe_libraries(lua_State *L) { open_library(L, luaopen_base, ""); @@ -121,7 +129,7 @@ std::optional read_script_file(std::string const &Folder, std::stri } // a folder or a device (CON, NUL, COM1...) isn't a regular file. in the code page of the system, as the game opens // its files - std::filesystem::path const path{Folder + std::string{Path}}; + std::filesystem::path const path{Folder + with_forward_slashes(Path)}; std::error_code error; if (false == std::filesystem::is_regular_file(path, error)) { diff --git a/scripting/luasandbox.h b/scripting/luasandbox.h index abdd21933..167060026 100644 --- a/scripting/luasandbox.h +++ b/scripting/luasandbox.h @@ -38,8 +38,13 @@ void open_clock_library(lua_State *L); // stack bool load_text_chunk(lua_State *L, std::string_view Code, std::string const &Name); +// Path with each '\' turned into '/', as the game reads the paths in its data (replace_slashes): a scenery made on +// Windows may name its folders either way, and on Linux only '/' separates them +std::string with_forward_slashes(std::string_view Path); + // the file Path of Folder, when Path is a relative path inside Folder (no '..', no drive, no leading separator) and -// names a regular file of at most max_script_file bytes. nothing otherwise +// names a regular file of at most max_script_file bytes. nothing otherwise. '\' separates folders in Path as '/' does, +// on every system std::optional read_script_file(std::string const &Folder, std::string_view Path); // reads the script Path of Folder (as read_script_file), loads it as text and runs it in protected mode. nothing when diff --git a/tests/unit/test_lua_sandbox.cpp b/tests/unit/test_lua_sandbox.cpp index f23cb0406..6768e27ed 100644 --- a/tests/unit/test_lua_sandbox.cpp +++ b/tests/unit/test_lua_sandbox.cpp @@ -148,8 +148,11 @@ TEST_CASE("lua sandbox: a scenery reads its scripts only from its own folder") { CHECK(lua_sandbox::read_script_file(folder, "test.lua") == std::optional{"return 2"}); CHECK(lua_sandbox::read_script_file(folder, "scripts/module.lua") == std::optional{"return 3"}); + // '\' separates the folders on Linux too, as in the rest of the scenery's paths + CHECK(lua_sandbox::with_forward_slashes("a\\b/c\\d.lua") == "a/b/c/d.lua"); CHECK(lua_sandbox::read_script_file(folder, "scripts\\module.lua") == std::optional{"return 3"}); for (auto const &path : {std::string{"../outside.lua"}, std::string{"scripts/../../outside.lua"}, std::string{"..\\outside.lua"}, + std::string{"scripts\\..\\..\\outside.lua"}, std::string{"scripts/..\\../outside.lua"}, root.path("outside.lua"), std::string{"/outside.lua"}, std::string{"\\outside.lua"}, std::string{"C:outside.lua"}, std::string{"missing.lua"}, std::string{"folder.lua"}, std::string{"scripts"}, std::string{}}) { CAPTURE(path); From fde6d10f32a7d1ecbda8e462b275e9b5425a9e0a Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 13 Nov 2026 18:55:19 +0100 Subject: [PATCH 011/136] feat(scripting): file functions for the scenery Lua scripts The sandbox took io away from the scenery scripts; this gives them files back the way the Lua screens have them. The screens have eu07.read_file(path); the scenery state now gets it too, together with a write function and one to read the written files back: - eu07.read_file(path): a file of the scenery folder (scenery/), or nil. The path rule of `lua ` and the screens (relative, no '..', no drive, no leading separator), a regular file of at most 16 MB. - eu07.write_file(path, text): writes the file in the scenery's data folder, replacing it, and makes the folders of path. true, or nil and the reason. - eu07.read_data_file(path): a file of the data folder, or nil. The data folder is per scenery and among the player's files, next to the user eu07.ini and eu07_odometers.txt (user_config_path): %APPDATA%/MaSzyna/scenery_data//, ~/.config/MaSzyna/ on Linux. Nothing is written into the game folder; with no user folder, writes are refused. The log names the folder when the scenery loads its first script. Writes are limited to 1 MB a file, 256 files and 16 MB a data folder, and to relative paths of at most 200 bytes and 8 folders, of portable names: no '.', '..', empty names, :<>"|?* or control characters, no trailing dot or space, no Windows device names (con, nul, com1, lpt1...). The parent folder is checked with canonical paths, so a link in the data folder doesn't lead a write out of it. The code is in scripting/luasandbox.{h,cpp} (read_file, which read_script_file now uses, is_safe_write_path, write_data_file, scenery_data_folder, open_file_library); lua.cpp only opens the functions and sets the folders in interpret(). The screens keep their own read_screen_file, which #356 changes. Documented in the "Scenery scripts" section of script_screens_doc.md; 8 new cases in test_lua_sandbox.cpp. --- script_screens_doc.md | 27 ++++ scripting/lua.cpp | 13 ++ scripting/lua.h | 4 + scripting/luasandbox.cpp | 276 +++++++++++++++++++++++++++++++- scripting/luasandbox.h | 47 ++++++ tests/unit/test_lua_sandbox.cpp | 206 ++++++++++++++++++++++++ 6 files changed, 569 insertions(+), 4 deletions(-) diff --git a/script_screens_doc.md b/script_screens_doc.md index 4cdc5badd..435706fe4 100644 --- a/script_screens_doc.md +++ b/script_screens_doc.md @@ -223,6 +223,33 @@ and works with memcells, tracks and vehicles through the table `eu07.events` (`e - a script that fails stops there, the error goes to the log with the file name and line, and the scenery goes on loading. An event handler that fails is logged with the name of the event, and the simulation goes on. +Instead of `io`, a scenery script reads and writes files through `eu07`, as the Lua screens read theirs: + +| function | meaning | +|----------------------------------|------------------------------------------------------------------------------------------| +| `eu07.read_file(path)` | the contents of a file of the scenery folder (`scenery/`), or `nil`: a regular file of at most 16 MB, the path as for `lua ` | +| `eu07.write_file(path, text)` | writes `text` (any bytes) to a file of the scenery's data folder, replacing what was there, and makes the folders of `path`; returns `true`, or `nil` and the reason | +| `eu07.read_data_file(path)` | the contents of a file of the scenery's data folder, or `nil`: what `write_file` wrote there | + +The data folder is the scenery's own, in the player's folder of the game: `%APPDATA%\MaSzyna\scenery_data\\` +on Windows, `~/.config/MaSzyna/scenery_data//` on Linux (`~/Library/Application Support/MaSzyna/...` on a +Mac), `` being the `.scn` file without `.scn` (`td.scn`: `scenery_data/td/`). The game writes nowhere else +for a script, and never into its own folder; the log says where the folder is when the scenery loads its first +script. What is written there stays for the next run of the scenery, and the player may delete it. + +A path to write to is relative, with `/` or `\` between the folders, at most 8 folders deep and 200 bytes long, and +each name in it portable: no `..`, no `.`, no empty name, no drive, no `:` `<` `>` `"` `|` `?` `*` or control +characters, no `.` or space at the end, and none of the names Windows keeps for its devices (`con`, `nul`, `com1`, +`lpt1`... with or without an extension). A file is at most 1 MB (1048576 bytes), and the data folder of a scenery holds at most 256 +files and 16 MB together; a write over these limits is refused, and leaves the file as it was. + +```lua +local saved = eu07.read_data_file("state.txt") +local runs = tonumber(saved or "0") + 1 +local ok, reason = eu07.write_file("state.txt", tostring(runs)) +if not ok then eu07.events.writelog("state not saved: " .. reason) end +``` + A script written for the earlier full libraries stops at the first call to one of them (`attempt to index global 'io' (a nil value)` in the log). For a scenery you trust, `eu07.ini` can give the scripts all of LuaJIT's libraries again: diff --git a/scripting/lua.cpp b/scripting/lua.cpp index 0854579d9..7079bb2c3 100644 --- a/scripting/lua.cpp +++ b/scripting/lua.cpp @@ -6,6 +6,7 @@ #include "vehicle/Driver.h" #include "simulation/simulation.h" #include "scripting/luasandbox.h" +#include "utilities/utilities.h" lua::lua() { @@ -45,6 +46,9 @@ lua::lua() {nullptr, nullptr} }; luaL_register(state, "eu07.events", api); + lua_pop(state, 1); + // eu07.read_file, eu07.write_file and eu07.read_data_file, the files of the scenery in place of io + lua_sandbox::open_file_library(state, &files); } lua::~lua() @@ -67,6 +71,15 @@ void lua::interpret(const std::string &folder, const std::string &file) full_libraries = true; WriteLog("lua: lua.fulllibraries is on, the scenery scripts run with all libraries (io, os, ffi, require...)", logtype::lua); } + // the scripts read the files of the scenery folder, and write theirs into a folder of the scenery among the + // player's files (%APPDATA%/MaSzyna, ~/.config/MaSzyna), never into the game + files.scenery = folder; + if (auto data = lua_sandbox::scenery_data_folder(user_config_path("scenery_data"), Global.SceneryFile); data != files.data) { + files.data = std::move(data); + auto const name = files.data.u8string(); + if (!name.empty()) + WriteLog("lua: the scenery scripts write their files (eu07.write_file) to \"" + std::string(name.begin(), name.end()) + "\"", logtype::lua); + } // a relative path inside the scenery folder, a file of text, run in protected mode: a script that fails stops // there, and the scenery goes on loading if (auto const error = lua_sandbox::run_script_file(state, folder, file)) { diff --git a/scripting/lua.h b/scripting/lua.h index 8663103df..a0a2b9333 100644 --- a/scripting/lua.h +++ b/scripting/lua.h @@ -1,6 +1,7 @@ #pragma once #include #include +#include "scripting/luasandbox.h" class basic_event; class TMemCell; @@ -11,6 +12,9 @@ class lua { lua_State *state; bool full_libraries = false; // lua.fulllibraries: all of LuaJIT's libraries opened + // what eu07.read_file reads (the scenery folder) and eu07.write_file writes (the scenery's data folder), known + // when the scenery loads its scripts (interpret()) + lua_sandbox::file_folders files; static int atpanic(lua_State *s); diff --git a/scripting/luasandbox.cpp b/scripting/luasandbox.cpp index ea5f98a88..bf6ab3961 100644 --- a/scripting/luasandbox.cpp +++ b/scripting/luasandbox.cpp @@ -15,6 +15,8 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include +#include #include namespace lua_sandbox @@ -121,22 +123,23 @@ bool load_text_chunk(lua_State *L, std::string_view const Code, std::string cons return 0 == luaL_loadbufferx(L, Code.data(), Code.size(), ("@" + Name).c_str(), "t"); } -std::optional read_script_file(std::string const &Folder, std::string_view const Path) +std::optional read_file(std::filesystem::path const &Folder, std::string_view const Path, std::uintmax_t const Limit) { - if (false == script_screens::is_safe_relative_path(Path)) + // a NUL would end the name the system sees + if (false == script_screens::is_safe_relative_path(Path) || Path.find('\0') != std::string_view::npos) { return std::nullopt; } // a folder or a device (CON, NUL, COM1...) isn't a regular file. in the code page of the system, as the game opens // its files - std::filesystem::path const path{Folder + with_forward_slashes(Path)}; + auto const path{Folder / with_forward_slashes(Path)}; std::error_code error; if (false == std::filesystem::is_regular_file(path, error)) { return std::nullopt; } auto const size{std::filesystem::file_size(path, error)}; - if (error || size > max_script_file) + if (error || size > Limit) { return std::nullopt; } @@ -152,6 +155,11 @@ std::optional read_script_file(std::string const &Folder, std::stri return contents; } +std::optional read_script_file(std::string const &Folder, std::string_view const Path) +{ + return read_file(std::filesystem::path{Folder}, Path, max_script_file); +} + std::optional run_script_file(lua_State *L, std::string const &Folder, std::string_view const Path) { auto const name{Folder + std::string{Path}}; @@ -172,4 +180,264 @@ std::optional run_script_file(lua_State *L, std::string const &Fold return std::nullopt; } +namespace +{ + +char lower_case(char const Character) +{ + return Character >= 'A' && Character <= 'Z' ? static_cast(Character - 'A' + 'a') : Character; +} + +// the names Windows opens as its devices, whatever the extension +bool is_device_name(std::string_view Name) +{ + // the extension, and the spaces before it, don't count ("nul.txt", "con .log") + Name = Name.substr(0, Name.find('.')); + while (false == Name.empty() && Name.back() == ' ') + { + Name.remove_suffix(1); + } + std::string name; + std::ranges::transform(Name, std::back_inserter(name), lower_case); + if (name == "con" || name == "prn" || name == "aux" || name == "nul" || name == "conin$" || name == "conout$") + { + return true; + } + return name.size() == 4 && (name.starts_with("com") || name.starts_with("lpt")) && name[3] >= '0' && name[3] <= '9'; +} + +// a name of a file or a folder that every system takes as it is +bool is_portable_name(std::string_view const Name) +{ + if (Name.empty() || Name == "." || Name == ".." || Name.back() == '.' || Name.back() == ' ') + { + return false; + } + for (auto const character : Name) + { + if (static_cast(character) < 0x20 || character == 0x7f || + std::string_view{"<>:\"|?*"}.find(character) != std::string_view::npos) + { + return false; + } + } + return false == is_device_name(Name); +} + +// true when Path, a canonical path, is Folder, a canonical path, or inside it +bool is_inside(std::filesystem::path const &Path, std::filesystem::path const &Folder) +{ + return std::mismatch(Folder.begin(), Folder.end(), Path.begin(), Path.end()).first == Folder.end(); +} + +file_folders const &folders_of(lua_State *L) +{ + return *static_cast(lua_touserdata(L, lua_upvalueindex(1))); +} + +std::string_view check_text(lua_State *L, int const Index) +{ + std::size_t length{0}; + auto const *text{luaL_checklstring(L, Index, &length)}; + return {text, length}; +} + +void push_contents(lua_State *L, std::optional const &Contents) +{ + if (Contents.has_value()) + { + lua_pushlstring(L, Contents->data(), Contents->size()); + } + else + { + lua_pushnil(L); + } +} + +// eu07.read_file(path): the contents of a file of the scenery folder, or nil +int api_read_file(lua_State *L) +{ + auto const path{check_text(L, 1)}; + auto const &folders{folders_of(L)}; + push_contents(L, folders.scenery.empty() ? std::nullopt : read_file(folders.scenery, path, max_script_file)); + return 1; +} + +// eu07.read_data_file(path): the contents of a file of the scenery's data folder, or nil +int api_read_data_file(lua_State *L) +{ + auto const path{check_text(L, 1)}; + auto const &folders{folders_of(L)}; + push_contents(L, folders.data.empty() ? std::nullopt : read_file(folders.data, path, max_data_file)); + return 1; +} + +// eu07.write_file(path, text): writes the file of the scenery's data folder. true, or nil and why not +int api_write_file(lua_State *L) +{ + auto const path{check_text(L, 1)}; + auto const contents{check_text(L, 2)}; + if (auto const error{write_data_file(folders_of(L).data, path, contents)}; error.has_value()) + { + lua_pushnil(L); + lua_pushlstring(L, error->data(), error->size()); + return 2; + } + lua_pushboolean(L, 1); + return 1; +} + +} // namespace + +bool is_safe_write_path(std::string_view const Path) +{ + if (Path.size() > max_data_path || false == script_screens::is_safe_relative_path(Path)) + { + return false; + } + std::size_t names{0}; + std::size_t start{0}; + while (start <= Path.size()) + { + auto const end{std::min(Path.find_first_of("/\\", start), Path.size())}; + if (false == is_portable_name(Path.substr(start, end - start))) + { + return false; + } + ++names; + start = end + 1; + } + // the folders, and the file in them + return names <= max_data_depth + 1; +} + +std::optional write_data_file(std::filesystem::path const &Folder, std::string_view const Path, std::string_view const Contents) +{ + namespace fs = std::filesystem; + std::string const name{Path}; + if (Folder.empty()) + { + return name + ": no folder to write to (the game knows no folder of the player)"; + } + if (false == is_safe_write_path(Path)) + { + return name + ": not a path to write to (a relative path of portable names, at most " + std::to_string(max_data_path) + + " bytes and " + std::to_string(max_data_depth) + " folders deep, without '..')"; + } + if (Contents.size() > max_data_file) + { + return name + ": larger than " + std::to_string(max_data_file) + " bytes"; + } + auto const target{Folder / with_forward_slashes(Path)}; + std::error_code error; + // a link, a folder or anything else that isn't a file stays as it is + auto const status{fs::symlink_status(target, error)}; + auto const exists{status.type() != fs::file_type::not_found}; + if (exists && status.type() != fs::file_type::regular) + { + return name + ": not a file"; + } + std::uintmax_t replaced{0}; + if (exists) + { + replaced = fs::file_size(target, error); + if (error) + { + return name + ": can't be replaced"; + } + } + // what the folder holds, and will hold with the file in place of what was there + std::uintmax_t held{0}; + std::size_t files{0}; + if (fs::is_directory(Folder, error)) + { + for (fs::recursive_directory_iterator entry{Folder, error}, end; !error && entry != end; entry.increment(error)) + { + std::error_code entryerror; + if (entry->symlink_status(entryerror).type() == fs::file_type::regular) + { + auto const size{entry->file_size(entryerror)}; + held += entryerror ? 0 : size; + ++files; + } + } + if (error) + { + return name + ": the data folder can't be read"; + } + } + if (files + (exists ? 0 : 1) > max_data_files) + { + return name + ": the data folder holds " + std::to_string(max_data_files) + " files already"; + } + if (held - std::min(replaced, held) + Contents.size() > max_data_folder) + { + return name + ": the data folder would hold more than " + std::to_string(max_data_folder) + " bytes"; + } + fs::create_directories(target.parent_path(), error); + if (error) + { + return name + ": its folder can't be made"; + } + // still inside the data folder, should a link in it lead elsewhere + auto const root{fs::canonical(Folder, error)}; + auto const parent{error ? fs::path{} : fs::canonical(target.parent_path(), error)}; + if (error || false == is_inside(parent, root)) + { + return name + ": outside the data folder"; + } + std::ofstream file{parent / target.filename(), std::ios::binary | std::ios::trunc}; + if (false == file.is_open()) + { + return name + ": can't be opened to write"; + } + file.write(Contents.data(), static_cast(Contents.size())); + file.close(); + if (file.fail()) + { + return name + ": couldn't be written whole"; + } + return std::nullopt; +} + +std::filesystem::path scenery_data_folder(std::filesystem::path const &Root, std::string_view const Scenery) +{ + auto name{with_forward_slashes(Scenery)}; + if (name.size() >= 4) + { + std::string extension; + std::ranges::transform(std::string_view{name}.substr(name.size() - 4), std::back_inserter(extension), lower_case); + if (extension == ".scn") + { + name.resize(name.size() - 4); + } + } + if (Root.empty() || false == is_safe_write_path(name)) + { + return {}; + } + return Root / name; +} + +void open_file_library(lua_State *L, file_folders const *Folders) +{ + // eu07, which the scenery scripts have for eu07.events, made when there is none + lua_getglobal(L, "eu07"); + if (false == lua_istable(L, -1)) + { + lua_pop(L, 1); + lua_newtable(L); + lua_pushvalue(L, -1); + lua_setglobal(L, "eu07"); + } + for (auto const &[name, function] : {std::pair{"read_file", api_read_file}, std::pair{"write_file", api_write_file}, + std::pair{"read_data_file", api_read_data_file}}) + { + lua_pushlightuserdata(L, const_cast(Folders)); + lua_pushcclosure(L, function, 1); + lua_setfield(L, -2, name); + } + lua_pop(L, 1); +} + } // namespace lua_sandbox diff --git a/scripting/luasandbox.h b/scripting/luasandbox.h index 167060026..5f57c62af 100644 --- a/scripting/luasandbox.h +++ b/scripting/luasandbox.h @@ -15,7 +15,9 @@ http://mozilla.org/MPL/2.0/. #include +#include #include +#include #include #include #include @@ -51,4 +53,49 @@ std::optional read_script_file(std::string const &Folder, std::stri // it ran, otherwise why it didn't std::optional run_script_file(lua_State *L, std::string const &Folder, std::string_view Path); +// the files a scenery script reads and writes itself (eu07.read_file, eu07.write_file, eu07.read_data_file): it reads +// the files of the scenery folder, and writes only into a data folder of its scenery, outside the game + +// the largest file a script writes, all the files of a data folder together, and how many files a data folder holds +constexpr std::uintmax_t max_data_file{1024 * 1024}; +constexpr std::uintmax_t max_data_folder{16 * 1024 * 1024}; +constexpr std::size_t max_data_files{256}; +// the longest path a script writes to, and how many folders deep it goes +constexpr std::size_t max_data_path{200}; +constexpr std::size_t max_data_depth{8}; + +// the file Path of Folder, when Path is a relative path inside Folder (as read_script_file) and names a regular file of +// at most Limit bytes. nothing otherwise +std::optional read_file(std::filesystem::path const &Folder, std::string_view Path, std::uintmax_t Limit); + +// true for a path a script may write to: a relative path inside the folder (is_safe_relative_path), '/' or '\' between +// the folders, at most max_data_path bytes and max_data_depth folders deep, each name portable: not empty, not '.' or +// '..', none of the characters Windows refuses (: < > " | ? * and the control characters), no '.' or ' ' at the end, +// and not a device of Windows (con, prn, aux, nul, com0-9, lpt0-9, conin$, conout$, with an extension or without) +bool is_safe_write_path(std::string_view Path); + +// writes Contents to the file Path of Folder (a data folder), replacing what was there, and makes Folder and the folders +// of Path. refused for a path that isn't safe (is_safe_write_path), for more than max_data_file bytes, when Folder would +// hold more than max_data_files files or max_data_folder bytes, when Path names something else than a file, and when it +// leads out of Folder through a link. nothing when written, otherwise why not +std::optional write_data_file(std::filesystem::path const &Folder, std::string_view Path, std::string_view Contents); + +// the data folder of the scenery Scenery (its .scn file, relative to the scenery folder) in Root: Root and the file +// without ".scn" (td.scn: Root/td). empty when Root is, or the name isn't a safe path (is_safe_write_path) +std::filesystem::path scenery_data_folder(std::filesystem::path const &Root, std::string_view Scenery); + +// where the file functions of a scenery script read and write +struct file_folders +{ + // the scenery folder, which eu07.read_file reads, ending with a separator. empty: nothing is read + std::string scenery; + // the data folder of the scenery, which eu07.write_file writes and eu07.read_data_file reads. empty: nothing is + // written there or read from it + std::filesystem::path data; +}; + +// adds eu07.read_file(path), eu07.write_file(path, text) and eu07.read_data_file(path) to the state, on the folders of +// Folders, read on every call: Folders is to outlive the state +void open_file_library(lua_State *L, file_folders const *Folders); + } // namespace lua_sandbox diff --git a/tests/unit/test_lua_sandbox.cpp b/tests/unit/test_lua_sandbox.cpp index 6768e27ed..344f51c63 100644 --- a/tests/unit/test_lua_sandbox.cpp +++ b/tests/unit/test_lua_sandbox.cpp @@ -12,6 +12,7 @@ #include "scripting/luasandbox.h" #include "scratch.h" +#include #include #include #include @@ -218,4 +219,209 @@ TEST_CASE("lua sandbox: a scenery script runs in protected mode, and its errors CHECK(lua.run("return ran") == "11"); } +TEST_CASE("lua sandbox: eu07.read_file reads a file of the scenery folder, and nothing outside it") { + test::scratch_folder const root{"lua_sandbox_read"}; + root.write("outside.txt", "secret"); + root.write("scenery/data.txt", "line 1\nline 2"); + root.write("scenery/sub/more.txt", "more"); + root.write("scenery/folder/inner.txt", "inner"); + auto const folder{std::filesystem::path{root.path("scenery")}}; + + CHECK(lua_sandbox::read_file(folder, "data.txt", 100) == std::optional{"line 1\nline 2"}); + CHECK(lua_sandbox::read_file(folder, "sub/more.txt", 100) == std::optional{"more"}); + CHECK(lua_sandbox::read_file(folder, "sub\\more.txt", 100) == std::optional{"more"}); + // the limit is the caller's + CHECK(lua_sandbox::read_file(folder, "sub/more.txt", 4).has_value()); + CHECK_FALSE(lua_sandbox::read_file(folder, "sub/more.txt", 3).has_value()); + for (auto const &path : {std::string{"../outside.txt"}, std::string{"sub/../../outside.txt"}, std::string{"..\\outside.txt"}, + std::string{"sub\\..\\..\\outside.txt"}, root.path("outside.txt"), std::string{"/outside.txt"}, + std::string{"\\outside.txt"}, std::string{"C:outside.txt"}, std::string{"missing.txt"}, + std::string{"folder"}, std::string{}, std::string{"data.txt\0x", 10}}) { + CAPTURE(path); + CHECK_FALSE(lua_sandbox::read_file(folder, path, 100).has_value()); + } +} + +TEST_CASE("lua sandbox: the paths a script may write to") { + for (auto const *path : {"state.txt", "saves/state.txt", "saves\\state.txt", "a/b/c/d/e/f/g/h/file.txt", "con_log.txt", "comx.txt", + "com10.txt", "nul_state", ".hidden", "stan poci\xc4\x85gu.txt", "a..b"}) { + CAPTURE(path); + CHECK(lua_sandbox::is_safe_write_path(path)); + } + for (auto const &path : {std::string{}, std::string{".."}, std::string{"../x.txt"}, std::string{"a/../../x.txt"}, std::string{"..\\x.txt"}, + std::string{"/x.txt"}, std::string{"\\x.txt"}, std::string{"C:x.txt"}, std::string{"C:\\x.txt"}, + std::string{"x.txt:stream"}, std::string{"a//b.txt"}, std::string{"a/"}, std::string{"./x.txt"}, + std::string{"a/./x.txt"}, std::string{"con"}, std::string{"CON.txt"}, std::string{"saves/nul.dat"}, + std::string{"Com1"}, std::string{"lpt9.log"}, std::string{"aux"}, std::string{"prn.x.y"}, + std::string{"conin$"}, std::string{"CONOUT$.txt"}, std::string{"con .txt"}, std::string{"ab"}, std::string{"a\"b"}, std::string{"a|b"}, std::string{"a?b"}, std::string{"a*b"}, + std::string{"x."}, std::string{"x "}, std::string{"dir./x"}, std::string{"a\tb"}, std::string{"a\nb"}, + std::string{"a\0b", 3}, std::string{"a/b/c/d/e/f/g/h/i/file.txt"}, + std::string(lua_sandbox::max_data_path + 1, 'x')}) { + CAPTURE(path); + CHECK_FALSE(lua_sandbox::is_safe_write_path(path)); + } + CHECK(lua_sandbox::is_safe_write_path(std::string(lua_sandbox::max_data_path, 'x'))); +} + +TEST_CASE("lua sandbox: a script writes into its data folder only, and reads back what it wrote") { + test::scratch_folder const root{"lua_sandbox_write"}; + root.write("outside.txt", "kept"); + auto const data{root.root() / "data" / "td"}; + + // the folder is made with the first file + CHECK_FALSE(lua_sandbox::write_data_file(data, "state.txt", "runs=1").has_value()); + CHECK(lua_sandbox::read_file(data, "state.txt", lua_sandbox::max_data_file) == std::optional{"runs=1"}); + // replaced, not appended + CHECK_FALSE(lua_sandbox::write_data_file(data, "state.txt", "runs=2").has_value()); + CHECK(lua_sandbox::read_file(data, "state.txt", lua_sandbox::max_data_file) == std::optional{"runs=2"}); + // any bytes, and the folders of the path + std::string const bytes{"a\0b\r\n\xff", 6}; + CHECK_FALSE(lua_sandbox::write_data_file(data, "saves\\day 1/bin.dat", bytes).has_value()); + CHECK(lua_sandbox::read_file(data, "saves/day 1/bin.dat", lua_sandbox::max_data_file) == std::optional{bytes}); + CHECK_FALSE(lua_sandbox::write_data_file(data, "empty.txt", "").has_value()); + CHECK(lua_sandbox::read_file(data, "empty.txt", lua_sandbox::max_data_file) == std::optional{""}); + + // nothing outside the folder + for (auto const *path : {"../outside.txt", "../../outside.txt", "..\\outside.txt", "saves/../../outside.txt", "nul", "con.txt", "x:y"}) { + CAPTURE(path); + auto const error{lua_sandbox::write_data_file(data, path, "overwritten")}; + REQUIRE(error.has_value()); + CHECK(contains(*error, "not a path to write to")); + } + CHECK(lua_sandbox::write_data_file(data, root.path("outside.txt"), "overwritten").has_value()); + CHECK(lua_sandbox::read_file(root.root(), "outside.txt", 100) == std::optional{"kept"}); + // a folder isn't replaced by a file + auto const folder{lua_sandbox::write_data_file(data, "saves", "x")}; + REQUIRE(folder.has_value()); + CHECK(contains(*folder, "not a file")); + CHECK(std::filesystem::is_directory(data / "saves")); + // no folder (the game knows no folder of the player), nothing written + CHECK(lua_sandbox::write_data_file(std::filesystem::path{}, "state.txt", "x").has_value()); +} + +TEST_CASE("lua sandbox: the limits of a data folder") { + test::scratch_folder const root{"lua_sandbox_limits"}; + auto const data{root.root() / "data"}; + std::string const full(static_cast(lua_sandbox::max_data_file), 'x'); + + SUBCASE("a file") { + CHECK_FALSE(lua_sandbox::write_data_file(data, "full.txt", full).has_value()); + CHECK(lua_sandbox::read_file(data, "full.txt", lua_sandbox::max_data_file).has_value()); + auto const over{lua_sandbox::write_data_file(data, "full.txt", full + "x")}; + REQUIRE(over.has_value()); + CHECK(contains(*over, "larger than")); + // the file stays as it was + CHECK(std::filesystem::file_size(data / "full.txt") == lua_sandbox::max_data_file); + } + SUBCASE("the bytes of the folder") { + auto const files{static_cast(lua_sandbox::max_data_folder / lua_sandbox::max_data_file)}; + for (int idx = 0; idx < files; ++idx) { + REQUIRE_FALSE(lua_sandbox::write_data_file(data, std::format("part{}.dat", idx), full).has_value()); + } + auto const over{lua_sandbox::write_data_file(data, "one_more.dat", "x")}; + REQUIRE(over.has_value()); + CHECK(contains(*over, "more than")); + CHECK_FALSE(std::filesystem::exists(data / "one_more.dat")); + // a file replaced counts with its new size: as large again fits, and a smaller one makes room + CHECK_FALSE(lua_sandbox::write_data_file(data, "part0.dat", full).has_value()); + CHECK_FALSE(lua_sandbox::write_data_file(data, "part0.dat", "small").has_value()); + CHECK_FALSE(lua_sandbox::write_data_file(data, "one_more.dat", "x").has_value()); + } + SUBCASE("the files of the folder") { + for (std::size_t idx = 0; idx < lua_sandbox::max_data_files; ++idx) { + REQUIRE_FALSE(lua_sandbox::write_data_file(data, std::format("sub{}/file{}.txt", idx % 4, idx), "x").has_value()); + } + auto const over{lua_sandbox::write_data_file(data, "one_more.txt", "x")}; + REQUIRE(over.has_value()); + CHECK(contains(*over, "files already")); + CHECK_FALSE(std::filesystem::exists(data / "one_more.txt")); + // one that is there is still replaced + CHECK_FALSE(lua_sandbox::write_data_file(data, "sub0/file0.txt", "y").has_value()); + } +} + +TEST_CASE("lua sandbox: a link in the data folder doesn't lead a write out of it") { + test::scratch_folder const root{"lua_sandbox_link"}; + root.write("outside/kept.txt", "kept"); + auto const data{root.root() / "data"}; + std::filesystem::create_directories(data); + std::error_code error; + std::filesystem::create_directory_symlink(root.root() / "outside", data / "link", error); + if (error) { + // Windows makes links only for an administrator or in developer mode + MESSAGE("no folder link made (" << error.message() << "), not tested"); + return; + } + auto const written{lua_sandbox::write_data_file(data, "link/kept.txt", "overwritten")}; + REQUIRE(written.has_value()); + CHECK(contains(*written, "outside the data folder")); + CHECK(lua_sandbox::read_file(root.root(), "outside/kept.txt", 100) == std::optional{"kept"}); +} + +TEST_CASE("lua sandbox: the data folder of a scenery") { + std::filesystem::path const root{"user/scenery_data"}; + CHECK(lua_sandbox::scenery_data_folder(root, "td.scn") == root / "td"); + CHECK(lua_sandbox::scenery_data_folder(root, "Td.SCN") == root / "Td"); + CHECK(lua_sandbox::scenery_data_folder(root, "lines\\l107.scn") == root / "lines/l107"); + CHECK(lua_sandbox::scenery_data_folder(root, "test.scm") == root / "test.scm"); + for (auto const *scenery : {"", ".scn", "../td.scn", "/td.scn", "C:td.scn", "con.scn"}) { + CAPTURE(scenery); + CHECK(lua_sandbox::scenery_data_folder(root, scenery).empty()); + } + CHECK(lua_sandbox::scenery_data_folder(std::filesystem::path{}, "td.scn").empty()); +} + +TEST_CASE("lua sandbox: the file functions of a scenery script") { + test::scratch_folder const root{"lua_sandbox_api"}; + root.write("outside.txt", "secret"); + root.write("scenery/settings.txt", "speed=40"); + lua_sandbox::file_folders folders{root.path("scenery") + "/", root.root() / "data" / "td"}; + + sandboxed_state const lua; + // next to eu07.events, as the scenery state has it + REQUIRE_FALSE(luaL_dostring(lua.get(), "eu07 = { events = { marker = 1 } }")); + lua_sandbox::open_file_library(lua.get(), &folders); + auto const top{lua_gettop(lua.get())}; + + CHECK(lua.run("return eu07.events.marker") == "1"); + CHECK(lua.run("return eu07.read_file('settings.txt')") == "speed=40"); + CHECK(lua.run("return eu07.read_file('../outside.txt')") == "nil"); + CHECK(lua.run("return eu07.read_file('missing.txt')") == "nil"); + CHECK(lua.run("return eu07.read_data_file('state.txt')") == "nil"); + CHECK(lua.run("return eu07.write_file('state.txt', 'runs=' .. 1)") == "true"); + CHECK(lua.run("return eu07.read_data_file('state.txt')") == "runs=1"); + // the scenery folder and the data folder are apart + CHECK(lua.run("return eu07.read_file('state.txt')") == "nil"); + CHECK(lua.run("return eu07.read_data_file('../../scenery/settings.txt')") == "nil"); + // a number is written as its text + CHECK(lua.run("return eu07.write_file('number.txt', 42)") == "true"); + CHECK(lua.run("return eu07.read_data_file('number.txt')") == "42"); + // a refused write gives nil and the reason + CHECK(lua.run("local ok, reason = eu07.write_file('../outside.txt', 'x') return tostring(ok) .. ' ' .. reason") == + "nil ../outside.txt: not a path to write to (a relative path of portable names, at most 200 bytes and 8 folders deep, without '..')"); + CHECK(lua.run("local ok, reason = eu07.write_file('big.txt', string.rep('x', 1024 * 1024 + 1)) return reason") == + "big.txt: larger than 1048576 bytes"); + CHECK(lua_sandbox::read_file(root.root(), "outside.txt", 100) == std::optional{"secret"}); + // the arguments are checked + CHECK(contains(lua.run("return eu07.write_file('x.txt')"), "bad argument #2")); + CHECK(contains(lua.run("return eu07.read_file()"), "bad argument #1")); + CHECK(contains(lua.run("return eu07.write_file({}, 'x')"), "bad argument #1")); + + // the folders are read on every call: without a data folder nothing is written or read there + folders.data.clear(); + CHECK(lua.run("local ok, reason = eu07.write_file('state.txt', 'x') return tostring(ok) .. ' ' .. reason") == + "nil state.txt: no folder to write to (the game knows no folder of the player)"); + CHECK(lua.run("return eu07.read_data_file('state.txt')") == "nil"); + CHECK(lua_gettop(lua.get()) == top); +} + +TEST_CASE("lua sandbox: the file functions make eu07 when there is none") { + lua_sandbox::file_folders const folders; + sandboxed_state const lua; + lua_sandbox::open_file_library(lua.get(), &folders); + CHECK(lua.run("return type(eu07.read_file) .. type(eu07.write_file) .. type(eu07.read_data_file)") == "functionfunctionfunction"); + CHECK(lua.run("return eu07.read_file('x.txt')") == "nil"); +} + #endif From 33609881449216d2731cdc6501ba3907279e88f9 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 10:28:06 +0100 Subject: [PATCH 012/136] feat(physics): criteria of derailment: overturning and flange climbing held over 2 m McZapkie/derailment.{h,cpp} in eu07_core: plain functions of the vehicle and the track under it, for the speed in a curve now and the collisions and the buckled track later. - overturning: the wheel unloading D = 2/s * a/g * (h + s0 (h - hc)) of the lateral acceleration the cant doesn't balance, v^2/R - g sin(cant), with the lean of the body on its suspension (s0 0.4, hc 0.5 m of the kinematic gauge), a lateral vibration of 0.05 g and the uneven track; over at D = 1 - flange climbing: Y/Q of the flanging wheel over 1.2 (Nadal, 70 degrees, friction 0.36). Y from the force the cant doesn't balance, the sideways part of the forces of the couplings in the curve and the guiding force of the leading axle; Q with the load the lateral forces move onto the wheel and the twist of the track takes off it - either has to hold over 2 m of track (the window of EN 14363), so the decision doesn't depend on the step - the centre of gravity of a vehicle from the height of its body, raised by the load; the friction of a vehicle sliding off the rails --- CMakeLists.txt | 1 + McZapkie/derailment.cpp | 232 +++++++++++++++++++++++++++++++++ McZapkie/derailment.h | 204 +++++++++++++++++++++++++++++ tests/unit/test_derailment.cpp | 227 ++++++++++++++++++++++++++++++++ 4 files changed, 664 insertions(+) create mode 100644 McZapkie/derailment.cpp create mode 100644 McZapkie/derailment.h create mode 100644 tests/unit/test_derailment.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index e97e41d03..76f359eab 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -537,6 +537,7 @@ set(CORE_SOURCES "McZapkie/hamulce.cpp" "McZapkie/Mover.cpp" "McZapkie/couplerphysics.cpp" +"McZapkie/derailment.cpp" "McZapkie/Oerlikon_ESt.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" diff --git a/McZapkie/derailment.cpp b/McZapkie/derailment.cpp new file mode 100644 index 000000000..382c5c14e --- /dev/null +++ b/McZapkie/derailment.cpp @@ -0,0 +1,232 @@ +/* +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 "derailment.h" + +#include +#include + +namespace derailment { + +namespace { + +// a curve with a radius under this is taken for a straight track [m] +constexpr double straight{1e-3}; + +bool curved(double const Radius) { + return std::abs(Radius) > straight; +} + +// the height the lateral force on the body acts at, with the lean of the body on its suspension [m] +double leaning_height(double const CentreOfGravity, suspension const &Suspension) { + return CentreOfGravity + Suspension.flexibility * std::max(0.0, CentreOfGravity - Suspension.roll_centre); +} + +bool has(int const Flags, int const Flag) { + return (Flags & Flag) != 0; +} + +// the acceleration [m/s2] of what moves with the track sideways, besides the curve: the sway of the body and the +// short waves of an uneven track +double dynamic_acceleration(track_state const &Track, double const Velocity) { + return body_vibration(Velocity) + uneven_share * Velocity * Velocity * std::abs(Track.uneven_curvature); +} + +// the sideways force of the couplings of both ends on the vehicle, positive out of the curve [N]: pushed in, the +// ends go out of the curve, pulled out, they go into it +double coupling_force(vehicle_state const &Vehicle, track_state const &Track) { + auto force{0.0}; + for (auto const &end : Vehicle.ends) { + force += end.compression * std::sin(coupling_angle(Vehicle.length, end.other_length, Track.radius)); + } + return force; +} + +} // namespace + +double contact_spacing(double const Gauge) { + return Gauge + rail_head_width; +} + +double default_centre_of_gravity(double const BodyHeight, vehicle_class const Class) { + auto const body{BodyHeight > 2.0 ? BodyHeight : 4.0}; + return body * (Class == vehicle_class::powered ? 0.38 : 0.35); +} + +double loaded_centre_of_gravity(double const EmptyHeight, double const EmptyMass, double const LoadMass, double const LoadShare, double const Floor, double const BodyHeight) { + if (LoadMass <= 0.0 || EmptyMass + LoadMass <= 0.0) { + return EmptyHeight; + } + auto const body{BodyHeight > 2.0 ? BodyHeight : 4.0}; + // a floor not given (or the older meaning of the keys) is that of a wagon + auto const floor{Floor > 0.3 ? Floor : 1.2}; + auto const load{floor + 0.5 * std::max(0.0, body - floor) * std::clamp(LoadShare, 0.0, 1.0)}; + return (EmptyHeight * EmptyMass + load * LoadMass) / (EmptyMass + LoadMass); +} + +double unbalanced_acceleration(double const Velocity, double const Radius, double const Cant) { + auto const cant{gravity * std::sin(std::abs(Cant))}; + if (false == curved(Radius)) { + return -cant; + } + return Velocity * Velocity / std::abs(Radius) - cant; +} + +double unloading_ratio(double const Acceleration, double const CentreOfGravity, double const ContactSpacing, suspension const &Suspension) { + return 2.0 / ContactSpacing * std::abs(Acceleration) / gravity * leaning_height(CentreOfGravity, Suspension); +} + +double overturning_acceleration(double const CentreOfGravity, double const ContactSpacing, suspension const &Suspension) { + return gravity * ContactSpacing / (2.0 * leaning_height(CentreOfGravity, Suspension)); +} + +double body_vibration(double const Velocity) { + return vibration * std::min(1.0, std::abs(Velocity) / (100.0 / 3.6)); +} + +double overturning_speed(double const Radius, double const Cant, double const CentreOfGravity, double const Gauge) { + if (false == curved(Radius)) { + return 0.0; + } + vehicle_state vehicle; + vehicle.mass = 1.0; + vehicle.centre_of_gravity = CentreOfGravity; + track_state track; + track.radius = Radius; + track.cant = Cant; + track.gauge = Gauge; + auto const spacing{contact_spacing(Gauge)}; + // the unloading grows with the speed: halve the range until the speed of D = 1 is found + auto low{0.0}; + auto high{200.0}; + for (int iteration = 0; iteration < 60; ++iteration) { + auto const middle{0.5 * (low + high)}; + auto const acceleration{body_acceleration(vehicle, track, middle)}; + // below the balancing speed the cant leans the vehicle the other way + auto const outwards{unbalanced_acceleration(middle, Radius, Cant) > 0.0}; + if (outwards && unloading_ratio(acceleration, CentreOfGravity, spacing) >= 1.0) { + high = middle; + } + else { + low = middle; + } + } + return high; +} + +double nadal_limit(double const FlangeAngle, double const Friction) { + auto const slope{std::tan(FlangeAngle)}; + return (slope - Friction) / (1.0 + Friction * slope); +} + +track_condition condition_of(track_state const &Track) { + track_condition condition; + // as the legacy criterion had it, a loose rail sways the vehicles 1.4 times as much + condition.lateral = 1.0 + 0.4 * has(Track.damage, track_damage::freerail) + 0.5 * has(Track.damage, track_damage::railbend) + 0.1 * has(Track.damage, track_damage::railwear) + + 0.1 * has(Track.damage, track_damage::thinrail); + // the twist of the track lifts a wheel: 1 % of its load for each mm of cross level, up to the 0.6 the twist test + // of EN 14363 lets the load drop by + condition.unloading = std::min(0.6, 0.01 * std::max(0.0, Track.uneven_cross) + 0.1 * has(Track.damage, track_damage::freerail) + 0.1 * has(Track.damage, track_damage::railbend)); + return condition; +} + +double coupling_angle(double const Length, double const OtherLength, double const Radius) { + if (false == curved(Radius) || OtherLength <= 0.0) { + return 0.0; + } + return (Length + OtherLength) / (4.0 * std::abs(Radius)); +} + +wheel_forces flange_forces(vehicle_state const &Vehicle, track_state const &Track, double const Velocity) { + wheel_forces result; + if (Vehicle.mass <= 0.0) { + return result; + } + auto const axles{static_cast(std::max(Vehicle.axles, 1))}; + auto const condition{condition_of(Track)}; + auto const spacing{contact_spacing(Track.gauge)}; + auto const height{leaning_height(Vehicle.centre_of_gravity, suspension{})}; + auto const staticload{Vehicle.mass * gravity / (2.0 * axles)}; + + auto const inertia{Vehicle.mass * unbalanced_acceleration(Velocity, Track.radius, Track.cant)}; + auto const couplings{coupling_force(Vehicle, Track)}; + auto const quasistatic{inertia + couplings}; + // the sway and the uneven track push the worst way: towards the rail the vehicle already leans on + auto const direction{quasistatic >= 0.0 ? 1.0 : -1.0}; + auto const dynamic{Vehicle.mass * dynamic_acceleration(Track, Velocity)}; + result.lateral = direction * (std::abs(quasistatic) + dynamic) * condition.lateral; + + // the leading axle meets the rail at an angle in a curve, the creep force of its inner wheel at most the friction + auto guiding{0.0}; + if (curved(Track.radius)) { + auto const attack{Vehicle.axle_base / (2.0 * std::abs(Track.radius))}; + guiding = tread_friction * staticload * std::min(1.0, attack / saturated_attack); + } + result.y = std::abs(result.lateral) / axles + guiding; + + // the lateral forces at their heights move the load onto the wheels they push towards + auto const moment{(direction * (inertia * height + couplings * buffer_height) + dynamic * height) * condition.lateral}; + auto const shift{moment / (spacing * axles)}; + result.q = std::max(0.0, (staticload + shift) * (1.0 - condition.unloading)); + return result; +} + +double body_acceleration(vehicle_state const &Vehicle, track_state const &Track, double const Velocity) { + if (Vehicle.mass <= 0.0) { + return 0.0; + } + auto const height{leaning_height(Vehicle.centre_of_gravity, suspension{})}; + // the couplings pull at the height of the buffers: as much of a lean as their moment gives + auto const moment{Vehicle.mass * unbalanced_acceleration(Velocity, Track.radius, Track.cant) * height + coupling_force(Vehicle, Track) * buffer_height}; + return (std::abs(moment) / (Vehicle.mass * height) + dynamic_acceleration(Track, Velocity)) * condition_of(Track).lateral; +} + +bool stretch::update(bool const Holds, double const Distance, double const Window) { + if (false == Holds) { + m_distance = 0.0; + return false; + } + m_distance += std::abs(Distance); + return m_distance >= Window; +} + +verdict monitor::update(vehicle_state const &Vehicle, track_state const &Track, double const Velocity, double const Distance) { + verdict result; + result.acceleration = body_acceleration(Vehicle, Track, Velocity); + result.unloading = unloading_ratio(result.acceleration, Vehicle.centre_of_gravity, contact_spacing(Track.gauge)); + result.flange_ratio = flange_forces(Vehicle, Track, Velocity).ratio(); + auto const overturns{m_overturning.update(result.unloading >= 1.0, Distance)}; + auto const climbs{m_climbing.update(result.flange_ratio >= climbing_limit, Distance)}; + if (overturns) { + result.result = outcome::overturned; + } + else if (climbs) { + result.result = outcome::off_rails; + } + return result; +} + +void monitor::reset() { + m_overturning.reset(); + m_climbing.reset(); +} + +double sliding_friction(outcome const Outcome) { + switch (Outcome) { + case outcome::off_rails: + return off_rails_friction; + case outcome::overturned: + return overturned_friction; + default: + return 0.0; + } +} + +} // namespace derailment diff --git a/McZapkie/derailment.h b/McZapkie/derailment.h new file mode 100644 index 000000000..39999d878 --- /dev/null +++ b/McZapkie/derailment.h @@ -0,0 +1,204 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include + +// the criteria of a vehicle leaving the rails, as plain functions of what the vehicle and the track under it are +// like, so the collisions and the buckled track can use them as well as the speed in a curve does +// (physics.derailment new in eu07.ini, see TMoverParameters::check_derailment()). two ways off the rails: +// +// overturning: the lateral acceleration the cant doesn't balance, a = v^2 / R - g * sin(cant), takes the load off the +// inner wheels; the unloading ratio D = dQ / Q = 2 / s * a / g * (h + s_flex * (h - h_c)) reaches 1 when they lift. +// s the distance between the contact points of the wheels, h the height of the centre of gravity, s_flex and h_c the +// flexibility coefficient and the roll centre height of the suspension, which lets the body lean out of the curve +// (the reference values of the kinematic gauge, EN 15273-2 / UIC 505-1). the body sways on top of that: a lateral +// vibration of 0.05 g at speed (as Kunieda's overturning formula of the Japanese railways adds one) and what the +// uneven track adds +// flange climbing: the ratio of the lateral to the vertical force of the flanging wheel, Y / Q, over Nadal's limit +// (tan d - mu) / (1 + mu * tan d). Y from the force the cant doesn't balance and the sideways part of the forces of +// the couplings in the curve, shared by the axles, plus the guiding force of the leading axle under its angle of +// attack; Q the static wheel load, with what the lateral forces at their heights move onto the wheel +// +// either has to hold over a stretch of track, not at an instant: EN 14363 takes the Y / Q of a 2 m sliding window, so +// a peak shorter than that, or the length of a simulation step, doesn't derail the vehicle +namespace derailment { + +inline constexpr double gravity{9.81}; // [m/s2] + +// the distance between the contact points of the wheels of a wheelset [m]: the gauge and the width of the rail head +// (1.5 m on the standard gauge) +inline constexpr double rail_head_width{0.065}; +double contact_spacing(double Gauge); + +// the suspension of the body, the reference vehicle of the kinematic gauge (EN 15273-2, UIC 505-1) +struct suspension { + double flexibility{0.4}; // roll of the body to the angle of the force on it, s0 + double roll_centre{0.5}; // height of the roll centre above the rail [m], h_c0 +}; + +// ---- the centre of gravity + +// what the vehicle is, for its centre of gravity when its definition gives none +enum class vehicle_class { + powered, // a locomotive, a motor car of a unit + unpowered // a coach, a wagon +}; +// height of the centre of gravity of the empty vehicle above the rail [m], from the height of the body: 0.38 of it for +// a locomotive or a motor car, 0.35 for a coach or a wagon (EU07: 1.65 m, the 430W coal wagon: 1.13 m, a 4 m high +// coach: 1.4 m). a body height up to 2 m in the definition is the height of the floor, the older meaning of the key: +// a 4 m high body is taken then +double default_centre_of_gravity(double BodyHeight, vehicle_class Class); +// the load raises it: the load lies on the floor, its centre half way up to the share of the height of the body +// above the floor it fills (the share of the load it can take), and the heights weigh with the masses [m] +double loaded_centre_of_gravity(double EmptyHeight, double EmptyMass, double LoadMass, double LoadShare, double Floor, double BodyHeight); + +// ---- overturning + +// the lateral acceleration [m/s2] the cant doesn't balance, positive out of the curve: v^2 / R - g sin(cant). the +// sign of the radius and of the cant is left out: the cant lifts the outer rail of a curve. on a straight piece of a +// transition the cant leans the vehicle into the curve to come +double unbalanced_acceleration(double Velocity, double Radius, double Cant); +// D = dQ / Q of the wheels on the inner side, at the lateral acceleration [m/s2] +double unloading_ratio(double Acceleration, double CentreOfGravity, double ContactSpacing, suspension const &Suspension = {}); +// the lateral acceleration [m/s2] which lifts the inner wheels off the rail (D = 1) +double overturning_acceleration(double CentreOfGravity, double ContactSpacing, suspension const &Suspension = {}); +// lateral vibration of the body on a good track [m/s2], growing with the speed up to 100 km/h +inline constexpr double vibration{0.05 * gravity}; +double body_vibration(double Velocity); +// the speed [m/s] at which the vehicle overturns in a curve of the radius [m] and the cant [rad], on a good track +double overturning_speed(double Radius, double Cant, double CentreOfGravity, double Gauge); + +// ---- flange climbing + +// Nadal's limit of Y / Q for the flange angle [rad] and the friction of the flange on the rail +double nadal_limit(double FlangeAngle, double Friction); +// 70 degrees, the flange of the S1002 and the Polish 1:40 profiles +inline constexpr double flange_angle{1.2217304763960306}; +// 1.2: Nadal with 70 degrees and a friction of 0.36 on a dry rail; the limit of EN 14363 for the flange climbing test +// in a tight curve on a twisted track. its 0.8 for the tests on the line is that with a margin for the acceptance of +// a vehicle, and a simulator wants the derailment itself +inline constexpr double climbing_limit{1.2}; +// friction of the tread of the inner wheel of the leading axle, the guiding force it gives under the angle of attack +inline constexpr double tread_friction{0.3}; +// angle of attack [rad] at which the creep force of the tread saturates +inline constexpr double saturated_attack{0.005}; +// height of the buffers and the couplings above the rail [m] (UIC: 940 to 1065 mm) +inline constexpr double buffer_height{1.0}; + +// one end of the vehicle in a train +struct end_force { + double compression{0.0}; // force of the coupling along the vehicle, pushing in [N]; negative pulls out + double other_length{0.0}; // length of the vehicle at that end [m], 0 without one +}; + +// the vehicle as the flange climbing sees it +struct vehicle_state { + double mass{0.0}; // with the load, without the rotating masses [kg] + int axles{4}; + double length{0.0}; // over the buffers [m] + double axle_base{0.0}; // the wheelbase of a bogie, or of the vehicle without bogies [m] + double centre_of_gravity{1.5}; // [m] + std::array ends{}; +}; + +// the dtrack_* flags of the track (MOVER.h) the criteria look at +namespace track_damage { +inline constexpr int railwear{2}; +inline constexpr int freerail{4}; +inline constexpr int thinrail{8}; +inline constexpr int railbend{16}; +} // namespace track_damage + +// the track under the vehicle +struct track_state { + double radius{0.0}; // [m], 0 on a straight one + double cant{0.0}; // [rad] + double gauge{1.435}; // [m] + double uneven_curvature{0.0}; // the lateral curvature of the unevenness under the vehicle [1/m] + double uneven_cross{0.0}; // the cross level unevenness of the track [mm] + int damage{0}; // dtrack_* flags +}; + +// what the state of the track does to the lateral forces and the wheel loads +struct track_condition { + double lateral{1.0}; // multiplier of the lateral acceleration + double unloading{0.0}; // share of the wheel load the twist of the track takes off +}; +track_condition condition_of(track_state const &Track); +// share of the vehicle that follows the short waves of an uneven track: the wheelsets and the bogies, the body not +inline constexpr double uneven_share{0.3}; + +// the angle [rad] between the vehicle and the line of the force of the coupling at the end, in a curve: half the +// angle between the two vehicles, whose middles are half their lengths apart along the curve +double coupling_angle(double Length, double OtherLength, double Radius); + +struct wheel_forces { + double lateral{0.0}; // the lateral force on the vehicle, positive out of the curve [N] + double y{0.0}; // lateral force of the flanging wheel [N] + double q{0.0}; // its vertical force [N] + double ratio() const { return q > 0.0 ? y / q : 1e9; } +}; +// the forces of the flanging wheel of the leading axle, at the speed [m/s] +wheel_forces flange_forces(vehicle_state const &Vehicle, track_state const &Track, double Velocity); +// the lateral acceleration of the body the overturning goes by [m/s2]: what the cant doesn't balance, the sideways +// pull of the couplings, the vibration and the uneven track, by the state of the track +double body_acceleration(vehicle_state const &Vehicle, track_state const &Track, double Velocity); + +// ---- the stretch a condition holds over + +// the distance [m] a condition has to hold over: the window of EN 14363 +inline constexpr double window{2.0}; + +// the distance travelled while the condition held, without a break. the same distance with any step: a step the +// condition holds at counts with its whole length +class stretch { +public: + // true once the condition held over the window, given the distance of the step [m] + bool update(bool Holds, double Distance, double Window = window); + double distance() const { return m_distance; } + void reset() { m_distance = 0.0; } + +private: + double m_distance{0.0}; +}; + +enum class outcome { + none, + off_rails, // the flange climbed the rail: the vehicle runs off the rails, upright + overturned // the vehicle fell over out of the curve +}; + +// what the vehicle came to in a step, with the values the decision went by +struct verdict { + outcome result{outcome::none}; + double unloading{0.0}; // D + double flange_ratio{0.0}; // Y / Q + double acceleration{0.0}; // of the body, [m/s2] +}; + +// both criteria of a vehicle, step by step +class monitor { +public: + // the step travelled the distance [m]; the condition at its end goes for the whole of it + verdict update(vehicle_state const &Vehicle, track_state const &Track, double Velocity, double Distance); + void reset(); + +private: + stretch m_overturning; + stretch m_climbing; +}; + +// the friction of a derailed vehicle sliding along [-]: on its wheels on the sleepers and the ballast, or on its side +inline constexpr double off_rails_friction{0.3}; +inline constexpr double overturned_friction{0.5}; +double sliding_friction(outcome Outcome); + +} // namespace derailment diff --git a/tests/unit/test_derailment.cpp b/tests/unit/test_derailment.cpp new file mode 100644 index 000000000..c66c8f72d --- /dev/null +++ b/tests/unit/test_derailment.cpp @@ -0,0 +1,227 @@ +#include "stdafx.h" +#include "doctest.h" +#include "McZapkie/derailment.h" + +#include +#include + +// the criteria of derailment (McZapkie/derailment.h): overturning by the lateral acceleration the cant doesn't +// balance, the flange climbing the rail by Nadal's Y/Q, either held over 2 m + +namespace dr = derailment; + +namespace { + +constexpr double kmh{1.0 / 3.6}; + +// the cant [rad] of the height of the outer rail [mm] on the standard gauge +double cant(double const Millimetres) { + return std::asin(Millimetres / 1000.0 / dr::contact_spacing(1.435)); +} + +// the centres of gravity the vehicles of data/fiz get without a CoGH of their own +// EU07 (4E): 80 t, a body 4.348 m high +double const eu07{dr::default_centre_of_gravity(4.348, dr::vehicle_class::powered)}; +// the 430W coal wagon: 20.5 t, a body 3.235 m high, 59.5 t of coal +double const coal_wagon{dr::default_centre_of_gravity(3.235, dr::vehicle_class::unpowered)}; +double const coal_wagon_loaded{dr::loaded_centre_of_gravity(coal_wagon, 20500.0, 59500.0, 1.0, 0.0, 3.235)}; + +} // namespace + +TEST_CASE("derailment: Nadal's limit of Y/Q") { + // 70 degrees of the flange: 1.34 with a friction of 0.3, 1.2 with 0.36, the limit the criterion takes + CHECK(dr::nadal_limit(dr::flange_angle, 0.3) == doctest::Approx(1.342).epsilon(0.001)); + CHECK(dr::nadal_limit(dr::flange_angle, 0.36) == doctest::Approx(dr::climbing_limit).epsilon(0.01)); + // a steeper flange holds more, a higher friction less + CHECK(dr::nadal_limit(dr::flange_angle + 0.05, 0.3) > dr::nadal_limit(dr::flange_angle, 0.3)); + CHECK(dr::nadal_limit(dr::flange_angle, 0.5) < dr::nadal_limit(dr::flange_angle, 0.3)); +} + +TEST_CASE("derailment: the centre of gravity") { + CHECK(eu07 == doctest::Approx(1.65).epsilon(0.01)); + CHECK(coal_wagon == doctest::Approx(1.13).epsilon(0.01)); + // the load raises it: a full coal wagon is near 2 m, the limit of the railways for a loaded wagon is 2 to 2.5 m + CHECK(coal_wagon_loaded == doctest::Approx(1.94).epsilon(0.01)); + CHECK(dr::loaded_centre_of_gravity(coal_wagon, 20500.0, 30000.0, 0.5, 0.0, 3.235) > coal_wagon); + CHECK(dr::loaded_centre_of_gravity(coal_wagon, 20500.0, 30000.0, 0.5, 0.0, 3.235) < coal_wagon_loaded); + CHECK(dr::loaded_centre_of_gravity(coal_wagon, 20500.0, 0.0, 0.0, 0.0, 3.235) == coal_wagon); + // a body height of 2 m or less is the floor, the older meaning of the key: a 4 m high body then + CHECK(dr::default_centre_of_gravity(1.2, dr::vehicle_class::unpowered) == doctest::Approx(1.4)); +} + +TEST_CASE("derailment: the overturning speed by the radius and the cant") { + struct expected { + char const *vehicle; + double centre; + double radius; + double cant; // mm + double speed; // km/h + }; + // EU07 overturns at 108 km/h in a 300 m curve without cant, as the legacy criterion had it near 112 km/h; at + // 119 km/h with a cant of 100 mm. a full coal wagon at 98 km/h, an empty one at 137 km/h + for (auto const &[name, centre, radius, height, speed] : { + expected{"EU07", eu07, 150.0, 0.0, 77.6}, + expected{"EU07", eu07, 300.0, 0.0, 107.8}, + expected{"EU07", eu07, 300.0, 100.0, 119.0}, + expected{"EU07", eu07, 600.0, 150.0, 175.8}, + expected{"430W empty", coal_wagon, 300.0, 0.0, 136.9}, + expected{"430W empty", coal_wagon, 300.0, 100.0, 145.9}, + expected{"430W loaded", coal_wagon_loaded, 300.0, 0.0, 97.5}, + expected{"430W loaded", coal_wagon_loaded, 300.0, 100.0, 109.6}, + expected{"430W loaded", coal_wagon_loaded, 1200.0, 150.0, 230.5}, + }) { + CAPTURE(name); + CAPTURE(radius); + CAPTURE(height); + CHECK(dr::overturning_speed(radius, cant(height), centre, 1.435) / kmh == doctest::Approx(speed).epsilon(0.002)); + } + // on the faster side of 100 km/h, where the vibration is all there: v^2 / R - g sin(cant) + 0.05 g = g s / 2 h' + auto const leaning{eu07 + 0.4 * (eu07 - 0.5)}; + auto const limit{dr::gravity * 1.5 / (2.0 * leaning)}; + CHECK(dr::overturning_acceleration(eu07, 1.5) == doctest::Approx(limit)); + auto const speed{std::sqrt((limit - dr::vibration + dr::gravity * std::sin(cant(100.0))) * 300.0)}; + CHECK(dr::overturning_speed(300.0, cant(100.0), eu07, 1.435) == doctest::Approx(speed).epsilon(0.001)); + // the legacy criterion, the lateral acceleration over g times the gauge to the height of the vehicle, without cant + auto const legacy{std::sqrt(dr::gravity * 1.435 / 4.348 * 300.0)}; + CHECK(dr::overturning_speed(300.0, 0.0, eu07, 1.435) == doctest::Approx(legacy).epsilon(0.05)); + // faster on a wider curve, as its square root + CHECK(dr::overturning_speed(1200.0, 0.0, eu07, 1.435) / dr::overturning_speed(300.0, 0.0, eu07, 1.435) == doctest::Approx(2.0).epsilon(0.001)); + // the cant only helps + CHECK(dr::overturning_speed(300.0, cant(150.0), eu07, 1.435) > dr::overturning_speed(300.0, cant(60.0), eu07, 1.435)); + // no overturning on a straight track + CHECK(dr::overturning_speed(0.0, 0.0, eu07, 1.435) == 0.0); +} + +TEST_CASE("derailment: below the balancing speed the cant leans the vehicle into the curve") { + // 100 mm on the 1.5 m between the contact points of the wheels + CHECK(dr::unbalanced_acceleration(0.0, 300.0, cant(100.0)) == doctest::Approx(-dr::gravity * 0.1 / 1.5)); + // at the balancing speed nothing's left + auto const balanced{std::sqrt(dr::gravity * 0.1 / 1.5 * 300.0)}; + CHECK(dr::unbalanced_acceleration(balanced, 300.0, cant(100.0)) == doctest::Approx(0.0).epsilon(1e-9)); + // the sign of the radius and of the cant doesn't matter + CHECK(dr::unbalanced_acceleration(30.0, -300.0, -cant(100.0)) == doctest::Approx(dr::unbalanced_acceleration(30.0, 300.0, cant(100.0)))); +} + +TEST_CASE("derailment: the decision and the place don't depend on the step") { + // EU07 runs at a steady speed into a 300 m curve without cant 100 m ahead, the track checked at the end of each step + dr::vehicle_state eu07vehicle; + eu07vehicle.mass = 80000.0; + eu07vehicle.axles = 4; + eu07vehicle.length = 15.915; + eu07vehicle.axle_base = 3.05; + eu07vehicle.centre_of_gravity = eu07; + auto const critical{dr::overturning_speed(300.0, 0.0, eu07, 1.435)}; + constexpr double curve{100.0}; + + // where the vehicle overturns, if it does within 400 m + auto const run = [&](double const Speed, double const Step) -> std::optional { + dr::monitor monitor; + dr::track_state track; + auto distance{0.0}; + while (distance < 400.0) { + auto const travelled{Speed * Step}; + distance += travelled; + track.radius = distance >= curve ? 300.0 : 0.0; + if (monitor.update(eu07vehicle, track, Speed, travelled).result == dr::outcome::overturned) { + return distance; + } + } + return std::nullopt; + }; + + for (auto const step : {0.01, 0.05, 0.5}) { + CAPTURE(step); + // 5 % too fast: overturns 2 m into the curve, give or take the step it got there in + auto const fast{run(1.05 * critical, step)}; + REQUIRE(fast.has_value()); + CHECK(*fast >= curve + dr::window - 1.05 * critical * step - 1e-6); + CHECK(*fast <= curve + dr::window + 1.05 * critical * step + 1e-6); + // 5 % below it: never + CHECK_FALSE(run(0.95 * critical, step).has_value()); + } + auto const fine{run(1.05 * critical, 0.01)}; + auto const coarse{run(1.05 * critical, 0.5)}; + REQUIRE(fine.has_value()); + REQUIRE(coarse.has_value()); + CHECK(std::abs(*coarse - *fine) <= 1.05 * critical * 0.5); +} + +TEST_CASE("derailment: a peak shorter than the window doesn't derail") { + dr::stretch stretch; + CHECK_FALSE(stretch.update(true, 1.5)); + CHECK_FALSE(stretch.update(false, 0.5)); + CHECK_FALSE(stretch.update(true, 1.5)); + CHECK(stretch.update(true, 0.5)); + CHECK(stretch.distance() == doctest::Approx(2.0)); +} + +TEST_CASE("derailment: pushing a light wagon between heavy vehicles in a curve") { + // the empty 3WL (10.5 t, 2 axles 6 m apart, 9.87 m long) between two EU07 in a 150 m curve: the more the train + // pushes, the more the couplings push the wagon out of the curve, the higher its Y/Q + dr::vehicle_state wagon; + wagon.mass = 10500.0; + wagon.axles = 2; + wagon.length = 9.87; + wagon.axle_base = 6.0; + wagon.centre_of_gravity = dr::default_centre_of_gravity(3.0, dr::vehicle_class::unpowered); + dr::track_state track; + track.radius = 150.0; + auto const speed{20.0 * kmh}; + + auto const ratio = [&](dr::vehicle_state Vehicle, double const Compression) { + for (auto &end : Vehicle.ends) { + end.compression = Compression; + end.other_length = 15.915; + } + return dr::flange_forces(Vehicle, track, speed).ratio(); + }; + auto previous{ratio(wagon, 0.0)}; + // the leading axle guides the wagon with the friction of its inner wheel: over 0.3 even unpushed + CHECK(previous > dr::tread_friction); + CHECK(previous < 0.4); + for (auto const compression : {100e3, 300e3, 600e3, 1000e3}) { + CAPTURE(compression); + auto const pushed{ratio(wagon, compression)}; + CHECK(pushed > previous); + previous = pushed; + } + // a loaded 430W in its place is pushed out less + dr::vehicle_state loaded; + loaded.mass = 80000.0; + loaded.axles = 4; + loaded.length = 14.028; + loaded.axle_base = 2.0; + loaded.centre_of_gravity = coal_wagon_loaded; + CHECK(ratio(loaded, 600e3) < ratio(wagon, 600e3)); + // pulled, the couplings draw the wagon into the curve: the flange of the inner wheel then + auto pulled{wagon}; + for (auto &end : pulled.ends) { + end.compression = -600e3; + end.other_length = 15.915; + } + CHECK(dr::flange_forces(pulled, track, speed).lateral < 0.0); + // on a twisted track the wheel is lighter, so the same push comes nearer the limit + auto const twisted{[&] { + auto const flat{ratio(wagon, 600e3)}; + track.uneven_cross = 30.0; + auto const result{ratio(wagon, 600e3)}; + track.uneven_cross = 0.0; + return result > flat; + }()}; + CHECK(twisted); + // on a bent rail, with a twist of 40 mm, the wagon pushed with 300 kN climbs the rail over 2 m, without falling over + track.damage = dr::track_damage::railbend; + track.uneven_cross = 40.0; + dr::monitor monitor; + auto pushed{wagon}; + for (auto &end : pushed.ends) { + end.compression = 300e3; + end.other_length = 15.915; + } + CHECK(monitor.update(pushed, track, speed, 1.0).result == dr::outcome::none); + auto const verdict{monitor.update(pushed, track, speed, 1.0)}; + CAPTURE(verdict.flange_ratio); + CAPTURE(verdict.unloading); + CHECK(verdict.unloading < 1.0); + CHECK(verdict.result == dr::outcome::off_rails); +} From a257d5d8034374734840b695f6d780e108dba95d Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 10:28:24 +0100 Subject: [PATCH 013/136] feat(physics): a vehicle too fast in a curve overturns or climbs the rail by the criteria, and slides on physics.derailment in eu07.ini: new (the default) checks the criteria of McZapkie/derailment.h in every full step over the distance travelled since the last one, so the decision doesn't depend on the frame rate; old keeps the per-step draw of the lateral acceleration against the gauge to the height of the vehicle; off, no derailment from the speed. - the cant of the track (dHrail) is taken off the lateral acceleration, the centre of gravity comes from the new optional CoGH key of the Dimensions of the .fiz (from the height of the body otherwise), raised by the load - the forces of the couplings at both ends push the vehicle out of the curve, or pull it into it - the uneven track under the outer axles (its lateral curvature and cross level, new fields of TTrackShape set by TDynamicObject) and the damage flags of the track add to it - off the rails by the criteria the vehicle opens its main switch, keeps its speed and slides with the friction of the ballast (0.3 upright, 0.5 on its side) instead of stopping dead; its torn brake hoses vent the brake pipe, the train brakes in emergency. TMoverParameters::Derailed tells overturned from derailed upright, the log says which with the numbers. Other derailments keep the legacy effects --- McZapkie/MOVER.h | 20 ++++ McZapkie/Mover.cpp | 104 ++++++++++++++++-- tests/unit/test_derailment_vehicle.cpp | 142 +++++++++++++++++++++++++ tests/unit/vehicle.cpp | 2 + tests/unit/vehicle.h | 2 + utilities/Globals.cpp | 18 ++++ utilities/Globals.h | 6 ++ vehicle/DynObj.cpp | 3 + 8 files changed, 291 insertions(+), 6 deletions(-) create mode 100644 tests/unit/test_derailment_vehicle.cpp diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index b619ba7de..a1754b7c6 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/. #include #include "hamulce.h" #include "couplerphysics.h" +#include "derailment.h" #include "scripting/ladderlogic.h" #include "vehicle/odometerreading.h" @@ -690,6 +691,10 @@ struct TTrackShape double dHtrack = 0.0; // nachylenie /// Track cant / superelevation. double dHrail = 0.0; // przechylka + /// Lateral curvature of the track unevenness under the vehicle [1/m], see world/TrackUneven.h. + double uneven_curvature = 0.0; + /// Cross level unevenness of the track [mm]. + double uneven_cross = 0.0; }; /// Per-segment track parameters: gauge, friction, category, load capacity, damage. @@ -1654,6 +1659,9 @@ class TMoverParameters TDimension Dim; /*wymiary*/ double Cx = 0.0; /*wsp. op. aerodyn.*/ float Floor = 0.96f; // poziom podłogi dla ładunków + // height of the centre of gravity of the empty vehicle above the rail [m] (CoGH in the Dimensions of the .fiz), + // negative when the definition gives none: derailment::default_centre_of_gravity() then + double CentreOfGravity = -1.0; float WheelDiameter = 1.f; /*srednica kol napednych*/ float WheelDiameterL = 0.9f; // Ra: srednica kol tocznych przednich float WheelDiameterT = 0.9f; // Ra: srednica kol tocznych tylnych @@ -2038,6 +2046,9 @@ class TMoverParameters int SoundFlag = 0; /*!o patrz stale sound_ */ int AIFlag{0}; // HACK: events of interest for consist owner double DistCounter = 0.0; /*! licznik kilometrow */ + // the criteria of derailment (physics.derailment new), and the distance travelled since they were checked [m] + derailment::monitor derailment_monitor; + double derailment_distance = 0.0; odometer::reading Odometer; // total distance run, kept between the sessions (eu07/maszyna#72) std::pair EnergyMeter; // energy from grid [kWh] double V = 0.0; // predkosc w [m/s] względem sprzęgów (dodania gdy jedzie w stronę 0) @@ -2424,6 +2435,15 @@ class TMoverParameters // was a broken coupler to repair bool repair_coupler(int const End); void Derail(DerailReason Reason); + // physics.derailment new: the criteria of derailment.h over the step, which travelled the Distance [m] + void check_derailment(TTrackShape const &Shape, TTrackParam const &Track, double Distance); + // the vehicle leaves the rails, as the criteria of derailment.h found + void derail(derailment::verdict const &Verdict, TTrackShape const &Shape); + // height of the centre of gravity above the rail with the load [m] + double centre_of_gravity() const; + // how the vehicle left the rails by the criteria of derailment.h: upright, or on its side. none for any other + // derailment, which stops it as the legacy model does + derailment::outcome Derailed{derailment::outcome::none}; bool DirectionForward(); bool DirectionBackward(void); /*! kierunek ruchu*/ bool EIMDirectionChangeAllow(void) const; diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 825137675..0e9cc3993 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1503,6 +1503,77 @@ bool TMoverParameters::repair_coupler(int const End) return true; } +static_assert(derailment::track_damage::railwear == dtrack_railwear && derailment::track_damage::freerail == dtrack_freerail && derailment::track_damage::thinrail == dtrack_thinrail && + derailment::track_damage::railbend == dtrack_railbend); + +double TMoverParameters::centre_of_gravity() const +{ + auto const kind{EngineType == TEngineType::None ? derailment::vehicle_class::unpowered : derailment::vehicle_class::powered}; + auto const empty{CentreOfGravity > 0.0 ? CentreOfGravity : derailment::default_centre_of_gravity(Dim.H, kind)}; + auto const loadmass{TotalMass - Mass - Mred}; + auto const loadshare{MaxLoad > 0.f ? LoadAmount / MaxLoad : 1.0}; + return derailment::loaded_centre_of_gravity(empty, Mass, loadmass, loadshare, Floor, Dim.H); +} + +void TMoverParameters::check_derailment(TTrackShape const &Shape, TTrackParam const &Track, double const Distance) +{ + if (TestFlag(DamageFlag, dtrain_out) || false == TestFlag(CategoryFlag, 1) || DebugModeFlag) + { + derailment_monitor.reset(); + return; + } + derailment::vehicle_state vehicle; + vehicle.mass = TotalMass - Mred; + vehicle.axles = NAxles > 0 ? NAxles : 4; + vehicle.length = Dim.L; + vehicle.axle_base = ADist > 0.0 ? ADist : BDist; + vehicle.centre_of_gravity = centre_of_gravity(); + for (int end = end::front; end <= end::rear; ++end) + { + auto const *other{Neighbours[end].vehicle}; + if (other == nullptr) + { + continue; + } + // the force of the coupling, or of the buffers touching, along this vehicle: forwards at the front pulls + vehicle.ends[end].compression = (end == end::front ? -1.0 : 1.0) * Couplers[end].CForce; + vehicle.ends[end].other_length = other->MoverParameters->Dim.L; + } + derailment::track_state track; + track.radius = Shape.R; + track.cant = Shape.dHrail; + track.gauge = TrackW; + track.uneven_curvature = Shape.uneven_curvature; + track.uneven_cross = Shape.uneven_cross; + track.damage = Track.DamageFlag; + + auto const verdict{derailment_monitor.update(vehicle, track, V, Distance)}; + if (verdict.result != derailment::outcome::none) + { + derail(verdict, Shape); + } +} + +void TMoverParameters::derail(derailment::verdict const &Verdict, TTrackShape const &Shape) +{ + if (false == SetFlag(DamageFlag, dtrain_out)) + { + return; + } + Derailed = Verdict.result; + EventFlag = true; + MainSwitch(false, range_t::local); + // the brake hoses tear: the brake pipe vents and the rest of the train brakes in emergency + if (std::any_of(std::begin(Couplers), std::end(Couplers), [](auto const &Coupler) { return (Coupler.CouplingFlag & coupling::brakehose) == coupling::brakehose; })) + { + AlarmChainFlag = true; + } + auto const cant{1000.0 * derailment::contact_spacing(TrackW) * std::sin(std::abs(Shape.dHrail))}; + ErrorLog(std::format("Bad driving: {} {} at {:.0f} km/h, curve radius {:.0f} m, cant {:.0f} mm: lateral acceleration {:.2f} m/s2, wheel unloading {:.2f}, Y/Q {:.2f}", Name, + Derailed == derailment::outcome::overturned ? "overturned" : "derailed, the flange climbed the rail", std::abs(V) * 3.6, std::abs(Shape.R), cant, Verdict.acceleration, + Verdict.unloading, Verdict.flange_ratio)); +} + void TMoverParameters::Derail(DerailReason const Reason) { if (SetFlag(DamageFlag, dtrain_out)) @@ -1578,7 +1649,8 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap AccS = std::lerp(AccSprev, FTotal / TotalMass, 0.5); // std::clamp( dt * 3.0, 0.0, 1.0 ) ); // prawo Newtona ale z wygladzaniem (średnia z poprzednim) - if (TestFlag(DamageFlag, dtrain_out)) + // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce() + if (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none) AccS = -Sign(V) * g * 1; // random(0.0, 0.1) // przyspieszenie normalne @@ -1621,7 +1693,9 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap { if (TestFlag(Track.DamageFlag, dtrack_norail)) Derail(END_OF_TRACK); - if (FuzzyLogic(AccN / g * (1.0 + 0.1 * (Track.DamageFlag & dtrack_freerail)), TrackW / Dim.H, 1)) + // too fast in a curve: the legacy draw in every step (physics.derailment old), or the physical criteria + // once the step's distance is known, below + if (Global.derailment == global_settings::derailment_model::old && FuzzyLogic(AccN / g * (1.0 + 0.1 * (Track.DamageFlag & dtrack_freerail)), TrackW / Dim.H, 1)) Derail(TOO_HIGH_SPEED); // wykolejanie na poszerzeniu toru if (FuzzyLogic(abs(Track.Width - TrackW), TrackW / 10.0, 1)) @@ -1634,6 +1708,12 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap // dL:=(V+AccS*dt/2)*dt; // przyrost dlugosci czyli przesuniecie dL = (3.0 * V - Vprev) * dt / 2.0; // metoda Adamsa-Bashfortha} + if (Global.derailment == global_settings::derailment_model::physical) + { + // over the distance of this step and of the simpler ones of the frame before it + check_derailment(Shape, Track, derailment_distance + std::abs(dL)); + } + derailment_distance = 0.0; // ale jesli jest kolizja (zas. zach. pedu) to...} for (int b = 0; b < 2; b++) if (Couplers[b].CheckCollision) @@ -1675,7 +1755,7 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh AccS = std::lerp(AccSprev, FTotal / TotalMass, 0.5); // std::clamp( dt * 3.0, 0.0, 1.0 ) ); // prawo Newtona ale z wygladzaniem (średnia z poprzednim) - if (TestFlag(DamageFlag, dtrain_out)) + if (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none) AccS = -Sign(V) * g * 1; // * random(0.0, 0.1) // simple mode skips calculation of normal acceleration @@ -1702,6 +1782,8 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh } dL = (3.0 * V - Vprev) * dt / 2.0; // metoda Adamsa-Bashfortha + // the criteria of derailment go by the distance, checked in the full step which ends the frame + derailment_distance += std::abs(dL); // ale jesli jest kolizja (zas. zach. pedu) to... for (int b = 0; b < 2; b++) if (Couplers[b].CheckCollision) @@ -5252,9 +5334,17 @@ void TMoverParameters::ComputeTotalForce(double dt) FStand = FrictionForce(); // siła oporów ruchu if (true == TestFlag(DamageFlag, dtrain_out)) { - // HACK: crude way to reduce speed after derailment - // TBD, TODO: more accurate approach? - FStand *= 1e20; + if (Derailed != derailment::outcome::none) + { + // off the rails by the physical criteria: the vehicle slides on the sleepers and the ballast, or on its side + FStand = derailment::sliding_friction(Derailed) * (TotalMass - Mred) * g; + } + else + { + // HACK: crude way to reduce speed after derailment + // TBD, TODO: more accurate approach? + FStand *= 1e20; + } } double old_nrot = abs(nrot); nrot = v2n(); // przeliczenie prędkości liniowej na obrotową @@ -10967,6 +11057,8 @@ void TMoverParameters::LoadFIZ_Dimensions(std::string const &line) extract_value(Dim.L, "L", line, ""); extract_value(Dim.H, "H", line, ""); extract_value(Dim.W, "W", line, ""); + // height of the centre of gravity of the empty vehicle [m], for the criteria of derailment + extract_value(CentreOfGravity, "CoGH", line, ""); extract_value(Cx, "Cx", line, "0.3"); if (Dim.H <= 2.0) diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp new file mode 100644 index 000000000..54ffc4504 --- /dev/null +++ b/tests/unit/test_derailment_vehicle.cpp @@ -0,0 +1,142 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "McZapkie/derailment.h" +#include "McZapkie/MOVER.h" +#include "utilities/Globals.h" + +// a vehicle too fast in a curve with physics.derailment of eu07.ini: the criteria of McZapkie/derailment.h checked by +// TMoverParameters::check_derailment(), and what the vehicle comes to off the rails + +using test::definition; +using test::vehicle; +namespace dr = derailment; + +namespace { + +constexpr double kmh{1.0 / 3.6}; + +// the given model of derailment for the test, restored after it +class model_setting { +public: + explicit model_setting(global_settings::derailment_model Model) : m_previous{Global.derailment} { Global.derailment = Model; } + ~model_setting() { Global.derailment = m_previous; } + model_setting(model_setting const &) = delete; + model_setting &operator=(model_setting const &) = delete; + +private: + global_settings::derailment_model m_previous; +}; + +// the centres of gravity of EU07 (4E) and of the 430W coal wagon of data/fiz, without a CoGH of their own +double const eu07{dr::default_centre_of_gravity(4.348, dr::vehicle_class::powered)}; +double const coal_wagon{dr::default_centre_of_gravity(3.235, dr::vehicle_class::unpowered)}; + +} // namespace + +TEST_CASE("derailment: a vehicle too fast in a curve") { + model_setting const physical{global_settings::derailment_model::physical}; + test::track curve; + curve.radius = 300.0; + auto const critical{dr::overturning_speed(300.0, 0.0, eu07, 1.435) / kmh}; + + SUBCASE("below the overturning speed it runs on") { + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical - 5.0}; + for (int step = 0; step < 300; ++step) { + eu07vehicle.step(curve); + } + CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + CHECK(eu07vehicle->Derailed == dr::outcome::none); + } + SUBCASE("over it, it falls over and slides to a stop on its side") { + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical + 5.0}; + CHECK(eu07vehicle->centre_of_gravity() == doctest::Approx(eu07)); + // 2 m at 113 km/h is 0.07 s + for (int step = 0; step < 10; ++step) { + eu07vehicle.step(curve); + } + REQUIRE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + CHECK(eu07vehicle->Derailed == dr::outcome::overturned); + CHECK_FALSE(eu07vehicle->Mains); + // not stopped dead as the legacy model has it: it slows down at half of g on the 80 of its 96 t + auto const start{eu07vehicle->V}; + CHECK(start > 0.95 * (critical + 5.0) * kmh); + for (int step = 0; step < 100; ++step) { + eu07vehicle.step(curve); + } + auto const deceleration{(start - eu07vehicle->V) / 1.0}; + CHECK(deceleration == doctest::Approx(0.5 * dr::gravity * 80.0 / 96.0).epsilon(0.05)); + for (int step = 0; step < 2000; ++step) { + eu07vehicle.step(curve); + } + CHECK(eu07vehicle->V == doctest::Approx(0.0)); + } + SUBCASE("a higher centre of gravity of its definition overturns it slower") { + vehicle high{definition::fiz("4e_v1/4e").set("Dimensions", "CoGH", 2.2), critical - 5.0}; + CHECK(high->centre_of_gravity() == doctest::Approx(2.2)); + for (int step = 0; step < 50; ++step) { + high.step(curve); + } + CHECK(high->Derailed == dr::outcome::overturned); + } + SUBCASE("the same with steps of 0.01 and 0.05 s") { + for (auto const dt : {0.01, 0.05}) { + CAPTURE(dt); + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical + 2.0}; + for (auto time = 0.0; time < 1.0; time += dt) { + eu07vehicle.step(curve, dt); + } + CHECK(eu07vehicle->Derailed == dr::outcome::overturned); + vehicle slower{definition::fiz("4e_v1/4e"), critical - 2.0}; + for (auto time = 0.0; time < 1.0; time += dt) { + slower.step(curve, dt); + } + CHECK(slower->Derailed == dr::outcome::none); + } + } + SUBCASE("a load raises the centre of gravity") { + vehicle wagon{definition::fiz("430w_v2/430w")}; + auto const empty{wagon->centre_of_gravity()}; + CHECK(empty == doctest::Approx(coal_wagon)); + wagon->AssignLoad("coal", 59.5f); + wagon->ComputeMass(); + CHECK(wagon->centre_of_gravity() > empty + 0.5); + } +} + +TEST_CASE("derailment: the model of eu07.ini") { + test::track curve; + curve.radius = 300.0; + SUBCASE("off: no derailment at any speed") { + model_setting const off{global_settings::derailment_model::off}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 160.0}; + for (int step = 0; step < 300; ++step) { + eu07vehicle.step(curve); + } + CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + } + SUBCASE("old: the legacy draw stops the vehicle dead") { + model_setting const old{global_settings::derailment_model::old}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 160.0}; + for (int step = 0; step < 600; ++step) { + eu07vehicle.step(curve); + } + // far over its threshold the draw comes out at once + CHECK(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + CHECK(eu07vehicle->Derailed == dr::outcome::none); + CHECK(eu07vehicle->V == doctest::Approx(0.0).epsilon(0.01)); + } +} + +TEST_CASE("derailment: the brake hoses tear") { + model_setting const physical{global_settings::derailment_model::physical}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 150.0}; + eu07vehicle->Couplers[end::rear].CouplingFlag = coupling::coupler | coupling::brakehose; + test::track curve; + curve.radius = 300.0; + for (int step = 0; step < 20; ++step) { + eu07vehicle.step(curve); + } + REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned); + CHECK(eu07vehicle->AlarmChainFlag); +} diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp index e38999f7d..100344369 100644 --- a/tests/unit/vehicle.cpp +++ b/tests/unit/vehicle.cpp @@ -170,6 +170,8 @@ TTrackShape shape_of(track const &Track) { TTrackShape shape; shape.Len = 1000.0; shape.dHtrack = Track.gradient; + shape.R = Track.radius; + shape.dHrail = Track.cant; return shape; } diff --git a/tests/unit/vehicle.h b/tests/unit/vehicle.h index e14f4e464..784a4486d 100644 --- a/tests/unit/vehicle.h +++ b/tests/unit/vehicle.h @@ -66,6 +66,8 @@ struct track { int category{0}; int iterations{1}; double width{1.435}; + double radius{0.0}; // of a curve [m], 0 straight + double cant{0.0}; // [rad] }; // the catenary of the Polish railways [V] diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index a2cb6f59d..746105ad6 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -882,6 +882,20 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + if (token == "physics.derailment") + { + // new: the physical criteria (McZapkie/derailment.h), old: the legacy draw, off: no derailment from the speed + std::string model; + ParseOne(Parser, model, 1); + if (model == "old") + derailment = derailment_model::old; + else if (model == "off" || model == "no") + derailment = derailment_model::off; + else + derailment = derailment_model::physical; + return true; + } + if (token == "controlcoupling.enginecheck") { ParseOne(Parser, control_coupling_engine_check, 1); @@ -1776,6 +1790,10 @@ global_settings::export_as_text( std::ostream &Output ) const { couplerphysics = "all"; } export_as_text( Output, "couplerphysics", couplerphysics ); + export_as_text( Output, "physics.derailment", std::string{ + derailment == derailment_model::old ? "old" : + derailment == derailment_model::off ? "off" : + "new" } ); export_as_text( Output, "ai.brakesetting.cw1", AIBrakeSettingCw1 ); export_as_text( Output, "scalespeculars", ScaleSpecularValues ); export_as_text( Output, "gfxrenderer", GfxRenderer ); diff --git a/utilities/Globals.h b/utilities/Globals.h index 8d32a463c..19dabab53 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -290,6 +290,12 @@ struct global_settings { // train with coupler_physics_all bool coupler_physics = false; bool coupler_physics_all = false; + // a vehicle too fast in a curve (physics.derailment in eu07.ini): new, it overturns or its flange climbs the rail + // by the criteria of McZapkie/derailment.h held over 2 m, and slides on with the friction of the ballast; old, the + // legacy draw of the lateral acceleration against the gauge to the height of the vehicle in every step, which stops + // it; off, it stays on the rails at any speed + enum class derailment_model { off, old, physical }; + derailment_model derailment = derailment_model::physical; bool control_coupling_engine_check = true; // no multiple-unit control between electric and diesel traction vehicles (eu07/maszyna#520) bool gui_defaultwindows = true; bool gui_showtranscripts = true; diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 24810a2e7..66b1007df 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -3227,6 +3227,9 @@ bool TDynamicObject::Update(double dt, double dt1) // między skrajnymi osiami // (!!!odwrotny) ts.dHrail = (Axle1.GetRoll() + Axle0.GetRoll()) * 0.5; //średnia przechyłka pudła + // the uneven track under the outer axles, for the criteria of derailment: its lateral curvature, and its cross level + ts.uneven_curvature = glm::dot( 0.5 * ( Axle0.UnevenBend() + Axle1.UnevenBend() ), vLeft ); + ts.uneven_cross = MyTrack->uneven_underway().cross; // TTrackParam tp; tp.Width = MyTrack->fTrackWidth; // McZapkie-250202 From f1dd033f24952deb47e0cd5e4c107e838e0a0b15 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 11:40:56 +0100 Subject: [PATCH 014/136] feat(physics): the damage flags of a track make the ride rougher, a derailed vehicle once stopped stays put Found running line 107 with every train driven by the AI: - a 401Ka wagon of a freight train overturned into a 282 m curve with a cant of 179 mm at 28 km/h: line 107 has damage 31 on every track, which scaled the whole lateral acceleration by 2.1, the cant too. The sceneries set the flags for the jolts of a worn track (thousands of tracks with 2, 31, 4 or 16), so they now scale only the sway of the body and the short waves of the uneven track, and no longer take load off the wheels; the cross level of the uneven track still does - the overturned wagon crept and stopped in turn in every step (the friction of the ballast against the pull of its train), which kept the physics of the whole train awake: the run went at half the speed after it. The friction now holds a stopped derailed vehicle until the forces on it are larger - a vehicle without a mass got Y/Q 1e9 (no wheel load), now none - the log of a derailment tells the mass, the centre of gravity, the forces of the couplings, the damage flags and the cross level as well --- McZapkie/MOVER.h | 2 +- McZapkie/Mover.cpp | 25 ++++++++--- McZapkie/derailment.cpp | 14 ++++--- McZapkie/derailment.h | 7 ++-- tests/unit/test_derailment.cpp | 57 +++++++++++++++++++++++++- tests/unit/test_derailment_vehicle.cpp | 21 ++++++++++ 6 files changed, 108 insertions(+), 18 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index a1754b7c6..63783419b 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2438,7 +2438,7 @@ class TMoverParameters // physics.derailment new: the criteria of derailment.h over the step, which travelled the Distance [m] void check_derailment(TTrackShape const &Shape, TTrackParam const &Track, double Distance); // the vehicle leaves the rails, as the criteria of derailment.h found - void derail(derailment::verdict const &Verdict, TTrackShape const &Shape); + void derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track); // height of the centre of gravity above the rail with the load [m] double centre_of_gravity() const; // how the vehicle left the rails by the criteria of derailment.h: upright, or on its side. none for any other diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 0e9cc3993..2fa19e184 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1550,11 +1550,11 @@ void TMoverParameters::check_derailment(TTrackShape const &Shape, TTrackParam co auto const verdict{derailment_monitor.update(vehicle, track, V, Distance)}; if (verdict.result != derailment::outcome::none) { - derail(verdict, Shape); + derail(verdict, vehicle, track); } } -void TMoverParameters::derail(derailment::verdict const &Verdict, TTrackShape const &Shape) +void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track) { if (false == SetFlag(DamageFlag, dtrain_out)) { @@ -1568,10 +1568,12 @@ void TMoverParameters::derail(derailment::verdict const &Verdict, TTrackShape co { AlarmChainFlag = true; } - auto const cant{1000.0 * derailment::contact_spacing(TrackW) * std::sin(std::abs(Shape.dHrail))}; - ErrorLog(std::format("Bad driving: {} {} at {:.0f} km/h, curve radius {:.0f} m, cant {:.0f} mm: lateral acceleration {:.2f} m/s2, wheel unloading {:.2f}, Y/Q {:.2f}", Name, - Derailed == derailment::outcome::overturned ? "overturned" : "derailed, the flange climbed the rail", std::abs(V) * 3.6, std::abs(Shape.R), cant, Verdict.acceleration, - Verdict.unloading, Verdict.flange_ratio)); + auto const cant{1000.0 * derailment::contact_spacing(Track.gauge) * std::sin(std::abs(Track.cant))}; + ErrorLog(std::format("Bad driving: {} {} at {:.0f} km/h, curve radius {:.0f} m, cant {:.0f} mm: lateral acceleration {:.2f} m/s2, wheel unloading {:.2f}, Y/Q {:.2f}" + " (mass {:.1f} t, centre of gravity {:.2f} m, couplings pushing {:.0f} / {:.0f} kN, track damage {}, cross level {:.0f} mm)", + Name, Derailed == derailment::outcome::overturned ? "overturned" : "derailed, the flange climbed the rail", std::abs(V) * 3.6, std::abs(Track.radius), cant, + Verdict.acceleration, Verdict.unloading, Verdict.flange_ratio, Vehicle.mass / 1000.0, Vehicle.centre_of_gravity, Vehicle.ends[end::front].compression / 1000.0, + Vehicle.ends[end::rear].compression / 1000.0, Track.damage, Track.uneven_cross)); } void TMoverParameters::Derail(DerailReason const Reason) @@ -1652,6 +1654,10 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce() if (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none) AccS = -Sign(V) * g * 1; // random(0.0, 0.1) + // stuck in the ballast: the friction holds a derailed vehicle once it stopped, until the forces on it are larger + auto const stuck{Derailed != derailment::outcome::none && V == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; + if (stuck) + AccS = 0.0; // przyspieszenie normalne if (abs(Shape.R) > 0.01) @@ -1662,6 +1668,8 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap // velocity change auto const Vprev{V}; V += (3.0 * AccS - AccSprev) * dt / 2.0; // przyrost predkosci + if (stuck) + V = 0.0; if (V * Vprev <= 0 && std::abs(FStand) > std::abs(FTrain)) { // tlumienie predkosci przy hamowaniu @@ -1757,12 +1765,17 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh if (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none) AccS = -Sign(V) * g * 1; // * random(0.0, 0.1) + auto const stuck{Derailed != derailment::outcome::none && V == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; + if (stuck) + AccS = 0.0; // simple mode skips calculation of normal acceleration // velocity change auto const Vprev{V}; V += (3.0 * AccS - AccSprev) * dt / 2.0; // przyrost predkosci + if (stuck) + V = 0.0; if (V * Vprev <= 0 && std::abs(FStand) > std::abs(FTrain)) { // tlumienie predkosci przy hamowaniu diff --git a/McZapkie/derailment.cpp b/McZapkie/derailment.cpp index 382c5c14e..5cccc9f9c 100644 --- a/McZapkie/derailment.cpp +++ b/McZapkie/derailment.cpp @@ -128,12 +128,14 @@ double nadal_limit(double const FlangeAngle, double const Friction) { track_condition condition_of(track_state const &Track) { track_condition condition; - // as the legacy criterion had it, a loose rail sways the vehicles 1.4 times as much + // the flags make the ride rougher: the sway of the vehicles and the short waves of the track grow, the curve and + // the cant stay what they are. sceneries set them for the jolts of a worn track (damage 31 on all of line 107), + // not for broken rails. a loose rail sways the vehicles 1.4 times as much, as the legacy criterion had it condition.lateral = 1.0 + 0.4 * has(Track.damage, track_damage::freerail) + 0.5 * has(Track.damage, track_damage::railbend) + 0.1 * has(Track.damage, track_damage::railwear) + 0.1 * has(Track.damage, track_damage::thinrail); // the twist of the track lifts a wheel: 1 % of its load for each mm of cross level, up to the 0.6 the twist test // of EN 14363 lets the load drop by - condition.unloading = std::min(0.6, 0.01 * std::max(0.0, Track.uneven_cross) + 0.1 * has(Track.damage, track_damage::freerail) + 0.1 * has(Track.damage, track_damage::railbend)); + condition.unloading = std::min(0.6, 0.01 * std::max(0.0, Track.uneven_cross)); return condition; } @@ -160,8 +162,8 @@ wheel_forces flange_forces(vehicle_state const &Vehicle, track_state const &Trac auto const quasistatic{inertia + couplings}; // the sway and the uneven track push the worst way: towards the rail the vehicle already leans on auto const direction{quasistatic >= 0.0 ? 1.0 : -1.0}; - auto const dynamic{Vehicle.mass * dynamic_acceleration(Track, Velocity)}; - result.lateral = direction * (std::abs(quasistatic) + dynamic) * condition.lateral; + auto const dynamic{Vehicle.mass * dynamic_acceleration(Track, Velocity) * condition.lateral}; + result.lateral = direction * (std::abs(quasistatic) + dynamic); // the leading axle meets the rail at an angle in a curve, the creep force of its inner wheel at most the friction auto guiding{0.0}; @@ -172,7 +174,7 @@ wheel_forces flange_forces(vehicle_state const &Vehicle, track_state const &Trac result.y = std::abs(result.lateral) / axles + guiding; // the lateral forces at their heights move the load onto the wheels they push towards - auto const moment{(direction * (inertia * height + couplings * buffer_height) + dynamic * height) * condition.lateral}; + auto const moment{direction * (inertia * height + couplings * buffer_height) + dynamic * height}; auto const shift{moment / (spacing * axles)}; result.q = std::max(0.0, (staticload + shift) * (1.0 - condition.unloading)); return result; @@ -185,7 +187,7 @@ double body_acceleration(vehicle_state const &Vehicle, track_state const &Track, auto const height{leaning_height(Vehicle.centre_of_gravity, suspension{})}; // the couplings pull at the height of the buffers: as much of a lean as their moment gives auto const moment{Vehicle.mass * unbalanced_acceleration(Velocity, Track.radius, Track.cant) * height + coupling_force(Vehicle, Track) * buffer_height}; - return (std::abs(moment) / (Vehicle.mass * height) + dynamic_acceleration(Track, Velocity)) * condition_of(Track).lateral; + return std::abs(moment) / (Vehicle.mass * height) + dynamic_acceleration(Track, Velocity) * condition_of(Track).lateral; } bool stretch::update(bool const Holds, double const Distance, double const Window) { diff --git a/McZapkie/derailment.h b/McZapkie/derailment.h index 39999d878..7d587517f 100644 --- a/McZapkie/derailment.h +++ b/McZapkie/derailment.h @@ -129,8 +129,8 @@ struct track_state { // what the state of the track does to the lateral forces and the wheel loads struct track_condition { - double lateral{1.0}; // multiplier of the lateral acceleration - double unloading{0.0}; // share of the wheel load the twist of the track takes off + double lateral{1.0}; // multiplier of the sway of the vehicle and of the short waves of an uneven track + double unloading{0.0}; // share of the wheel load the twist of the track (its cross level) takes off }; track_condition condition_of(track_state const &Track); // share of the vehicle that follows the short waves of an uneven track: the wheelsets and the bogies, the body not @@ -144,7 +144,8 @@ struct wheel_forces { double lateral{0.0}; // the lateral force on the vehicle, positive out of the curve [N] double y{0.0}; // lateral force of the flanging wheel [N] double q{0.0}; // its vertical force [N] - double ratio() const { return q > 0.0 ? y / q : 1e9; } + // a wheel lifted off the rail with a force on it is past any limit; no force at all (a vehicle without a mass) none + double ratio() const { return q > 0.0 ? y / q : (y > 0.0 ? 1e9 : 0.0); } }; // the forces of the flanging wheel of the leading axle, at the speed [m/s] wheel_forces flange_forces(vehicle_state const &Vehicle, track_state const &Track, double Velocity); diff --git a/tests/unit/test_derailment.cpp b/tests/unit/test_derailment.cpp index c66c8f72d..4fa314fcd 100644 --- a/tests/unit/test_derailment.cpp +++ b/tests/unit/test_derailment.cpp @@ -155,6 +155,19 @@ TEST_CASE("derailment: a peak shorter than the window doesn't derail") { CHECK(stretch.distance() == doctest::Approx(2.0)); } +TEST_CASE("derailment: a vehicle without a mass never derails") { + // a definition without M (or with all of it in the rotating masses) gives no forces, not a lifted wheel + dr::vehicle_state massless; + massless.mass = 0.0; + dr::track_state track; + track.radius = 150.0; + CHECK(dr::flange_forces(massless, track, 30.0).ratio() == 0.0); + dr::monitor monitor; + for (int step = 0; step < 10; ++step) { + CHECK(monitor.update(massless, track, 30.0, 1.0).result == dr::outcome::none); + } +} + TEST_CASE("derailment: pushing a light wagon between heavy vehicles in a curve") { // the empty 3WL (10.5 t, 2 axles 6 m apart, 9.87 m long) between two EU07 in a 150 m curve: the more the train // pushes, the more the couplings push the wagon out of the curve, the higher its Y/Q @@ -209,9 +222,9 @@ TEST_CASE("derailment: pushing a light wagon between heavy vehicles in a curve") return result > flat; }()}; CHECK(twisted); - // on a bent rail, with a twist of 40 mm, the wagon pushed with 300 kN climbs the rail over 2 m, without falling over + // on a bent rail, with a twist of 50 mm, the wagon pushed with 300 kN climbs the rail over 2 m, without falling over track.damage = dr::track_damage::railbend; - track.uneven_cross = 40.0; + track.uneven_cross = 50.0; dr::monitor monitor; auto pushed{wagon}; for (auto &end : pushed.ends) { @@ -225,3 +238,43 @@ TEST_CASE("derailment: pushing a light wagon between heavy vehicles in a curve") CHECK(verdict.unloading < 1.0); CHECK(verdict.result == dr::outcome::off_rails); } + +TEST_CASE("derailment: the damage flags of the track make the ride rougher, not the curve sharper") { + // line 107 has damage 31 on every track, for the jolts. a 401Ka wagon creeping at 28 km/h through a 282 m curve + // with a cant of 179 mm, pulled by a freight train, stays on: in the 2026-11-15 run with the flags scaling the + // whole lateral acceleration it overturned into the curve + dr::vehicle_state wagon; + wagon.mass = 23000.0; + wagon.axles = 4; + wagon.length = 14.7; + wagon.axle_base = 1.8; + wagon.centre_of_gravity = dr::default_centre_of_gravity(4.2, dr::vehicle_class::unpowered); + for (auto &end : wagon.ends) { + end.compression = -200e3; + end.other_length = 14.7; + } + dr::track_state track; + track.radius = 282.0; + track.cant = std::asin(0.179 / 1.5); + auto const speed{28.0 * kmh}; + auto const smooth{dr::body_acceleration(wagon, track, speed)}; + track.damage = 31; + auto const rough{dr::body_acceleration(wagon, track, speed)}; + // the sway grows, by what a rough track adds to the sway at that speed + CHECK(rough > smooth); + CHECK(rough - smooth == doctest::Approx(1.1 * dr::body_vibration(speed))); + CHECK(dr::unloading_ratio(rough, wagon.centre_of_gravity, 1.5) < 0.5); + CHECK(dr::flange_forces(wagon, track, speed).ratio() < 0.8); + // at speed the rough track still lowers the overturning speed some, as the legacy criterion's factor did + { + dr::vehicle_state eu07vehicle; + eu07vehicle.mass = 80000.0; + eu07vehicle.centre_of_gravity = eu07; + dr::track_state good; + good.radius = 300.0; + auto worn{good}; + worn.damage = 31; + CHECK(dr::body_acceleration(eu07vehicle, worn, 30.0) > dr::body_acceleration(eu07vehicle, good, 30.0)); + CHECK(dr::body_acceleration(eu07vehicle, worn, 30.0) - dr::body_acceleration(eu07vehicle, good, 30.0) == doctest::Approx(1.1 * dr::vibration)); + } +} diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index 54ffc4504..23e395fdc 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -140,3 +140,24 @@ TEST_CASE("derailment: the brake hoses tear") { REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned); CHECK(eu07vehicle->AlarmChainFlag); } + +TEST_CASE("derailment: a stopped derailed vehicle stays put on a gradient") { + // the friction of the ballast holds it, rather than the vehicle creeping and stopping in turn in every step, which + // kept the physics of its whole train awake (the run of line 107 went at half the speed after a derailment) + model_setting const physical{global_settings::derailment_model::physical}; + test::track curve; + curve.radius = 300.0; + curve.gradient = 0.01; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 150.0}; + for (int step = 0; step < 2000; ++step) { + eu07vehicle.step(curve); + } + REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned); + REQUIRE(eu07vehicle->V == 0.0); + auto still{true}; + for (int step = 0; step < 500; ++step) { + eu07vehicle.step(curve); + still = still && eu07vehicle->V == 0.0 && eu07vehicle->AccS == 0.0; + } + CHECK(still); +} From 822182d26e8f2f0725ceb6e146b9366fa789eb56 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 11:14:37 +0100 Subject: [PATCH 015/136] feat(track): welded track buckles in the heat, drawn and followed by the axles world/TrackBuckle.h: the buckle of continuous welded rail as plain functions. - the shape: a main lobe and a side lobe of the other way on each side, a cosine under a cos^2 window over three lobes, so the side lobes come to a quarter of the main one and the curvature runs on smoothly into the straight track; peak curvature 11/9 pi^2 a / L^2. A straight track 0.4 m by 14 m, a curve (R < 1500 m) 0.2 m by 11 m out of the curve (Kish, Samavedam) - the heat: rail = air + 17 K in full sun (by the height of the sun and the clouds), the force E*A*alpha*dT, the limits of the rise above the neutral temperature (26 C, PLK) a track buckles at under a train and by itself: good 40/55 K, average 32/45, weak or worked lately 22/32, lowered in curves and by an uneven line; the chance of a pass growing between them - the draws by an FNV-1a hash of the name of the track and the seed The buckle is a part of TSegment::stray() across the path, so the rails, the sleepers and the axles on it follow it (the direction stays as designed); the path is divided every 1 m where it has one. Its curvature is kept apart from the unevenness (TSegment::buckle_bend()). - scenery: "buckle ;;[;]" and "cwr ;[;]" of a plain rail track, written back - event "trackbuckle [ [ []]]" buckles the target tracks during the game (0 straightens them), making their geometry again - physics.trackbuckling off|scenery|auto in eu07.ini, scenery by default; auto also buckles the weak places (one in 10 km of track, and the tracks worked on lately) by the temperature of the rails, by themselves or under a train going fast or braking --- CMakeLists.txt | 1 + editor/editorTrack.cpp | 3 + simulation/simulation.cpp | 2 + tests/unit/test_track_buckle.cpp | 321 ++++++++++++++++++++++ utilities/Globals.cpp | 18 ++ utilities/Globals.h | 4 + world/Event.cpp | 64 +++++ world/Event.h | 26 ++ world/Segment.cpp | 51 +++- world/Segment.h | 17 +- world/Track.cpp | 35 ++- world/Track.h | 29 ++ world/TrackBuckle.cpp | 233 ++++++++++++++++ world/TrackBuckle.h | 440 +++++++++++++++++++++++++++++++ 14 files changed, 1228 insertions(+), 16 deletions(-) create mode 100644 tests/unit/test_track_buckle.cpp create mode 100644 world/TrackBuckle.cpp create mode 100644 world/TrackBuckle.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 76f359eab..98e703cc0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -113,6 +113,7 @@ set(SOURCES "world/RailCarve.cpp" "world/RailLayer.cpp" "world/TrackUneven.cpp" +"world/TrackBuckle.cpp" "world/Road.cpp" "world/Sweep.cpp" "world/RoadPoint.cpp" diff --git a/editor/editorTrack.cpp b/editor/editorTrack.cpp index 548a794d8..f88c91a18 100644 --- a/editor/editorTrack.cpp +++ b/editor/editorTrack.cpp @@ -3400,6 +3400,9 @@ void write_ending(std::ostream &Text, TTrack const &Style, bool const Switch) if ((Style.iCategoryFlag & 15) == 1 && false == Style.m_profile1.first.empty()) Text << "railprofile " << Style.m_profile1.first << ' '; Text << track_uneven::write_attribute(Style.m_uneven, Switch); + // the welded rail goes on in the piece; a buckle stays where it was + if (false == Switch && (Style.iCategoryFlag & 15) == 1) + Text << track_buckle::write_cwr(Style.m_cwr); // a piece of the track made from another one stays in its track circuit and under the same overhead line for (auto const *isolated : Style.Isolated) Text << "isolated " << isolated->asName << ' '; diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp index 87cce81b6..a25e4ccc7 100644 --- a/simulation/simulation.cpp +++ b/simulation/simulation.cpp @@ -130,6 +130,8 @@ state_manager::update( double const Deltatime, int Iterationcount ) { simulation::Junctions.update( totaltime ); simulation::Roadpoints.update( totaltime ); simulation::Vehicles.update( Deltatime, Iterationcount ); + // the tracks the heat buckles, by itself or under the trains just moved + TTrack::update_buckling( totaltime ); } void diff --git a/tests/unit/test_track_buckle.cpp b/tests/unit/test_track_buckle.cpp new file mode 100644 index 000000000..df26c74ab --- /dev/null +++ b/tests/unit/test_track_buckle.cpp @@ -0,0 +1,321 @@ +#include "stdafx.h" +#include "doctest.h" +#include "world/TrackBuckle.h" + +#include + +// the buckling of welded track in the heat, world/TrackBuckle.h: the shape the track takes, the force and the temperature of the rails, +// the limits it buckles at and the draws, repeated with the same seed + +namespace { + +double constexpr pi_squared{9.869604401089358}; + +int count_buckled(double const Rise, track_buckle::limits const &Limits, std::uint32_t const Seed, int const Passes) +{ + auto count{0}; + for (int pass = 1; pass <= Passes; ++pass) + { + auto const draw{track_buckle::draw(track_buckle::name_hash("tor_1234"), Seed, track_buckle::pass, static_cast(pass))}; + if (track_buckle::decide(Rise, Limits, true, draw) == track_buckle::verdict::under_train) + ++count; + } + return count; +} + +} // namespace + +TEST_CASE("the force in a rail held from growing longer is E*A*alpha*dT") +{ + // PLK ST-T1-A8 designs for 35 K, 665 kN in a 60E1 rail, with its own alpha of about 1.18e-5 + auto const force{track_buckle::thermal_force(track_buckle::area_60e1, 35.0)}; + CHECK(force == doctest::Approx(650e3).epsilon(0.03)); + CHECK(force == doctest::Approx(665e3).epsilon(0.03)); + // Kish, Samavedam: about 2.5 kips a rail for each degree F in a 136 lb rail (13.35 sq in), 20.0 kN/K + CHECK(track_buckle::thermal_force(13.35 * 6.4516e-4, 1.0) == doctest::Approx(20.0e3).epsilon(0.05)); + // lighter rails press less + CHECK(track_buckle::thermal_force(track_buckle::area_49e1, 35.0) < force); + CHECK(track_buckle::rail_area("49E1_rail") == track_buckle::area_49e1); + CHECK(track_buckle::rail_area("S42") == track_buckle::area_s42); + CHECK(track_buckle::rail_area("") == track_buckle::area_60e1); +} + +TEST_CASE("a rail is as warm as the air at night or under clouds, 17 K warmer in full sun") +{ + CHECK(track_buckle::rail_temperature(30.0, -10.0, 0.0) == doctest::Approx(30.0)); + CHECK(track_buckle::rail_temperature(30.0, 90.0, 0.0) == doctest::Approx(47.0)); + CHECK(track_buckle::rail_temperature(30.0, 90.0, 1.0) == doctest::Approx(30.0)); + // rain cools as much as clouds + CHECK(track_buckle::rail_temperature(30.0, 90.0, 2.0) == doctest::Approx(30.0)); + CHECK(track_buckle::rail_temperature(30.0, 30.0, 0.0) == doctest::Approx(38.5)); + CHECK(track_buckle::rail_temperature(30.0, 60.0, 0.5) == doctest::Approx(30.0 + 17.0 * std::sin(60.0 * 3.141592653589793 / 180.0) * 0.5)); +} + +TEST_CASE("the limits of the grades meet the heat the tracks of PLK deform in") +{ + track_buckle::cwr track; + auto const average{track_buckle::limits_of(track, 0.0, 0.0)}; + // at the neutral 26 C under a train from rails at 58 C, by itself from 71 C: PLK, deformations with the rails above 70 C + CHECK(track.neutral + average.low == doctest::Approx(58.0)); + CHECK(track.neutral + average.high == doctest::Approx(71.0)); + // Kish, Samavedam: the chance of a buckle of a straight track grows fast from rails at 63 C with the neutral at 27 C, 36 K + CHECK(36.0 > average.low); + CHECK(36.0 < average.high); + // the design of PLK, 35 K, is short of where a good track buckles under a train + track.grade = track_buckle::grade::good; + CHECK(track_buckle::limits_of(track, 0.0, 0.0).low > 35.0); + // worked lately: weak whatever the grade + track.worked = true; + auto const worked{track_buckle::limits_of(track, 0.0, 0.0)}; + CHECK(worked.low == doctest::Approx(22.0)); + CHECK(worked.high == doctest::Approx(32.0)); + // curves and an uneven line lower them + track = {}; + CHECK(track_buckle::limits_of(track, 500.0, 0.0).low == doctest::Approx(29.0)); + CHECK(track_buckle::limits_of(track, -250.0, 0.0).low == doctest::Approx(26.0)); + CHECK(track_buckle::limits_of(track, 2000.0, 0.0).low == doctest::Approx(32.0)); + CHECK(track_buckle::limits_of(track, 0.0, 20.0).high == doctest::Approx(42.0)); + // FRA, the dynamic test: a 7.5 degree curve (233 m) with a 19 mm misalignment buckled under the train at 34 K + auto const fra{track_buckle::limits_of(track, 233.0, 19.0)}; + CHECK(34.0 > fra.low); + CHECK(34.0 < fra.high); +} + +TEST_CASE("below the lower limit a track never buckles, at the upper one it buckles by itself") +{ + track_buckle::limits const limits{32.0, 45.0}; + for (auto const draw : {0.0, 0.3, 0.999}) + { + CHECK(track_buckle::decide(31.9, limits, true, draw) == track_buckle::verdict::none); + CHECK(track_buckle::decide(31.9, limits, false, draw) == track_buckle::verdict::none); + CHECK(track_buckle::decide(45.0, limits, false, draw) == track_buckle::verdict::by_itself); + // in between only under a train + CHECK(track_buckle::decide(44.0, limits, false, draw) == track_buckle::verdict::none); + } + CHECK(track_buckle::chance(32.0, limits) == doctest::Approx(0.0)); + CHECK(track_buckle::chance(38.5, limits) == doctest::Approx(0.5)); + CHECK(track_buckle::chance(50.0, limits) == doctest::Approx(1.0)); + // a train going slowly and not braking doesn't stir it up + CHECK_FALSE(track_buckle::stirs(30.0, false)); + CHECK(track_buckle::stirs(30.0, true)); + CHECK(track_buckle::stirs(60.0, false)); + CHECK_FALSE(track_buckle::stirs(3.0, true)); +} + +TEST_CASE("the share of the passes that buckle a track grows with the heat, and repeats with the seed") +{ + track_buckle::limits const limits{32.0, 45.0}; + auto const passes{4000}; + auto const quarter{count_buckled(32.0 + 0.25 * 13.0, limits, 7, passes)}; + auto const most{count_buckled(32.0 + 0.75 * 13.0, limits, 7, passes)}; + CHECK(quarter == doctest::Approx(0.25 * passes).epsilon(0.1)); + CHECK(most == doctest::Approx(0.75 * passes).epsilon(0.05)); + CHECK(count_buckled(31.0, limits, 7, passes) == 0); + // the same seed and track, the same passes + CHECK(count_buckled(38.0, limits, 7, passes) == count_buckled(38.0, limits, 7, passes)); + auto const key{track_buckle::name_hash("tor_1234")}; + CHECK(track_buckle::draw(key, 7, track_buckle::pass, 3) == track_buckle::draw(key, 7, track_buckle::pass, 3)); + // another seed, other draws + auto differ{0}; + for (std::uint64_t pass = 1; pass <= 100; ++pass) + if (track_buckle::draw(key, 7, track_buckle::pass, pass) != track_buckle::draw(key, 8, track_buckle::pass, pass)) + ++differ; + CHECK(differ == 100); + // and another track + CHECK(track_buckle::draw(track_buckle::name_hash("tor_1235"), 7, track_buckle::pass, 3) != track_buckle::draw(key, 7, track_buckle::pass, 3)); + // the draws spread over 0 to 1 + auto low{0}; + for (std::uint64_t pass = 1; pass <= 1000; ++pass) + { + auto const draw{track_buckle::draw(key, 7, track_buckle::pass, pass)}; + CHECK(draw >= 0.0); + CHECK(draw < 1.0); + if (draw < 0.5) + ++low; + } + CHECK(low == doctest::Approx(500).epsilon(0.1)); +} + +TEST_CASE("the heat buckles a track at one place in about 10 km, and wherever the bed was worked on") +{ + auto sites{0}; + auto const tracks{20000}; + for (int track = 0; track < tracks; ++track) + if (track_buckle::weak_spot(track_buckle::name_hash("t" + std::to_string(track)), 3, 500.0, false)) + ++sites; + // 500 m each, 10 000 km together: about 1000 + CHECK(sites == doctest::Approx(1000).epsilon(0.1)); + CHECK(track_buckle::weak_spot(track_buckle::name_hash("t1"), 3, 1.0, true)); +} + +TEST_CASE("the buckle has its amplitude in the middle, side lobes the other way and ends smoothly") +{ + track_buckle::shape const shape{0.4, 14.0, 60.0}; + CHECK(track_buckle::offset(shape, 60.0) == doctest::Approx(0.4)); + CHECK(track_buckle::slope(shape, 60.0) == doctest::Approx(0.0)); + // the main lobe crosses the line one length apart + CHECK(track_buckle::offset(shape, 60.0 - 7.0) == doctest::Approx(0.0)); + CHECK(track_buckle::offset(shape, 60.0 + 7.0) == doctest::Approx(0.0)); + // the side lobes the other way, a quarter as far out + CHECK(track_buckle::offset(shape, 60.0 + 14.0) == doctest::Approx(-0.1)); + CHECK(track_buckle::offset(shape, 60.0 - 14.0) == doctest::Approx(-0.1)); + // into the straight track at the ends with no displacement, slope or curvature + CHECK(track_buckle::reach(shape) == doctest::Approx(21.0)); + for (auto const at : {-21.0 + 1e-6, 21.0 - 1e-6}) + { + CAPTURE(at); + CHECK(track_buckle::offset(shape, 60.0 + at) == doctest::Approx(0.0)); + CHECK(track_buckle::slope(shape, 60.0 + at) == doctest::Approx(0.0)); + CHECK(track_buckle::bend(shape, 60.0 + at) == doctest::Approx(0.0)); + } + // nothing beyond + CHECK(track_buckle::offset(shape, 60.0 + 21.5) == 0.0); + CHECK(track_buckle::bend(shape, 60.0 - 30.0) == 0.0); + // symmetric + for (auto const at : {1.0, 4.0, 7.5, 12.0, 16.0, 20.0}) + CHECK(track_buckle::offset(shape, 60.0 + at) == doctest::Approx(track_buckle::offset(shape, 60.0 - at))); + // the largest curvature 11/9 pi^2 a / L^2 in the middle, bending back towards the line + auto const peak{track_buckle::peak_bend(0.4, 14.0)}; + CHECK(peak == doctest::Approx(11.0 / 9.0 * pi_squared * 0.4 / (14.0 * 14.0))); + CHECK(track_buckle::bend(shape, 60.0) == doctest::Approx(-peak)); + // none larger anywhere, and the curvature with no jumps + auto previous{track_buckle::bend(shape, 35.0)}; + for (auto at = 35.0; at <= 85.0; at += 0.01) + { + auto const bend{track_buckle::bend(shape, at)}; + CHECK(std::abs(bend) <= peak * 1.0001); + CHECK(std::abs(bend - previous) < 0.01 * peak); + previous = bend; + } + // the curvature as the displacement has it + auto const step{0.01}; + for (auto const at : {42.0, 50.5, 55.0, 61.0, 66.0, 73.0, 79.0}) + { + CAPTURE(at); + auto const slope{(track_buckle::offset(shape, at + step) - track_buckle::offset(shape, at - step)) / (2.0 * step)}; + auto const bend{(track_buckle::offset(shape, at + step) - 2.0 * track_buckle::offset(shape, at) + track_buckle::offset(shape, at - step)) / (step * step)}; + CHECK(track_buckle::slope(shape, at) == doctest::Approx(slope).epsilon(1e-4)); + CHECK(track_buckle::bend(shape, at) == doctest::Approx(bend).epsilon(1e-3)); + } + // to the left + track_buckle::shape const left{-0.4, 14.0, 60.0}; + CHECK(track_buckle::offset(left, 60.0) == doctest::Approx(-0.4)); + CHECK(track_buckle::bend(left, 60.0) == doctest::Approx(peak)); + // none + CHECK(track_buckle::offset(track_buckle::shape{}, 60.0) == 0.0); + CHECK_FALSE(track_buckle::active(track_buckle::shape{})); +} + +TEST_CASE("a bogie feels the curvature of the buckle averaged over its wheelbase, a body that of its pivots") +{ + track_buckle::shape const shape{0.3, 20.0, 50.0}; + auto const peak{track_buckle::peak_bend(0.3, 20.0)}; + CHECK(track_buckle::mean_bend(shape, 50.0, 0.0) == doctest::Approx(track_buckle::bend(shape, 50.0))); + // a bogie 2.5 m long, almost the whole of it + CHECK(std::abs(track_buckle::mean_bend(shape, 50.0, 2.5)) > 0.95 * peak); + // the mean of the curvature over the stretch, anywhere + for (auto const at : {32.0, 42.0, 50.0, 57.5, 64.0}) + { + CAPTURE(at); + auto sum{0.0}; + auto const parts{2500}; + for (int part = 0; part < parts; ++part) + sum += track_buckle::bend(shape, at - 1.25 + (part + 0.5) * 2.5 / parts); + CHECK(track_buckle::mean_bend(shape, at, 2.5) == doctest::Approx(sum / parts).epsilon(1e-3)); + } + // a body on the pivots 0 apart is a bogie + CHECK(track_buckle::body_bend(shape, 47.0, 0.0, 2.5) == doctest::Approx(track_buckle::mean_bend(shape, 47.0, 2.5))); + // a coach with its pivots 17 m apart over the main lobe: its pivots are on the flanks, which bend the other way + auto const across{track_buckle::body_bend(shape, 50.0, 17.0, 2.5)}; + CHECK(std::abs(across) < 0.5 * peak); + // the most the body feels, at any place, is less than a bogie does + auto most{0.0}; + for (auto at = 20.0; at <= 80.0; at += 0.05) + most = std::max(most, std::abs(track_buckle::body_bend(shape, at, 17.0, 2.5))); + CHECK(most < 0.95 * peak); + CHECK(most > 0.3 * peak); +} + +TEST_CASE("the equivalent radius of a buckle") +{ + // the default ones as sharp as the raised cosine lobes of the research note: 0.4 m by 18 m on a straight 41 m, 0.2 by 14 in a curve 50 m + CHECK(1.0 / track_buckle::peak_bend(track_buckle::straight_amplitude, track_buckle::straight_length) == doctest::Approx(41.0).epsilon(0.02)); + CHECK(1.0 / track_buckle::peak_bend(track_buckle::curve_amplitude, track_buckle::curve_length) == doctest::Approx(49.6).epsilon(0.02)); + CHECK(1.0 / track_buckle::peak_bend(0.3, 20.0) == doctest::Approx(110.5).epsilon(0.01)); +} + +TEST_CASE("the entries buckle and cwr are read and written back") +{ + auto const buckle{track_buckle::read_buckle("400;18;60")}; + CHECK(buckle.amplitude == 400.f); + CHECK(buckle.length == 18.f); + CHECK(buckle.centre == 60.f); + CHECK(buckle.side == 0); + CHECK(track_buckle::write_buckle(buckle) == "buckle 400;18;60 "); + auto const left{track_buckle::read_buckle("250;;;-1")}; + CHECK(left.amplitude == 250.f); + CHECK(left.length < 0.f); + CHECK(left.centre < 0.f); + CHECK(left.side == -1); + CHECK(track_buckle::write_buckle(left) == "buckle 250;;;-1 "); + CHECK(track_buckle::read_buckle(track_buckle::write_buckle(left).substr(7)).side == -1); + // kept within bounds + auto const wild{track_buckle::read_buckle("5000;100;-5;3")}; + CHECK(wild.amplitude == 1000.f); + CHECK(wild.length == 60.f); + CHECK(wild.centre < 0.f); + CHECK(wild.side == 1); + CHECK(track_buckle::read_buckle("300;1").length == 4.f); + // none + CHECK_FALSE(track_buckle::given(track_buckle::read_buckle("0;18;60"))); + CHECK_FALSE(track_buckle::given(track_buckle::read_buckle("x"))); + CHECK(track_buckle::write_buckle(track_buckle::declared{}).empty()); + + auto const cwr{track_buckle::read_cwr("20;2;1")}; + CHECK(cwr.neutral == 20.f); + CHECK(cwr.grade == track_buckle::grade::weak); + CHECK(cwr.worked); + CHECK(track_buckle::write_cwr(cwr) == "cwr 20;2;1 "); + auto const partial{track_buckle::read_cwr("22")}; + CHECK(partial.neutral == 22.f); + CHECK(partial.grade == track_buckle::grade::average); + CHECK_FALSE(partial.worked); + CHECK(track_buckle::write_cwr(partial) == "cwr 22;1 "); + auto const bounded{track_buckle::read_cwr("99;7")}; + CHECK(bounded.neutral == 60.f); + CHECK(bounded.grade == 2); + // the default isn't written + CHECK(track_buckle::write_cwr(track_buckle::read_cwr("26;1;0")).empty()); +} + +TEST_CASE("a buckle is laid into its track away from the ends, out of a curve") +{ + auto const values{track_buckle::read_buckle("400;18;60")}; + auto const straight{track_buckle::resolve(values, 200.0, 0, 0.0, 0.5, 0.2)}; + CHECK(straight.centre == 60.0); + CHECK(straight.length == 18.0); + // the side drawn on a straight + CHECK(straight.amplitude == doctest::Approx(-0.4)); + CHECK(track_buckle::resolve(values, 200.0, 0, 0.0, 0.5, 0.7).amplitude == doctest::Approx(0.4)); + // out of a curve, whatever the draw + CHECK(track_buckle::resolve(values, 200.0, 1, 400.0, 0.5, 0.2).amplitude == doctest::Approx(0.4)); + CHECK(track_buckle::resolve(values, 200.0, -1, 400.0, 0.5, 0.7).amplitude == doctest::Approx(-0.4)); + // the side given wins + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18;60;-1"), 200.0, 1, 400.0, 0.5, 0.7).amplitude == doctest::Approx(-0.4)); + // the centre kept away from the ends by the reach, 1.5 lengths, and a margin + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18;5"), 200.0, 0, 0.0, 0.5, 0.2).centre == doctest::Approx(29.0)); + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18;195"), 200.0, 0, 0.0, 0.5, 0.2).centre == doctest::Approx(171.0)); + // drawn where not given + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18"), 200.0, 0, 0.0, 0.0, 0.2).centre == doctest::Approx(29.0)); + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18"), 200.0, 0, 0.0, 1.0, 0.2).centre == doctest::Approx(171.0)); + // the length by the shape of the track: a curve goes out less far and shorter + CHECK(track_buckle::resolve(track_buckle::read_buckle("200"), 200.0, 1, 400.0, 0.5, 0.2).length == track_buckle::curve_length); + CHECK(track_buckle::resolve(track_buckle::read_buckle("400"), 200.0, 0, 0.0, 0.5, 0.2).length == track_buckle::straight_length); + CHECK(track_buckle::resolve(track_buckle::read_buckle("400"), 200.0, 1, 3000.0, 0.5, 0.2).length == track_buckle::straight_length); + // too short a track + CHECK_FALSE(track_buckle::active(track_buckle::resolve(values, 57.9, 0, 0.0, 0.5, 0.2))); + CHECK(track_buckle::active(track_buckle::resolve(values, 58.0, 0, 0.0, 0.5, 0.2))); + // the natural ones + CHECK(track_buckle::natural(true).amplitude == 200.f); + CHECK(track_buckle::natural(false).length == 14.f); +} diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 746105ad6..37dd30eed 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -872,6 +872,20 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + if (token == "physics.trackbuckling") + { + // off, scenery: the buckles of the scenery and its events, auto: also by the temperature of the rails + std::string mode; + ParseOne(Parser, mode, 1); + if (mode == "off" || mode == "no") + track_buckling = track_buckling_mode::off; + else if (mode == "auto") + track_buckling = track_buckling_mode::automatic; + else + track_buckling = track_buckling_mode::scenery; + return true; + } + if (token == "couplerphysics") { // yes: the player's train and the trains it closes in on, all: every train @@ -1783,6 +1797,10 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "scenario.time.offset", ScenarioTimeOffset ); export_as_text( Output, "scenario.time.current", ScenarioTimeCurrent ); export_as_text( Output, "scenario.weather.temperature", AirTemperature ); + export_as_text( Output, "physics.trackbuckling", std::string{ + track_buckling == track_buckling_mode::off ? "off" : + track_buckling == track_buckling_mode::automatic ? "auto" : + "scenery" } ); export_as_text( Output, "ai.trainman", AITrainman ); export_as_text( Output, "controlcoupling.enginecheck", control_coupling_engine_check ); std::string couplerphysics { coupler_physics ? "yes" : "no" }; diff --git a/utilities/Globals.h b/utilities/Globals.h index 19dabab53..e82beddd4 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -284,6 +284,10 @@ struct global_settings { bool captureonstart = true; bool render_cab = true; bool crash_damage = true; + // the buckling of welded track in the heat (physics.trackbuckling in eu07.ini, see world/TrackBuckle.h): off, none; scenery, the + // buckles the scenery enters and its trackbuckle events; automatic, also by the temperature of the rails at the weak places + enum class track_buckling_mode { off, scenery, automatic }; + track_buckling_mode track_buckling = track_buckling_mode::scenery; // the physical model of the couplings (McZapkie/couplerphysics.h): progressive buffers and draw gear with hysteresis, // the play of the coupling, its yield and breaking; the legacy model of TMoverParameters::CouplerForce() without it. // it covers the player's train and the trains it closes in on (vehicle_table::update_coupler_physics()), or every diff --git a/world/Event.cpp b/world/Event.cpp index 80697cfa2..2452b7881 100644 --- a/world/Event.cpp +++ b/world/Event.cpp @@ -2054,6 +2054,69 @@ track_event::export_as_text_( std::ostream &Output ) const { +// prepares event for use +void +buckle_event::init() { + + init_targets( simulation::Paths, "track" ); +} + +// event type string +std::string +buckle_event::type() const { + + return "trackbuckle"; +} + +// deserialize() subclass details +void +buckle_event::deserialize_( cParser &Input, scene::scratch_data &Scratchpad ) { + + Input.getTokens(); + Input >> m_buckle.amplitude; + m_buckle.amplitude = std::clamp( m_buckle.amplitude, 0.f, static_cast( 1000.0 * track_buckle::most_amplitude ) ); + Input.getTokens(); + // the length, the centre and the side, each optional + if( false == is_keyword( Input.peek() ) ) { + Input >> m_buckle.length; + if( m_buckle.length > 0.f ) { + m_buckle.length = std::clamp( m_buckle.length, static_cast( track_buckle::least_length ), static_cast( track_buckle::most_length ) ); + } + Input.getTokens(); + } + if( false == is_keyword( Input.peek() ) ) { + Input >> m_buckle.centre; + Input.getTokens(); + } + if( false == is_keyword( Input.peek() ) ) { + auto side { 0.f }; + Input >> side; + m_buckle.side = ( side > 0.f ? 1 : side < 0.f ? -1 : 0 ); + Input.getTokens(); + } +} + +// run() subclass details +void +buckle_event::run_() { + + WriteLog( "Type: TrackBuckle - [" + to_string( m_buckle.amplitude, 0 ) + " mm]" ); + for( auto &target : m_targets ) { + auto *targettrack = static_cast( std::get( target ) ); + if( targettrack == nullptr ) { continue; } + targettrack->buckle_now( m_buckle, "event " + m_name ); + } +} + +// export_as_text() subclass details +void +buckle_event::export_as_text_( std::ostream &Output ) const { + + Output << m_buckle.amplitude << ' ' << m_buckle.length << ' ' << m_buckle.centre << ' ' << m_buckle.side << ' '; +} + + + // prepares event for use void voltage_event::init() { @@ -2310,6 +2373,7 @@ make_event( cParser &Input, scene::scratch_data &Scratchpad ) { else if( type == "multiple" ) { event = new multi_event(); } else if( type == "switch" ) { event = new switch_event(); } else if( type == "trackvel" ) { event = new track_event(); } + else if( type == "trackbuckle" ) { event = new buckle_event(); } else if( type == "sound" ) { event = new sound_event(); } else if( type == "texture" ) { event = new texture_event(); } else if( type == "animation" ) { event = new animation_event(); } diff --git a/world/Event.h b/world/Event.h index f1d75689b..090d165d6 100644 --- a/world/Event.h +++ b/world/Event.h @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "scene/scene.h" #include "utilities/Names.h" #include "world/EvLaunch.h" +#include "world/TrackBuckle.h" #include "utilities/Logs.h" #include "input/command.h" #include "utilities/comparison.h" @@ -527,6 +528,31 @@ private: +// trackbuckle [ [ []]]: the target tracks buckle in the heat as the entry +// "buckle" of a track says (see world/TrackBuckle.h), amplitude 0 straightens them +class buckle_event : public basic_event { + +public: +// methods + // prepares event for use + void init() override; + +private: +// methods + // event type string + std::string type() const override; + // deserialize() subclass details + void deserialize_( cParser &Input, scene::scratch_data &Scratchpad ) override; + // run() subclass details + void run_() override; + // export_as_text() subclass details + void export_as_text_( std::ostream &Output ) const override; +// members + track_buckle::declared m_buckle; +}; + + + class voltage_event : public basic_event { public: diff --git a/world/Segment.cpp b/world/Segment.cpp index d1c5f2c89..5e0f47116 100644 --- a/world/Segment.cpp +++ b/world/Segment.cpp @@ -141,6 +141,10 @@ bool TSegment::Init(glm::dvec3 &NewPoint1, glm::dvec3 NewCPointOut, glm::dvec3 N // dense enough for the waves; a switch keeps its division, the blades depend on it fStep = std::min( fStep, 2.0 ); } + if( m_setting.buckled ) { + // and for the lobes of a buckle, 9 m and more + fStep = std::min( fStep, 1.0 ); + } // NOTE: optionally replace this part with the commented version, after solving geometry issues with double switches if( pOwner->eType == tt_Switch && fStep * (3.0 * Global.SplineFidelity) > fLength ) { @@ -431,14 +435,33 @@ Math3D::vector3 TSegment::GetPoint(double const fDistance) const }; */ -glm::dvec3 TSegment::stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance ) const { - auto const field { track_uneven::field( Point ) }; - glm::dvec3 result { field.x * Amount.side, field.y * Amount.up, field.z * Amount.side }; - result *= track_uneven::stray_per_mm; - result.y -= pOwner->joint_dip( Distance ); +glm::dvec3 TSegment::stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance, glm::dvec3 const &Across ) const { + glm::dvec3 result { 0.0 }; + if( m_setting.uneven ) { + auto const field { track_uneven::field( Point ) }; + result = glm::dvec3 { field.x * Amount.side, field.y * Amount.up, field.z * Amount.side } * track_uneven::stray_per_mm; + result.y -= pOwner->joint_dip( Distance ); + } + if( m_setting.buckled && m_pieces.empty() ) { + result += Across * track_buckle::offset( pOwner->buckle(), Distance ); + } return result; } +double TSegment::buckle_bend( double const Distance, double const Base ) const { + if( false == m_setting.buckled || false == m_pieces.empty() ) { + return 0.0; + } + return track_buckle::mean_bend( pOwner->buckle(), Distance, Base ); +} + +glm::dvec3 TSegment::across_at( double const Distance ) const { + glm::dvec3 point; + glm::dvec3 across; + plan_frame( Distance, point, across ); + return across; +} + glm::dvec3 TSegment::uneven_bend( double const Distance ) const { if( false == m_setting.uneven ) { return glm::dvec3 { 0.0 }; @@ -453,12 +476,13 @@ glm::dvec3 TSegment::uneven_bend( double const Distance ) const { if( auto const direction { FastGetDirection( t, 0.1 / fLength ) }; on != At && glm::length( direction ) > 0.0 ) { point += direction * ( ( At - on ) / glm::length( direction ) ); } - return stray( point, pOwner->uneven_at( At, m_setting.path ), At ); }; + // the buckle left out: its curvature is taken on its own, see buckle_bend() + return stray( point, pOwner->uneven_at( At, m_setting.path ), At, glm::dvec3 { 0.0 } ); }; return ( strayed( Distance + reach ) - 2.0 * strayed( Distance ) + strayed( Distance - reach ) ) / ( reach * reach ); } void TSegment::settle_vertex( gfx::basic_vertex &Vertex, glm::dvec3 const &Origin, glm::vec3 const &Position, glm::vec3 const &Parallel, double const Distance ) const { - if( false == m_setting.uneven ) { + if( false == m_setting.uneven && false == m_setting.buckled ) { return; } // the rails settling apart turn about the middle of the track, what's outside them follows the rail; the foot of the ballast stays @@ -468,9 +492,9 @@ void TSegment::settle_vertex( gfx::basic_vertex &Vertex, glm::dvec3 const &Origi if( share <= 0.0 ) { return; } - auto const amount { pOwner->uneven_at( Distance, m_setting.path ) }; + auto const amount { m_setting.uneven ? pOwner->uneven_at( Distance, m_setting.path ) : track_uneven::amounts {} }; Vertex.position.y -= static_cast( share * track_uneven::stray_per_mm * amount.cross * track_uneven::level( Origin + glm::dvec3 { Position }, glm::dvec3 { Parallel } ) * across / gauge ); - Vertex.position += glm::vec3 { share * stray( Origin + glm::dvec3 { Vertex.position }, amount, Distance ) }; + Vertex.position += glm::vec3 { share * stray( Origin + glm::dvec3 { Vertex.position }, amount, Distance, glm::dvec3 { Parallel } ) }; } void TSegment::RaPositionGet(double const fDistance, glm::dvec3 &position, glm::vec3 &rotation) const { @@ -500,17 +524,18 @@ void TSegment::RaPositionGet(double const fDistance, glm::dvec3 &position, glm:: rotation.y = static_cast(fStoop); // pochylenie toru prostego rotation.z = static_cast(fDirection); // kierunek toru w planie } - if( false == m_setting.uneven ) { + if( false == m_setting.uneven && false == m_setting.buckled ) { return; } - // direction and slope stay as designed: the physics takes the curve radius and the grade from them + // direction and slope stay as designed: the physics takes the curve radius and the grade from them, and the curvature of a buckle + // on its own (buckle_bend()) auto const gauge { std::max( std::abs( pOwner->fTrackWidth ), 0.1f ) }; glm::dvec3 const across { -std::cos( rotation.z ), 0.0, -std::sin( rotation.z ) }; - auto const amount { pOwner->uneven_at( fDistance, m_setting.path ) }; + auto const amount { m_setting.uneven ? pOwner->uneven_at( fDistance, m_setting.path ) : track_uneven::amounts {} }; rotation.x += static_cast( track_uneven::stray_per_mm * ( amount.up * track_uneven::roll( position, across, gauge ) + amount.cross * track_uneven::level( position, across ) / gauge ) ); - position += track_uneven::across_only( stray( position, amount, fDistance ), across ); + position += track_uneven::across_only( stray( position, amount, fDistance, across ), across ); }; void TSegment::plan_frame( double const Distance, glm::dvec3 &Point, glm::dvec3 &Across ) const { diff --git a/world/Segment.h b/world/Segment.h index 3255de362..58d5785f3 100644 --- a/world/Segment.h +++ b/world/Segment.h @@ -96,6 +96,7 @@ class TSegment struct setting { std::array designrolls { 0.f, 0.f }; // as entered; fRoll1 and fRoll2 can differ at a joint bool uneven { false }; // see TrackUneven.h + bool buckled { false }; // see TrackBuckle.h int path { 0 }; // which path of a switch // where the path meets the next one: the middle of their ends and their common vector across std::array>, 2> joints; @@ -132,8 +133,9 @@ class TSegment // moves a lofted vertex with the unevenness of the track void settle_vertex( gfx::basic_vertex &Vertex, glm::dvec3 const &Origin, glm::vec3 const &Position, glm::vec3 const &Parallel, double const Distance ) const; - // displacement of a point by the unevenness, at a distance along the path - glm::dvec3 stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance ) const; + // displacement of a point by the unevenness, at a distance along the path, and by the buckle of the track across it, along Across + // (none along a zero vector) + glm::dvec3 stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance, glm::dvec3 const &Across ) const; public: bool bCurve = false; @@ -188,6 +190,10 @@ public: set_uneven( bool const Uneven, int const Path = 0 ) { m_setting.uneven = Uneven; m_setting.path = Path; } + // call before Init too + void + set_buckled( bool const Buckled ) { + m_setting.buckled = Buckled; } // a point of the path and the unit vector across it in the plan, towards the right rail profile; zero for a path never made void plan_frame( double const Distance, glm::dvec3 &Point, glm::dvec3 &Across ) const; @@ -201,6 +207,13 @@ public: // second derivative of the displacement along the path; times speed squared: acceleration of an axle glm::dvec3 uneven_bend( double const Distance ) const; + // the curvature the buckle of the track adds to the path at the distance, 1/m, positive bending towards its right; averaged over Base + // around it, as a bogie or a body takes it + double + buckle_bend( double const Distance, double const Base = 0.0 ) const; + // the unit vector across the path at the distance, towards its right + glm::dvec3 + across_at( double const Distance ) const; glm::dvec3 FastGetPoint(double const t) const; inline glm::dvec3 diff --git a/world/Track.cpp b/world/Track.cpp index 947a5836c..27bf7c9dc 100644 --- a/world/Track.cpp +++ b/world/Track.cpp @@ -756,6 +756,20 @@ void TTrack::Load(cParser *parser, glm::dvec3 const &pOrigin) m_uneven = track_uneven::read_attribute( values, eType == tt_Switch ); } } + else if( str == "buckle" ) { + // buckle ;;[;]: the track buckled by the heat, see TrackBuckle.h + auto const values { parser->getToken( false, "\n\r\t " ) }; + if( eType == tt_Normal && iCategoryFlag == 1 ) { + m_buckledeclared = track_buckle::read_buckle( values ); + } + } + else if( str == "cwr" ) { + // cwr ;[;]: the welded rail, for the buckling by the temperature + auto const values { parser->getToken( false, "\n\r\t " ) }; + if( eType == tt_Normal && iCategoryFlag == 1 ) { + m_cwr = track_buckle::read_cwr( values ); + } + } else if( str == "friction" ) { // memory cell holding friction value modifiers m_friction.first = parser->getToken(); @@ -818,8 +832,15 @@ void TTrack::Load(cParser *parser, glm::dvec3 const &pOrigin) // from the scenery is put back after it auto const velocity { fVelocity }; init_segments( true ); + // the buckle goes along the path made + if( Global.track_buckling != global_settings::track_buckling_mode::off && track_buckle::given( m_buckledeclared ) ) { + m_buckle = resolve_buckle( m_buckledeclared, 0 ); + if( false == is_buckled() ) { + ErrorLog( "Bad track: \"" + m_name + "\" too short for its buckle" ); + } + } // made with no unevenness, which is read with the attributes and goes onto them by making them again - if( is_uneven() ) { + if( is_uneven() || is_buckled() ) { init_segments( false ); } if( SwitchExtension ) { @@ -875,6 +896,7 @@ void TTrack::init_segments( bool const Initial ) { } else if( Segment ) { Segment->set_uneven( is_uneven() ); + Segment->set_buckled( is_buckled() ); } switch (eType) { @@ -1266,6 +1288,10 @@ bool TTrack::AddDynamicObject(TDynamicObject *Dynamic) } } } + if( Dynamics.empty() ) { + // a train comes onto the track, which can buckle under it in the heat + buckle_pass_enter( *Dynamic ); + } Dynamics.emplace_back( Dynamic ); Dynamic->MyTrack = this; // ABu: na ktorym torze jesteśmy if( Dynamic->iOverheadMask ) { @@ -1313,6 +1339,10 @@ bool TTrack::RemoveDynamicObject(TDynamicObject *Dynamic) } } } + if( result ) { + // the head of a train leaving the track the pass was drawn to buckle + buckle_pass_leave(); + } if( Global.iMultiplayer ) { // jeśli multiplayer if( true == Dynamics.empty() ) { @@ -2868,6 +2898,9 @@ TTrack::export_as_text_( std::ostream &Output ) const { Output << "railprofile " << m_profile1.first << ' '; } Output << track_uneven::write_attribute( m_uneven, eType == tt_Switch ); + if( eType == tt_Normal && iCategoryFlag == 1 ) { + Output << track_buckle::write_buckle( m_buckledeclared ) << track_buckle::write_cwr( m_cwr ); + } if( false == m_friction.first.empty() ) { Output << "friction " << m_friction.first << ' '; } diff --git a/world/Track.h b/world/Track.h index 033bee610..3fefde977 100644 --- a/world/Track.h +++ b/world/Track.h @@ -21,6 +21,7 @@ http://mozilla.org/MPL/2.0/. #include "world/Segment.h" #include "world/RailLayout.h" #include "world/TrackSleepers.h" +#include "world/TrackBuckle.h" #include "world/TrackUneven.h" #include "model/material.h" #include "scene/scenenode.h" @@ -278,6 +279,8 @@ public: int iAction = 0; // czy modyfikowany eventami (specjalna obsługa przy skanowaniu) float fOverhead = -1.0; // można normalnie pobierać prąd (0 dla jazdy bezprądowej po danym odcinku, >0-z opuszczonym i ograniczeniem prędkości) track_uneven::attribute m_uneven; // plain tracks and switches + track_buckle::declared m_buckledeclared; // the buckle entered in the scenery; plain rail tracks + track_buckle::cwr m_cwr; // the welded rail, for the buckling by the temperature private: double fVelocity = -1.0; // ograniczenie prędkości // prędkość dla AI (powyżej rośnie prawdopowobieństwo wykolejenia) public: @@ -412,6 +415,17 @@ public: track_uneven::amounts uneven_at( double const Distance, int const Path = 0 ); // how much of the displacement a point of the profile at the depth takes double uneven_bed_share( double const Depth ) const; + // the buckle the track has now (see TrackBuckle.h): none with physics.trackbuckling off + track_buckle::shape const &buckle() const { + return m_buckle; } + bool is_buckled() const { + return track_buckle::active( m_buckle ); } + // buckles the track during the game as the values say, or with none straightens it, and makes its geometry again. Cause goes to the log + bool buckle_now( track_buckle::declared const &Values, std::string const &Cause ); + // the buckling of the tracks by the temperature of the rails, physics.trackbuckling auto; once a minute + static void update_buckling( double const Deltatime ); + // the radius of the path in the plan at the distance, 0 straight, and the side away from its centre: -1 left, 1 right, 0 straight + double plan_radius( double const Distance, int &Outward ) const; // closes the gaps and steps of cant between the ends of joined paths void share_joints(); double joint_depth() const; // mm @@ -473,6 +487,21 @@ private: int stamp { -1 }; }; switch_stray m_switchstray; + track_buckle::shape m_buckle; + // the buckling by the temperature: the passes of the trains over the track, and the pass which will buckle it as its head leaves + std::uint32_t m_buckle_passes { 0 }; + bool m_buckle_armed { false }; + // the buckle of the values on this track, its place and side drawn with the seed where not given + track_buckle::shape resolve_buckle( track_buckle::declared const &Values, std::uint32_t const Seed ) const; + // the draws for this track: by its name, by where it is for one with none + std::uint64_t buckle_key() const; + // whether the temperature can buckle the track, and the rise of the rails above its neutral temperature it does it at + bool buckles_by_heat() const; + track_buckle::limits buckle_limits() const; + // a train coming onto the track and its head leaving it, for the buckling under a train + void buckle_pass_enter( TDynamicObject const &Dynamic ); + void buckle_pass_leave(); + void buckle_under_train(); switch_stray const &switch_uneven(); void settle_switch_stray(); void settle_switch_ends(); diff --git a/world/TrackBuckle.cpp b/world/TrackBuckle.cpp new file mode 100644 index 000000000..b49dd5753 --- /dev/null +++ b/world/TrackBuckle.cpp @@ -0,0 +1,233 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "world/Track.h" +#include "simulation/simulation.h" +#include "simulation/simulationenvironment.h" +#include "scene/scene.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "vehicle/DynObj.h" + +#include + +namespace { + +// how often the temperature is checked, s of the simulation +double constexpr check_interval { 60.0 }; +// the tracks the temperature can buckle, found at the first check +std::vector heat_sites; +bool heat_sites_found { false }; +double heat_clock { 0.0 }; +// the tracks to buckle under a train, done with the next update rather than amid the moves of the vehicles +std::vector heat_due; + +double rail_temperature_now() { + + return track_buckle::rail_temperature( Global.AirTemperature, simulation::Environment.sun().getAngle(), Global.Overcast ); +} + +} // namespace + +double TTrack::plan_radius( double const Distance, int &Outward ) const { + + Outward = 0; + if( Segment == nullptr || eType != tt_Normal ) { + return 0.0; + } + auto const length { Segment->GetLength() }; + auto const reach { std::min( 5.0, 0.25 * length ) }; + auto const at { std::clamp( Distance, reach, length - reach ) }; + glm::dvec3 behind, middle, ahead, across; + Segment->plan_frame( at - reach, behind, across ); + Segment->plan_frame( at + reach, ahead, across ); + Segment->plan_frame( at, middle, across ); + auto bend { ( behind + ahead - 2.0 * middle ) / ( reach * reach ) }; + bend.y = 0.0; + auto const curvature { glm::length( bend ) }; + // straighter than the curves the tracks are laid with + if( curvature < 1.0 / 20000.0 ) { + return 0.0; + } + // away from the centre, which the bend points to + Outward = ( glm::dot( bend, across ) > 0.0 ? -1 : 1 ); + return 1.0 / curvature; +} + +std::uint64_t TTrack::buckle_key() const { + + if( false == m_name.empty() && m_name != "none" ) { + return track_buckle::name_hash( m_name ); + } + auto const point { location() }; + return track_buckle::name_hash( std::format( "{:.1f};{:.1f};{:.1f}", point.x, point.y, point.z ) ); +} + +track_buckle::shape TTrack::resolve_buckle( track_buckle::declared const &Values, std::uint32_t const Seed ) const { + + if( Segment == nullptr || eType != tt_Normal || iCategoryFlag != 1 ) { + return {}; + } + auto const length { Segment->GetLength() }; + auto const key { buckle_key() }; + auto const place { track_buckle::draw( key, Seed, track_buckle::place ) }; + // the side out of the curve where the buckle is + auto const centre { Values.centre >= 0.f ? static_cast( Values.centre ) : 0.5 * length }; + auto outward { 0 }; + auto const radius { plan_radius( centre, outward ) }; + return track_buckle::resolve( Values, length, outward, radius, place, track_buckle::draw( key, Seed, track_buckle::way ) ); +} + +bool TTrack::buckle_now( track_buckle::declared const &Values, std::string const &Cause ) { + + if( Global.track_buckling == global_settings::track_buckling_mode::off ) { + return false; + } + if( eType != tt_Normal || iCategoryFlag != 1 || Segment == nullptr ) { + ErrorLog( "Bad track: \"" + m_name + "\" can't buckle, it isn't a plain rail track" ); + return false; + } + auto const shape { resolve_buckle( Values, 0 ) }; + if( track_buckle::given( Values ) && false == track_buckle::active( shape ) ) { + ErrorLog( std::format( "Bad track: \"{}\" too short for a buckle {:.0f} m long", m_name, 2.0 * track_buckle::reach_share * ( Values.length > 0.f ? Values.length : track_buckle::straight_length ) ) ); + return false; + } + m_buckle = shape; + m_buckle_armed = false; + // made again with the buckle, which the rails, the sleepers and the axles on the track follow + init_segments( false ); + auto const rebuild = []( TTrack &Track ) { + auto §ion { simulation::Region->section( Track.location() ) }; + Track.rebuild_geometry( section.m_geometrycreated ? section.m_geometrybank : gfx::geometrybank_handle {} ); }; + rebuild( *this ); + for( auto *crossing : m_crossings ) { + if( crossing != nullptr && crossing != this ) { + rebuild( *crossing ); + } + } + if( is_buckled() ) { + WriteLog( std::format( + "Track \"{}\" buckled ({}): {:.0f} mm to the {} at {:.1f} m, main lobe {:.1f} m, curvature up to 1/{:.0f} m", + m_name, Cause, std::abs( 1000.0 * m_buckle.amplitude ), m_buckle.amplitude > 0.0 ? "right" : "left", m_buckle.centre, m_buckle.length, + 1.0 / track_buckle::peak_bend( m_buckle.amplitude, m_buckle.length ) ) ); + } + else { + WriteLog( "Track \"" + m_name + "\" straightened (" + Cause + ")" ); + } + return true; +} + +bool TTrack::buckles_by_heat() const { + + if( eType != tt_Normal || iCategoryFlag != 1 || Segment == nullptr || is_buckled() || false == m_crossings.empty() ) { + return false; + } + auto outward { 0 }; + auto const radius { plan_radius( 0.5 * Segment->GetLength(), outward ) }; + // continuous welded rail is laid down to a radius of 190 m (PLK ST-T1-A8) + if( radius > 0.0 && radius < 190.0 ) { + return false; + } + auto const natural { track_buckle::natural( outward != 0 && radius < track_buckle::curve_radius ) }; + if( Segment->GetLength() < 2.0 * ( track_buckle::reach_share * natural.length + track_buckle::end_margin ) ) { + return false; + } + return track_buckle::weak_spot( buckle_key(), Global.random_seed, Segment->GetLength(), m_cwr.worked ); +} + +track_buckle::limits TTrack::buckle_limits() const { + + auto outward { 0 }; + auto const radius { plan_radius( 0.5 * Segment->GetLength(), outward ) }; + return track_buckle::limits_of( m_cwr, radius, uneven_declared().side ); +} + +void TTrack::update_buckling( double const Deltatime ) { + + if( Global.track_buckling != global_settings::track_buckling_mode::automatic ) { + return; + } + if( false == heat_sites_found ) { + heat_sites_found = true; + for( auto *track : simulation::Paths.sequence() ) { + if( track != nullptr && track->buckles_by_heat() ) { + heat_sites.push_back( track ); + } + } + WriteLog( std::format( "Track buckling: {} places the heat can buckle", heat_sites.size() ) ); + // the first check right away, a scenario can start in the heat + heat_clock = check_interval; + } + for( auto *track : heat_due ) { + track->buckle_under_train(); + } + heat_due.clear(); + heat_clock += Deltatime; + if( heat_clock < check_interval ) { + return; + } + heat_clock = 0.0; + auto const rail { rail_temperature_now() }; + for( auto *track : heat_sites ) { + if( track->is_buckled() ) { + continue; + } + auto const rise { rail - track->m_cwr.neutral }; + if( track_buckle::decide( rise, track->buckle_limits(), false, 1.0 ) == track_buckle::verdict::by_itself ) { + auto outward { 0 }; + auto const radius { track->plan_radius( 0.5 * track->Segment->GetLength(), outward ) }; + auto values { track_buckle::natural( outward != 0 && radius < track_buckle::curve_radius ) }; + values.centre = static_cast( track_buckle::resolve( values, track->Segment->GetLength(), outward, radius, + track_buckle::draw( track->buckle_key(), Global.random_seed, track_buckle::place ), 0.0 ).centre ); + track->buckle_now( values, std::format( "rails at {:.0f} C, {:.0f} K above neutral, {:.0f} kN in each", rail, rise, + 0.001 * track_buckle::thermal_force( track_buckle::rail_area( track->m_profile1.first ), rise ) ) ); + } + } +} + +void TTrack::buckle_pass_enter( TDynamicObject const &Dynamic ) { + + if( Global.track_buckling != global_settings::track_buckling_mode::automatic || is_buckled() || false == heat_sites_found ) { + return; + } + if( std::ranges::find( heat_sites, this ) == heat_sites.end() ) { + return; + } + ++m_buckle_passes; + auto const *mover { Dynamic.MoverParameters }; + auto const train { mover != nullptr && track_buckle::stirs( std::abs( mover->Vel ), mover->BrakePress > 0.5 ) }; + auto const rise { rail_temperature_now() - m_cwr.neutral }; + auto const draw { track_buckle::draw( buckle_key(), Global.random_seed, track_buckle::pass, m_buckle_passes ) }; + m_buckle_armed = ( track_buckle::decide( rise, buckle_limits(), train, draw ) != track_buckle::verdict::none ); +} + +void TTrack::buckle_pass_leave() { + + if( false == m_buckle_armed ) { + return; + } + m_buckle_armed = false; + heat_due.push_back( this ); +} + +void TTrack::buckle_under_train() { + + if( is_buckled() ) { + return; + } + // under the rest of the train, which lifts the track between its bogies + auto const rail { rail_temperature_now() }; + auto outward { 0 }; + auto const radius { plan_radius( 0.5 * Segment->GetLength(), outward ) }; + auto values { track_buckle::natural( outward != 0 && radius < track_buckle::curve_radius ) }; + values.centre = static_cast( track_buckle::resolve( values, Segment->GetLength(), outward, radius, + track_buckle::draw( buckle_key(), Global.random_seed, track_buckle::place ), 0.0 ).centre ); + buckle_now( values, std::format( "under a train, rails at {:.0f} C, {:.0f} K above neutral", rail, rail - m_cwr.neutral ) ); +} diff --git a/world/TrackBuckle.h b/world/TrackBuckle.h new file mode 100644 index 000000000..25825ed99 --- /dev/null +++ b/world/TrackBuckle.h @@ -0,0 +1,440 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Lateral buckling of continuous welded rail: in the heat the rails, held from growing longer, press on the track along it with +// E*A*alpha*dT, and where the bed holds it too weakly sideways the track jumps out to the side. The track of the scenery takes it as +// a displacement across it (TSegment::stray()), drawn and followed by the axles as the unevenness of TrackUneven.h is. +// Sources: Kish, Samavedam, "Risk analysis based CWR track buckling safety evaluations" (Volpe, about 2001); FRA, "Dynamic buckling +// test analyses of a high degree CWR track"; PKP PLK ST-T1-A8 (2021); the answers of the ministry to interpellations 3875 (2026) and +// 2575 (2025). The thresholds and the shape are fitted to the numbers there, see test_track_buckle.cpp. +namespace track_buckle { + +// the shape: a main lobe and a side lobe of the other way on each side of it, as the buckled shapes of Kerr and Kish have it. A +// cosine of a period twice the main lobe under a window cos^2 over three lobes: the side lobes come to a quarter of the main one, and +// the curvature runs on smoothly all along, into the straight track at the ends too, as a bent rail has it +// straight track jumps out far at once, a curve goes out step by step and less far, to the outside of the curve (Kish, Samavedam) +inline constexpr double straight_amplitude { 0.4 }; // m +inline constexpr double straight_length { 14.0 }; // m, main lobe +inline constexpr double curve_amplitude { 0.2 }; // m +inline constexpr double curve_length { 11.0 }; // m +inline constexpr double curve_radius { 1500.0 }; // m, below which a track counts as a curve for the shape +inline constexpr double end_margin { 2.0 }; // m between the buckle and the ends of the track +inline constexpr double most_amplitude { 1.0 }; // m +inline constexpr double least_length { 4.0 }; // m +inline constexpr double most_length { 60.0 }; // m +// how far the side lobes reach from the centre, in lengths of the main lobe +inline constexpr double reach_share { 1.5 }; + +struct shape { + double amplitude { 0.0 }; // of the main lobe, m: positive to the right of the path looking from its start to its end, negative to the left + double length { 0.0 }; // of the main lobe between the points it crosses the line, m; each side lobe is as long + double centre { 0.0 }; // of the main lobe, distance from the start of the path, m +}; + +inline bool active( shape const &Shape ) { + + return Shape.amplitude != 0.0 && Shape.length > 0.0; +} + +// the wave and the window at a distance from the centre, with their derivatives +struct parts { + double wave, wave1, wave2; + double window, window1, window2; +}; + +inline parts parts_at( shape const &Shape, double const Distance ) { + + auto const from { Distance - Shape.centre }; + auto const k { glm::pi() / Shape.length }; + // cos^2(b x) = ( 1 + cos( 2 b x ) ) / 2 reaching 0 at the ends of the side lobes + auto const b { glm::pi() / ( 2.0 * reach_share * Shape.length ) }; + return { + std::cos( k * from ), -k * std::sin( k * from ), -k * k * std::cos( k * from ), + 0.5 * ( 1.0 + std::cos( 2.0 * b * from ) ), -b * std::sin( 2.0 * b * from ), -2.0 * b * b * std::cos( 2.0 * b * from ) }; +} + +inline bool within( shape const &Shape, double const Distance ) { + + return active( Shape ) && std::abs( Distance - Shape.centre ) < reach_share * Shape.length; +} + +// displacement across the path at a distance along it, m +inline double offset( shape const &Shape, double const Distance ) { + + if( false == within( Shape, Distance ) ) { + return 0.0; + } + auto const p { parts_at( Shape, Distance ) }; + return Shape.amplitude * p.wave * p.window; +} + +// its first derivative along the path +inline double slope( shape const &Shape, double const Distance ) { + + if( false == within( Shape, Distance ) ) { + return 0.0; + } + auto const p { parts_at( Shape, Distance ) }; + return Shape.amplitude * ( p.wave1 * p.window + p.wave * p.window1 ); +} + +// and the second: the curvature the buckle adds to the path, 1/m, positive bending to the right +inline double bend( shape const &Shape, double const Distance ) { + + if( false == within( Shape, Distance ) ) { + return 0.0; + } + auto const p { parts_at( Shape, Distance ) }; + return Shape.amplitude * ( p.wave2 * p.window + 2.0 * p.wave1 * p.window1 + p.wave * p.window2 ); +} + +// the mean curvature over a stretch around a distance, as a bogie over its wheelbase feels it: the difference of the slopes at its ends +// over its length +inline double mean_bend( shape const &Shape, double const Distance, double const Base ) { + + if( Base <= 0.0 ) { + return bend( Shape, Distance ); + } + return ( slope( Shape, Distance + 0.5 * Base ) - slope( Shape, Distance - 0.5 * Base ) ) / Base; +} + +// and as a body on two bogies: it goes sideways by the mean of its pivots, so its lateral acceleration is v^2 times the mean of the +// curvatures at the pivots, each over the wheelbase of the bogie (without bogies: the pivots are the axles, with no base) +inline double body_bend( shape const &Shape, double const Distance, double const Pivots, double const Base ) { + + return 0.5 * ( mean_bend( Shape, Distance - 0.5 * Pivots, Base ) + mean_bend( Shape, Distance + 0.5 * Pivots, Base ) ); +} + +// how far from the centre the buckle reaches on each side +inline double reach( shape const &Shape ) { + + return active( Shape ) ? reach_share * Shape.length : 0.0; +} + +// the largest curvature of the buckle, 1/m, in the middle of the main lobe: pi^2 a / L^2 of the wave and 2/9 of it from the window +inline double peak_bend( double const Amplitude, double const Length ) { + + return ( 1.0 + 2.0 / ( 4.0 * reach_share * reach_share ) ) * glm::pi() * glm::pi() * std::abs( Amplitude ) / ( Length * Length ); +} + +// the heat + +inline constexpr double steel_modulus { 210e9 }; // Pa +inline constexpr double steel_expansion { 1.15e-5 }; // 1/K +inline constexpr double sun_heating { 17.0 }; // K a rail in full sun is warmer than the air: 30 F (Kish, Samavedam) +inline constexpr float neutral_default { 26.f }; // C, the rail stress-free temperature PLK lays its tracks at since 2025 +inline constexpr double area_60e1 { 76.70e-4 }; // m2 +inline constexpr double area_49e1 { 62.92e-4 }; +inline constexpr double area_s42 { 54.2e-4 }; + +// the rail section by the name of the rail profile, 60E1 if it tells nothing +inline double rail_area( std::string_view const Profile ) { + + auto const has = [ Profile ]( std::string_view const Part ) { + return std::search( Profile.begin(), Profile.end(), Part.begin(), Part.end(), []( char const Left, char const Right ) { + return std::tolower( static_cast( Left ) ) == std::tolower( static_cast( Right ) ); } ) != Profile.end(); }; + if( has( "49" ) ) { + return area_49e1; + } + if( has( "s42" ) ) { + return area_s42; + } + return area_60e1; +} + +// the force along a rail held from growing longer, N, pressing for Rise above the neutral temperature +inline double thermal_force( double const Area, double const Rise ) { + + return steel_modulus * Area * steel_expansion * Rise; +} + +// the temperature of a rail, C, from the air, the height of the sun over the horizon in degrees and the clouds (0 clear, 1 overcast; +// above 1 it rains, which cools as much) +inline double rail_temperature( double const Air, double const Sun, double const Overcast ) { + + auto const sun { std::max( 0.0, std::sin( glm::radians( Sun ) ) ) }; + return Air + sun_heating * sun * ( 1.0 - std::clamp( Overcast, 0.0, 1.0 ) ); +} + +// the state of the track, from the scenery +namespace grade { +inline constexpr int good { 0 }; // concrete sleepers, full ballast shoulder, consolidated +inline constexpr int average { 1 }; +inline constexpr int weak { 2 }; // timber sleepers, ballast missing, or the bed disturbed by tamping or sleeper renewal not yet consolidated +} + +struct cwr { + float neutral { neutral_default }; // C + int grade { grade::average }; + bool worked { false }; // works on the bed lately: weak whatever the grade +}; + +// the rise above the neutral temperature at which the track buckles: from low on under a passing train, which lifts it between the +// bogies and takes away part of its hold sideways, at high and above by itself +struct limits { + double low { 0.0 }; // K + double high { 0.0 }; +}; + +inline constexpr std::array grade_limits { { { 40.0, 55.0 }, { 32.0, 45.0 }, { 22.0, 32.0 } } }; + +// for the grade of the track, lowered in a curve, which presses outwards, and by an uneven line, which gives it a start +inline limits limits_of( cwr const &Track, double const Radius, double const Side ) { + + auto const kind { Track.worked ? grade::weak : std::clamp( Track.grade, grade::good, grade::weak ) }; + auto result { grade_limits[ kind ] }; + auto less { 0.0 }; + auto const radius { std::abs( Radius ) }; + if( radius > 0.0 && radius < 300.0 ) { + less += 6.0; + } + else if( radius > 0.0 && radius < 600.0 ) { + less += 3.0; + } + if( Side > 15.0 ) { + less += 3.0; + } + result.low -= less; + result.high -= less; + return result; +} + +// the share of the passes of a train which buckle the track at the rise: none below low, all at high +inline double chance( double const Rise, limits const &Limits ) { + + if( Limits.high <= Limits.low ) { + return Rise >= Limits.high ? 1.0 : 0.0; + } + return std::clamp( ( Rise - Limits.low ) / ( Limits.high - Limits.low ), 0.0, 1.0 ); +} + +enum class verdict { + none, + under_train, + by_itself +}; + +// with Train the track has a train going over it hard enough, Draw is the draw of the pass, 0 to 1 +inline verdict decide( double const Rise, limits const &Limits, bool const Train, double const Draw ) { + + if( Rise >= Limits.high ) { + return verdict::by_itself; + } + if( Train && Rise >= Limits.low && Draw < chance( Rise, Limits ) ) { + return verdict::under_train; + } + return verdict::none; +} + +// a train stirs the track up when it goes fast or brakes on it +inline constexpr double stirring_speed { 40.0 }; // km/h +inline bool stirs( double const Speed, bool const Braking ) { + + return Speed > stirring_speed || ( Braking && Speed > 5.0 ); +} + +// draws, the same for the same track and seed + +// FNV-1a, which std::hash isn't on every compiler +inline std::uint64_t name_hash( std::string_view const Name ) { + + std::uint64_t hash { 14695981039346656037ULL }; + for( auto const character : Name ) { + hash ^= static_cast( character ); + hash *= 1099511628211ULL; + } + return hash; +} + +// the splitmix64 finalizer, so close numbers give far apart draws +inline std::uint64_t scramble( std::uint64_t Value ) { + + Value += 0x9e3779b97f4a7c15ULL; + Value = ( Value ^ ( Value >> 30 ) ) * 0xbf58476d1ce4e5b9ULL; + Value = ( Value ^ ( Value >> 27 ) ) * 0x94d049bb133111ebULL; + return Value ^ ( Value >> 31 ); +} + +// what a draw is for, so the draws for one track don't go together +enum purpose : std::uint64_t { + pass = 1, + site = 2, + place = 3, + way = 4 +}; + +// a fraction 0 to 1 +inline double draw( std::uint64_t const Name, std::uint32_t const Seed, std::uint64_t const Purpose, std::uint64_t const Number = 0 ) { + + auto const value { scramble( scramble( scramble( Name ^ Purpose ) + Seed ) + Number ) }; + // the 53 high bits + return static_cast( value >> 11 ) / 9007199254740992.0; +} + +// where the track buckles by the temperature on its own: one place in so many metres of track, and the tracks worked on lately. +// Elsewhere the bed holds far beyond the limits of the grade (Sweden: 200 buckles in the hot summer of 2018 on 14 000 km) +inline constexpr double site_spacing { 10000.0 }; // m + +inline bool weak_spot( std::uint64_t const Name, std::uint32_t const Seed, double const Length, bool const Worked ) { + + return Worked || draw( Name, Seed, site ) < Length / site_spacing; +} + +// the entries in the scenery + +// buckle ;;[;] +struct declared { + float amplitude { 0.f }; // mm + float length { -1.f }; // m, negative: by the shape of the track + float centre { -1.f }; // m, negative: drawn + int side { 0 }; +}; + +inline bool given( declared const &Values ) { + + return Values.amplitude > 0.f; +} + +// the numbers of an entry like "400;18;60", NaN where left out +template +std::array read_numbers( std::string_view const Text ) { + + std::array result; + result.fill( std::numeric_limits::quiet_NaN() ); + auto rest { Text }; + for( auto &field : result ) { + auto const end { std::min( rest.find( ';' ), rest.size() ) }; + if( auto value { 0.f }; end > 0 && std::from_chars( rest.data(), rest.data() + end, value ).ec == std::errc {} && std::isfinite( value ) ) { + field = value; + } + if( end == rest.size() ) { + break; + } + rest.remove_prefix( end + 1 ); + } + return result; +} + +inline declared read_buckle( std::string_view const Text ) { + + auto const fields { read_numbers<4>( Text ) }; + declared result; + if( std::isfinite( fields[ 0 ] ) ) { + result.amplitude = std::clamp( fields[ 0 ], 0.f, static_cast( most_amplitude * 1000.0 ) ); + } + if( std::isfinite( fields[ 1 ] ) && fields[ 1 ] > 0.f ) { + result.length = std::clamp( fields[ 1 ], static_cast( least_length ), static_cast( most_length ) ); + } + if( std::isfinite( fields[ 2 ] ) && fields[ 2 ] >= 0.f ) { + result.centre = fields[ 2 ]; + } + if( std::isfinite( fields[ 3 ] ) ) { + result.side = ( fields[ 3 ] > 0.f ? 1 : fields[ 3 ] < 0.f ? -1 : 0 ); + } + return result; +} + +inline std::string write_buckle( declared const &Values ) { + + if( false == given( Values ) ) { + return {}; + } + std::ostringstream text; + text << "buckle " << Values.amplitude << ';'; + if( Values.length > 0.f ) { + text << Values.length; + } + text << ';'; + if( Values.centre >= 0.f ) { + text << Values.centre; + } + if( Values.side != 0 ) { + text << ';' << Values.side; + } + text << ' '; + return text.str(); +} + +// cwr ;[;] +inline cwr read_cwr( std::string_view const Text ) { + + auto const fields { read_numbers<3>( Text ) }; + cwr result; + if( std::isfinite( fields[ 0 ] ) ) { + result.neutral = std::clamp( fields[ 0 ], -20.f, 60.f ); + } + if( std::isfinite( fields[ 1 ] ) ) { + result.grade = std::clamp( static_cast( std::lround( fields[ 1 ] ) ), 0, 2 ); + } + if( std::isfinite( fields[ 2 ] ) ) { + result.worked = fields[ 2 ] > 0.f; + } + return result; +} + +inline std::string write_cwr( cwr const &Values ) { + + if( Values.neutral == neutral_default && Values.grade == grade::average && false == Values.worked ) { + return {}; + } + std::ostringstream text; + text << "cwr " << Values.neutral << ';' << Values.grade; + if( Values.worked ) { + text << ";1"; + } + text << ' '; + return text.str(); +} + +// the buckle of the values on a track of the length, which curves to the side Outward (-1 left, 1 right, 0 straight), with radius +// Radius (0 straight); None for one which doesn't fit into the track. Place and Way are draws for the centre and the side not given +inline shape resolve( declared const &Values, double const Length, int const Outward, double const Radius, double const Place, double const Way ) { + + if( false == given( Values ) ) { + return {}; + } + auto const curve { Outward != 0 && Radius > 0.0 && Radius < curve_radius }; + shape result; + result.length = Values.length > 0.f ? static_cast( Values.length ) : ( curve ? curve_length : straight_length ); + auto const first { reach_share * result.length + end_margin }; + auto const last { Length - reach_share * result.length - end_margin }; + if( last < first ) { + return {}; + } + result.centre = Values.centre >= 0.f ? std::clamp( static_cast( Values.centre ), first, last ) : first + ( last - first ) * Place; + auto const side { Values.side != 0 ? Values.side : Outward != 0 ? Outward : ( Way < 0.5 ? -1 : 1 ) }; + result.amplitude = side * 0.001 * Values.amplitude; + return result; +} + +// the buckle the temperature makes on a track: as large as a curve or a straight one makes +inline declared natural( bool const Curve ) { + + declared result; + result.amplitude = static_cast( 1000.0 * ( Curve ? curve_amplitude : straight_amplitude ) ); + result.length = static_cast( Curve ? curve_length : straight_length ); + return result; +} + +} // namespace track_buckle From b5f7811f645345ce399e7a978af0f6c7732aca5b Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 11:48:52 +0100 Subject: [PATCH 016/136] feat(physics): the curvature of a buckled track in the criteria of derailment derailment::track_state::buckle_curvature [1/m], positive bending with the curve (either way on a straight track), taken whole (buckle_share 1.0): a buckle is a long wave the body follows as it does the curve. It adds to 1/R in the lateral acceleration the cant doesn't balance and in the angle of attack of the leading axle; where the buckle bends the line against the curve, out of the bend is into the curve, where the cant leans the vehicle too. The body feels the mean of the curvatures at its pivots, each bogie averaging it over its wheelbase (track_buckle::body_bend()). A coach (42 t, pivots 17.2 m) over a buckle 0.3 m by 20 m on a straight track: goes over at 30 and 60 km/h, off the rails from 125 km/h, the same within 2 km/h with steps of 0.002, 0.01 and 0.03 s; 0.6 m by 20 m from 89 km/h, the default buckle of a straight track (0.4 m by 14 m) from 57 km/h, a two-axle wagon (9 m) over 0.3 by 20 from 92 km/h. Out of a curve of 600 m the 0.3 m buckle derails it from 102 km/h, the curve alone from 169 km/h. --- McZapkie/derailment.cpp | 24 +++- McZapkie/derailment.h | 11 ++ tests/unit/test_track_buckle_derailment.cpp | 131 ++++++++++++++++++++ 3 files changed, 162 insertions(+), 4 deletions(-) create mode 100644 tests/unit/test_track_buckle_derailment.cpp diff --git a/McZapkie/derailment.cpp b/McZapkie/derailment.cpp index 5cccc9f9c..9ddf31917 100644 --- a/McZapkie/derailment.cpp +++ b/McZapkie/derailment.cpp @@ -79,6 +79,22 @@ double unbalanced_acceleration(double const Velocity, double const Radius, doubl return Velocity * Velocity / std::abs(Radius) - cant; } +double line_curvature(track_state const &Track) { + auto const buckle{buckle_share * Track.buckle_curvature}; + if (false == curved(Track.radius)) { + return std::abs(buckle); + } + return 1.0 / std::abs(Track.radius) + buckle; +} + +double line_acceleration(track_state const &Track, double const Velocity) { + if (Track.buckle_curvature == 0.0) { + return unbalanced_acceleration(Velocity, Track.radius, Track.cant); + } + // bent against the curve, out of the bend is into the curve, where the cant leans the vehicle too + return Velocity * Velocity * line_curvature(Track) - gravity * std::sin(std::abs(Track.cant)); +} + double unloading_ratio(double const Acceleration, double const CentreOfGravity, double const ContactSpacing, suspension const &Suspension) { return 2.0 / ContactSpacing * std::abs(Acceleration) / gravity * leaning_height(CentreOfGravity, Suspension); } @@ -157,7 +173,7 @@ wheel_forces flange_forces(vehicle_state const &Vehicle, track_state const &Trac auto const height{leaning_height(Vehicle.centre_of_gravity, suspension{})}; auto const staticload{Vehicle.mass * gravity / (2.0 * axles)}; - auto const inertia{Vehicle.mass * unbalanced_acceleration(Velocity, Track.radius, Track.cant)}; + auto const inertia{Vehicle.mass * line_acceleration(Track, Velocity)}; auto const couplings{coupling_force(Vehicle, Track)}; auto const quasistatic{inertia + couplings}; // the sway and the uneven track push the worst way: towards the rail the vehicle already leans on @@ -167,8 +183,8 @@ wheel_forces flange_forces(vehicle_state const &Vehicle, track_state const &Trac // the leading axle meets the rail at an angle in a curve, the creep force of its inner wheel at most the friction auto guiding{0.0}; - if (curved(Track.radius)) { - auto const attack{Vehicle.axle_base / (2.0 * std::abs(Track.radius))}; + if (auto const curvature{std::abs(line_curvature(Track))}; curvature > 0.0) { + auto const attack{0.5 * Vehicle.axle_base * curvature}; guiding = tread_friction * staticload * std::min(1.0, attack / saturated_attack); } result.y = std::abs(result.lateral) / axles + guiding; @@ -186,7 +202,7 @@ double body_acceleration(vehicle_state const &Vehicle, track_state const &Track, } auto const height{leaning_height(Vehicle.centre_of_gravity, suspension{})}; // the couplings pull at the height of the buffers: as much of a lean as their moment gives - auto const moment{Vehicle.mass * unbalanced_acceleration(Velocity, Track.radius, Track.cant) * height + coupling_force(Vehicle, Track) * buffer_height}; + auto const moment{Vehicle.mass * line_acceleration(Track, Velocity) * height + coupling_force(Vehicle, Track) * buffer_height}; return std::abs(moment) / (Vehicle.mass * height) + dynamic_acceleration(Track, Velocity) * condition_of(Track).lateral; } diff --git a/McZapkie/derailment.h b/McZapkie/derailment.h index 7d587517f..65058bd4a 100644 --- a/McZapkie/derailment.h +++ b/McZapkie/derailment.h @@ -124,6 +124,9 @@ struct track_state { double gauge{1.435}; // [m] double uneven_curvature{0.0}; // the lateral curvature of the unevenness under the vehicle [1/m] double uneven_cross{0.0}; // the cross level unevenness of the track [mm] + // the curvature a buckle of the track adds under the vehicle [1/m], see world/TrackBuckle.h: positive bending with + // the curve, on a straight track either way + double buckle_curvature{0.0}; int damage{0}; // dtrack_* flags }; @@ -135,6 +138,14 @@ struct track_condition { track_condition condition_of(track_state const &Track); // share of the vehicle that follows the short waves of an uneven track: the wheelsets and the bogies, the body not inline constexpr double uneven_share{0.3}; +// and the long wave of a buckle, which the body follows whole, as it does the curve +inline constexpr double buckle_share{1.0}; +// the curvature of the line under the vehicle [1/m], positive towards the centre of the curve: the curve, and a +// buckle on it. negative where a buckle bends the line the other way more than the curve does +double line_curvature(track_state const &Track); +// the lateral acceleration [m/s2] the cant doesn't balance on that line, positive out of the curve: +// unbalanced_acceleration() with a buckle +double line_acceleration(track_state const &Track, double Velocity); // the angle [rad] between the vehicle and the line of the force of the coupling at the end, in a curve: half the // angle between the two vehicles, whose middles are half their lengths apart along the curve diff --git a/tests/unit/test_track_buckle_derailment.cpp b/tests/unit/test_track_buckle_derailment.cpp new file mode 100644 index 000000000..1b72db4cc --- /dev/null +++ b/tests/unit/test_track_buckle_derailment.cpp @@ -0,0 +1,131 @@ +#include "stdafx.h" +#include "doctest.h" +#include "McZapkie/derailment.h" +#include "world/TrackBuckle.h" + +#include + +// a vehicle over a buckled track, by the criteria of derailment.h: the curvature of the buckle goes into the track +// under the vehicle as buckle_curvature (world/TrackBuckle.h: the body by the mean of its pivots, each bogie over its +// wheelbase), whole, as the curvature of the curve does + +namespace { + +// a four-axle coach: 42 t, 24.5 m over the buffers, the pivots 17.2 m and the axles of a bogie 2.5 m apart +derailment::vehicle_state coach() +{ + derailment::vehicle_state vehicle; + vehicle.mass = 42000.0; + vehicle.axles = 4; + vehicle.length = 24.5; + vehicle.axle_base = 2.5; + vehicle.centre_of_gravity = 1.4; + return vehicle; +} +double constexpr pivots{17.2}; + +// a two-axle wagon: 25 t, 14 m over the buffers, the axles 9 m apart, which are its pivots +derailment::vehicle_state wagon() +{ + derailment::vehicle_state vehicle; + vehicle.mass = 25000.0; + vehicle.axles = 2; + vehicle.length = 14.0; + vehicle.axle_base = 9.0; + vehicle.centre_of_gravity = 1.6; + return vehicle; +} + +struct rolling_stock { + derailment::vehicle_state vehicle; + double pivots; + double base; // of the bogies, 0 without +}; +rolling_stock const four_axle{coach(), pivots, 2.5}; +rolling_stock const two_axle{wagon(), 9.0, 0.0}; + +// Outward: the side out of the curve of Radius (-1 left, 1 right), 0 on a straight track +derailment::outcome ride(track_buckle::shape const &Shape, double const Radius, int const Outward, double const Speed, double const Step, rolling_stock const &Stock = four_axle) +{ + auto const &vehicle{Stock.vehicle}; + derailment::monitor monitor; + auto const velocity{Speed / 3.6}; + auto const reach{track_buckle::reach(Shape) + Stock.pivots}; + for (auto at = Shape.centre - reach - 5.0; at <= Shape.centre + reach + 5.0; at += velocity * Step) + { + derailment::track_state track; + track.radius = Radius; + auto const bend{track_buckle::body_bend(Shape, at, Stock.pivots, Stock.base)}; + // positive bending with the curve, whose centre is away from the outer side + track.buckle_curvature = (Outward != 0 ? -Outward * bend : bend); + auto const verdict{monitor.update(vehicle, track, velocity, velocity * Step)}; + if (verdict.result != derailment::outcome::none) + return verdict.result; + } + return derailment::outcome::none; +} + +// the lowest speed it leaves the rails at, km/h, to 0.5 km/h +double limit(track_buckle::shape const &Shape, double const Radius, int const Outward, double const Step, rolling_stock const &Stock = four_axle) +{ + auto low{5.0}; + auto high{300.0}; + while (high - low > 0.5) + { + auto const middle{0.5 * (low + high)}; + if (ride(Shape, Radius, Outward, middle, Step, Stock) != derailment::outcome::none) + high = middle; + else + low = middle; + } + return high; +} + +} // namespace + +TEST_CASE("a coach goes over a buckle slowly, and leaves the rails on it fast") +{ + // 0.3 m out over a main lobe of 20 m on a straight track: an equivalent radius of 110 m, felt by the body less + track_buckle::shape const shape{0.3, 20.0, 60.0}; + CHECK(ride(shape, 0.0, 0, 30.0, 0.01) == derailment::outcome::none); + CHECK(ride(shape, 0.0, 0, 60.0, 0.01) == derailment::outcome::none); + CHECK(ride(shape, 0.0, 0, 140.0, 0.01) != derailment::outcome::none); + auto const speed{limit(shape, 0.0, 0, 0.01)}; + MESSAGE("coach over a buckle 0.3 m by 20 m on a straight track: off the rails from ", speed, " km/h"); + CHECK(speed > 60.0); + CHECK(speed < 140.0); + // the same with any step + CHECK(limit(shape, 0.0, 0, 0.002) == doctest::Approx(speed).epsilon(2.0 / speed)); + CHECK(limit(shape, 0.0, 0, 0.03) == doctest::Approx(speed).epsilon(2.0 / speed)); + // either way on a straight track + track_buckle::shape const left{-0.3, 20.0, 60.0}; + CHECK(limit(left, 0.0, 0, 0.01) == doctest::Approx(speed).epsilon(1.0 / speed)); + // a larger buckle derails it slower + auto const large{limit(track_buckle::shape{0.6, 20.0, 60.0}, 0.0, 0, 0.01)}; + MESSAGE("0.6 m by 20 m: ", large, " km/h"); + CHECK(large < speed); + // the default one of a straight track, 0.4 m by 14 m + auto const natural{limit(track_buckle::shape{track_buckle::straight_amplitude, track_buckle::straight_length, 60.0}, 0.0, 0, 0.01)}; + MESSAGE("the default buckle of a straight track, 0.4 m by 14 m: ", natural, " km/h"); + CHECK(natural < speed); + // a body on two axles 9 m apart doesn't span the main lobe as one on bogies 17.2 m apart does: it follows the + // buckle closer, and goes off the rails slower + auto const short_wagon{limit(shape, 0.0, 0, 0.01, two_axle)}; + MESSAGE("a two-axle wagon over 0.3 m by 20 m: ", short_wagon, " km/h"); + CHECK(short_wagon < speed); + CHECK(ride(shape, 0.0, 0, 30.0, 0.01, two_axle) == derailment::outcome::none); +} + +TEST_CASE("a buckle out of a curve derails a coach slower than the same on a straight track") +{ + track_buckle::shape const shape{0.3, 20.0, 60.0}; + auto const straight{limit(shape, 0.0, 0, 0.01)}; + // a curve of 600 m without cant, the buckle to the right out of it (a curve to the left) + auto const curve{limit(track_buckle::shape{}, 600.0, 0, 0.01)}; + auto const outwards{limit(shape, 600.0, 1, 0.01)}; + MESSAGE("R 600 m: the curve alone from ", curve, " km/h, with the buckle out of it from ", outwards, " km/h, on a straight ", straight, " km/h"); + CHECK(outwards < straight); + CHECK(outwards < curve); + // one into the curve (not what the heat does) still lowers it, by its flanks which bend with the curve + CHECK(limit(track_buckle::shape{-0.3, 20.0, 60.0}, 600.0, 1, 0.01) < curve); +} From 7b41be312715b3f4f9c7f96376d3bb12ef0dab77 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 12:25:29 +0100 Subject: [PATCH 017/136] feat(physics): a vehicle passes on the curvature of a buckle under it TTrackShape::buckle_curvature, set by TDynamicObject next to the radius: the mean of the curvatures of the buckle at the outer axles, each averaged over the wheelbase of its bogie (TTrackFollower::BuckleCurvature(), TTrack::buckle_curvature()), positive bending with the curve. check_derailment() takes it into derailment::track_state::buckle_curvature, and a vehicle derailed with a buckle under it says so in the log ("derailed on buckled track"). --- McZapkie/MOVER.h | 2 ++ McZapkie/Mover.cpp | 6 ++++++ vehicle/DynObj.cpp | 2 ++ world/Track.h | 3 +++ world/TrackBuckle.cpp | 12 ++++++++++++ world/TrkFoll.cpp | 5 +++++ world/TrkFoll.h | 2 ++ 7 files changed, 32 insertions(+) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 63783419b..d4a7cb2b2 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -695,6 +695,8 @@ struct TTrackShape double uneven_curvature = 0.0; /// Cross level unevenness of the track [mm]. double uneven_cross = 0.0; + /// Curvature a buckle of the track adds under the body [1/m], positive with the curve, see world/TrackBuckle.h. + double buckle_curvature = 0.0; }; /// Per-segment track parameters: gauge, friction, category, load capacity, damage. diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 2fa19e184..d73479058 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1545,6 +1545,7 @@ void TMoverParameters::check_derailment(TTrackShape const &Shape, TTrackParam co track.gauge = TrackW; track.uneven_curvature = Shape.uneven_curvature; track.uneven_cross = Shape.uneven_cross; + track.buckle_curvature = Shape.buckle_curvature; track.damage = Track.DamageFlag; auto const verdict{derailment_monitor.update(vehicle, track, V, Distance)}; @@ -1574,6 +1575,11 @@ void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::ve Name, Derailed == derailment::outcome::overturned ? "overturned" : "derailed, the flange climbed the rail", std::abs(V) * 3.6, std::abs(Track.radius), cant, Verdict.acceleration, Verdict.unloading, Verdict.flange_ratio, Vehicle.mass / 1000.0, Vehicle.centre_of_gravity, Vehicle.ends[end::front].compression / 1000.0, Vehicle.ends[end::rear].compression / 1000.0, Track.damage, Track.uneven_cross)); + if (Track.buckle_curvature != 0.0) + { + ErrorLog(std::format("Bad driving: {} derailed on buckled track, the buckle bending the line by 1/{:.0f} m {} the curve", Name, 1.0 / std::abs(Track.buckle_curvature), + Track.buckle_curvature > 0.0 ? "with" : "against")); + } } void TMoverParameters::Derail(DerailReason const Reason) diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 66b1007df..ca4ca771f 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -3230,6 +3230,8 @@ bool TDynamicObject::Update(double dt, double dt1) // the uneven track under the outer axles, for the criteria of derailment: its lateral curvature, and its cross level ts.uneven_curvature = glm::dot( 0.5 * ( Axle0.UnevenBend() + Axle1.UnevenBend() ), vLeft ); ts.uneven_cross = MyTrack->uneven_underway().cross; + // a buckle of the track under the body: the mean of the curvatures at the outer axles, each over the wheelbase of its bogie + ts.buckle_curvature = 0.5 * ( Axle0.BuckleCurvature( MoverParameters->ADist ) + Axle1.BuckleCurvature( MoverParameters->ADist ) ); // TTrackParam tp; tp.Width = MyTrack->fTrackWidth; // McZapkie-250202 diff --git a/world/Track.h b/world/Track.h index 3fefde977..81c80785d 100644 --- a/world/Track.h +++ b/world/Track.h @@ -426,6 +426,9 @@ public: static void update_buckling( double const Deltatime ); // the radius of the path in the plan at the distance, 0 straight, and the side away from its centre: -1 left, 1 right, 0 straight double plan_radius( double const Distance, int &Outward ) const; + // the curvature the buckle adds at the distance, averaged over Base around it, 1/m: positive bending with the curve, on a straight + // track to the right of the path + double buckle_curvature( double const Distance, double const Base ) const; // closes the gaps and steps of cant between the ends of joined paths void share_joints(); double joint_depth() const; // mm diff --git a/world/TrackBuckle.cpp b/world/TrackBuckle.cpp index b49dd5753..c8c20fe08 100644 --- a/world/TrackBuckle.cpp +++ b/world/TrackBuckle.cpp @@ -61,6 +61,18 @@ double TTrack::plan_radius( double const Distance, int &Outward ) const { return 1.0 / curvature; } +double TTrack::buckle_curvature( double const Distance, double const Base ) const { + + if( false == is_buckled() || false == track_buckle::within( m_buckle, Distance ) ) { + return 0.0; + } + auto const bend { track_buckle::mean_bend( m_buckle, Distance, Base ) }; + auto outward { 0 }; + plan_radius( Distance, outward ); + // the centre of the curve is away from the outer side + return outward != 0 ? -outward * bend : bend; +} + std::uint64_t TTrack::buckle_key() const { if( false == m_name.empty() && m_name != "none" ) { diff --git a/world/TrkFoll.cpp b/world/TrkFoll.cpp index 035e0bd96..ca215e3ba 100644 --- a/world/TrkFoll.cpp +++ b/world/TrkFoll.cpp @@ -272,6 +272,11 @@ double TTrackFollower::RailPhase( double const Offset ) const { return pCurrentTrack != nullptr ? pCurrentTrack->rail_phase( fCurrentDistance + fDirection * Offset ) : -1.0; } +double TTrackFollower::BuckleCurvature( double const Base ) const { + + return pCurrentTrack != nullptr ? pCurrentTrack->buckle_curvature( fCurrentDistance, Base ) : 0.0; +} + bool TTrackFollower::ComputatePosition() { // ustalenie współrzędnych XYZ if (pCurrentSegment) // o ile jest tor diff --git a/world/TrkFoll.h b/world/TrkFoll.h index 62f386a95..f4741e3ec 100644 --- a/world/TrkFoll.h +++ b/world/TrkFoll.h @@ -43,6 +43,8 @@ public: return pCurrentSegment ? pCurrentSegment->uneven_bend( fCurrentDistance ) : glm::dvec3 { 0.0 }; }; // TTrack::rail_phase of the point Offset ahead of the axle along the vehicle double RailPhase( double const Offset ) const; + // TTrack::buckle_curvature at the axle, averaged over Base around it + double BuckleCurvature( double const Base ) const; bool Init(TTrack *pTrack, TDynamicObject *NewOwner, double fDir); void Reset(); void Render(float fNr); From 4d2c8c2d59a46dd58d2d9be006b95ca35e7832dd Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 12:35:35 +0100 Subject: [PATCH 018/136] feat(physics): the crush of the vehicle ends past the buffers, the override and the push off the track McZapkie/collision.{h,cpp} in eu07_core, plain functions of the vehicles and of the hit, for the collisions of physics.derailment new: - the force-crush curve of an end: a peak, a lower plateau as it folds, packing down past a depth, rigid past its limit (the shape of the FRA full scale tests); defaults for a wagon or a coach (3 / 2 MN), a locomotive (4 / 3 MN) and a crash zone of EN 15227 (2 MN over 0.8 m), optional keys of the .fiz per end - the hit on the stop of the buffers limited to the force the weaker end gives at: the motion of the pair integrated in slices over the step, the crush going to the weaker end, the elastic rest springing back with the old restitution. the momentum is kept, the force never goes past the crush force, and the depth doesn't depend on the step - the override: past 0.35 m of crush the lighter vehicle, or the one with its buffers 40 mm higher, climbs onto the other one, past 0.6 m both; interlocked anticlimbers hold them until a crush zone is used up - the push off the track: Y / Q of the leading wheel of an end pressed in, from the angle of the force in a curve and of the crushed end, and the pitch of the vehicle unloading it; 250 kN in a curve of 150 m (EN 15566) keeps an empty two-axle wagon on, 600 kN pushes it off - the buffers of the categories of EN 15551 the physical model of the coupling meets the buffers of a pair closer by the crush of its ends --- CMakeLists.txt | 1 + McZapkie/collision.cpp | 310 ++++++++++++++++++++++++++++++++++++ McZapkie/collision.h | 214 +++++++++++++++++++++++++ McZapkie/couplerphysics.cpp | 2 +- McZapkie/couplerphysics.h | 1 + 5 files changed, 527 insertions(+), 1 deletion(-) create mode 100644 McZapkie/collision.cpp create mode 100644 McZapkie/collision.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 76f359eab..d89b9a45d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -538,6 +538,7 @@ set(CORE_SOURCES "McZapkie/Mover.cpp" "McZapkie/couplerphysics.cpp" "McZapkie/derailment.cpp" +"McZapkie/collision.cpp" "McZapkie/Oerlikon_ESt.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" diff --git a/McZapkie/collision.cpp b/McZapkie/collision.cpp new file mode 100644 index 000000000..60bcf4a41 --- /dev/null +++ b/McZapkie/collision.cpp @@ -0,0 +1,310 @@ +/* +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 "collision.h" + +#include +#include +#include + +#include "derailment.h" + +namespace collision { + +namespace { + +// the hit is integrated in slices of this length at most, and in no more than so many of them [s] +constexpr double slice{0.0005}; +constexpr double slices_max{200.0}; + +// the force of a curve over a range of crush within one of its parts, the force linear in it there [J] +double linear_work(double const ForceFrom, double const ForceTo, double const Length) { + return 0.5 * (ForceFrom + ForceTo) * std::max(Length, 0.0); +} + +} // namespace + +double crush_curve::force(double const Crush) const { + if (Crush >= limit) { + return std::numeric_limits::infinity(); + } + if (Crush < onset) { + return peak; + } + if (Crush < densify) { + return plateau; + } + return plateau * (1.0 + hardening * (Crush - densify)); +} + +double crush_curve::energy(double const From, double const To) const { + auto const from{std::max(From, 0.0)}; + auto const to{std::min(To, limit)}; + if (to <= from) { + return 0.0; + } + auto work{0.0}; + // the peak + work += peak * std::max(0.0, std::min(to, onset) - from); + // the plateau + auto const plateaufrom{std::max(from, onset)}; + auto const plateauto{std::min(to, std::max(densify, onset))}; + work += plateau * std::max(0.0, plateauto - plateaufrom); + // packing down + auto const densefrom{std::max(from, std::max(densify, onset))}; + if (to > densefrom) { + work += linear_work(force(densefrom), plateau * (1.0 + hardening * (to - densify)), to - densefrom); + } + return work; +} + +crush_curve default_crush(vehicle_kind const Kind) { + switch (Kind) { + case vehicle_kind::locomotive: + return {4.0e6, 3.0e6, 0.05, 0.6, 2.0, 1.2}; + case vehicle_kind::crash_zone: + return {2.0e6, 2.0e6, 0.0, 0.8, 2.5, 1.2}; + case vehicle_kind::wagon: + case vehicle_kind::coach: + default: + return {3.0e6, 2.0e6, 0.05, 0.8, 2.0, 1.5}; + } +} + +vehicle_kind kind_of(bool const Powered, bool const Passenger, bool const CrashZone) { + if (CrashZone) { + return vehicle_kind::crash_zone; + } + if (Passenger) { + return vehicle_kind::coach; + } + return Powered ? vehicle_kind::locomotive : vehicle_kind::wagon; +} + +crush_curve crush_of(end_definition const &Definition, vehicle_kind const Kind) { + auto curve{default_crush(Definition.crash_zone.value_or(false) ? vehicle_kind::crash_zone : Kind)}; + curve.peak = std::max(Definition.peak.value_or(curve.peak), 1.0); + curve.plateau = std::max(Definition.plateau.value_or(curve.plateau), 1.0); + curve.onset = std::max(Definition.onset.value_or(curve.onset), 0.0); + curve.densify = std::max(Definition.densify.value_or(curve.densify), curve.onset); + curve.hardening = std::max(Definition.hardening.value_or(curve.hardening), 0.0); + curve.limit = std::max(Definition.limit.value_or(curve.limit), curve.onset); + return curve; +} + +bool anticlimber_of(end_definition const &Definition, vehicle_kind const Kind) { + return Definition.anticlimber.value_or(Definition.crash_zone.value_or(Kind == vehicle_kind::crash_zone)); +} + +double buffer_height(end_definition const &Definition, vehicle_kind const Kind, double const LoadShare) { + auto const wagon{Kind == vehicle_kind::wagon}; + auto const empty{Definition.buffer_height.value_or(wagon ? 1.065 : 1.040)}; + // the springs of a wagon give 125 mm under its full load + return wagon ? empty - 0.125 * std::clamp(LoadShare, 0.0, 1.0) : empty; +} + +buffer_rating rating(buffer_category const Category) { + switch (Category) { + case buffer_category::B: + return {0.105, 50.0e3}; + case buffer_category::C: + return {0.105, 70.0e3}; + case buffer_category::L: + return {0.150, 70.0e3}; + case buffer_category::passenger: + return {0.110, 30.0e3}; + case buffer_category::A: + default: + return {0.105, 30.0e3}; + } +} + +coupler_physics::spring_curve buffer_curve(buffer_category const Category, double const Progression) { + auto const buffer{rating(Category)}; + auto const progression{std::clamp(Progression, 0.0, 0.9)}; + // the energy of the curve to the end of the stroke is F_end * stroke * ((1 - p) / 2 + p / 4), of two buffers + auto const endforce{2.0 * buffer.energy / (buffer.stroke * ((1.0 - progression) / 2.0 + progression / 4.0))}; + return {endforce / buffer.stroke, buffer.stroke, progression}; +} + +std::optional buffer_category_of(char const Name) { + switch (Name) { + case 'A': + case 'a': + return buffer_category::A; + case 'B': + case 'b': + return buffer_category::B; + case 'C': + case 'c': + return buffer_category::C; + case 'L': + case 'l': + return buffer_category::L; + case 'P': + case 'p': + return buffer_category::passenger; + default: + return std::nullopt; + } +} + +hit_result hit(end_state const &First, end_state const &Second, hit_input const &Input) { + hit_result result; + if (Input.velocity <= 0.0 || Input.mass1 <= 0.0 || Input.mass2 <= 0.0 || Input.dt <= 0.0) { + return result; + } + auto const mass{Input.mass1 * Input.mass2 / (Input.mass1 + Input.mass2)}; + auto const restitution{std::clamp(Input.restitution, 0.0, 0.95)}; + // the elastic hit on the steel at the closing velocity adds root * velocity to the force of the springs + auto const root{std::sqrt(std::max(Input.stiffness, 1.0) * mass)}; + auto const springs{std::max(Input.springs, 0.0)}; + // the closing velocity the step started with: the springs slow the pair over the step as well, the hit adds what + // they don't carry of the force the end gives at + auto velocity{Input.start_velocity > 0.0 ? std::max(Input.start_velocity, Input.velocity) : Input.velocity + springs * Input.dt / mass}; + // where the forces of the step alone would take the pair + auto const unhit{velocity - springs * Input.dt / mass}; + + auto crush1{First.crush}; + auto crush2{Second.crush}; + auto const elastic_limit = [&](double const Force) { return std::max(0.0, Force - springs) / root; }; + { + auto const force{std::min(First.curve.force(crush1), Second.curve.force(crush2))}; + if (false == std::isfinite(force) || velocity <= elastic_limit(force)) { + // the steel takes it all: the legacy elastic exchange + return result; + } + } + result.crushing = true; + + auto const slices{std::clamp(std::ceil(Input.dt / slice), 1.0, slices_max)}; + auto const length{Input.dt / slices}; + auto time{0.0}; + auto rebound{false}; + auto crushtime{0.0}; + while (Input.dt - time > 1e-12) { + auto const force1{First.curve.force(crush1)}; + auto const force2{Second.curve.force(crush2)}; + auto const force{std::min(force1, force2)}; + if (false == std::isfinite(force) || velocity <= elastic_limit(force)) { + // both ends crushed all the way, or the pair slowed down to what the steel takes back + rebound = true; + break; + } + auto const limit{elastic_limit(force)}; + auto step{std::min(length, Input.dt - time)}; + auto change{force * step / mass}; + if (velocity - change < limit) { + step = (velocity - limit) * mass / force; + change = velocity - limit; + } + auto const crush{(velocity - 0.5 * change) * step}; + // the weaker end gives, both alike when they're alike + if (std::abs(force1 - force2) <= 1e-9 * force) { + crush1 += 0.5 * crush; + crush2 += 0.5 * crush; + } + else if (force1 < force2) { + crush1 += crush; + } + else { + crush2 += crush; + } + velocity -= change; + time += step; + crushtime += step; + result.force = std::max(result.force, force); + } + + auto after{velocity}; + auto duration{crushtime}; + if (rebound) { + // the steel springs back with the restitution, the springs push the pair apart over the rest of the step + // under the force the weaker end gives at, as the slices stopped there + result.force = std::max(result.force, springs + velocity * root); + if (velocity > 0.0) { + duration += (1.0 + restitution) * velocity * mass / std::max(velocity * root, 1.0); + } + after = -restitution * velocity - springs * (Input.dt - time) / mass; + } + result.velocity = after; + result.impulse = mass * (unhit - after); + result.duration = std::min(duration, Input.dt); + result.crush1 = crush1 - First.crush; + result.crush2 = crush2 - Second.crush; + return result; +} + +override_result override_of(override_input const &Input) { + override_result result; + if (Input.anticlimbers) { + // interlocked, they keep the ends level until the crush zone of one of them is used up + auto const spent1{Input.zone1 <= 0.0 || Input.crush1 >= Input.zone1}; + auto const spent2{Input.zone2 <= 0.0 || Input.crush2 >= Input.zone2}; + if (false == spent1 && false == spent2) { + return result; + } + } + auto const crush{Input.crush1 + Input.crush2}; + if (crush > override_both) { + result.first = true; + result.second = true; + return result; + } + if (crush <= override_crush) { + return result; + } + if (Input.mass1 * override_mass_ratio < Input.mass2) { + result.first = true; + } + else if (Input.mass2 * override_mass_ratio < Input.mass1) { + result.second = true; + } + else if (false == Input.anticlimbers && std::abs(Input.height1 - Input.height2) >= override_height - 1e-9) { + // the higher one rides up + result.first = Input.height1 > Input.height2; + result.second = false == result.first; + } + return result; +} + +double pushed_ratio(pushed_vehicle const &Vehicle, pushed_end const &End, double const Radius) { + if (Vehicle.mass <= 0.0 || End.force <= 0.0) { + return 0.0; + } + auto const axles{static_cast(std::max(Vehicle.axles, 1))}; + // the axles of the half of the vehicle at the end: its bogie, or its axle + auto const half{std::max(axles / 2.0, 1.0)}; + auto const wheelload{Vehicle.mass * gravity / (2.0 * axles)}; + auto const halflength{std::max(0.5 * Vehicle.length, 1.0)}; + auto const angle{straight_angle + derailment::coupling_angle(Vehicle.length, End.other_length, Radius) + crush_angle * std::max(End.crush, 0.0) / halflength}; + // in a curve the leading axle meets the rail at an angle, the creep force of its inner wheel at most the friction + auto guiding{0.0}; + if (std::abs(Radius) > 1e-3) { + auto const attack{Vehicle.axle_base / (2.0 * std::abs(Radius))}; + guiding = derailment::tread_friction * wheelload * std::min(1.0, attack / derailment::saturated_attack); + } + auto const lateral{End.force * angle / half + guiding}; + // the force off the height it's carried at pitches the vehicle: the bogie at the end pressed in takes the load off + auto const pivots{Vehicle.pivots > 0.0 ? Vehicle.pivots : halflength}; + auto const vertical{wheelload - End.force * eccentricity / (2.0 * half * pivots)}; + return vertical > 0.0 ? lateral / vertical : 1e9; +} + +bool pushed_monitor::update(bool const Holds, double const Duration) { + if (false == Holds) { + m_time = 0.0; + return false; + } + m_time += std::max(Duration, 0.0); + return m_time >= pushed_time - 1e-9; +} + +} // namespace collision diff --git a/McZapkie/collision.h b/McZapkie/collision.h new file mode 100644 index 000000000..dd3dad55e --- /dev/null +++ b/McZapkie/collision.h @@ -0,0 +1,214 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include + +#include "couplerphysics.h" + +// what a collision of two vehicles does to them past their buffers (physics.derailment new in eu07.ini, see +// TMoverParameters::CollisionDetect()), as plain functions of the vehicles and the hit: +// +// crush: once the buffers of the pair are pressed all the way, the underframes carry the rest of the hit, up to the +// force the weaker end gives at. past it the end crushes for good: a short peak of force, then a lower plateau as +// the structure folds, then it packs down and stiffens (the force-crush curves of the full scale tests of the FRA: +// Tyrell et al., IMECE2002-33247). the hit is an impulse limited to that force over the step, so the force never +// goes past it and the depth of the crush is the same with any step; the depth stays with the end +// override: an end crushed deep enough no longer holds the other one down: the lighter of the two vehicles, or the +// one with its buffers higher (40 mm, the vertical offset of the design collision of EN 15227), climbs onto the +// other one and leaves the rails; past a deeper crush both do. interlocked anticlimbers hold them until the crush +// zone of an end is used up +// pushed off the track: the force pressing a vehicle's end acts at an angle to it, the more in a curve and the +// deeper the end is crushed, which gives a lateral force on its wheels; acting off the height of the centre of the +// vehicle it lifts its leading wheels. Y / Q over Nadal's limit for long enough and the flange climbs the rail +// (the light wagon between heavy ones goes first, in a curve sooner than on a straight track: EN 15566 takes +// 250 kN of the pair of buffers in a curve of 150 m as the safe push) +namespace collision { + +inline constexpr double gravity{9.81}; // [m/s2] + +// ---- the crush of an end + +// force-crush characteristic of the underframe at one end of a vehicle +struct crush_curve { + double peak{3.0e6}; // the force the crushing starts at [N] + double plateau{2.0e6}; // of the crushing past the onset [N] + double onset{0.05}; // the crush past which the peak drops to the plateau [m] + double densify{0.8}; // the crush past which the crushed structure packs down and stiffens [m] + double hardening{2.0}; // the growth of the force past it, to the plateau for each metre [1/m] + double limit{1.5}; // the end can't be crushed past it, it's rigid from there [m] + + // the force the end gives at with the crush [N]; past the limit there's no force it gives at + double force(double Crush) const; + // the work it takes to crush the end from the one depth to the other one [J] + double energy(double From, double To) const; +}; + +// what the vehicle is, for its defaults +enum class vehicle_kind { + wagon, // a freight wagon + coach, // a passenger coach, or a car of a unit + locomotive, + crash_zone // a vehicle built to EN 15227, with the energy absorbers and the anticlimbers at its ends +}; +// the defaults of the kind: a wagon or a coach gives at 1.5 times the force of the proof test of EN 12663 at the +// height of the buffers (2 MN), a locomotive at 4 MN; the plateau is the 2 MN of the crush of the cab car of the FRA +// test. the absorbers of a crash zone give a steady 2 MN over 0.8 m, as the deformation tubes and the crash buffers +// do (2 MN of the crash buffers in service) +crush_curve default_crush(vehicle_kind Kind); + +// the optional keys of the .fiz for an end (BuffCoupl): what's not given comes from the kind of the vehicle +struct end_definition { + std::optional peak; // FcrushPeak [N] + std::optional plateau; // FcrushPlateau [N] + std::optional onset; // CrushOnset [m] + std::optional densify; // CrushDensify [m] + std::optional hardening; // CrushHardening [1/m] + std::optional limit; // CrushLimit [m] + std::optional crash_zone; // CrashZone: built to EN 15227 + std::optional anticlimber; // AntiClimber + std::optional buffer_height; // BufferHeight, of the empty vehicle above the rail [m] +}; +vehicle_kind kind_of(bool Powered, bool Passenger, bool CrashZone); +crush_curve crush_of(end_definition const &Definition, vehicle_kind Kind); +bool anticlimber_of(end_definition const &Definition, vehicle_kind Kind); +// height of the buffers above the rail [m]: UIC 940 to 1065 mm. without a given one, a wagon has them at the top of +// the range empty and lower by 125 mm fully loaded on its springs, a locomotive or a coach at 1040 mm +double buffer_height(end_definition const &Definition, vehicle_kind Kind, double LoadShare); + +// ---- the buffers, EN 15551 + +enum class buffer_category { + A, // 105 mm, 30 kJ + B, // 105 mm, 50 kJ + C, // 105 mm, 70 kJ + L, // the long stroke, 150 mm + passenger // 110 mm, of the coaches +}; +struct buffer_rating { + double stroke{0.105}; // [m] + double energy{30.0e3}; // dynamic energy of one buffer [J] +}; +buffer_rating rating(buffer_category Category); +// the spring curve of the two buffers of an end side by side, of the progression given, which takes in their energy +// over the stroke +coupler_physics::spring_curve buffer_curve(buffer_category Category, double Progression); +std::optional buffer_category_of(char Name); + +// ---- the hit past the buffers + +// an end of the pair, as the hit sees it +struct end_state { + crush_curve curve; + double crush{0.0}; // the depth it's crushed to already [m] +}; + +struct hit_input { + double velocity{0.0}; // the pair closes in on the stop at [m/s] + double mass1{0.0}; // [kg] + double mass2{0.0}; + double restitution{0.2}; // coefficient of restitution of the elastic rest of the hit + double stiffness{1.0e8}; // of the steel parts of both ends in series, past the springs [N/m] + double springs{0.0}; // the force the springs of the pair carry at the stop over the step [N] + double dt{0.01}; // the length of the step [s] + // the closing velocity the pair started the step with, before the forces of the step [m/s]; without it (0), the + // velocity with what the springs took off it over the step + double start_velocity{0.0}; +}; + +struct hit_result { + bool crushing{false}; // false: the hit stays elastic, it's the legacy exchange of momentum + double impulse{0.0}; // the hit adds to the forces of the step, pushing the vehicles apart [N s] + double velocity{0.0}; // the closing velocity after the step [m/s], negative as they part + double force{0.0}; // the peak force between the ends, with the springs [N] + double duration{0.0}; // how long that force acted over the step [s] + double crush1{0.0}; // added to the end of the first vehicle [m] + double crush2{0.0}; // of the second one +}; + +// the hit of the step: the steel takes the hit elastically up to the force the weaker end gives at, past that the end +// crushes at that force until the pair closes in no faster than the steel takes back. the motion over the step is +// integrated in short slices, with the springs slowing the pair as well, so the crush doesn't depend on the step +hit_result hit(end_state const &First, end_state const &Second, hit_input const &Input); + +// a crush of an end deeper than this is a damage worth the log [m] +inline constexpr double crush_mark{0.05}; +// the draw gear sits behind the headstock: crushed this deep, the coupling of the end is torn off [m] +inline constexpr double draw_gear_crush{0.15}; + +// ---- override + +// the crush of the contact of both ends past which the lighter (or the higher) vehicle climbs onto the other one, +// and past which both leave the rails [m] +inline constexpr double override_crush{0.35}; +inline constexpr double override_both{0.6}; +// the masses differ enough for the lighter one to climb +inline constexpr double override_mass_ratio{1.3}; +// the buffers differ in height enough for the higher one to climb: the vertical offset of the design collision of +// EN 15227 [m] +inline constexpr double override_height{0.04}; + +struct override_input { + double crush1{0.0}; // of the end of the first vehicle [m] + double crush2{0.0}; + double mass1{0.0}; // [kg] + double mass2{0.0}; + double height1{1.0}; // of its buffers [m] + double height2{1.0}; + bool anticlimbers{false}; // both ends have them, interlocked + double zone1{0.0}; // the crush zone of the end with the anticlimber, its densify [m] + double zone2{0.0}; +}; +struct override_result { + bool first{false}; // the first vehicle left the rails + bool second{false}; +}; +override_result override_of(override_input const &Input); + +// ---- pushed off the track + +// the angle of the force at the end of a vehicle to it on a straight track: the play of the wheelsets and of the +// bogies, the buffer heads off the middle [rad] +inline constexpr double straight_angle{0.006}; +// the crushed end no longer keeps the ends in line: the angle grows by this share of the crush to the half length +inline constexpr double crush_angle{0.1}; +// the height the force acts at off the height it's carried at, the buffers of the pair not at the same height [m] +inline constexpr double eccentricity{0.10}; +// the time Y / Q has to stay over the limit for the flange to climb the rail [s] +inline constexpr double pushed_time{0.05}; + +struct pushed_vehicle { + double mass{0.0}; // with the load, without the rotating masses [kg] + int axles{4}; + double length{0.0}; // over the buffers [m] + double pivots{0.0}; // the distance of the bogie pivots, of the axles without bogies [m] + double axle_base{0.0}; // the wheelbase of a bogie, of the vehicle without bogies [m] +}; +struct pushed_end { + double force{0.0}; // pressing the end in [N] + double other_length{0.0}; // of the vehicle at that end [m] + double crush{0.0}; // of the end [m] +}; +// Y / Q of the leading wheel at the end pressed in by the force, in a curve of the radius [m] (0 straight) +double pushed_ratio(pushed_vehicle const &Vehicle, pushed_end const &End, double Radius); + +// the time the condition held, without a break +class pushed_monitor { +public: + // true once the condition held for the time it takes the flange to climb, given how long it held in the step [s] + bool update(bool Holds, double Duration); + void reset() { m_time = 0.0; } + double time() const { return m_time; } + +private: + double m_time{0.0}; +}; + +} // namespace collision diff --git a/McZapkie/couplerphysics.cpp b/McZapkie/couplerphysics.cpp index f6a226b55..31afd26fe 100644 --- a/McZapkie/couplerphysics.cpp +++ b/McZapkie/couplerphysics.cpp @@ -235,7 +235,7 @@ pair_result update_pair(end_parameters const &First, end_parameters const &Secon else { State.draw_gear.reset(); } - auto const pushed{press(buffers_of(First, Second, Input.adapter), State.buffers, -Input.gap, -Input.gap_rate)}; + auto const pushed{press(buffers_of(First, Second, Input.adapter), State.buffers, -Input.gap - std::max(Input.crush, 0.0), -Input.gap_rate)}; result.tension = pulled.force; result.compression = pushed.force; diff --git a/McZapkie/couplerphysics.h b/McZapkie/couplerphysics.h index 47789aba2..8d7f9b06e 100644 --- a/McZapkie/couplerphysics.h +++ b/McZapkie/couplerphysics.h @@ -112,6 +112,7 @@ struct pair_input { bool coupled{false}; bool adapter{false}; // an adapter on either end: the buffers don't meet, the coupler takes the push alone bool damage{false}; // the link can stretch and break (crash damage on) + double crush{0.0}; // the ends of both crushed for good (collision.h), the buffers meet that much closer [m] }; struct pair_result { From 369f58a04a29f76adf05cb526be508108aceac98 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 12:41:40 +0100 Subject: [PATCH 019/136] feat(physics): collisions crush the ends of the vehicles, override and push them off the track With physics.derailment new, CollisionDetect() hands a hit on the stop of the buffers harder than the steel takes elastically to crush_hit() (collision.h): - the weaker end crushes for good at its crush force, the vehicles take the limited impulse, the depth stays with the end (TCoupling::crush) and lets the buffers of the pair meet closer, in both models of the coupling - the crush lets the lighter vehicle, or the one with its buffers higher, climb onto the other one; the end crushed by 0.15 m tears off its draw gear, with the brake hose both parts of the train brake in emergency, and an automatic coupler torn off doesn't couple again - after the collisions of each step the force pressing the ends pushes a light vehicle off the track by Y / Q held for 0.05 s - off the rails in a collision the vehicle is upright off the rails as by the criteria of the speed: it slides with the friction of the ballast and keeps taking the hits and passing the forces on, instead of standing as a wall. CollisionDerail and the log tell the override from the push off; a crushed end logs the collision It works in CollisionDetect(), which both models of the coupling reach once their buffers go solid, so the trains of the AI the physical model of the coupling doesn't cover crush alike. Hits the steel takes, and the draw gear going solid, stay the legacy collision. physics.derailment old and off keep the legacy collisions: the rule of 15 km/h weighed by the masses, the chance of the coupler smashed, a derailed vehicle a wall; the tests of that rule run with old. The buffers of a category of EN 15551 and the crush, crash zone, anticlimber and buffer height of an end are new optional keys of BuffCoupl. --- McZapkie/MOVER.h | 31 ++ McZapkie/Mover.cpp | 368 +++++++++++++++- tests/unit/test_collisions.cpp | 648 ++++++++++++++++++++++++++++ tests/unit/test_controls.cpp | 9 + tests/unit/test_couplers.cpp | 17 + tests/unit/test_couplers_trains.cpp | 21 +- 6 files changed, 1086 insertions(+), 8 deletions(-) create mode 100644 tests/unit/test_collisions.cpp diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 63783419b..8c612cca0 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "hamulce.h" #include "couplerphysics.h" #include "derailment.h" +#include "collision.h" #include "scripting/ladderlogic.h" #include "vehicle/odometerreading.h" @@ -176,6 +177,10 @@ enum DerailReason COLLISION = 5, // powód wykolejenia: zderzenie z innym pojazdem /// Trailing through a switch with a movable nose set the other way. TRAILED_SWITCH = 6, // powód wykolejenia: rozprucie rozjazdu z ruchomym dziobem + /// Climbed onto the vehicle it hit, its end crushed (physics.derailment new). + COLLISION_OVERRIDE = 7, // najechanie + /// Pushed off the track by the force pressing its end (physics.derailment new). + COLLISION_PUSHED_OFF = 8, // wyciśnięcie z toru }; /*wagi prawdopodobienstwa dla funkcji FuzzyLogic*/ @@ -1288,6 +1293,15 @@ struct TCoupling // and the state of the coupling with the vehicle at this end, which that vehicle keeps alike on its own end coupler_physics::end_parameters physics; coupler_physics::pair_state physics_state; + // the collisions past the buffers (physics.derailment new), see collision.h: the optional keys of this end, the depth + // it's crushed to for good [m], and the hit of the pair in the step: whether either vehicle handled it already, its + // peak force [N] and how long that acted [s] + collision::end_definition collision; + double crush{0.0}; + double closing{0.0}; // the velocity the buffers of the pair closed in at, at the start of the step [m/s] + bool hit_handled{false}; + double hit_force{0.0}; + double hit_duration{0.0}; int sounds{0}; // sounds emitted by the coupling devices bool Render = false; /*ABu: czy rysowac jak zaczepiony sprzeg*/ @@ -2444,6 +2458,23 @@ class TMoverParameters // how the vehicle left the rails by the criteria of derailment.h: upright, or on its side. none for any other // derailment, which stops it as the legacy model does derailment::outcome Derailed{derailment::outcome::none}; + // physics.derailment new: what the vehicle is for the defaults of its crush and its buffers, the crush curve and the + // height of the buffers of an end, and how long the push of its ends held its wheels over the climbing limit + collision::vehicle_kind collision_kind() const; + collision::crush_curve crush_curve_at(int End) const; + double buffer_height_at(int End) const; + collision::pushed_monitor pushed_off_monitor; + // how the vehicle left the rails in a collision (physics.derailment new): overriding or pushed off, NONE otherwise + DerailReason CollisionDerail{NONE}; + // physics.derailment new: the hit of the end on the stop of its buffers, harder than the steel takes, crushes the + // weaker end and may let one vehicle climb onto the other one, see collision.h. returns: whether it did, and the + // velocities took the hit; the legacy collision takes the rest + bool crush_hit(int End, double dt); + // the force pressing the ends pushes the vehicle off the track (physics.derailment new) + void check_pushed_off(double dt); + // the vehicle leaves the rails in a collision, the reason told in the log, and slides on as the criteria of + // derailment.h have it + void derail_in_collision(DerailReason Reason, std::string const &Why); bool DirectionForward(); bool DirectionBackward(void); /*! kierunek ruchu*/ bool EIMDirectionChangeAllow(void) const; diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 2fa19e184..00a4b775c 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1338,6 +1338,12 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) auto const &othercoupler{othervehicle->Couplers[otherend]}; auto const physical{coupler_physics_at(End)}; + // physics.derailment new: past the buffers the ends crush (collision.h); a hit the steel takes stays the legacy one + auto const crushing{Global.derailment == global_settings::derailment_model::physical}; + if (crushing && (thiscoupler.hit_handled || crush_hit(End, dt))) + { + return; + } if (physical && false == coupler_stop_hit(End, *othervehicle, otherend)) { return; @@ -1373,7 +1379,8 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) } } - if (Global.crash_damage) + // the new model crushes the ends and derails the vehicles by the crush, see crush_hit() + if (Global.crash_damage && false == crushing) { // the physical model breaks the coupling and crushes the buffers by the force of the hit (coupler_stop_hit()) if (false == physical && -thiscoupler.Dist >= thiscoupler.DmaxB && FuzzyLogic(std::abs(CCF), 5.0 * (thiscoupler.FmaxC + 1.0), p_coupldmg)) @@ -1409,13 +1416,15 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) // integration of the next step (ComputeMovement()) would carry a quarter of an acceleration spike over into the // velocity once more, and the vehicles would bounce off the stop faster than they hit it auto const accelerationspike{physical ? 0.0 : 1.0}; - if (false == TestFlag(DamageFlag, dtrain_out)) + // derailed the legacy way a vehicle is a wall, off the rails by the new criteria it slides on and takes the hit + auto const wall = [crushing](TMoverParameters const &Vehicle) { return TestFlag(Vehicle.DamageFlag, dtrain_out) && (false == crushing || Vehicle.Derailed == derailment::outcome::none); }; + if (false == wall(*this)) { auto const accelerationchange{(velocity - V) / dt}; AccS += accelerationchange * accelerationspike; V = velocity; } - if (false == TestFlag(othervehicle->DamageFlag, dtrain_out)) + if (false == wall(*othervehicle)) { auto const othervehiclenewvelocity{othervehiclevelocity * otherdirection}; // back along the other vehicle's axis auto const othervehicleaccelerationchange{(othervehiclenewvelocity - othervehicle->V) / dt}; @@ -1465,6 +1474,278 @@ void TMoverParameters::damage_coupler(int const End) WriteLog("Bad driving: " + Name + " broke a coupler"); } +// ************************************************************************************************* +// physics.derailment new: the collisions past the buffers, see collision.h +// ************************************************************************************************* +collision::vehicle_kind TMoverParameters::collision_kind() const +{ + auto const powered{EngineType != TEngineType::None && EngineType != TEngineType::Dumb}; + auto const unit{(TrainType & (dt_EZT | dt_DMU)) != 0}; + auto const passengers{std::any_of(LoadAttributes.begin(), LoadAttributes.end(), [](auto const &Load) { return ToLower(Load.name).starts_with("passenger"); })}; + // a coach heats its compartments; the crash zone is a matter of each end (crush_of()) + return collision::kind_of(powered, unit || passengers || (false == powered && HeatingPower > 0.0), false); +} + +collision::crush_curve TMoverParameters::crush_curve_at(int const End) const +{ + return collision::crush_of(Couplers[End].collision, collision_kind()); +} + +double TMoverParameters::buffer_height_at(int const End) const +{ + auto const loadshare{MaxLoad > 0.f ? LoadAmount / MaxLoad : 0.0}; + return collision::buffer_height(Couplers[End].collision, collision_kind(), loadshare); +} + +void TMoverParameters::derail_in_collision(DerailReason const Reason, std::string const &Why) +{ + if (false == SetFlag(DamageFlag, dtrain_out)) + { + return; + } + // upright, it slides on the sleepers and keeps passing the forces on + Derailed = derailment::outcome::off_rails; + CollisionDerail = Reason; + EventFlag = true; + MainSwitch(false, range_t::local); + if (Vel < 5.0) + { + // HACK: prevent permanent axle spin in static vehicle after a collision + nrot = 0.0; + SlippingWheels = false; + } + // the brake hoses tear: the brake pipe vents and the rest of the train brakes in emergency + if (std::any_of(std::begin(Couplers), std::end(Couplers), [](auto const &Coupler) { return (Coupler.CouplingFlag & coupling::brakehose) == coupling::brakehose; })) + { + AlarmChainFlag = true; + } + derailment_monitor.reset(); + pushed_off_monitor.reset(); + ErrorLog(std::format("Bad driving: {} derailed in a collision, {}: {}", Name, Reason == COLLISION_OVERRIDE ? "overriding" : "pushed off the track", Why)); +} + +namespace +{ + +char const *end_name(int const End) +{ + return End == end::front ? "front" : "rear"; +} + +// the force pressing the end in, of the coupling or of the buffers touching [N]: forwards at the front pulls +double compression_at(TCoupling const &Coupler, int const End) +{ + return std::max(0.0, (End == end::front ? -1.0 : 1.0) * Coupler.CForce); +} + +// the steel parts of both ends in series [N/m] +double steel_stiffness(TCoupling const &First, TCoupling const &Second) +{ + auto const first{std::max(First.physics.link_stiffness, 1.0)}; + auto const second{std::max(Second.physics.link_stiffness, 1.0)}; + return first * second / (first + second); +} + +// the hit of the pair in the step, for the push off the track: the peak force and how long it acted +void record_hit(TCoupling &Coupler, double const Force, double const Duration) +{ + Coupler.hit_force = std::max(Coupler.hit_force, Force); + Coupler.hit_duration = std::max(Coupler.hit_duration, Duration); +} + +} // namespace + +bool TMoverParameters::crush_hit(int const End, double const dt) +{ + auto &thiscoupler{Couplers[End]}; + auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; + auto const otherend{Neighbours[End].vehicle_end}; + auto &othercoupler{othervehicle->Couplers[otherend]}; + + auto const physical{coupler_physics_at(End)}; + // the buffers pressed all the way, not the draw gear pulled all the way, and the pair still closing in + auto const buffers{physical ? thiscoupler.physics_state.stop < 0 : thiscoupler.Dist < 0.0}; + auto const closing{-CouplerVelocityDifference(End, *othervehicle, otherend) * DirF(End)}; + if (false == Global.crash_damage || false == buffers || closing <= 0.0) + { + return false; + } + // a vehicle derailed the legacy way (the end of the track, say) stays where it is, whatever hits it + auto const wall{TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none}; + auto const otherwall{TestFlag(othervehicle->DamageFlag, dtrain_out) && othervehicle->Derailed == derailment::outcome::none}; + if (wall && otherwall) + { + return false; + } + constexpr double immovable{1e12}; + auto const mass{wall ? immovable : TotalMass}; + auto const othermass{otherwall ? immovable : othervehicle->TotalMass}; + auto const loss{physical ? coupler_physics::solid_hit_loss(thiscoupler.physics, othercoupler.physics) : (thiscoupler.beta + othercoupler.beta) / 2.0}; + + auto const firstcurve{crush_curve_at(End)}; + auto const secondcurve{othervehicle->crush_curve_at(otherend)}; + auto const stiffness{steel_stiffness(thiscoupler, othercoupler)}; + auto const springs{compression_at(thiscoupler, End)}; + collision::hit_input input; + input.velocity = closing; + input.mass1 = mass; + input.mass2 = othermass; + input.restitution = std::sqrt(std::max(0.0, 1.0 - loss)); + input.stiffness = stiffness; + input.springs = springs; + input.dt = dt; + input.start_velocity = thiscoupler.closing; + auto const hit{collision::hit({firstcurve, thiscoupler.crush}, {secondcurve, othercoupler.crush}, input)}; + if (false == hit.crushing) + { + // the steel takes it, the legacy collision follows; its peak, under the force an end gives at, for the push + // off the track + auto const reduced{mass * othermass / (mass + othermass)}; + auto const weaker{std::min(firstcurve.force(thiscoupler.crush), secondcurve.force(othercoupler.crush))}; + auto const peak{std::min(springs + coupler_physics::impact_force(closing, stiffness, mass, othermass), weaker)}; + auto const duration{std::min(dt, (1.0 + input.restitution) * std::sqrt(reduced / stiffness))}; + record_hit(thiscoupler, peak, duration); + record_hit(othercoupler, peak, duration); + return false; + } + // the other vehicle doesn't take it again in this step + thiscoupler.hit_handled = true; + othercoupler.hit_handled = true; + + // the hit at the force the weaker end gives at pushes the vehicles apart: the velocities alone change, along this + // vehicle's axis as in CollisionDetect() + auto const otherdirection{DirPatch(End, otherend)}; + auto const apart{End == end::front ? -1.0 : 1.0}; + if (false == wall) + { + V += apart * hit.impulse / mass; + } + if (false == otherwall) + { + othervehicle->V -= apart * hit.impulse / othermass * otherdirection; + } + record_hit(thiscoupler, hit.force, hit.duration); + record_hit(othercoupler, hit.force, hit.duration); + + auto const crushed = [&](TMoverParameters const &Vehicle, int const VehicleEnd, double const Before, double const After) { + if (Before < collision::crush_mark && After >= collision::crush_mark) + { + ErrorLog(std::format("Bad driving: {} and {} collided at {:.0f} km/h, the {} end of {} crushed", Name, othervehicle->Name, closing * 3.6, end_name(VehicleEnd), Vehicle.Name)); + } + }; + auto const before{thiscoupler.crush}; + auto const otherbefore{othercoupler.crush}; + thiscoupler.crush += hit.crush1; + othercoupler.crush += hit.crush2; + crushed(*this, End, before, thiscoupler.crush); + crushed(*othervehicle, otherend, otherbefore, othercoupler.crush); + + // the crushed headstock tears off the draw gear, with the brake hose: both parts of the train brake in emergency. + // the coupler of an end not coupled is gone as well, it doesn't couple any more + if (thiscoupler.CouplingFlag != coupling::faux && std::max(thiscoupler.crush, othercoupler.crush) >= collision::draw_gear_crush) + { + auto const hose{(thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose}; + damage_coupler(End); + if (hose) + { + othervehicle->AlarmChainFlag = true; + } + } + else if (thiscoupler.CouplingFlag == coupling::faux) + { + if (thiscoupler.crush >= collision::draw_gear_crush && false == thiscoupler.broken) + { + damage_coupler(End); + } + if (othercoupler.crush >= collision::draw_gear_crush && false == othercoupler.broken) + { + othervehicle->damage_coupler(otherend); + } + } + + // the end crushed deep enough lets one vehicle climb onto the other one + collision::override_input climbing; + climbing.crush1 = thiscoupler.crush; + climbing.crush2 = othercoupler.crush; + climbing.mass1 = TotalMass - Mred; + climbing.mass2 = othervehicle->TotalMass - othervehicle->Mred; + climbing.height1 = buffer_height_at(End); + climbing.height2 = othervehicle->buffer_height_at(otherend); + climbing.anticlimbers = collision::anticlimber_of(thiscoupler.collision, collision_kind()) && collision::anticlimber_of(othercoupler.collision, othervehicle->collision_kind()); + climbing.zone1 = firstcurve.densify; + climbing.zone2 = secondcurve.densify; + auto const climbed{collision::override_of(climbing)}; + auto const why = [&](TMoverParameters const &Climber, TMoverParameters const &Other) { + return std::format("{} rode up onto {} at {:.0f} km/h, the ends crushed by {:.2f} m", Climber.Name, Other.Name, closing * 3.6, thiscoupler.crush + othercoupler.crush); + }; + if (climbed.first) + { + derail_in_collision(COLLISION_OVERRIDE, why(*this, *othervehicle)); + } + if (climbed.second) + { + othervehicle->derail_in_collision(COLLISION_OVERRIDE, why(*othervehicle, *this)); + } + return true; +} + +void TMoverParameters::check_pushed_off(double const dt) +{ + if (Global.derailment != global_settings::derailment_model::physical || false == Global.crash_damage || TestFlag(DamageFlag, dtrain_out) || false == TestFlag(CategoryFlag, 1) || + DebugModeFlag) + { + pushed_off_monitor.reset(); + return; + } + collision::pushed_vehicle vehicle; + vehicle.mass = TotalMass - Mred; + vehicle.axles = NAxles > 0 ? NAxles : 4; + vehicle.length = Dim.L; + vehicle.pivots = BDist; + vehicle.axle_base = ADist > 0.0 ? ADist : BDist; + + auto holds{false}; + auto duration{0.0}; + auto worst{0.0}; + auto worstforce{0.0}; + auto worstend{static_cast(end::front)}; + for (int end = end::front; end <= end::rear; ++end) + { + auto const *other{Neighbours[end].vehicle}; + if (other == nullptr) + { + continue; + } + auto const &coupler{Couplers[end]}; + collision::pushed_end pushed; + pushed.other_length = other->MoverParameters->Dim.L; + pushed.crush = coupler.crush; + // the steady push of the springs over the step, or the peak of a hit for as long as it lasted + for (auto const &[force, time] : {std::pair{compression_at(coupler, end), dt}, std::pair{coupler.hit_force, coupler.hit_duration}}) + { + pushed.force = force; + auto const ratio{collision::pushed_ratio(vehicle, pushed, RunningShape.R)}; + if (ratio < derailment::climbing_limit) + { + continue; + } + holds = true; + duration = std::max(duration, time); + if (ratio > worst) + { + worst = ratio; + worstforce = force; + worstend = end; + } + } + } + if (pushed_off_monitor.update(holds, duration)) + { + derail_in_collision(COLLISION_PUSHED_OFF, std::format("{:.0f} kN pressing its {} end in, at {:.0f} km/h, curve radius {:.0f} m: Y/Q {:.2f}", worstforce / 1000.0, end_name(worstend), Vel, + std::abs(RunningShape.R), std::min(worst, 99.0))); + } +} + namespace { @@ -1726,6 +2007,7 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap for (int b = 0; b < 2; b++) if (Couplers[b].CheckCollision) CollisionDetect(b, dt); // zmienia niejawnie AccS, V !!! + check_pushed_off(dt); } // liczone dL, predkosc i przyspieszenie @@ -1788,7 +2070,8 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh // simple mode skips calculation of vertical acceleration AccVert = 0.0; - if (true == TestFlag(DamageFlag, dtrain_out) && Vel < 1.0) + // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce() + if (true == TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none && Vel < 1.0) { V = 0.0; AccS = 0.0; @@ -1801,6 +2084,7 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh for (int b = 0; b < 2; b++) if (Couplers[b].CheckCollision) CollisionDetect(b, dt); // zmienia niejawnie AccS, V !!! + check_pushed_off(dt); } // liczone dL, predkosc i przyspieszenie auto const d{(EngineType == TEngineType::WheelsDriven ? dL * CabActive : // na chwile dla testu @@ -5456,8 +5740,15 @@ void TMoverParameters::ComputeTotalForce(double dt) // doliczenie sił z innych pojazdów for (int end = end::front; end <= end::rear; ++end) { + // a new step: the hit of the pair not taken by either vehicle yet + Couplers[end].hit_handled = false; + Couplers[end].hit_force = 0.0; + Couplers[end].hit_duration = 0.0; + Couplers[end].closing = 0.0; if (Neighbours[end].vehicle != nullptr) { + // the velocities before the step, the forces of all the vehicles come before their movement + Couplers[end].closing = -CouplerVelocityDifference(end, *Neighbours[end].vehicle->MoverParameters, Neighbours[end].vehicle_end) * DirF(end); Couplers[end].CForce = CouplerForce(end, dt); FTrain += Couplers[end].CForce; } @@ -5674,7 +5965,10 @@ double TMoverParameters::CouplerForce(int const End, double dt) auto const initialdistance{Neighbours[End].distance}; // odległość od sprzęgu sąsiada auto const distancedelta{(End == end::front ? othervehiclemove - dMoveLen : dMoveLen - othervehiclemove)}; - auto const newdistance{initialdistance + 10.0 * distancedelta}; + // the ends crushed for good (physics.derailment new, see collision.h) let the buffers meet that much closer + auto const crushed{thiscoupler.crush + othercoupler.crush}; + auto const rawdistance{initialdistance + 10.0 * distancedelta}; + auto const newdistance{rawdistance < 0.0 ? std::min(0.0, rawdistance + crushed) : rawdistance}; auto const dV{CouplerVelocityDifference(End, *othervehicle, otherend)}; auto const absdV{std::abs(dV)}; @@ -5819,6 +6113,11 @@ void TMoverParameters::automatic_coupling(int const End, TMoverParameters &Other { return; } + // a coupler torn off by the crush of its end (physics.derailment new) doesn't catch + if (Global.derailment == global_settings::derailment_model::physical && (thiscoupler.broken || othercoupler.broken)) + { + return; + } // sprzeganie wagonow z samoczynnymi sprzegami auto couplingtype{thiscoupler.AutomaticCouplingFlag & othercoupler.AutomaticCouplingFlag}; // potentially exclude incompatible control coupling @@ -5898,7 +6197,7 @@ double TMoverParameters::coupler_force_physical(int const End, double const dt) auto const previousgap{state.gap}; auto const previousdrawgear{state.draw_gear.deflection}; - auto const result{coupler_physics::update_pair(thiscoupler.physics, othercoupler.physics, state, {gap, gaprate, coupled, adapter, Global.crash_damage})}; + auto const result{coupler_physics::update_pair(thiscoupler.physics, othercoupler.physics, state, {gap, gaprate, coupled, adapter, Global.crash_damage, thiscoupler.crush + othercoupler.crush})}; SetFlag(thiscoupler.sounds, coupler_sounds({gap, previousgap, gaprate, state.draw_gear.deflection, previousdrawgear, coupled, adapter, Vel > 1.0})); @@ -5952,7 +6251,8 @@ bool TMoverParameters::coupler_stop_hit(int const End, TMoverParameters &Other, auto const hit{coupler_physics::impact(thiscoupler.physics, othercoupler.physics, state, closing, TotalMass, Other.TotalMass)}; // the other vehicle keeps the state of the pair alike othercoupler.physics_state.elongation = state.elongation; - if (hit.broken || hit.crushed) + // with physics.derailment new the crush of the ends past the buffers is crush_hit()'s + if (hit.broken || (hit.crushed && Global.derailment != global_settings::derailment_model::physical)) { damage_coupler(End); } @@ -11425,6 +11725,45 @@ void scale_strength(coupler_physics::link_strength &Link, double const Factor) Link.ultimate *= Factor; } +// the optional keys of the collisions past the buffers (physics.derailment new, see collision.h), what's not given +// comes from the kind of the vehicle: +// FcrushPeak, FcrushPlateau [kN] the force the end starts to crush at, and keeps crushing at +// CrushOnset, CrushDensify, CrushLimit [m] the crush the peak drops at, it packs down past, it can't go past +// CrushHardening [1/m] the growth of the force past CrushDensify, to the plateau for each metre +// CrashZone [yes/no] built to EN 15227: energy absorbers and anticlimbers; AntiClimber [yes/no] on its own +// BufferHeight [m] of the empty vehicle above the rail +// BufferCategory [A/B/C/L/P] the buffers of EN 15551 (P those of the coaches) in place of kB and DmaxB +collision::end_definition collision_definition(std::string const &Line) +{ + collision::end_definition definition; + auto const number = [&Line](std::string const &Key, double const Scale) -> std::optional { + auto value{0.0}; + if (extract_value(value, Key, Line, "") && value >= 0.0) + { + return value * Scale; + } + return std::nullopt; + }; + auto const flag = [&Line](std::string const &Key) -> std::optional { + auto value{false}; + if (extract_value(value, Key, Line, "")) + { + return value; + } + return std::nullopt; + }; + definition.peak = number("FcrushPeak", 1000.0); + definition.plateau = number("FcrushPlateau", 1000.0); + definition.onset = number("CrushOnset", 1.0); + definition.densify = number("CrushDensify", 1.0); + definition.hardening = number("CrushHardening", 1.0); + definition.limit = number("CrushLimit", 1.0); + definition.crash_zone = flag("CrashZone"); + definition.anticlimber = flag("AntiClimber"); + definition.buffer_height = number("BufferHeight", 1.0); + return definition; +} + } // namespace void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Index) @@ -11505,7 +11844,22 @@ void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Inde thiscoupler->DmaxB = std::max(0.05, thiscoupler->FmaxC / thiscoupler->SpringKB); } + // the buffers of a category of EN 15551 in place of the springs given + auto const categoryname{extract_value("BufferCategory", line)}; + auto const category{categoryname.empty() ? std::nullopt : collision::buffer_category_of(categoryname.front())}; + auto const buffered{thiscoupler->CouplerType != TCouplerType::NoCoupler && thiscoupler->CouplerType != TCouplerType::Bare && thiscoupler->CouplerType != TCouplerType::Articulated}; + if (category && buffered) + { + auto const linear{collision::buffer_curve(*category, 0.0)}; + thiscoupler->SpringKB = linear.stiffness; + thiscoupler->DmaxB = linear.travel; + } thiscoupler->physics = coupler_physics_parameters(*thiscoupler, line); + if (category && buffered) + { + thiscoupler->physics.buffers = collision::buffer_curve(*category, thiscoupler->physics.buffers.progression); + } + thiscoupler->collision = collision_definition(line); if (Index == 0) { diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp new file mode 100644 index 000000000..c689c709f --- /dev/null +++ b/tests/unit/test_collisions.cpp @@ -0,0 +1,648 @@ +#include "stdafx.h" +#include "doctest.h" +#include "consist.h" +#include "vehicle.h" +#include "McZapkie/collision.h" +#include "McZapkie/MOVER.h" +#include "utilities/Globals.h" + +#include +#include +#include +#include + +// collisions past the buffers with physics.derailment new (McZapkie/collision.h): the crush of the ends, the override, +// the push off the track, and what they do in trains of real vehicles + +using test::consist; +using test::definition; +using test::vehicle; +namespace cl = collision; + +namespace { + +constexpr double kmh{1.0 / 3.6}; + +// the given model of derailment for the test, restored after it +class model_setting { +public: + explicit model_setting(global_settings::derailment_model Model) : m_previous{Global.derailment} { Global.derailment = Model; } + ~model_setting() { Global.derailment = m_previous; } + model_setting(model_setting const &) = delete; + model_setting &operator=(model_setting const &) = delete; + +private: + global_settings::derailment_model m_previous; +}; + +// the given setting of a global flag for the test, restored after it +class flag_setting { +public: + flag_setting(bool &Flag, bool Enabled) : m_flag{Flag}, m_previous{Flag} { m_flag = Enabled; } + ~flag_setting() { m_flag = m_previous; } + flag_setting(flag_setting const &) = delete; + flag_setting &operator=(flag_setting const &) = delete; + +private: + bool &m_flag; + bool m_previous; +}; + +// ---- the hit of two masses on the stop of their buffers, the way the vehicles take it + +struct pair_outcome { + double crush1{0.0}; + double crush2{0.0}; + double velocity1{0.0}; + double velocity2{0.0}; + double peak{0.0}; // force +}; + +// the first mass runs at the velocity into the second one standing, their buffers pressed all the way already; the +// springs carry the given force while pressed, stepped by Dt as the vehicles are: the springs over the step first, the +// hit after them +pair_outcome hit_pair(cl::end_state First, cl::end_state Second, double const Mass1, double const Mass2, double const Velocity, double const Springs, double const Dt) { + pair_outcome result; + auto velocity1{Velocity}; + auto velocity2{0.0}; + for (int step = 0; step < 1000000; ++step) { + velocity1 -= Springs * Dt / Mass1; + velocity2 += Springs * Dt / Mass2; + auto const closing{velocity1 - velocity2}; + if (closing <= 0.0) { + break; + } + cl::hit_input input; + input.velocity = closing; + input.mass1 = Mass1; + input.mass2 = Mass2; + input.restitution = 0.2; + input.stiffness = 1.4e8; + input.springs = Springs; + input.dt = Dt; + auto const hit{cl::hit(First, Second, input)}; + if (false == hit.crushing) { + // elastic: bounced apart with the restitution + auto const reduced{Mass1 * Mass2 / (Mass1 + Mass2)}; + auto const impulse{reduced * closing * (1.0 + input.restitution)}; + velocity1 -= impulse / Mass1; + velocity2 += impulse / Mass2; + break; + } + velocity1 -= hit.impulse / Mass1; + velocity2 += hit.impulse / Mass2; + First.crush += hit.crush1; + Second.crush += hit.crush2; + result.peak = std::max(result.peak, hit.force); + if (hit.velocity <= 0.0) { + break; + } + } + result.crush1 = First.crush; + result.crush2 = Second.crush; + result.velocity1 = velocity1; + result.velocity2 = velocity2; + return result; +} + +cl::crush_curve const wagon_curve{cl::default_crush(cl::vehicle_kind::wagon)}; +cl::crush_curve const locomotive_curve{cl::default_crush(cl::vehicle_kind::locomotive)}; + +// ---- trains of real vehicles + +bool derailed(TMoverParameters const &Vehicle) { + return TestFlag(Vehicle.DamageFlag, dtrain_out); +} + +double crush_of(TMoverParameters const &Vehicle) { + return std::max(Vehicle.Couplers[end::front].crush, Vehicle.Couplers[end::rear].crush); +} + +// a mixed freight train as the PoC has it: every third wagon from the given one an empty two-axle 3WL (10.5 t), the +// rest 430W coal wagons loaded full (80 t) +definition mixed_wagon(int const Index) { + return definition::fiz(Index % 3 == 1 ? "3wl_v2/3wl" : "430w_v2/430w"); +} + +vehicle &add_mixed(consist &Train, int const Index, int const Coupling, double const Velocity, double const Gap) { + auto &wagon{Train.add(mixed_wagon(Index), 0, Coupling, Velocity, Gap)}; + if (Index % 3 != 1) { + wagon->AssignLoad("coal", 59.5f); + wagon->ComputeMass(); + } + return wagon; +} + +struct crash_outcome { + int derailed{0}; + int overridden{0}; + int pushed{0}; + int crushed{0}; // ends crushed past the mark + int broken{0}; // couplings torn off + double crush{0.0}; // the deepest crush of an end + bool locomotive{false}; // it derailed + std::string list; // what happened to which vehicle, for the messages +}; + +// the PoC of G14: a locomotive (EU07, 80 t) with 12 mixed wagons running into the rear of 8 mixed wagons standing +// braked, in emergency, on a straight track or in a curve +crash_outcome freight_crash(double const Speed, double const Radius, double const Dt = 0.01) { + test::track track; + track.radius = Radius; + consist train; + // the standing train, the wagon it's hit at last; its brakes charged, then in emergency + constexpr int standing{8}; + for (int i = standing - 1; i >= 0; --i) { + add_mixed(train, i, consist::full_coupling, 0.0, 0.0).hold_brake_pipe(5.0); + } + train.run(90.0, track); + for (int i = 0; i < standing; ++i) { + train[i].hold_brake_pipe(0.0); + } + train.run(30.0, track); + // the train running into it, its locomotive leading, a metre short of the hit + train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, Speed, 1.0); + for (int i = 0; i < 12; ++i) { + add_mixed(train, i, consist::full_coupling, Speed, 0.0); + } + train.run(12.0, track, Dt); + + crash_outcome result; + for (std::size_t i = 0; i < train.size(); ++i) { + auto const &vehicle{train[i].mover()}; + auto const name{i < standing ? std::format("standing {}", standing - 1 - i) : i == standing ? std::string{"locomotive"} : std::format("running {}", i - standing - 1)}; + for (auto const end : {end::front, end::rear}) { + if (vehicle.Couplers[end].crush >= cl::crush_mark) { + ++result.crushed; + } + } + result.crush = std::max(result.crush, crush_of(vehicle)); + if (derailed(vehicle)) { + ++result.derailed; + result.overridden += vehicle.CollisionDerail == COLLISION_OVERRIDE; + result.pushed += vehicle.CollisionDerail == COLLISION_PUSHED_OFF; + result.locomotive = result.locomotive || i == standing; + result.list += std::format("{} ({:.1f} t) {}; ", name, vehicle.TotalMass / 1000.0, vehicle.CollisionDerail == COLLISION_OVERRIDE ? "overrode" : "pushed off"); + } + else if (crush_of(vehicle) >= cl::crush_mark) { + result.list += std::format("{} crushed {:.2f} m; ", name, crush_of(vehicle)); + } + } + for (std::size_t i = 0; i + 1 < train.size(); ++i) { + result.broken += train[i]->Couplers[end::rear].broken; + } + return result; +} + +// a locomotive running into a loaded coal wagon standing free, both on the rails: the crush of the pair after the hit +double locomotive_into_wagon(double const Speed, double const Dt) { + consist train; + auto &wagon{train.add(definition::fiz("430w_v2/430w"))}; + wagon->AssignLoad("coal", 59.5f); + wagon->ComputeMass(); + // behind the wagon, running forwards into its rear end + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, Speed, 0.5)}; + train.run(3.0, {}, Dt); + return wagon->Couplers[end::rear].crush + locomotive->Couplers[end::front].crush; +} + +} // namespace + +// ---- the crush curve + +TEST_CASE("collisions: the crush curve, a peak, a plateau, packing down, and the limit") { + auto const &curve{wagon_curve}; + CHECK(curve.force(0.0) == doctest::Approx(3.0e6)); + CHECK(curve.force(0.049) == doctest::Approx(3.0e6)); + CHECK(curve.force(0.05) == doctest::Approx(2.0e6)); + CHECK(curve.force(0.79) == doctest::Approx(2.0e6)); + // 2 / m past 0.8 m: a metre further it's three times the plateau + CHECK(curve.force(1.3) == doctest::Approx(2.0e6 * (1.0 + 2.0 * 0.5))); + CHECK_FALSE(std::isfinite(curve.force(1.5))); + // the energy is the area under it + CHECK(curve.energy(0.0, 0.05) == doctest::Approx(3.0e6 * 0.05)); + CHECK(curve.energy(0.0, 0.8) == doctest::Approx(3.0e6 * 0.05 + 2.0e6 * 0.75)); + CHECK(curve.energy(0.8, 1.3) == doctest::Approx(0.5 * (2.0e6 + 4.0e6) * 0.5)); + CHECK(curve.energy(0.0, 0.3) + curve.energy(0.3, 1.0) == doctest::Approx(curve.energy(0.0, 1.0))); + // past the limit there's nothing more to crush + CHECK(curve.energy(1.5, 3.0) == 0.0); + + // the kinds of vehicles; a crash zone gives a steady force with no peak + CHECK(locomotive_curve.peak > wagon_curve.peak); + auto const zone{cl::default_crush(cl::vehicle_kind::crash_zone)}; + CHECK(zone.force(0.0) == doctest::Approx(zone.force(0.5))); + // the keys of the .fiz override the defaults of the kind + cl::end_definition given; + given.plateau = 1.0e6; + given.crash_zone = true; + auto const own{cl::crush_of(given, cl::vehicle_kind::coach)}; + CHECK(own.plateau == doctest::Approx(1.0e6)); + CHECK(own.densify == doctest::Approx(zone.densify)); + CHECK(cl::anticlimber_of(given, cl::vehicle_kind::coach)); + CHECK_FALSE(cl::anticlimber_of({}, cl::vehicle_kind::locomotive)); +} + +TEST_CASE("collisions: the buffers of EN 15551, their stroke and energy") { + for (auto const category : {cl::buffer_category::A, cl::buffer_category::B, cl::buffer_category::C, cl::buffer_category::L, cl::buffer_category::passenger}) { + auto const rated{cl::rating(category)}; + for (auto const progression : {0.0, 0.5, 0.9}) { + auto const curve{cl::buffer_curve(category, progression)}; + CHECK(curve.travel == doctest::Approx(rated.stroke)); + // two buffers side by side + CHECK(curve.energy(curve.travel) == doctest::Approx(2.0 * rated.energy)); + } + } + CHECK(cl::rating(cl::buffer_category::A).energy < cl::rating(cl::buffer_category::C).energy); + CHECK(cl::buffer_category_of('C') == cl::buffer_category::C); + CHECK_FALSE(cl::buffer_category_of('X').has_value()); + // the triangle of category A: 2 x 30 kJ over 105 mm is about 1.1 MN at the end of the stroke, 570 kN a buffer + CHECK(cl::buffer_curve(cl::buffer_category::A, 0.0).end_force() == doctest::Approx(4.0 * 30.0e3 / 0.105)); +} + +// ---- the hit + +TEST_CASE("collisions: a hit the steel takes stays elastic, a harder one crushes the weaker end") { + cl::hit_input input; + input.mass1 = 80.0e3; + input.mass2 = 80.0e3; + input.stiffness = 1.4e8; + input.dt = 0.01; + // 40 t reduced: the steel takes 3 MN at 3 / sqrt(1.4e8 * 4e4) = 1.27 m/s + input.velocity = 1.0; + CHECK_FALSE(cl::hit({wagon_curve, 0.0}, {wagon_curve, 0.0}, input).crushing); + input.velocity = 5.0; + auto const hit{cl::hit({locomotive_curve, 0.0}, {wagon_curve, 0.0}, input)}; + REQUIRE(hit.crushing); + // the wagon gives, the locomotive doesn't; at its peak force for the whole step + CHECK(hit.crush1 == 0.0); + CHECK(hit.crush2 > 0.0); + CHECK(hit.force == doctest::Approx(3.0e6)); + CHECK(hit.impulse == doctest::Approx(3.0e6 * 0.01)); + CHECK(hit.duration == doctest::Approx(0.01)); + CHECK(hit.velocity == doctest::Approx(5.0 - 3.0e6 * 0.01 / 40.0e3)); + // with the springs carrying a part of the force, the hit adds the rest + input.springs = 1.0e6; + auto const sprung{cl::hit({locomotive_curve, 0.0}, {wagon_curve, 0.0}, input)}; + CHECK(sprung.impulse == doctest::Approx(2.0e6 * 0.01)); + // two alike crush alike + input.springs = 0.0; + auto const alike{cl::hit({wagon_curve, 0.0}, {wagon_curve, 0.0}, input)}; + CHECK(alike.crush1 == doctest::Approx(alike.crush2)); + // a wall: the end crushed all the way doesn't give, the other one does + auto const wall{cl::hit({wagon_curve, 2.0}, {wagon_curve, 0.0}, input)}; + CHECK(wall.crush1 == 0.0); + CHECK(wall.crush2 > 0.0); + // both crushed all the way: rigid, the legacy exchange + CHECK_FALSE(cl::hit({wagon_curve, 2.0}, {wagon_curve, 2.0}, input).crushing); +} + +TEST_CASE("collisions: the crush doesn't depend on the step, and it takes the energy of the hit") { + struct pair { + char const *name; + double mass1; + double mass2; + double velocity; + double springs; + }; + for (auto const &[name, mass1, mass2, velocity, springs] : { + pair{"80 t into 80 t at 25 km/h", 80.0e3, 80.0e3, 25.0 * kmh, 0.0}, + pair{"80 t into 80 t at 40 km/h, the springs at 1 MN", 80.0e3, 80.0e3, 40.0 * kmh, 1.0e6}, + pair{"80 t into 12 t at 40 km/h", 80.0e3, 12.0e3, 40.0 * kmh, 0.5e6}, + pair{"300 t into 80 t at 35 km/h, past the densification", 300.0e3, 80.0e3, 35.0 * kmh, 0.0}, + }) { + CAPTURE(name); + auto const fine{hit_pair({locomotive_curve, 0.0}, {wagon_curve, 0.0}, mass1, mass2, velocity, springs, 0.001)}; + REQUIRE(fine.crush2 > 0.05); + CHECK(fine.crush1 == 0.0); + for (auto const dt : {0.005, 0.01, 0.05}) { + CAPTURE(dt); + auto const coarse{hit_pair({locomotive_curve, 0.0}, {wagon_curve, 0.0}, mass1, mass2, velocity, springs, dt)}; + CHECK(coarse.crush2 == doctest::Approx(fine.crush2).epsilon(0.02)); + // the momentum stays with the pair + CHECK(mass1 * coarse.velocity1 + mass2 * coarse.velocity2 == doctest::Approx(mass1 * velocity)); + // never past the force the wagon gives at: its peak, or what it packed down to + CHECK(coarse.peak <= std::max(wagon_curve.peak, wagon_curve.force(coarse.crush2)) * (1.0 + 1e-9)); + } + if (springs == 0.0) { + // the energy of the relative motion goes into the crush, but for what the steel takes back + auto const reduced{mass1 * mass2 / (mass1 + mass2)}; + auto const kinetic{0.5 * reduced * velocity * velocity}; + auto const crushforce{wagon_curve.force(fine.crush2)}; + auto const elastic{crushforce * crushforce / (2.0 * 1.4e8)}; + CHECK(wagon_curve.energy(0.0, fine.crush2) == doctest::Approx(kinetic - elastic).epsilon(0.01)); + } + } +} + +TEST_CASE("collisions: the crush of two pairs of masses at the speeds of the table") { + // 80 t on 80 t: the steel takes the hit up to 1.3 m/s past the buffers; at 25 km/h the two ends alike crush by + // 0.4 m between them, the 0.97 MJ at 3 MN to 0.05 m each and at 2 MN past it (the buffers aren't here) + auto const slow{hit_pair({wagon_curve, 0.0}, {wagon_curve, 0.0}, 80.0e3, 80.0e3, 1.2, 0.0, 0.01)}; + CHECK(slow.crush1 + slow.crush2 == 0.0); + auto const hard{hit_pair({wagon_curve, 0.0}, {wagon_curve, 0.0}, 80.0e3, 80.0e3, 25.0 * kmh, 0.0, 0.01)}; + CHECK(hard.crush1 + hard.crush2 > 0.2); + CHECK(hard.crush1 + hard.crush2 < 0.5); +} + +// ---- override + +TEST_CASE("collisions: the lighter or the higher vehicle climbs onto the other one, both past a deeper crush") { + cl::override_input input; + input.mass1 = 80.0e3; + input.mass2 = 80.0e3; + input.height1 = 1.040; + input.height2 = 1.040; + SUBCASE("a shallow crush holds") { + input.crush1 = 0.3; + auto const result{cl::override_of(input)}; + CHECK_FALSE(result.first); + CHECK_FALSE(result.second); + } + SUBCASE("alike: past 0.35 m they hold, past 0.6 m both climb") { + input.crush1 = 0.4; + CHECK_FALSE(cl::override_of(input).first); + input.crush2 = 0.25; + auto const result{cl::override_of(input)}; + CHECK(result.first); + CHECK(result.second); + } + SUBCASE("the lighter one climbs past 0.35 m") { + input.mass1 = 12.0e3; + input.crush1 = 0.4; + auto const result{cl::override_of(input)}; + CHECK(result.first); + CHECK_FALSE(result.second); + } + SUBCASE("40 mm higher, the higher one climbs") { + input.height2 = 1.000; + input.crush1 = 0.2; + input.crush2 = 0.2; + auto const result{cl::override_of(input)}; + CHECK(result.first); + CHECK_FALSE(result.second); + } + SUBCASE("interlocked anticlimbers hold them until the crush zone of an end is used up") { + input.anticlimbers = true; + input.zone1 = 0.8; + input.zone2 = 0.8; + input.height2 = 1.000; + input.mass1 = 40.0e3; + input.crush1 = 0.5; + input.crush2 = 0.5; + auto const held{cl::override_of(input)}; + CHECK_FALSE(held.first); + CHECK_FALSE(held.second); + input.crush1 = 0.85; + auto const spent{cl::override_of(input)}; + CHECK(spent.first); + CHECK(spent.second); + } +} + +// ---- pushed off the track + +TEST_CASE("collisions: an empty two-axle wagon between loaded ones in a curve of 150 m is pushed off past the safe push of EN 15566") { + // the vehicles of data/fiz: the 3WL empty (10.5 t, two axles 6 m apart), between 430W coal wagons + vehicle empty{definition::fiz("3wl_v2/3wl")}; + vehicle loaded{definition::fiz("430w_v2/430w")}; + cl::pushed_vehicle wagon; + wagon.mass = empty->TotalMass - empty->Mred; + wagon.axles = empty->NAxles; + wagon.length = empty->Dim.L; + wagon.pivots = empty->BDist; + wagon.axle_base = empty->ADist > 0.0 ? empty->ADist : empty->BDist; + REQUIRE(wagon.axles == 2); + cl::pushed_end end; + end.other_length = loaded->Dim.L; + auto const ratio = [&](double const Force, double const Radius) { + end.force = Force; + return cl::pushed_ratio(wagon, end, Radius); + }; + // 250 kN on the pair of buffers in a curve of 150 m is safe (EN 15566, 4.2); 600 kN pushes it off + CHECK(ratio(250.0e3, 150.0) < 1.2); + CHECK(ratio(250.0e3, 150.0) > 0.5); + CHECK(ratio(600.0e3, 150.0) > 1.2); + // the wider the curve the more it takes; on a straight track the empty wagon lifts off past 1.5 MN: the force + // pitching it takes the load off its leading wheels + CHECK(ratio(600.0e3, 500.0) < ratio(600.0e3, 150.0)); + CHECK(ratio(600.0e3, 0.0) < 1.2); + CHECK(ratio(1.5e6, 0.0) < 1.2); + CHECK(ratio(2.5e6, 0.0) > 1.2); + // a crushed end no longer holds the ends in line + end.crush = 0.5; + CHECK(ratio(1.5e6, 0.0) > 1.2); + end.crush = 0.0; + + // the loaded wagon, four axles, takes it + cl::pushed_vehicle heavy; + heavy.mass = loaded->TotalMass - loaded->Mred + 59.5e3; + heavy.axles = loaded->NAxles; + heavy.length = loaded->Dim.L; + heavy.pivots = loaded->BDist; + heavy.axle_base = loaded->ADist; + end.force = 600.0e3; + CHECK(cl::pushed_ratio(heavy, end, 150.0) < 0.5); + + // it has to hold for 0.05 s, however long the steps + cl::pushed_monitor monitor; + CHECK_FALSE(monitor.update(true, 0.03)); + CHECK_FALSE(monitor.update(false, 0.01)); + CHECK_FALSE(monitor.update(true, 0.03)); + CHECK(monitor.update(true, 0.03)); +} + +// ---- the model of eu07.ini + +TEST_CASE("collisions: the legacy rule with physics.derailment old, the crush with new") { + flag_setting const crashdamage{Global.crash_damage, true}; + struct collision { + char const *name; + char const *front; + char const *back; + double speed; // of the back one, running into the front one standing + bool frontout_old; + bool backout_old; + bool frontout_new; + bool backout_new; + }; + // the legacy rule: over 15 km/h weighed by the ratio of the masses. the crush: the light wagon is crushed deep and + // climbs onto the locomotive at 60 km/h; two locomotives at 25 km/h crush their ends 0.1-0.3 m and stay on the rails + for (auto const &[name, front, back, speed, frontout_old, backout_old, frontout_new, backout_new] : { + collision{"locomotive into a wagon at 60", "3wl_v2/3wl", "4e_v1/4e", 60.0, true, false, true, false}, + collision{"locomotive into a locomotive at 25", "4e_v1/4e", "4e_v1/4e", 25.0, true, true, false, false}, + collision{"locomotive into a locomotive at 50", "4e_v1/4e", "4e_v1/4e", 50.0, true, true, true, true}, + }) { + CAPTURE(name); + for (auto const model : {global_settings::derailment_model::old, global_settings::derailment_model::physical}) { + auto const physical{model == global_settings::derailment_model::physical}; + CAPTURE(physical); + model_setting const setting{model}; + consist train; + train.add(definition::fiz(front)); + train.add(definition::fiz(back), 0, coupling::faux, speed, 20.0); + train.run(10.0); + CHECK(derailed(train[0].mover()) == (physical ? frontout_new : frontout_old)); + CHECK(derailed(train[1].mover()) == (physical ? backout_new : backout_old)); + auto const crush{train[0]->Couplers[end::rear].crush + train[1]->Couplers[end::front].crush}; + if (physical) { + MESSAGE(name, ": crush ", crush, " m"); + CHECK(crush > 0.05); + } + else { + CHECK(crush == 0.0); + } + } + } +} + +TEST_CASE("collisions: the crush of a locomotive hitting a wagon doesn't depend on the step, nor on the model of the coupling") { + model_setting const physical{global_settings::derailment_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const physics : {false, true}) { + CAPTURE(physics); + flag_setting const couplerphysics{Global.coupler_physics, physics}; + flag_setting const everywhere{Global.coupler_physics_all, physics}; + auto const fine{locomotive_into_wagon(30.0, 0.001)}; + auto const game{locomotive_into_wagon(30.0, 0.01)}; + auto const coarse{locomotive_into_wagon(30.0, 0.05)}; + MESSAGE(std::format("30 km/h, couplerphysics {}: crush {:.3f} / {:.3f} / {:.3f} m with dt 0.001 / 0.01 / 0.05 s", physics, fine, game, coarse)); + REQUIRE(fine > 0.05); + // the step of the game, and a step five times as long, which the buffers past the crush aren't made for + CHECK(game == doctest::Approx(fine).epsilon(0.1)); + CHECK(coarse == doctest::Approx(fine).epsilon(0.5)); + } + // the models of the coupling differ in their buffers, not past them + { + auto const legacy{locomotive_into_wagon(30.0, 0.01)}; + flag_setting const couplerphysics{Global.coupler_physics, true}; + flag_setting const everywhere{Global.coupler_physics_all, true}; + CHECK(locomotive_into_wagon(30.0, 0.01) == doctest::Approx(legacy).epsilon(0.3)); + } + // slow enough, the buffers take it all + CHECK(locomotive_into_wagon(5.0, 0.01) == 0.0); +} + +TEST_CASE("collisions: automatic couplers hit too fast don't catch, the ends crush; torn off, they don't couple again") { + model_setting const physical{global_settings::derailment_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + auto const automatic{definition::load("wagon").set("BuffCoupl", "CType", "Automatic").set("BuffCoupl", "AutomaticFlag", coupling::coupler | coupling::brakehose)}; + for (auto const speed : {20.0, 30.0, 45.0}) { + CAPTURE(speed); + vehicle moving{automatic, speed, "moving"}; + vehicle standing{automatic, 0.0, "standing"}; + test::pair pair{moving, end::front, standing, end::rear, 1.0}; + auto coupled{false}; + auto fast{false}; // coupled while closing in faster than the couplers catch + for (int i = 0; i < 1000; ++i) { + auto const closing{moving->CollisionVelocity(end::front, standing.mover(), end::rear)}; + pair.step(); + fast = fast || (pair.coupled() && false == coupled && closing > TMoverParameters::SafeCollisionVelocity); + coupled = coupled || pair.coupled(); + } + auto const crush{moving->Couplers[end::front].crush + standing->Couplers[end::rear].crush}; + MESSAGE(speed, " km/h: crush ", crush, " m, derailed ", derailed(moving.mover()), " ", derailed(standing.mover()), ", coupled later ", coupled); + CHECK_FALSE(fast); + CHECK(crush > 0.0); + // crushed past the draw gear, the coupler is gone; short of it, the wagons may roll together again slowly + // after the hit, and couple then + if (std::max(moving->Couplers[end::front].crush, standing->Couplers[end::rear].crush) >= cl::draw_gear_crush) { + CHECK_FALSE(coupled); + CHECK((moving->Couplers[end::front].broken || standing->Couplers[end::rear].broken)); + } + // the two alike: neither climbs onto the other until the crush is deep enough for both to + CHECK(derailed(moving.mover()) == derailed(standing.mover())); + CHECK(derailed(moving.mover()) == (crush > cl::override_both)); + } +} + +TEST_CASE("collisions: a vehicle off the rails by the new model stays in the chain of forces") { + model_setting const physical{global_settings::derailment_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + consist train; + auto &wagon{train.add(definition::fiz("430w_v2/430w"))}; + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, 10.0, 0.5)}; + wagon->derail_in_collision(COLLISION_PUSHED_OFF, "for the test"); + REQUIRE(derailed(wagon.mover())); + auto const before{wagon->TotalMass * wagon->V + locomotive->TotalMass * locomotive->V}; + // the hit is over within a second, the friction of the derailed wagon slows the pair down over it + train.run(1.0); + auto const after{wagon->TotalMass * wagon->V + locomotive->TotalMass * locomotive->V}; + // pushed along, not a wall the locomotive bounces off + CHECK(wagon.speed() > 1.0); + CHECK(locomotive.speed() > 0.0); + CHECK(after < before); + CHECK(after > 0.5 * before); + // and it slides on with the friction of the ballast, stopping before long + train.run(10.0); + CHECK(std::abs(wagon.speed()) < 0.1); +} + +TEST_CASE("collisions: a freight train running into a standing one, the cases of the PoC of G14") { + model_setting const physical{global_settings::derailment_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + struct crash { + double speed; + double radius; + }; + for (auto const &[speed, radius] : {crash{10.0, 0.0}, crash{15.0, 0.0}, crash{15.0, 190.0}, crash{25.0, 0.0}, crash{25.0, 190.0}, crash{40.0, 0.0}, crash{40.0, 190.0}}) { + CAPTURE(speed); + CAPTURE(radius); + auto const result{freight_crash(speed, radius)}; + MESSAGE(std::format("{:.0f} km/h, R {:.0f}: {} derailed ({} overrode, {} pushed off), {} ends crushed (deepest {:.2f} m), {} couplings broken: {}", speed, radius, result.derailed, + result.overridden, result.pushed, result.crushed, result.crush, result.broken, result.list)); + if (speed <= 10.0) { + // the buffers take it + CHECK(result.derailed == 0); + CHECK(result.crushed == 0); + } + } +} + +TEST_CASE("collisions: identical units built to EN 15227 at 36 km/h") { + model_setting const physical{global_settings::derailment_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + // two coaches of data/wagon.json (42.2 t) a unit, their ends crash zones with anticlimbers, unbraked + auto const unit = [](bool const Anticlimbers, double const Height) { + return definition::load("wagon").set("BuffCoupl", "CrashZone", "Yes").set("BuffCoupl", "AntiClimber", Anticlimbers ? "Yes" : "No").set("BuffCoupl", "BufferHeight", Height); + }; + auto const crash = [&](bool const Anticlimbers, double const Speed, double const Offset) { + consist train; + train.add(unit(Anticlimbers, 1.040)); + train.add(unit(Anticlimbers, 1.040)); + train.add(unit(Anticlimbers, 1.040 + Offset), 0, coupling::faux, Speed, 1.0); + train.add(unit(Anticlimbers, 1.040 + Offset), 0, consist::full_coupling, Speed); + train.run(6.0); + struct { + double crush; + double inner; + int derailed; + bool higher; + } result{train[1]->Couplers[end::rear].crush + train[2]->Couplers[end::front].crush, std::max(crush_of(train[0].mover()), crush_of(train[3].mover())), 0, + derailed(train[2].mover())}; + for (std::size_t i = 0; i < train.size(); ++i) { + result.derailed += derailed(train[i].mover()); + } + return result; + }; + SUBCASE("scenario 1: the crush stays in the zones, nothing climbs") { + auto const result{crash(true, 36.0, 0.04)}; + MESSAGE("36 km/h, 40 mm offset: crush ", result.crush, " m, the far ends ", result.inner, " m"); + CHECK(result.crush > 0.2); + CHECK(result.crush < 2.0 * 0.8); + CHECK(result.derailed == 0); + } + SUBCASE("the same units without the anticlimbers override") { + auto const result{crash(false, 36.0, 0.0)}; + CHECK(result.derailed >= 2); + } + SUBCASE("slower, without the anticlimbers, the higher one climbs") { + auto const result{crash(false, 32.0, 0.04)}; + MESSAGE("32 km/h, 40 mm offset: crush ", result.crush, " m"); + CHECK(result.crush > cl::override_crush); + CHECK(result.crush < cl::override_both); + CHECK(result.higher); + CHECK(result.derailed == 1); + auto const held{crash(true, 32.0, 0.04)}; + CHECK(held.derailed == 0); + } +} diff --git a/tests/unit/test_controls.cpp b/tests/unit/test_controls.cpp index 4e5255ff4..f42ecd731 100644 --- a/tests/unit/test_controls.cpp +++ b/tests/unit/test_controls.cpp @@ -4,6 +4,7 @@ #include "drive.h" #include "McZapkie/hamulce.h" +#include "utilities/Globals.h" #include "utilities/utilities.h" // characterisation of the controls a driver and a crew use besides driving and braking: doors, direction and @@ -495,6 +496,14 @@ TEST_CASE("controls: a freight wagon loaded and braked") { } TEST_CASE("controls: a locomotive running into a standing wagon") { + // the legacy collisions of physics.derailment old: derailed, the wagon is a wall (test_collisions.cpp has the new) + struct legacy { + global_settings::derailment_model previous{Global.derailment}; + legacy() { Global.derailment = global_settings::derailment_model::old; } + ~legacy() { Global.derailment = previous; } + legacy(legacy const &) = delete; + legacy &operator=(legacy const &) = delete; + } const model; for (auto const speed : {5.0, 15.0, 40.0}) { CAPTURE(speed); scenario scenario{std::format("controls/collision/{} kmh", static_cast(speed)), motion()}; diff --git a/tests/unit/test_couplers.cpp b/tests/unit/test_couplers.cpp index bbb1c0dd9..c6a3f4a5d 100644 --- a/tests/unit/test_couplers.cpp +++ b/tests/unit/test_couplers.cpp @@ -49,6 +49,19 @@ private: bool m_previous{Global.crash_damage}; }; +// the legacy collisions of physics.derailment old for the test, restored after it: the rule of the safe closing speed +// weighed by the ratio of the masses (the crush of the ends of the new model is in test_collisions.cpp) +class legacy_collisions { +public: + legacy_collisions() { Global.derailment = global_settings::derailment_model::old; } + ~legacy_collisions() { Global.derailment = m_previous; } + legacy_collisions(legacy_collisions const &) = delete; + legacy_collisions &operator=(legacy_collisions const &) = delete; + +private: + global_settings::derailment_model m_previous{Global.derailment}; +}; + } // namespace // issue #86: automatic couplers used to catch at any closing speed, so the vehicles never collided nor derailed @@ -202,6 +215,7 @@ TEST_CASE("couplers: a wagon rolling slowly into a standing one couples with it" TEST_CASE("couplers: a wagon hitting a standing one too fast doesn't couple, nor once the hit has slowed it down") { crash_damage_setting const crashdamage{true}; + legacy_collisions const legacy; auto moving{automatic_wagon(30.0, "moving")}; auto standing{automatic_wagon(0.0, "standing")}; test::pair pair{moving, end::front, standing, end::rear, 1.0}; @@ -268,6 +282,7 @@ TEST_CASE("couplers: the automatic coupling locked by a hit is unlocked once the TEST_CASE("couplers: a hit a little too fast for the couplers bounces the vehicles apart, uncoupled and on the rails") { crash_damage_setting const crashdamage{true}; + legacy_collisions const legacy; auto moving{automatic_wagon(20.0, "moving")}; auto standing{automatic_wagon(0.0, "standing")}; test::pair pair{moving, end::front, standing, end::rear, 1.0}; @@ -281,6 +296,7 @@ TEST_CASE("couplers: a hit a little too fast for the couplers bounces the vehicl TEST_CASE("couplers: a hit too fast for the couplers derails the vehicles over the limit adjusted for their mass ratio") { crash_damage_setting const crashdamage{true}; + legacy_collisions const legacy; SUBCASE("equal masses: both derail") { auto moving{automatic_wagon(30.0, "moving")}; @@ -318,6 +334,7 @@ TEST_CASE("couplers: a hit too fast for the couplers derails the vehicles over t TEST_CASE("couplers: wagons running head-on into each other couple only up to the safe closing speed") { crash_damage_setting const crashdamage{true}; + legacy_collisions const legacy; SUBCASE("7 + 7 km/h, the couplers catch") { auto first{automatic_wagon(7.0, "first")}; diff --git a/tests/unit/test_couplers_trains.cpp b/tests/unit/test_couplers_trains.cpp index 926964dbe..e17a8f86d 100644 --- a/tests/unit/test_couplers_trains.cpp +++ b/tests/unit/test_couplers_trains.cpp @@ -3,6 +3,7 @@ #include "consist.h" #include "scenario.h" +#include "utilities/Globals.h" #include "utilities/utilities.h" // characterisation of the couplers between vehicles: coupling and uncoupling by hand (Attach, DettachStatus, @@ -14,6 +15,22 @@ using test::definition; using test::scenario; using namespace test::channels; +namespace { + +// the given model of derailment for the test, restored after it +class model_setting { +public: + explicit model_setting(global_settings::derailment_model Model) : m_previous{Global.derailment} { Global.derailment = Model; } + ~model_setting() { Global.derailment = m_previous; } + model_setting(model_setting const &) = delete; + model_setting &operator=(model_setting const &) = delete; + +private: + global_settings::derailment_model m_previous; +}; + +} // namespace + TEST_CASE("couplers: coupled by hand, touching or apart, of the same kind or not") { consist train; auto &locomotive{train.add(definition::fiz("4e_v1/4e")).mover()}; @@ -147,7 +164,9 @@ TEST_CASE("couplers: a coupler broken, with its brake hose torn off") { TEST_CASE("couplers: collisions fast enough to derail") { // a locomotive running into a standing wagon from behind, and a wagon running backwards into a standing - // locomotive; over 15 km/h, weighed by the ratio of the masses, the vehicles derail + // locomotive; over 15 km/h, weighed by the ratio of the masses, the vehicles derail. the legacy rule of + // physics.derailment old: the new model crushes the ends (test_collisions.cpp) + model_setting const legacy{global_settings::derailment_model::old}; struct collision { char const *name; char const *frontpath; From b182e560e18a05dccffc32d02a025890153b6af9 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 13:04:55 +0100 Subject: [PATCH 020/136] test(scenarios): a curve of td.scn buckles with an event ahead of the timetable train eu07_td_buckle_event: 30 mm out of the curve tdo_n222 at 10:35, laid again during the game; the EU07 keeps on the rails and stops at Przystanek. eu07_td_buckle_derails: 600 mm over a main lobe of 8 m; the EU07 runs into it at 46 km/h and overturns, the log says it derailed on buckled track. --- .../cases/eu07_td_buckle_derails.json | 19 +++++++++++++++++++ .../scenarios/cases/eu07_td_buckle_event.json | 19 +++++++++++++++++++ tests/scenarios/cases/td_buckle_event.scn | 11 +++++++++++ 3 files changed, 49 insertions(+) create mode 100644 tests/scenarios/cases/eu07_td_buckle_derails.json create mode 100644 tests/scenarios/cases/eu07_td_buckle_event.json create mode 100644 tests/scenarios/cases/td_buckle_event.scn diff --git a/tests/scenarios/cases/eu07_td_buckle_derails.json b/tests/scenarios/cases/eu07_td_buckle_derails.json new file mode 100644 index 000000000..5caaa60b6 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_buckle_derails.json @@ -0,0 +1,19 @@ +{ + "description": "EU07 on td.scn on the td/rozklad timetable; at 10:35, as it leaves, the curve tdo_n222 about 950 m ahead buckles hard with a trackbuckle event: 600 mm out of the curve over a main lobe of 8 m (an equivalent radius of 9 m, about 30 m for the body on axles 11 m apart). The AI doesn't see it and runs into it at the 46 km/h it has there: the locomotive leaves the rails on the buckle and stops short of Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_buckle_event.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic", + "amplitude": "600 8" + }, + "ini": ["gfxrenderer null"], + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Track \"tdo_n222\" buckled \\(event autotest_buckle\\): 600 mm to the (left|right) at [0-9.]+ m, main lobe 8.0 m" }, + { "type": "log_contains", "pattern": "Bad driving: autotest_\\S+ derailed on buckled track" }, + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "distance", "max": 1100 } + ] +} diff --git a/tests/scenarios/cases/eu07_td_buckle_event.json b/tests/scenarios/cases/eu07_td_buckle_event.json new file mode 100644 index 000000000..192fa9b5a --- /dev/null +++ b/tests/scenarios/cases/eu07_td_buckle_event.json @@ -0,0 +1,19 @@ +{ + "description": "EU07 on td.scn on the td/rozklad timetable; at 10:35, as it leaves, the curve tdo_n222 about 950 m ahead buckles with a trackbuckle event (30 mm out of the curve, as the heat does: an equivalent radius of 330 m, too little to derail it). The track is laid again during the game and the train keeps on it to Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_buckle_event.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic", + "amplitude": "30" + }, + "ini": ["gfxrenderer null"], + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Track \"tdo_n222\" buckled \\(event autotest_buckle\\): 30 mm to the (left|right)" }, + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 }, + { "type": "log_lacks", "pattern": "Bad driving" } + ] +} diff --git a/tests/scenarios/cases/td_buckle_event.scn b/tests/scenarios/cases/td_buckle_event.scn new file mode 100644 index 000000000..b9d47d434 --- /dev/null +++ b/tests/scenarios/cases/td_buckle_event.scn @@ -0,0 +1,11 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed: +// td_timetable.scn (the timetable train from track 1 of Stacja1 to Przystanek), and at 10:35, as the train leaves, +// the curve tdo_n222 (R 600 m, about 950 m ahead of it) buckles in the heat out of the curve with the +// trackbuckle event of {{amplitude}} mm (see world/TrackBuckle.h) +trainset td/rozklad tdo_n1734 0.0 0.1 +{{consist}} +endtrainset + +node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end +event autotest_buckle trackbuckle 0 tdo_n222 {{amplitude}} endevent +node -1 0 autotest_buckle_launcher eventlauncher 0 0 0 -1 none 1035 autotest_buckle end From a69589f2d39889a268303a66fa95605110dc0c08 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 13:12:48 +0100 Subject: [PATCH 021/136] test(scenarios): an EN57-2000 hitting a standing one at 20 km/h crushes the cab ends and stays on the rails With physics.derailment new: too fast for the automatic couplers, past the buffers the ends crush, too little for either unit to climb onto the other. The case of #86 at 50 km/h keeps passing: there the rear car of the standing unit overrides. --- tests/scenarios/cases/en57_2000_crush_new.json | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 tests/scenarios/cases/en57_2000_crush_new.json diff --git a/tests/scenarios/cases/en57_2000_crush_new.json b/tests/scenarios/cases/en57_2000_crush_new.json new file mode 100644 index 000000000..e13c2299d --- /dev/null +++ b/tests/scenarios/cases/en57_2000_crush_new.json @@ -0,0 +1,17 @@ +{ + "description": "G14 stage 2: an EN57-2000 unit without a driver runs at 20 km/h into a standing one on td.scn, with physics.derailment new. Too fast for the automatic couplers to catch: past the buffers the cab ends crush, a few decimetres, too little for either unit to climb onto the other, so both stay on the rails; the run ends on the 60 s test timeout.", + "base_scenery": "td.scn", + "ini": ["crashdamage yes", "physics.derailment new"], + "fragment": "td_automatic_coupler_hit.scn", + "vars": { + "velocity": "20", + "offset": "0" + }, + "expect": "timeout", + "duration": 60, + "timeout": 300, + "checks": [ + { "type": "log_contains", "pattern": "Bad driving: autotest_\\S+ and autotest_\\S+ collided at \\d+ km/h, the \\w+ end of autotest_\\S+ crushed" }, + { "type": "log_lacks", "pattern": "Bad driving: autotest_\\S+ derailed" } + ] +} From 65fa4a1cc60078825fdb91110bba38fe5926ed0b Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 13:32:08 +0100 Subject: [PATCH 022/136] fix(physics): the traffic of the roads keeps the legacy collisions; the log of a crush tells what it went by Found running line 107 with every train driven by the AI: two cars of its traffic (Fiat 126p, Skoda 1100) met head-on at 119 km/h. With physics.derailment new they bounced off each other elastically: their couplers have no steel to speak of, so the steel took the hit and the legacy rule of 15 km/h was off. The crush of the ends is for rail vehicles now; road vehicles keep the legacy rule and derail as before. The log of a crushed end, of an override and of a push off the track tells the masses and the kinds of the vehicles, the crush and the force each end gives at, the force of the hit and of the springs, the closing velocity and the force, time and Y/Q of a push. --- McZapkie/Mover.cpp | 42 +++++++++++++++++++++++++++++----- tests/unit/test_collisions.cpp | 17 ++++++++++++++ 2 files changed, 53 insertions(+), 6 deletions(-) diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 00a4b775c..b946d4aca 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1338,8 +1338,9 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) auto const &othercoupler{othervehicle->Couplers[otherend]}; auto const physical{coupler_physics_at(End)}; - // physics.derailment new: past the buffers the ends crush (collision.h); a hit the steel takes stays the legacy one - auto const crushing{Global.derailment == global_settings::derailment_model::physical}; + // physics.derailment new: past the buffers the ends of rail vehicles crush (collision.h); a hit the steel takes stays + // the legacy one, and so do the collisions of the road vehicles (the traffic of a scenery), with the legacy rule + auto const crushing{Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1) && TestFlag(othervehicle->CategoryFlag, 1)}; if (crushing && (thiscoupler.hit_handled || crush_hit(End, dt))) { return; @@ -1532,6 +1533,22 @@ char const *end_name(int const End) return End == end::front ? "front" : "rear"; } +char const *kind_name(collision::vehicle_kind const Kind) +{ + switch (Kind) + { + case collision::vehicle_kind::locomotive: + return "locomotive"; + case collision::vehicle_kind::coach: + return "coach"; + case collision::vehicle_kind::crash_zone: + return "crash zone"; + case collision::vehicle_kind::wagon: + default: + return "wagon"; + } +} + // the force pressing the end in, of the coupling or of the buffers touching [N]: forwards at the front pulls double compression_at(TCoupling const &Coupler, int const End) { @@ -1627,10 +1644,18 @@ bool TMoverParameters::crush_hit(int const End, double const dt) record_hit(thiscoupler, hit.force, hit.duration); record_hit(othercoupler, hit.force, hit.duration); + // what the log tells of the pair, for the analysis of a crush + auto const pair = [&]() { + return std::format("{} {:.1f} t {}, {} end crushed {:.2f} m, gives at {:.0f} kN; {} {:.1f} t {}, {} end crushed {:.2f} m, gives at {:.0f} kN; force {:.0f} kN, springs {:.0f} kN, " + "closing at {:.1f} km/h at the start of the step", + Name, TotalMass / 1000.0, kind_name(collision_kind()), end_name(End), thiscoupler.crush, firstcurve.force(thiscoupler.crush) / 1000.0, othervehicle->Name, + othervehicle->TotalMass / 1000.0, kind_name(othervehicle->collision_kind()), end_name(otherend), othercoupler.crush, + secondcurve.force(othercoupler.crush) / 1000.0, hit.force / 1000.0, springs / 1000.0, input.start_velocity * 3.6); + }; auto const crushed = [&](TMoverParameters const &Vehicle, int const VehicleEnd, double const Before, double const After) { if (Before < collision::crush_mark && After >= collision::crush_mark) { - ErrorLog(std::format("Bad driving: {} and {} collided at {:.0f} km/h, the {} end of {} crushed", Name, othervehicle->Name, closing * 3.6, end_name(VehicleEnd), Vehicle.Name)); + ErrorLog(std::format("Bad driving: {} and {} collided at {:.0f} km/h, the {} end of {} crushed ({})", Name, othervehicle->Name, closing * 3.6, end_name(VehicleEnd), Vehicle.Name, pair())); } }; auto const before{thiscoupler.crush}; @@ -1676,7 +1701,8 @@ bool TMoverParameters::crush_hit(int const End, double const dt) climbing.zone2 = secondcurve.densify; auto const climbed{collision::override_of(climbing)}; auto const why = [&](TMoverParameters const &Climber, TMoverParameters const &Other) { - return std::format("{} rode up onto {} at {:.0f} km/h, the ends crushed by {:.2f} m", Climber.Name, Other.Name, closing * 3.6, thiscoupler.crush + othercoupler.crush); + return std::format("{} rode up onto {} at {:.0f} km/h, the ends crushed by {:.2f} m, buffers at {:.0f} / {:.0f} mm, anticlimbers {} ({})", Climber.Name, Other.Name, closing * 3.6, + thiscoupler.crush + othercoupler.crush, climbing.height1 * 1000.0, climbing.height2 * 1000.0, climbing.anticlimbers ? "yes" : "no", pair()); }; if (climbed.first) { @@ -1741,8 +1767,12 @@ void TMoverParameters::check_pushed_off(double const dt) } if (pushed_off_monitor.update(holds, duration)) { - derail_in_collision(COLLISION_PUSHED_OFF, std::format("{:.0f} kN pressing its {} end in, at {:.0f} km/h, curve radius {:.0f} m: Y/Q {:.2f}", worstforce / 1000.0, end_name(worstend), Vel, - std::abs(RunningShape.R), std::min(worst, 99.0))); + derail_in_collision(COLLISION_PUSHED_OFF, std::format("{:.0f} kN pressing its {} end in for {:.3f} s, at {:.0f} km/h, curve radius {:.0f} m: Y/Q {:.2f} ({:.1f} t {}, {} axles, " + "springs {:.0f} / {:.0f} kN, hits {:.0f} / {:.0f} kN, crushed {:.2f} / {:.2f} m)", + worstforce / 1000.0, end_name(worstend), pushed_off_monitor.time(), Vel, std::abs(RunningShape.R), std::min(worst, 99.0), + vehicle.mass / 1000.0, kind_name(collision_kind()), vehicle.axles, compression_at(Couplers[end::front], end::front) / 1000.0, + compression_at(Couplers[end::rear], end::rear) / 1000.0, Couplers[end::front].hit_force / 1000.0, Couplers[end::rear].hit_force / 1000.0, + Couplers[end::front].crush, Couplers[end::rear].crush)); } } diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index c689c709f..f4af0151c 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -555,6 +555,23 @@ TEST_CASE("collisions: automatic couplers hit too fast don't catch, the ends cru } } +TEST_CASE("collisions: road vehicles keep the legacy rule") { + // the traffic of a scenery: cars and buses have no underframe to crush; over 15 km/h weighed by the masses they + // derail, as with physics.derailment old (found running line 107: two cars of its traffic, 119 km/h head-on) + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const model : {global_settings::derailment_model::old, global_settings::derailment_model::physical}) { + model_setting const setting{model}; + consist road; + road.add(definition::fiz("road/man/nl293")); + road.add(definition::fiz("road/man/nl293"), 0, coupling::faux, 40.0, 5.0); + road.run(5.0); + CHECK(derailed(road[0].mover())); + CHECK(derailed(road[1].mover())); + CHECK(road[0]->Couplers[end::rear].crush == 0.0); + CHECK(road[1]->CollisionDerail == NONE); + } +} + TEST_CASE("collisions: a vehicle off the rails by the new model stays in the chain of forces") { model_setting const physical{global_settings::derailment_model::physical}; flag_setting const crashdamage{Global.crash_damage, true}; From 6111773f5368f95be9a12984155367cdbd43e6ab Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 18:57:04 +0100 Subject: [PATCH 023/136] test(physics): count the steps of the derailment tests in integers, read the distances checked SonarCloud: a float loop counter (S2193) and the optional read after REQUIRE taken for a garbage value (S836). --- tests/unit/test_derailment.cpp | 2 +- tests/unit/test_derailment_vehicle.cpp | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/unit/test_derailment.cpp b/tests/unit/test_derailment.cpp index 4fa314fcd..201c2e3bc 100644 --- a/tests/unit/test_derailment.cpp +++ b/tests/unit/test_derailment.cpp @@ -143,7 +143,7 @@ TEST_CASE("derailment: the decision and the place don't depend on the step") { auto const coarse{run(1.05 * critical, 0.5)}; REQUIRE(fine.has_value()); REQUIRE(coarse.has_value()); - CHECK(std::abs(*coarse - *fine) <= 1.05 * critical * 0.5); + CHECK(std::abs(coarse.value() - fine.value()) <= 1.05 * critical * 0.5); } TEST_CASE("derailment: a peak shorter than the window doesn't derail") { diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index 23e395fdc..690284ba2 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -5,6 +5,8 @@ #include "McZapkie/MOVER.h" #include "utilities/Globals.h" +#include + // a vehicle too fast in a curve with physics.derailment of eu07.ini: the criteria of McZapkie/derailment.h checked by // TMoverParameters::check_derailment(), and what the vehicle comes to off the rails @@ -82,13 +84,14 @@ TEST_CASE("derailment: a vehicle too fast in a curve") { SUBCASE("the same with steps of 0.01 and 0.05 s") { for (auto const dt : {0.01, 0.05}) { CAPTURE(dt); + auto const steps{static_cast(std::lround(1.0 / dt))}; vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical + 2.0}; - for (auto time = 0.0; time < 1.0; time += dt) { + for (auto step = 0; step < steps; ++step) { eu07vehicle.step(curve, dt); } CHECK(eu07vehicle->Derailed == dr::outcome::overturned); vehicle slower{definition::fiz("4e_v1/4e"), critical - 2.0}; - for (auto time = 0.0; time < 1.0; time += dt) { + for (auto step = 0; step < steps; ++step) { slower.step(curve, dt); } CHECK(slower->Derailed == dr::outcome::none); From f2d9926e6689972abc33e190f8fe9e58f6b0ac98 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 18:57:08 +0100 Subject: [PATCH 024/136] test(track): count the steps along a buckle in integers SonarCloud S2193: no float loop counters. --- tests/unit/test_track_buckle.cpp | 7 ++++--- tests/unit/test_track_buckle_derailment.cpp | 6 +++++- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/tests/unit/test_track_buckle.cpp b/tests/unit/test_track_buckle.cpp index df26c74ab..589ed125d 100644 --- a/tests/unit/test_track_buckle.cpp +++ b/tests/unit/test_track_buckle.cpp @@ -180,8 +180,9 @@ TEST_CASE("the buckle has its amplitude in the middle, side lobes the other way CHECK(track_buckle::bend(shape, 60.0) == doctest::Approx(-peak)); // none larger anywhere, and the curvature with no jumps auto previous{track_buckle::bend(shape, 35.0)}; - for (auto at = 35.0; at <= 85.0; at += 0.01) + for (auto step = 0; step <= 5000; ++step) { + auto const at{35.0 + 0.01 * step}; auto const bend{track_buckle::bend(shape, at)}; CHECK(std::abs(bend) <= peak * 1.0001); CHECK(std::abs(bend - previous) < 0.01 * peak); @@ -230,8 +231,8 @@ TEST_CASE("a bogie feels the curvature of the buckle averaged over its wheelbase CHECK(std::abs(across) < 0.5 * peak); // the most the body feels, at any place, is less than a bogie does auto most{0.0}; - for (auto at = 20.0; at <= 80.0; at += 0.05) - most = std::max(most, std::abs(track_buckle::body_bend(shape, at, 17.0, 2.5))); + for (auto step = 0; step <= 1200; ++step) + most = std::max(most, std::abs(track_buckle::body_bend(shape, 20.0 + 0.05 * step, 17.0, 2.5))); CHECK(most < 0.95 * peak); CHECK(most > 0.3 * peak); } diff --git a/tests/unit/test_track_buckle_derailment.cpp b/tests/unit/test_track_buckle_derailment.cpp index 1b72db4cc..2f5d99592 100644 --- a/tests/unit/test_track_buckle_derailment.cpp +++ b/tests/unit/test_track_buckle_derailment.cpp @@ -51,8 +51,12 @@ derailment::outcome ride(track_buckle::shape const &Shape, double const Radius, derailment::monitor monitor; auto const velocity{Speed / 3.6}; auto const reach{track_buckle::reach(Shape) + Stock.pivots}; - for (auto at = Shape.centre - reach - 5.0; at <= Shape.centre + reach + 5.0; at += velocity * Step) + auto const start{Shape.centre - reach - 5.0}; + auto const advance{velocity * Step}; + auto const steps{static_cast(std::floor((2.0 * (reach + 5.0)) / advance))}; + for (auto step = 0; step <= steps; ++step) { + auto const at{start + step * advance}; derailment::track_state track; track.radius = Radius; auto const bend{track_buckle::body_bend(Shape, at, Stock.pivots, Stock.base)}; From 8070f79a3a7a1a175e7c1eb63183a41c1097a0e6 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 20:09:57 +0100 Subject: [PATCH 025/136] feat(physics): physics.collisions new|old|monitor, apart from the model of the derailment The crush of the ends, the override and the push off the track went by physics.derailment new. They have a switch of their own now, physics.collisions, new by default: the derailment in a curve and the collisions can each be new or the legacy ones. old is exactly the legacy rule of the safe closing speed weighed by the masses. monitor runs as old, and for a hit on the buffers the crush model would not take elastically it logs once what the crush of the whole hit would be (collision monitor: the closing speed, the crush of each end, the force, whether the draw gear tears off and which vehicle would ride up onto the other one), without changing anything. The push off the track is not monitored: it builds up from the crushed ends of the new model. The road vehicles keep the legacy rule with any value. The tests that pin the legacy collisions pin physics.collisions old. --- McZapkie/MOVER.h | 21 +++-- McZapkie/Mover.cpp | 80 ++++++++++++++----- McZapkie/collision.h | 2 +- .../scenarios/cases/en57_2000_crush_new.json | 4 +- tests/unit/test_collisions.cpp | 79 +++++++++++++----- tests/unit/test_controls.cpp | 8 +- tests/unit/test_couplers.cpp | 8 +- tests/unit/test_couplers_trains.cpp | 12 +-- utilities/Globals.cpp | 11 +++ utilities/Globals.h | 21 +++++ 10 files changed, 180 insertions(+), 66 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 8c612cca0..7e708d5c8 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -177,9 +177,9 @@ enum DerailReason COLLISION = 5, // powód wykolejenia: zderzenie z innym pojazdem /// Trailing through a switch with a movable nose set the other way. TRAILED_SWITCH = 6, // powód wykolejenia: rozprucie rozjazdu z ruchomym dziobem - /// Climbed onto the vehicle it hit, its end crushed (physics.derailment new). + /// Climbed onto the vehicle it hit, its end crushed (physics.collisions new). COLLISION_OVERRIDE = 7, // najechanie - /// Pushed off the track by the force pressing its end (physics.derailment new). + /// Pushed off the track by the force pressing its end (physics.collisions new). COLLISION_PUSHED_OFF = 8, // wyciśnięcie z toru }; @@ -1293,7 +1293,7 @@ struct TCoupling // and the state of the coupling with the vehicle at this end, which that vehicle keeps alike on its own end coupler_physics::end_parameters physics; coupler_physics::pair_state physics_state; - // the collisions past the buffers (physics.derailment new), see collision.h: the optional keys of this end, the depth + // the collisions past the buffers (physics.collisions new), see collision.h: the optional keys of this end, the depth // it's crushed to for good [m], and the hit of the pair in the step: whether either vehicle handled it already, its // peak force [N] and how long that acted [s] collision::end_definition collision; @@ -1302,6 +1302,8 @@ struct TCoupling bool hit_handled{false}; double hit_force{0.0}; double hit_duration{0.0}; + // physics.collisions monitor: the log told of the crush of this hit of the pair already + bool crush_monitored{false}; int sounds{0}; // sounds emitted by the coupling devices bool Render = false; /*ABu: czy rysowac jak zaczepiony sprzeg*/ @@ -2458,19 +2460,22 @@ class TMoverParameters // how the vehicle left the rails by the criteria of derailment.h: upright, or on its side. none for any other // derailment, which stops it as the legacy model does derailment::outcome Derailed{derailment::outcome::none}; - // physics.derailment new: what the vehicle is for the defaults of its crush and its buffers, the crush curve and the + // physics.collisions new: what the vehicle is for the defaults of its crush and its buffers, the crush curve and the // height of the buffers of an end, and how long the push of its ends held its wheels over the climbing limit collision::vehicle_kind collision_kind() const; collision::crush_curve crush_curve_at(int End) const; double buffer_height_at(int End) const; collision::pushed_monitor pushed_off_monitor; - // how the vehicle left the rails in a collision (physics.derailment new): overriding or pushed off, NONE otherwise + // how the vehicle left the rails in a collision (physics.collisions new): overriding or pushed off, NONE otherwise DerailReason CollisionDerail{NONE}; - // physics.derailment new: the hit of the end on the stop of its buffers, harder than the steel takes, crushes the + // physics.collisions monitor: how many crushes the log told of, of the hits of this vehicle on the others + int crush_reports{0}; + // physics.collisions new: the hit of the end on the stop of its buffers, harder than the steel takes, crushes the // weaker end and may let one vehicle climb onto the other one, see collision.h. returns: whether it did, and the - // velocities took the hit; the legacy collision takes the rest + // velocities took the hit; the legacy collision takes the rest. physics.collisions monitor: the log tells what the + // crush of the whole hit would be, once for a hit, nothing changes, and it returns false bool crush_hit(int End, double dt); - // the force pressing the ends pushes the vehicle off the track (physics.derailment new) + // the force pressing the ends pushes the vehicle off the track (physics.collisions new) void check_pushed_off(double dt); // the vehicle leaves the rails in a collision, the reason told in the log, and slides on as the criteria of // derailment.h have it diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index b946d4aca..f33bbb8ed 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1338,13 +1338,19 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) auto const &othercoupler{othervehicle->Couplers[otherend]}; auto const physical{coupler_physics_at(End)}; - // physics.derailment new: past the buffers the ends of rail vehicles crush (collision.h); a hit the steel takes stays + // physics.collisions new: past the buffers the ends of rail vehicles crush (collision.h); a hit the steel takes stays // the legacy one, and so do the collisions of the road vehicles (the traffic of a scenery), with the legacy rule - auto const crushing{Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1) && TestFlag(othervehicle->CategoryFlag, 1)}; + auto const rails{TestFlag(CategoryFlag, 1) && TestFlag(othervehicle->CategoryFlag, 1)}; + auto const crushing{Global.collisions == global_settings::collision_model::physical && rails}; if (crushing && (thiscoupler.hit_handled || crush_hit(End, dt))) { return; } + // physics.collisions monitor: the legacy collision follows, the log tells what the crush would be + if (Global.collisions == global_settings::collision_model::monitor && rails) + { + crush_hit(End, dt); + } if (physical && false == coupler_stop_hit(End, *othervehicle, otherend)) { return; @@ -1476,7 +1482,7 @@ void TMoverParameters::damage_coupler(int const End) } // ************************************************************************************************* -// physics.derailment new: the collisions past the buffers, see collision.h +// physics.collisions new: the collisions past the buffers, see collision.h // ************************************************************************************************* collision::vehicle_kind TMoverParameters::collision_kind() const { @@ -1585,8 +1591,12 @@ bool TMoverParameters::crush_hit(int const End, double const dt) auto const closing{-CouplerVelocityDifference(End, *othervehicle, otherend) * DirF(End)}; if (false == Global.crash_damage || false == buffers || closing <= 0.0) { + // the hit is over, the next one is another one for the monitor + thiscoupler.crush_monitored = false; + othercoupler.crush_monitored = false; return false; } + auto const monitor{Global.collisions == global_settings::collision_model::monitor}; // a vehicle derailed the legacy way (the end of the track, say) stays where it is, whatever hits it auto const wall{TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none}; auto const otherwall{TestFlag(othervehicle->DamageFlag, dtrain_out) && othervehicle->Derailed == derailment::outcome::none}; @@ -1610,9 +1620,46 @@ bool TMoverParameters::crush_hit(int const End, double const dt) input.restitution = std::sqrt(std::max(0.0, 1.0 - loss)); input.stiffness = stiffness; input.springs = springs; - input.dt = dt; + // the monitor takes the whole hit at once, over a second, longer than the crush of any hit lasts + input.dt = monitor ? 1.0 : dt; input.start_velocity = thiscoupler.closing; auto const hit{collision::hit({firstcurve, thiscoupler.crush}, {secondcurve, othercoupler.crush}, input)}; + // the override, by the crush of both ends + auto const climbing_of = [&](double const Crush1, double const Crush2) { + collision::override_input climbing; + climbing.crush1 = Crush1; + climbing.crush2 = Crush2; + climbing.mass1 = TotalMass - Mred; + climbing.mass2 = othervehicle->TotalMass - othervehicle->Mred; + climbing.height1 = buffer_height_at(End); + climbing.height2 = othervehicle->buffer_height_at(otherend); + climbing.anticlimbers = collision::anticlimber_of(thiscoupler.collision, collision_kind()) && collision::anticlimber_of(othercoupler.collision, othervehicle->collision_kind()); + climbing.zone1 = firstcurve.densify; + climbing.zone2 = secondcurve.densify; + return climbing; + }; + if (monitor) + { + if (hit.crushing && false == thiscoupler.crush_monitored) + { + thiscoupler.crush_monitored = true; + othercoupler.crush_monitored = true; + ++crush_reports; + auto const crush1{thiscoupler.crush + hit.crush1}; + auto const crush2{othercoupler.crush + hit.crush2}; + auto const climbed{collision::override_of(climbing_of(crush1, crush2))}; + auto const torn{std::max(crush1, crush2) >= collision::draw_gear_crush}; + std::string const outcome{climbed.first && climbed.second ? std::string{"both would leave the rails"} + : climbed.first ? Name + " would ride up onto " + othervehicle->Name + : climbed.second ? othervehicle->Name + " would ride up onto " + Name + : std::string{"both would stay on the rails"}}; + WriteLog(std::format("collision monitor: {} and {} collided at {:.0f} km/h: the {} end of {} ({:.1f} t {}) would crush by {:.2f} m, the {} end of {} ({:.1f} t {}) by {:.2f} m, " + "at {:.0f} kN; draw gear {}; {}", + Name, othervehicle->Name, closing * 3.6, end_name(End), Name, TotalMass / 1000.0, kind_name(collision_kind()), crush1, end_name(otherend), othervehicle->Name, + othervehicle->TotalMass / 1000.0, kind_name(othervehicle->collision_kind()), crush2, hit.force / 1000.0, torn ? "torn off" : "holds", outcome)); + } + return false; + } if (false == hit.crushing) { // the steel takes it, the legacy collision follows; its peak, under the force an end gives at, for the push @@ -1689,16 +1736,7 @@ bool TMoverParameters::crush_hit(int const End, double const dt) } // the end crushed deep enough lets one vehicle climb onto the other one - collision::override_input climbing; - climbing.crush1 = thiscoupler.crush; - climbing.crush2 = othercoupler.crush; - climbing.mass1 = TotalMass - Mred; - climbing.mass2 = othervehicle->TotalMass - othervehicle->Mred; - climbing.height1 = buffer_height_at(End); - climbing.height2 = othervehicle->buffer_height_at(otherend); - climbing.anticlimbers = collision::anticlimber_of(thiscoupler.collision, collision_kind()) && collision::anticlimber_of(othercoupler.collision, othervehicle->collision_kind()); - climbing.zone1 = firstcurve.densify; - climbing.zone2 = secondcurve.densify; + auto const climbing{climbing_of(thiscoupler.crush, othercoupler.crush)}; auto const climbed{collision::override_of(climbing)}; auto const why = [&](TMoverParameters const &Climber, TMoverParameters const &Other) { return std::format("{} rode up onto {} at {:.0f} km/h, the ends crushed by {:.2f} m, buffers at {:.0f} / {:.0f} mm, anticlimbers {} ({})", Climber.Name, Other.Name, closing * 3.6, @@ -1717,7 +1755,7 @@ bool TMoverParameters::crush_hit(int const End, double const dt) void TMoverParameters::check_pushed_off(double const dt) { - if (Global.derailment != global_settings::derailment_model::physical || false == Global.crash_damage || TestFlag(DamageFlag, dtrain_out) || false == TestFlag(CategoryFlag, 1) || + if (Global.collisions != global_settings::collision_model::physical || false == Global.crash_damage || TestFlag(DamageFlag, dtrain_out) || false == TestFlag(CategoryFlag, 1) || DebugModeFlag) { pushed_off_monitor.reset(); @@ -5995,7 +6033,7 @@ double TMoverParameters::CouplerForce(int const End, double dt) auto const initialdistance{Neighbours[End].distance}; // odległość od sprzęgu sąsiada auto const distancedelta{(End == end::front ? othervehiclemove - dMoveLen : dMoveLen - othervehiclemove)}; - // the ends crushed for good (physics.derailment new, see collision.h) let the buffers meet that much closer + // the ends crushed for good (physics.collisions new, see collision.h) let the buffers meet that much closer auto const crushed{thiscoupler.crush + othercoupler.crush}; auto const rawdistance{initialdistance + 10.0 * distancedelta}; auto const newdistance{rawdistance < 0.0 ? std::min(0.0, rawdistance + crushed) : rawdistance}; @@ -6143,8 +6181,8 @@ void TMoverParameters::automatic_coupling(int const End, TMoverParameters &Other { return; } - // a coupler torn off by the crush of its end (physics.derailment new) doesn't catch - if (Global.derailment == global_settings::derailment_model::physical && (thiscoupler.broken || othercoupler.broken)) + // a coupler torn off by the crush of its end (physics.collisions new) doesn't catch + if (Global.collisions == global_settings::collision_model::physical && (thiscoupler.broken || othercoupler.broken)) { return; } @@ -6281,8 +6319,8 @@ bool TMoverParameters::coupler_stop_hit(int const End, TMoverParameters &Other, auto const hit{coupler_physics::impact(thiscoupler.physics, othercoupler.physics, state, closing, TotalMass, Other.TotalMass)}; // the other vehicle keeps the state of the pair alike othercoupler.physics_state.elongation = state.elongation; - // with physics.derailment new the crush of the ends past the buffers is crush_hit()'s - if (hit.broken || (hit.crushed && Global.derailment != global_settings::derailment_model::physical)) + // with physics.collisions new the crush of the ends past the buffers is crush_hit()'s + if (hit.broken || (hit.crushed && Global.collisions != global_settings::collision_model::physical)) { damage_coupler(End); } @@ -11755,7 +11793,7 @@ void scale_strength(coupler_physics::link_strength &Link, double const Factor) Link.ultimate *= Factor; } -// the optional keys of the collisions past the buffers (physics.derailment new, see collision.h), what's not given +// the optional keys of the collisions past the buffers (physics.collisions new, see collision.h), what's not given // comes from the kind of the vehicle: // FcrushPeak, FcrushPlateau [kN] the force the end starts to crush at, and keeps crushing at // CrushOnset, CrushDensify, CrushLimit [m] the crush the peak drops at, it packs down past, it can't go past diff --git a/McZapkie/collision.h b/McZapkie/collision.h index dd3dad55e..b51fc6561 100644 --- a/McZapkie/collision.h +++ b/McZapkie/collision.h @@ -13,7 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "couplerphysics.h" -// what a collision of two vehicles does to them past their buffers (physics.derailment new in eu07.ini, see +// what a collision of two vehicles does to them past their buffers (physics.collisions new in eu07.ini, see // TMoverParameters::CollisionDetect()), as plain functions of the vehicles and the hit: // // crush: once the buffers of the pair are pressed all the way, the underframes carry the rest of the hit, up to the diff --git a/tests/scenarios/cases/en57_2000_crush_new.json b/tests/scenarios/cases/en57_2000_crush_new.json index e13c2299d..9de8c1688 100644 --- a/tests/scenarios/cases/en57_2000_crush_new.json +++ b/tests/scenarios/cases/en57_2000_crush_new.json @@ -1,7 +1,7 @@ { - "description": "G14 stage 2: an EN57-2000 unit without a driver runs at 20 km/h into a standing one on td.scn, with physics.derailment new. Too fast for the automatic couplers to catch: past the buffers the cab ends crush, a few decimetres, too little for either unit to climb onto the other, so both stay on the rails; the run ends on the 60 s test timeout.", + "description": "G14 stage 2: an EN57-2000 unit without a driver runs at 20 km/h into a standing one on td.scn, with physics.collisions new. Too fast for the automatic couplers to catch: past the buffers the cab ends crush, a few decimetres, too little for either unit to climb onto the other, so both stay on the rails; the run ends on the 60 s test timeout.", "base_scenery": "td.scn", - "ini": ["crashdamage yes", "physics.derailment new"], + "ini": ["crashdamage yes", "physics.collisions new"], "fragment": "td_automatic_coupler_hit.scn", "vars": { "velocity": "20", diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index f4af0151c..c08c714dc 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -11,7 +11,7 @@ #include #include -// collisions past the buffers with physics.derailment new (McZapkie/collision.h): the crush of the ends, the override, +// collisions past the buffers with physics.collisions new (McZapkie/collision.h): the crush of the ends, the override, // the push off the track, and what they do in trains of real vehicles using test::consist; @@ -23,16 +23,16 @@ namespace { constexpr double kmh{1.0 / 3.6}; -// the given model of derailment for the test, restored after it +// the given model of collisions for the test, restored after it class model_setting { public: - explicit model_setting(global_settings::derailment_model Model) : m_previous{Global.derailment} { Global.derailment = Model; } - ~model_setting() { Global.derailment = m_previous; } + explicit model_setting(global_settings::collision_model Model) : m_previous{Global.collisions} { Global.collisions = Model; } + ~model_setting() { Global.collisions = m_previous; } model_setting(model_setting const &) = delete; model_setting &operator=(model_setting const &) = delete; private: - global_settings::derailment_model m_previous; + global_settings::collision_model m_previous; }; // the given setting of a global flag for the test, restored after it @@ -453,7 +453,7 @@ TEST_CASE("collisions: an empty two-axle wagon between loaded ones in a curve of // ---- the model of eu07.ini -TEST_CASE("collisions: the legacy rule with physics.derailment old, the crush with new") { +TEST_CASE("collisions: the legacy rule with physics.collisions old, the crush with new") { flag_setting const crashdamage{Global.crash_damage, true}; struct collision { char const *name; @@ -464,18 +464,22 @@ TEST_CASE("collisions: the legacy rule with physics.derailment old, the crush wi bool backout_old; bool frontout_new; bool backout_new; + int monitored; // the hits the monitor tells of }; // the legacy rule: over 15 km/h weighed by the ratio of the masses. the crush: the light wagon is crushed deep and // climbs onto the locomotive at 60 km/h; two locomotives at 25 km/h crush their ends 0.1-0.3 m and stay on the rails - for (auto const &[name, front, back, speed, frontout_old, backout_old, frontout_new, backout_new] : { - collision{"locomotive into a wagon at 60", "3wl_v2/3wl", "4e_v1/4e", 60.0, true, false, true, false}, - collision{"locomotive into a locomotive at 25", "4e_v1/4e", "4e_v1/4e", 25.0, true, true, false, false}, - collision{"locomotive into a locomotive at 50", "4e_v1/4e", "4e_v1/4e", 50.0, true, true, true, true}, + // the monitor tells of each hit once: the wagon derailed by the legacy rule is a wall, which the locomotive behind + // it hits once more; the locomotives derailed both stay where they are + for (auto const &[name, front, back, speed, frontout_old, backout_old, frontout_new, backout_new, monitored] : { + collision{"locomotive into a wagon at 60", "3wl_v2/3wl", "4e_v1/4e", 60.0, true, false, true, false, 2}, + collision{"locomotive into a locomotive at 25", "4e_v1/4e", "4e_v1/4e", 25.0, true, true, false, false, 1}, + collision{"locomotive into a locomotive at 50", "4e_v1/4e", "4e_v1/4e", 50.0, true, true, true, true, 1}, }) { CAPTURE(name); - for (auto const model : {global_settings::derailment_model::old, global_settings::derailment_model::physical}) { - auto const physical{model == global_settings::derailment_model::physical}; - CAPTURE(physical); + // monitor: the legacy rule, and the log tells of the crush once + for (auto const model : {global_settings::collision_model::old, global_settings::collision_model::physical, global_settings::collision_model::monitor}) { + auto const physical{model == global_settings::collision_model::physical}; + CAPTURE(name_of(model)); model_setting const setting{model}; consist train; train.add(definition::fiz(front)); @@ -491,12 +495,46 @@ TEST_CASE("collisions: the legacy rule with physics.derailment old, the crush wi else { CHECK(crush == 0.0); } + CHECK(train[0]->crush_reports + train[1]->crush_reports == (model == global_settings::collision_model::monitor ? monitored : 0)); + } + } +} + +TEST_CASE("collisions: the names of the models in eu07.ini") { + using model = global_settings::collision_model; + CHECK(collision_model_of("new") == model::physical); + CHECK(collision_model_of("old") == model::old); + CHECK(collision_model_of("monitor") == model::monitor); + // a name it doesn't know is the default + CHECK(collision_model_of("physical") == model::physical); + CHECK(global_settings{}.collisions == model::physical); + for (auto const value : {model::old, model::physical, model::monitor}) { + CHECK(collision_model_of(name_of(value)) == value); + } + CHECK(name_of(model::physical) == "new"); +} + +TEST_CASE("collisions: the model of the collisions goes apart from the one of the derailment") { + // the crush with the legacy draw of the derailment in a curve, the legacy collisions with the criteria + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const derailment : {global_settings::derailment_model::old, global_settings::derailment_model::physical}) { + for (auto const collisions : {global_settings::collision_model::old, global_settings::collision_model::physical}) { + auto const previous{Global.derailment}; + Global.derailment = derailment; + model_setting const setting{collisions}; + consist train; + train.add(definition::fiz("4e_v1/4e")); + train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, 25.0, 20.0); + train.run(10.0); + Global.derailment = previous; + auto const crush{train[0]->Couplers[end::rear].crush + train[1]->Couplers[end::front].crush}; + CHECK((crush > 0.05) == (collisions == global_settings::collision_model::physical)); } } } TEST_CASE("collisions: the crush of a locomotive hitting a wagon doesn't depend on the step, nor on the model of the coupling") { - model_setting const physical{global_settings::derailment_model::physical}; + model_setting const physical{global_settings::collision_model::physical}; flag_setting const crashdamage{Global.crash_damage, true}; for (auto const physics : {false, true}) { CAPTURE(physics); @@ -523,7 +561,7 @@ TEST_CASE("collisions: the crush of a locomotive hitting a wagon doesn't depend } TEST_CASE("collisions: automatic couplers hit too fast don't catch, the ends crush; torn off, they don't couple again") { - model_setting const physical{global_settings::derailment_model::physical}; + model_setting const physical{global_settings::collision_model::physical}; flag_setting const crashdamage{Global.crash_damage, true}; auto const automatic{definition::load("wagon").set("BuffCoupl", "CType", "Automatic").set("BuffCoupl", "AutomaticFlag", coupling::coupler | coupling::brakehose)}; for (auto const speed : {20.0, 30.0, 45.0}) { @@ -557,9 +595,9 @@ TEST_CASE("collisions: automatic couplers hit too fast don't catch, the ends cru TEST_CASE("collisions: road vehicles keep the legacy rule") { // the traffic of a scenery: cars and buses have no underframe to crush; over 15 km/h weighed by the masses they - // derail, as with physics.derailment old (found running line 107: two cars of its traffic, 119 km/h head-on) + // derail, as with physics.collisions old (found running line 107: two cars of its traffic, 119 km/h head-on) flag_setting const crashdamage{Global.crash_damage, true}; - for (auto const model : {global_settings::derailment_model::old, global_settings::derailment_model::physical}) { + for (auto const model : {global_settings::collision_model::old, global_settings::collision_model::physical, global_settings::collision_model::monitor}) { model_setting const setting{model}; consist road; road.add(definition::fiz("road/man/nl293")); @@ -569,11 +607,12 @@ TEST_CASE("collisions: road vehicles keep the legacy rule") { CHECK(derailed(road[1].mover())); CHECK(road[0]->Couplers[end::rear].crush == 0.0); CHECK(road[1]->CollisionDerail == NONE); + CHECK(road[0]->crush_reports + road[1]->crush_reports == 0); } } TEST_CASE("collisions: a vehicle off the rails by the new model stays in the chain of forces") { - model_setting const physical{global_settings::derailment_model::physical}; + model_setting const physical{global_settings::collision_model::physical}; flag_setting const crashdamage{Global.crash_damage, true}; consist train; auto &wagon{train.add(definition::fiz("430w_v2/430w"))}; @@ -595,7 +634,7 @@ TEST_CASE("collisions: a vehicle off the rails by the new model stays in the cha } TEST_CASE("collisions: a freight train running into a standing one, the cases of the PoC of G14") { - model_setting const physical{global_settings::derailment_model::physical}; + model_setting const physical{global_settings::collision_model::physical}; flag_setting const crashdamage{Global.crash_damage, true}; struct crash { double speed; @@ -616,7 +655,7 @@ TEST_CASE("collisions: a freight train running into a standing one, the cases of } TEST_CASE("collisions: identical units built to EN 15227 at 36 km/h") { - model_setting const physical{global_settings::derailment_model::physical}; + model_setting const physical{global_settings::collision_model::physical}; flag_setting const crashdamage{Global.crash_damage, true}; // two coaches of data/wagon.json (42.2 t) a unit, their ends crash zones with anticlimbers, unbraked auto const unit = [](bool const Anticlimbers, double const Height) { diff --git a/tests/unit/test_controls.cpp b/tests/unit/test_controls.cpp index f42ecd731..ba9404482 100644 --- a/tests/unit/test_controls.cpp +++ b/tests/unit/test_controls.cpp @@ -496,11 +496,11 @@ TEST_CASE("controls: a freight wagon loaded and braked") { } TEST_CASE("controls: a locomotive running into a standing wagon") { - // the legacy collisions of physics.derailment old: derailed, the wagon is a wall (test_collisions.cpp has the new) + // the legacy collisions of physics.collisions old: derailed, the wagon is a wall (test_collisions.cpp has the new) struct legacy { - global_settings::derailment_model previous{Global.derailment}; - legacy() { Global.derailment = global_settings::derailment_model::old; } - ~legacy() { Global.derailment = previous; } + global_settings::collision_model previous{Global.collisions}; + legacy() { Global.collisions = global_settings::collision_model::old; } + ~legacy() { Global.collisions = previous; } legacy(legacy const &) = delete; legacy &operator=(legacy const &) = delete; } const model; diff --git a/tests/unit/test_couplers.cpp b/tests/unit/test_couplers.cpp index c6a3f4a5d..19421c52b 100644 --- a/tests/unit/test_couplers.cpp +++ b/tests/unit/test_couplers.cpp @@ -49,17 +49,17 @@ private: bool m_previous{Global.crash_damage}; }; -// the legacy collisions of physics.derailment old for the test, restored after it: the rule of the safe closing speed +// the legacy collisions of physics.collisions old for the test, restored after it: the rule of the safe closing speed // weighed by the ratio of the masses (the crush of the ends of the new model is in test_collisions.cpp) class legacy_collisions { public: - legacy_collisions() { Global.derailment = global_settings::derailment_model::old; } - ~legacy_collisions() { Global.derailment = m_previous; } + legacy_collisions() { Global.collisions = global_settings::collision_model::old; } + ~legacy_collisions() { Global.collisions = m_previous; } legacy_collisions(legacy_collisions const &) = delete; legacy_collisions &operator=(legacy_collisions const &) = delete; private: - global_settings::derailment_model m_previous{Global.derailment}; + global_settings::collision_model m_previous{Global.collisions}; }; } // namespace diff --git a/tests/unit/test_couplers_trains.cpp b/tests/unit/test_couplers_trains.cpp index e17a8f86d..cbe002bb1 100644 --- a/tests/unit/test_couplers_trains.cpp +++ b/tests/unit/test_couplers_trains.cpp @@ -17,16 +17,16 @@ using namespace test::channels; namespace { -// the given model of derailment for the test, restored after it +// the given model of collisions for the test, restored after it class model_setting { public: - explicit model_setting(global_settings::derailment_model Model) : m_previous{Global.derailment} { Global.derailment = Model; } - ~model_setting() { Global.derailment = m_previous; } + explicit model_setting(global_settings::collision_model Model) : m_previous{Global.collisions} { Global.collisions = Model; } + ~model_setting() { Global.collisions = m_previous; } model_setting(model_setting const &) = delete; model_setting &operator=(model_setting const &) = delete; private: - global_settings::derailment_model m_previous; + global_settings::collision_model m_previous; }; } // namespace @@ -165,8 +165,8 @@ TEST_CASE("couplers: a coupler broken, with its brake hose torn off") { TEST_CASE("couplers: collisions fast enough to derail") { // a locomotive running into a standing wagon from behind, and a wagon running backwards into a standing // locomotive; over 15 km/h, weighed by the ratio of the masses, the vehicles derail. the legacy rule of - // physics.derailment old: the new model crushes the ends (test_collisions.cpp) - model_setting const legacy{global_settings::derailment_model::old}; + // physics.collisions old: the new model crushes the ends (test_collisions.cpp) + model_setting const legacy{global_settings::collision_model::old}; struct collision { char const *name; char const *frontpath; diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 746105ad6..faf2d5660 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -896,6 +896,16 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + if (token == "physics.collisions") + { + // new: the crush of the ends past the buffers (McZapkie/collision.h), old: the legacy rule, monitor: the legacy + // rule, and the crush to the log + std::string model; + ParseOne(Parser, model, 1); + collisions = collision_model_of(model); + return true; + } + if (token == "controlcoupling.enginecheck") { ParseOne(Parser, control_coupling_engine_check, 1); @@ -1794,6 +1804,7 @@ global_settings::export_as_text( std::ostream &Output ) const { derailment == derailment_model::old ? "old" : derailment == derailment_model::off ? "off" : "new" } ); + export_as_text( Output, "physics.collisions", std::string{ name_of( collisions ) } ); export_as_text( Output, "ai.brakesetting.cw1", AIBrakeSettingCw1 ); export_as_text( Output, "scalespeculars", ScaleSpecularValues ); export_as_text( Output, "gfxrenderer", GfxRenderer ); diff --git a/utilities/Globals.h b/utilities/Globals.h index 19dabab53..03fb2ff09 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -296,6 +296,12 @@ struct global_settings { // it; off, it stays on the rails at any speed enum class derailment_model { off, old, physical }; derailment_model derailment = derailment_model::physical; + // the collisions of rail vehicles past their buffers (physics.collisions in eu07.ini): new, the ends crush, a vehicle + // may ride up onto the other one or be pushed off the track (McZapkie/collision.h); old, the legacy rule of the safe + // closing speed weighed by the masses; monitor, the legacy rule decides and the log tells what the crush would be + // (collision monitor:, once for a hit). the road vehicles of the traffic keep the legacy rule with any + enum class collision_model { old, physical, monitor }; + collision_model collisions = collision_model::physical; bool control_coupling_engine_check = true; // no multiple-unit control between electric and diesel traction vehicles (eu07/maszyna#520) bool gui_defaultwindows = true; bool gui_showtranscripts = true; @@ -445,6 +451,21 @@ template <> void global_settings::export_as_text( std::ostream &Output, std::string const Key, bool const &Value ) const; +// the models of physics.collisions by their names in eu07.ini: new (the default, also for a name it doesn't know), old, +// monitor +inline global_settings::collision_model collision_model_of( std::string_view const Name ) { + if( Name == "old" ) { return global_settings::collision_model::old; } + if( Name == "monitor" ) { return global_settings::collision_model::monitor; } + return global_settings::collision_model::physical; +} +inline std::string_view name_of( global_settings::collision_model const Model ) { + switch( Model ) { + case global_settings::collision_model::old: { return "old"; } + case global_settings::collision_model::monitor: { return "monitor"; } + default: { return "new"; } + } +} + extern global_settings& GetGlobalSettings(); #define Global (GetGlobalSettings()) From c83c987e3f2725390c8178c8f01abdbb1ee23d9a Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 20:11:10 +0100 Subject: [PATCH 026/136] feat(physics): physics.derailment monitor tells what the criteria would do, the legacy draw decides With monitor the run goes as with old: the legacy draw derails a vehicle too fast in a curve, with the legacy effects. The criteria of derailment.h are evaluated as with new, and where they would derail a vehicle the log gets one line (derailment monitor:) with the data of the entry of a real derailment: the vehicle, the track, the speed, the radius, the cant, the lateral acceleration, D, Y/Q, the mass, the centre of gravity, the forces of the couplings, the damage flags and the cross level. Once for a vehicle on a track, so one run of a scenery shows what new would do without changing its course. The entry of a derailment by the criteria names the track as well; derailment::report() writes both. The names of the models in eu07.ini go through derailment_model_of() and name_of(), read and written back alike. --- McZapkie/MOVER.h | 11 ++++- McZapkie/Mover.cpp | 30 ++++++++----- McZapkie/derailment.cpp | 10 +++++ McZapkie/derailment.h | 7 +++ tests/unit/test_derailment.cpp | 21 +++++++++ tests/unit/test_derailment_vehicle.cpp | 62 ++++++++++++++++++++++++++ tests/unit/vehicle.cpp | 1 + tests/unit/vehicle.h | 1 + utilities/Globals.cpp | 15 ++----- utilities/Globals.h | 22 ++++++++- vehicle/DynObj.cpp | 1 + 11 files changed, 155 insertions(+), 26 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 63783419b..1d2280bcc 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -712,6 +712,8 @@ struct TTrackParam int DamageFlag = 0; /// Maximum allowed velocity on this segment (used by AI driver). double Velmax; /*dla uzytku maszynisty w ai_driver*/ + /// Name of the track, for the log; nullptr where there is none. + std::string const *Name = nullptr; }; /// Traction-supply parameters at the vehicle's current location. @@ -2049,6 +2051,10 @@ class TMoverParameters // the criteria of derailment (physics.derailment new), and the distance travelled since they were checked [m] derailment::monitor derailment_monitor; double derailment_distance = 0.0; + // physics.derailment monitor: the name of the track the criteria were last reported on (one report on a track), and + // how many reports there were + std::optional derailment_reported; + int derailment_reports = 0; odometer::reading Odometer; // total distance run, kept between the sessions (eu07/maszyna#72) std::pair EnergyMeter; // energy from grid [kWh] double V = 0.0; // predkosc w [m/s] względem sprzęgów (dodania gdy jedzie w stronę 0) @@ -2435,10 +2441,11 @@ class TMoverParameters // was a broken coupler to repair bool repair_coupler(int const End); void Derail(DerailReason Reason); - // physics.derailment new: the criteria of derailment.h over the step, which travelled the Distance [m] + // physics.derailment new: the criteria of derailment.h over the step, which travelled the Distance [m]; monitor: what + // they would do, to the log void check_derailment(TTrackShape const &Shape, TTrackParam const &Track, double Distance); // the vehicle leaves the rails, as the criteria of derailment.h found - void derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track); + void derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track, std::string const *TrackName = nullptr); // height of the centre of gravity above the rail with the load [m] double centre_of_gravity() const; // how the vehicle left the rails by the criteria of derailment.h: upright, or on its side. none for any other diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 2fa19e184..2dfb8d484 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1548,13 +1548,26 @@ void TMoverParameters::check_derailment(TTrackShape const &Shape, TTrackParam co track.damage = Track.DamageFlag; auto const verdict{derailment_monitor.update(vehicle, track, V, Distance)}; - if (verdict.result != derailment::outcome::none) + if (verdict.result == derailment::outcome::none) { - derail(verdict, vehicle, track); + return; } + if (Global.derailment == global_settings::derailment_model::physical) + { + derail(verdict, vehicle, track, Track.Name); + return; + } + // physics.derailment monitor: the legacy draw decides, the log tells what the criteria would do, once on a track + if (derailment_reported.has_value() && *derailment_reported == Track.Name) + { + return; + } + derailment_reported = Track.Name; + ++derailment_reports; + WriteLog("derailment monitor: " + Name + " " + derailment::report(verdict, vehicle, track, V, Track.Name != nullptr ? *Track.Name : std::string{})); } -void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track) +void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track, std::string const *TrackName) { if (false == SetFlag(DamageFlag, dtrain_out)) { @@ -1568,12 +1581,7 @@ void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::ve { AlarmChainFlag = true; } - auto const cant{1000.0 * derailment::contact_spacing(Track.gauge) * std::sin(std::abs(Track.cant))}; - ErrorLog(std::format("Bad driving: {} {} at {:.0f} km/h, curve radius {:.0f} m, cant {:.0f} mm: lateral acceleration {:.2f} m/s2, wheel unloading {:.2f}, Y/Q {:.2f}" - " (mass {:.1f} t, centre of gravity {:.2f} m, couplings pushing {:.0f} / {:.0f} kN, track damage {}, cross level {:.0f} mm)", - Name, Derailed == derailment::outcome::overturned ? "overturned" : "derailed, the flange climbed the rail", std::abs(V) * 3.6, std::abs(Track.radius), cant, - Verdict.acceleration, Verdict.unloading, Verdict.flange_ratio, Vehicle.mass / 1000.0, Vehicle.centre_of_gravity, Vehicle.ends[end::front].compression / 1000.0, - Vehicle.ends[end::rear].compression / 1000.0, Track.damage, Track.uneven_cross)); + ErrorLog("Bad driving: " + Name + " " + derailment::report(Verdict, Vehicle, Track, V, TrackName != nullptr ? *TrackName : std::string{})); } void TMoverParameters::Derail(DerailReason const Reason) @@ -1703,7 +1711,7 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap Derail(END_OF_TRACK); // too fast in a curve: the legacy draw in every step (physics.derailment old), or the physical criteria // once the step's distance is known, below - if (Global.derailment == global_settings::derailment_model::old && FuzzyLogic(AccN / g * (1.0 + 0.1 * (Track.DamageFlag & dtrack_freerail)), TrackW / Dim.H, 1)) + if ((Global.derailment == global_settings::derailment_model::old || Global.derailment == global_settings::derailment_model::monitor) && FuzzyLogic(AccN / g * (1.0 + 0.1 * (Track.DamageFlag & dtrack_freerail)), TrackW / Dim.H, 1)) Derail(TOO_HIGH_SPEED); // wykolejanie na poszerzeniu toru if (FuzzyLogic(abs(Track.Width - TrackW), TrackW / 10.0, 1)) @@ -1716,7 +1724,7 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap // dL:=(V+AccS*dt/2)*dt; // przyrost dlugosci czyli przesuniecie dL = (3.0 * V - Vprev) * dt / 2.0; // metoda Adamsa-Bashfortha} - if (Global.derailment == global_settings::derailment_model::physical) + if (Global.derailment == global_settings::derailment_model::physical || Global.derailment == global_settings::derailment_model::monitor) { // over the distance of this step and of the simpler ones of the frame before it check_derailment(Shape, Track, derailment_distance + std::abs(dL)); diff --git a/McZapkie/derailment.cpp b/McZapkie/derailment.cpp index 5cccc9f9c..48e61aee5 100644 --- a/McZapkie/derailment.cpp +++ b/McZapkie/derailment.cpp @@ -12,6 +12,7 @@ http://mozilla.org/MPL/2.0/. #include #include +#include namespace derailment { @@ -231,4 +232,13 @@ double sliding_friction(outcome const Outcome) { } } +std::string report(verdict const &Verdict, vehicle_state const &Vehicle, track_state const &Track, double const Velocity, std::string_view const TrackName) { + auto const cant{1000.0 * contact_spacing(Track.gauge) * std::sin(std::abs(Track.cant))}; + return std::format("{} at {:.0f} km/h on track {}, curve radius {:.0f} m, cant {:.0f} mm: lateral acceleration {:.2f} m/s2, wheel unloading {:.2f}, Y/Q {:.2f}" + " (mass {:.1f} t, centre of gravity {:.2f} m, couplings pushing {:.0f} / {:.0f} kN, track damage {}, cross level {:.0f} mm)", + Verdict.result == outcome::overturned ? "overturned" : "derailed, the flange climbed the rail", std::abs(Velocity) * 3.6, TrackName.empty() ? "(none)" : TrackName, + std::abs(Track.radius), cant, Verdict.acceleration, Verdict.unloading, Verdict.flange_ratio, Vehicle.mass / 1000.0, Vehicle.centre_of_gravity, + Vehicle.ends[0].compression / 1000.0, Vehicle.ends[1].compression / 1000.0, Track.damage, Track.uneven_cross); +} + } // namespace derailment diff --git a/McZapkie/derailment.h b/McZapkie/derailment.h index 7d587517f..00088e0d7 100644 --- a/McZapkie/derailment.h +++ b/McZapkie/derailment.h @@ -10,6 +10,8 @@ http://mozilla.org/MPL/2.0/. #pragma once #include +#include +#include // the criteria of a vehicle leaving the rails, as plain functions of what the vehicle and the track under it are // like, so the collisions and the buckled track can use them as well as the speed in a curve does @@ -202,4 +204,9 @@ inline constexpr double off_rails_friction{0.3}; inline constexpr double overturned_friction{0.5}; double sliding_friction(outcome Outcome); +// what the criteria found, for the log: "overturned at 113 km/h on track t1, curve radius 300 m, cant 0 mm: lateral +// acceleration ..., wheel unloading ..., Y/Q ... (mass ..., centre of gravity ..., couplings pushing ... / ... kN, +// track damage ..., cross level ... mm)" +std::string report(verdict const &Verdict, vehicle_state const &Vehicle, track_state const &Track, double Velocity, std::string_view TrackName); + } // namespace derailment diff --git a/tests/unit/test_derailment.cpp b/tests/unit/test_derailment.cpp index 201c2e3bc..f078d7c6e 100644 --- a/tests/unit/test_derailment.cpp +++ b/tests/unit/test_derailment.cpp @@ -278,3 +278,24 @@ TEST_CASE("derailment: the damage flags of the track make the ride rougher, not CHECK(dr::body_acceleration(eu07vehicle, worn, 30.0) - dr::body_acceleration(eu07vehicle, good, 30.0) == doctest::Approx(1.1 * dr::vibration)); } } + +TEST_CASE("derailment: the report of the log") { + dr::verdict verdict; + verdict.result = dr::outcome::overturned; + verdict.acceleration = 3.31; + verdict.unloading = 1.02; + verdict.flange_ratio = 0.55; + dr::vehicle_state vehicle; + vehicle.mass = 80000.0; + vehicle.centre_of_gravity = 1.65; + vehicle.ends[1].compression = 50000.0; + dr::track_state track; + track.radius = -300.0; + track.damage = 31; + auto const text{dr::report(verdict, vehicle, track, 113.0 / 3.6, "track_7")}; + CHECK(text == + "overturned at 113 km/h on track track_7, curve radius 300 m, cant 0 mm: lateral acceleration 3.31 m/s2, wheel unloading 1.02, Y/Q 0.55 (mass 80.0 t, centre of gravity 1.65 m," + " couplings pushing 0 / 50 kN, track damage 31, cross level 0 mm)"); + verdict.result = dr::outcome::off_rails; + CHECK(dr::report(verdict, vehicle, track, 20.0, "").starts_with("derailed, the flange climbed the rail at 72 km/h on track (none),")); +} diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index 690284ba2..b425fcd2c 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -164,3 +164,65 @@ TEST_CASE("derailment: a stopped derailed vehicle stays put on a gradient") { } CHECK(still); } + +TEST_CASE("derailment: monitor, the legacy draw decides and the log tells what the criteria would do") { + model_setting const monitor{global_settings::derailment_model::monitor}; + test::track curve; + curve.radius = 300.0; + curve.name = "curve_1"; + auto const critical{dr::overturning_speed(300.0, 0.0, eu07, 1.435) / kmh}; + // over the speed the criteria overturn the EU07 at, under the threshold of the legacy draw (112 km/h) + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical + 2.0}; + REQUIRE(critical + 2.0 < 112.0); + for (int step = 0; step < 100; ++step) { + eu07vehicle.step(curve); + } + CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + CHECK(eu07vehicle->Derailed == dr::outcome::none); + // once on a track, however long it stays over the criteria + CHECK(eu07vehicle->derailment_reports == 1); + REQUIRE(eu07vehicle->derailment_reported.has_value()); + CHECK(*eu07vehicle->derailment_reported == &curve.name); + // and once more on the next one + test::track next{curve}; + next.name = "curve_2"; + for (int step = 0; step < 100; ++step) { + eu07vehicle.step(next); + } + CHECK(eu07vehicle->derailment_reports == 2); + CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + + SUBCASE("under the criteria nothing is told") { + vehicle slower{definition::fiz("4e_v1/4e"), critical - 5.0}; + for (int step = 0; step < 100; ++step) { + slower.step(curve); + } + CHECK(slower->derailment_reports == 0); + } + SUBCASE("far over the legacy threshold the legacy draw derails it, the legacy way") { + vehicle faster{definition::fiz("4e_v1/4e"), 160.0}; + for (int step = 0; step < 600; ++step) { + faster.step(curve); + } + CHECK(TestFlag(faster->DamageFlag, dtrain_out)); + CHECK(faster->Derailed == dr::outcome::none); + CHECK(faster->V == doctest::Approx(0.0).epsilon(0.01)); + } +} + +TEST_CASE("derailment: the names of the models in eu07.ini") { + using model = global_settings::derailment_model; + CHECK(derailment_model_of("new") == model::physical); + CHECK(derailment_model_of("old") == model::old); + CHECK(derailment_model_of("off") == model::off); + CHECK(derailment_model_of("no") == model::off); + CHECK(derailment_model_of("monitor") == model::monitor); + // a name it doesn't know is the default + CHECK(derailment_model_of("physical") == model::physical); + CHECK(global_settings{}.derailment == model::physical); + // written back the way it's read + for (auto const value : {model::off, model::old, model::physical, model::monitor}) { + CHECK(derailment_model_of(name_of(value)) == value); + } + CHECK(name_of(model::physical) == "new"); +} diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp index 100344369..61609d3ba 100644 --- a/tests/unit/vehicle.cpp +++ b/tests/unit/vehicle.cpp @@ -179,6 +179,7 @@ TTrackParam parameters_of(track const &Track, TMoverParameters const &Mover) { TTrackParam param; param.Width = Track.width; param.friction = Track.friction; + param.Name = &Track.name; // the vehicle's own kind of way: a road vehicle on rails derails as soon as it moves if (Track.category != 0) { param.CategoryFlag = Track.category; diff --git a/tests/unit/vehicle.h b/tests/unit/vehicle.h index 784a4486d..1e7db3599 100644 --- a/tests/unit/vehicle.h +++ b/tests/unit/vehicle.h @@ -68,6 +68,7 @@ struct track { double width{1.435}; double radius{0.0}; // of a curve [m], 0 straight double cant{0.0}; // [rad] + std::string name; // for the log }; // the catenary of the Polish railways [V] diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 746105ad6..bef7e5ab2 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -884,15 +884,11 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& if (token == "physics.derailment") { - // new: the physical criteria (McZapkie/derailment.h), old: the legacy draw, off: no derailment from the speed + // new: the physical criteria (McZapkie/derailment.h), old: the legacy draw, off: no derailment from the speed, + // monitor: the legacy draw, and the criteria to the log std::string model; ParseOne(Parser, model, 1); - if (model == "old") - derailment = derailment_model::old; - else if (model == "off" || model == "no") - derailment = derailment_model::off; - else - derailment = derailment_model::physical; + derailment = derailment_model_of(model); return true; } @@ -1790,10 +1786,7 @@ global_settings::export_as_text( std::ostream &Output ) const { couplerphysics = "all"; } export_as_text( Output, "couplerphysics", couplerphysics ); - export_as_text( Output, "physics.derailment", std::string{ - derailment == derailment_model::old ? "old" : - derailment == derailment_model::off ? "off" : - "new" } ); + export_as_text( Output, "physics.derailment", std::string{ name_of( derailment ) } ); export_as_text( Output, "ai.brakesetting.cw1", AIBrakeSettingCw1 ); export_as_text( Output, "scalespeculars", ScaleSpecularValues ); export_as_text( Output, "gfxrenderer", GfxRenderer ); diff --git a/utilities/Globals.h b/utilities/Globals.h index 19dabab53..b5ff2b3a2 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -293,8 +293,9 @@ struct global_settings { // a vehicle too fast in a curve (physics.derailment in eu07.ini): new, it overturns or its flange climbs the rail // by the criteria of McZapkie/derailment.h held over 2 m, and slides on with the friction of the ballast; old, the // legacy draw of the lateral acceleration against the gauge to the height of the vehicle in every step, which stops - // it; off, it stays on the rails at any speed - enum class derailment_model { off, old, physical }; + // it; off, it stays on the rails at any speed; monitor, the legacy draw decides and the log tells where the criteria + // would derail a vehicle (derailment monitor:, once for a vehicle on a track), for the run of a scenery as it was + enum class derailment_model { off, old, physical, monitor }; derailment_model derailment = derailment_model::physical; bool control_coupling_engine_check = true; // no multiple-unit control between electric and diesel traction vehicles (eu07/maszyna#520) bool gui_defaultwindows = true; @@ -445,6 +446,23 @@ template <> void global_settings::export_as_text( std::ostream &Output, std::string const Key, bool const &Value ) const; +// the models of physics.derailment by their names in eu07.ini: new (the default, also for a name it doesn't know), old, off +// or no, monitor +inline global_settings::derailment_model derailment_model_of(std::string_view const Name) { + if( Name == "old" ) { return global_settings::derailment_model::old; } + if( Name == "off" || Name == "no" ) { return global_settings::derailment_model::off; } + if( Name == "monitor" ) { return global_settings::derailment_model::monitor; } + return global_settings::derailment_model::physical; +} +inline std::string_view name_of( global_settings::derailment_model const Model ) { + switch( Model ) { + case global_settings::derailment_model::old: { return "old"; } + case global_settings::derailment_model::off: { return "off"; } + case global_settings::derailment_model::monitor: { return "monitor"; } + default: { return "new"; } + } +} + extern global_settings& GetGlobalSettings(); #define Global (GetGlobalSettings()) diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 66b1007df..39ab5c4b6 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -3237,6 +3237,7 @@ bool TDynamicObject::Update(double dt, double dt1) tp.CategoryFlag = MyTrack->iCategoryFlag & 15; tp.DamageFlag = MyTrack->iDamageFlag; tp.QualityFlag = MyTrack->iQualityFlag; + tp.Name = &MyTrack->name(); // couplers if( MoverParameters->Couplers[0].CouplingFlag != coupling::faux From 0074197c1d60c4a19815e802afbe3f6aadb74a96 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 15 Nov 2026 20:11:11 +0100 Subject: [PATCH 027/136] feat(physics): physics.trackcheck logs the tracks of a scenery the criteria of derailment find suspicious With physics.trackcheck yes (no by default) every rail track is checked once the scenery loaded, and the suspicious ones are logged, a line for each (trackcheck:), with a summary of the count of each kind: a speed limit over the speed a reference vehicle overturns or climbs the rail at in the curve (an EU07 and a 4-axle coach from the defaults of derailment.h, no .fiz needed; a track without a limit of its own gets 125 km/h and is counted apart), cant held on a straight track, cant over 160 mm, a curve under 40 m with a limit over 40 km/h, and unevenness out of the plausible range. The damage flags are only counted by their value: the sceneries set them for the jolts. The radius is the tightest of the design geometry of the path, so curves given by their control points only count as well. The check is a plain function of the data of the tracks with a log sink (world/TrackCheck.h, in eu07_core), tested on its own; derailment::climbing_speed() gives the speed the flange climbs at, none where it doesn't. --- CMakeLists.txt | 1 + McZapkie/derailment.cpp | 23 +++ McZapkie/derailment.h | 6 + simulation/simulationstateserializer.cpp | 3 + tests/unit/test_derailment.cpp | 44 ++++++ tests/unit/test_derailment_vehicle.cpp | 1 + tests/unit/test_track_check.cpp | 158 +++++++++++++++++++ utilities/Globals.cpp | 7 + utilities/Globals.h | 3 + world/Track.cpp | 63 ++++++++ world/Track.h | 3 + world/TrackCheck.cpp | 184 +++++++++++++++++++++++ world/TrackCheck.h | 96 ++++++++++++ 13 files changed, 592 insertions(+) create mode 100644 tests/unit/test_track_check.cpp create mode 100644 world/TrackCheck.cpp create mode 100644 world/TrackCheck.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 76f359eab..64872ab14 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -538,6 +538,7 @@ set(CORE_SOURCES "McZapkie/Mover.cpp" "McZapkie/couplerphysics.cpp" "McZapkie/derailment.cpp" +"world/TrackCheck.cpp" "McZapkie/Oerlikon_ESt.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" diff --git a/McZapkie/derailment.cpp b/McZapkie/derailment.cpp index 48e61aee5..ed55754b9 100644 --- a/McZapkie/derailment.cpp +++ b/McZapkie/derailment.cpp @@ -232,6 +232,29 @@ double sliding_friction(outcome const Outcome) { } } +std::optional climbing_speed(vehicle_state const &Vehicle, track_state const &Track) { + auto const climbs = [&](double const Velocity) { return flange_forces(Vehicle, Track, Velocity).ratio() >= climbing_limit; }; + // from the speed the cant balances, where the vehicle starts to lean on the outer rail + auto const balancing{curved(Track.radius) ? std::sqrt(gravity * std::abs(Track.radius) * std::sin(std::abs(Track.cant))) : 0.0}; + if (climbs(balancing)) { + return balancing; + } + // in steps of 1 m/s up to the first speed it climbs at, which needn't hold above it, then halving the step + constexpr double fastest{200.0}; + for (auto low{balancing}; low < fastest; low += 1.0) { + auto high{std::min(low + 1.0, fastest)}; + if (false == climbs(high)) { + continue; + } + for (int iteration = 0; iteration < 30; ++iteration) { + auto const middle{0.5 * (low + high)}; + (climbs(middle) ? high : low) = middle; + } + return high; + } + return std::nullopt; +} + std::string report(verdict const &Verdict, vehicle_state const &Vehicle, track_state const &Track, double const Velocity, std::string_view const TrackName) { auto const cant{1000.0 * contact_spacing(Track.gauge) * std::sin(std::abs(Track.cant))}; return std::format("{} at {:.0f} km/h on track {}, curve radius {:.0f} m, cant {:.0f} mm: lateral acceleration {:.2f} m/s2, wheel unloading {:.2f}, Y/Q {:.2f}" diff --git a/McZapkie/derailment.h b/McZapkie/derailment.h index 00088e0d7..fd9ad6daa 100644 --- a/McZapkie/derailment.h +++ b/McZapkie/derailment.h @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #pragma once #include +#include #include #include @@ -204,6 +205,11 @@ inline constexpr double off_rails_friction{0.3}; inline constexpr double overturned_friction{0.5}; double sliding_friction(outcome Outcome); +// the lowest speed [m/s] from the one the cant balances at which the flange of the leading axle climbs the rail (Y / Q +// at the climbing limit); none when it doesn't climb up to 200 m/s: a lone vehicle on a good track mostly overturns +// first, its Y / Q goes to the ratio of the contact spacing to the height of the centre of gravity at speed +std::optional climbing_speed(vehicle_state const &Vehicle, track_state const &Track); + // what the criteria found, for the log: "overturned at 113 km/h on track t1, curve radius 300 m, cant 0 mm: lateral // acceleration ..., wheel unloading ..., Y/Q ... (mass ..., centre of gravity ..., couplings pushing ... / ... kN, // track damage ..., cross level ... mm)" diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index 9d1e94869..3a4edb7b1 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -445,6 +445,9 @@ state_serializer::deserialize_firstinit( cParser &Input, scene::scratch_data &Sc Scratchpad.binary.terrain_binaryfiles.clear(); simulation::Paths.InitTracks(); + if( Global.track_check ) { + simulation::Paths.CheckTracks(); + } // the roads tie up their own lanes where they gain or lose some, the junctions tie the lanes of the roads together, // what's left loose after that gets closed by the roads simulation::Roads.InitLanes(); diff --git a/tests/unit/test_derailment.cpp b/tests/unit/test_derailment.cpp index f078d7c6e..3afca6a26 100644 --- a/tests/unit/test_derailment.cpp +++ b/tests/unit/test_derailment.cpp @@ -279,6 +279,50 @@ TEST_CASE("derailment: the damage flags of the track make the ride rougher, not } } +TEST_CASE("derailment: the speed the flange climbs the rail at") { + dr::vehicle_state vehicle; + vehicle.mass = 80000.0; + vehicle.axles = 4; + vehicle.length = 16.0; + vehicle.axle_base = 3.0; + vehicle.centre_of_gravity = 1.65; + dr::track_state track; + track.radius = 300.0; + SUBCASE("a lone vehicle on a good track overturns first: its Y/Q stays under the limit") { + CHECK_FALSE(dr::climbing_speed(vehicle, track).has_value()); + } + SUBCASE("on a twisted track it climbs, at the speed Y/Q reaches the limit") { + // 50 mm of cross level takes half the load off the wheel + track.uneven_cross = 50.0; + auto const speed{dr::climbing_speed(vehicle, track)}; + REQUIRE(speed.has_value()); + CHECK(*speed > 0.0); + CHECK(dr::flange_forces(vehicle, track, *speed).ratio() >= dr::climbing_limit); + CHECK(dr::flange_forces(vehicle, track, *speed - 0.01).ratio() < dr::climbing_limit); + SUBCASE("the cant moves it up") { + track.cant = std::asin(0.1 / 1.5); + auto const canted{dr::climbing_speed(vehicle, track)}; + REQUIRE(canted.has_value()); + CHECK(*canted > *speed); + } + } + SUBCASE("pushed hard enough it climbs at a standstill: from the speed the cant balances") { + // an empty 3WL between heavy vehicles pushing 1 MN in a curve of 150 m, on 40 mm of cross level + vehicle.mass = 10500.0; + vehicle.axles = 2; + vehicle.length = 9.0; + vehicle.axle_base = 5.0; + vehicle.centre_of_gravity = 1.1; + vehicle.ends[0] = {1000000.0, 16.0}; + vehicle.ends[1] = {1000000.0, 16.0}; + track.radius = 150.0; + track.uneven_cross = 40.0; + auto const speed{dr::climbing_speed(vehicle, track)}; + REQUIRE(speed.has_value()); + CHECK(*speed == 0.0); + } +} + TEST_CASE("derailment: the report of the log") { dr::verdict verdict; verdict.result = dr::outcome::overturned; diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index b425fcd2c..6e8e4661a 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -220,6 +220,7 @@ TEST_CASE("derailment: the names of the models in eu07.ini") { // a name it doesn't know is the default CHECK(derailment_model_of("physical") == model::physical); CHECK(global_settings{}.derailment == model::physical); + CHECK_FALSE(global_settings{}.track_check); // written back the way it's read for (auto const value : {model::off, model::old, model::physical, model::monitor}) { CHECK(derailment_model_of(name_of(value)) == value); diff --git a/tests/unit/test_track_check.cpp b/tests/unit/test_track_check.cpp new file mode 100644 index 000000000..ce0424d81 --- /dev/null +++ b/tests/unit/test_track_check.cpp @@ -0,0 +1,158 @@ +#include "stdafx.h" +#include "doctest.h" +#include "world/TrackCheck.h" + +#include +#include +#include +#include + +// physics.trackcheck: the geometry of the rail tracks of a scenery the criteria of derailment find suspicious, see +// world/TrackCheck.h + +namespace tc = track_check; + +namespace { + +bool has(tc::findings const &Found, tc::kind const Kind) { + return std::find(Found.kinds.begin(), Found.kinds.end(), Kind) != Found.kinds.end(); +} + +tc::track curve(double const Radius, double const Velocity, double const Cant = 0.0) { + tc::track track; + track.name = "t1"; + track.radius = Radius; + track.velocity = Velocity; + track.cant = {Cant, Cant}; + return track; +} + +double overturning(double const Radius, double const Cant = 0.0) { + auto const &eu07{tc::default_references().front().vehicle}; + return derailment::overturning_speed(Radius, std::asin(Cant / 1500.0), eu07.centre_of_gravity, 1.435) * 3.6; +} + +} // namespace + +TEST_CASE("trackcheck: the default vehicles") { + auto const &references{tc::default_references()}; + REQUIRE(references.size() == 2); + CHECK(references[0].name == "EU07"); + CHECK(references[0].vehicle.centre_of_gravity == doctest::Approx(1.65).epsilon(0.01)); + CHECK(references[1].vehicle.centre_of_gravity == doctest::Approx(1.42).epsilon(0.01)); + // the EU07 overturns at 108 km/h in a curve of 300 m without cant + CHECK(overturning(300.0) == doctest::Approx(108.0).epsilon(0.02)); +} + +TEST_CASE("trackcheck: the speed limit of a curve") { + auto const critical{overturning(300.0)}; + SUBCASE("under the speeds of the vehicles nothing") { + CHECK(tc::check(curve(300.0, critical - 10.0)).empty()); + } + SUBCASE("over the overturning speed of the EU07") { + auto const found{tc::check(curve(300.0, critical + 5.0))}; + CHECK(has(found, tc::kind::overturning)); + CHECK_FALSE(has(found, tc::kind::overturning_default)); + CHECK(found.text.find("over the overturning speed of EU07") != std::string::npos); + CHECK(found.text.find("speed limit 113 km/h") != std::string::npos); + } + SUBCASE("the cant raises it") { + CHECK(tc::check(curve(300.0, critical + 5.0, 100.0)).empty()); + } + SUBCASE("without a speed limit of its own the default one goes, counted apart") { + auto const found{tc::check(curve(300.0, -1.0))}; + CHECK(has(found, tc::kind::overturning_default)); + CHECK_FALSE(has(found, tc::kind::overturning)); + CHECK(found.text.find("default speed 125 km/h") != std::string::npos); + CHECK(found.text.find("speed limit none") != std::string::npos); + } + SUBCASE("a closed track (speed 0) is not checked") { + CHECK(tc::check(curve(100.0, 0.0)).empty()); + } + SUBCASE("nor the speed of a switch") { + auto track{curve(150.0, 100.0)}; + track.plain = false; + CHECK(tc::check(track).empty()); + } + SUBCASE("the cant at the end with the less of it") { + auto track{curve(300.0, critical + 5.0, 100.0)}; + track.cant[0] = 0.0; + CHECK(has(tc::check(track), tc::kind::overturning)); + } +} + +TEST_CASE("trackcheck: the cant") { + SUBCASE("the same cant at both ends of a straight track") { + auto const found{tc::check(curve(0.0, 100.0, 60.0))}; + CHECK(has(found, tc::kind::cant_on_straight)); + CHECK(found.text.starts_with("cant 60 / 60 mm on a straight track")); + } + SUBCASE("a transition has it at one end only") { + auto track{curve(0.0, 100.0, 60.0)}; + track.cant[0] = 0.0; + CHECK(tc::check(track).empty()); + } + SUBCASE("a few mm are left alone") { + CHECK(tc::check(curve(0.0, 100.0, 4.0)).empty()); + } + SUBCASE("over 160 mm") { + auto const found{tc::check(curve(1000.0, 60.0, 170.0))}; + CHECK(has(found, tc::kind::cant_excess)); + CHECK(found.kinds.size() == 1); + CHECK(tc::check(curve(1000.0, 60.0, 150.0)).empty()); + } +} + +TEST_CASE("trackcheck: a tight curve") { + CHECK(has(tc::check(curve(30.0, 50.0)), tc::kind::tight_curve)); + CHECK_FALSE(has(tc::check(curve(30.0, 30.0)), tc::kind::tight_curve)); + CHECK_FALSE(has(tc::check(curve(60.0, 50.0)), tc::kind::tight_curve)); +} + +TEST_CASE("trackcheck: the unevenness") { + auto track{curve(0.0, 100.0)}; + track.uneven.value = 14.f; + track.uneven.side = 20.f; + track.uneven.cross = 20.f; + CHECK(tc::check(track).empty()); + track.uneven.side = 40.f; + track.uneven.cross = 26.f; + auto const found{tc::check(track)}; + CHECK(has(found, tc::kind::uneven)); + CHECK(found.text.starts_with("uneven side 40, cross 26 mm out of range")); +} + +TEST_CASE("trackcheck: the scan of a scenery") { + std::vector tracks; + tracks.push_back(curve(300.0, 140.0)); + tracks.back().name = "fast"; + tracks.push_back(curve(0.0, 100.0)); + tracks.back().name = "worn"; + tracks.back().damage = 31; + tracks.push_back(curve(0.0, 100.0, 50.0)); + tracks.back().name = "leaning"; + tracks.back().damage = 31; + tracks.push_back(curve(0.0, 100.0)); + tracks.back().name = "fine"; + tracks.back().damage = 2; + + std::vector log; + auto const summary{tc::scan(tracks, [&](std::string const &Line) { log.push_back(Line); })}; + CHECK(summary.tracks == 4); + CHECK(summary.suspicious == 2); + CHECK(summary.count(tc::kind::overturning) == 1); + CHECK(summary.count(tc::kind::cant_on_straight) == 1); + CHECK(summary.count(tc::kind::tight_curve) == 0); + // the damage flags are counted, not told track by track + CHECK(summary.damage.at(31) == 2); + CHECK(summary.damage.at(2) == 1); + REQUIRE(log.size() == 4); + CHECK(log[0].starts_with("trackcheck: fast: speed limit 140 km/h over the overturning speed of EU07")); + CHECK(log[1].starts_with("trackcheck: leaning: cant 50 / 50 mm on a straight track")); + CHECK(log[1].ends_with("damage 31)")); + CHECK(log[2].starts_with("trackcheck: 4 rail tracks checked, 2 suspicious: overturning 1; flange climbing 0;")); + CHECK(log[3] == "trackcheck: damage flags: 2 on 1; 31 on 2"); + for (auto const &line : log) { + CHECK(line.starts_with("trackcheck: ")); + } +} diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index bef7e5ab2..8b134503a 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -892,6 +892,12 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + if (token == "physics.trackcheck") + { + ParseOne(Parser, track_check, 1); + return true; + } + if (token == "controlcoupling.enginecheck") { ParseOne(Parser, control_coupling_engine_check, 1); @@ -1787,6 +1793,7 @@ global_settings::export_as_text( std::ostream &Output ) const { } export_as_text( Output, "couplerphysics", couplerphysics ); export_as_text( Output, "physics.derailment", std::string{ name_of( derailment ) } ); + export_as_text( Output, "physics.trackcheck", track_check ); export_as_text( Output, "ai.brakesetting.cw1", AIBrakeSettingCw1 ); export_as_text( Output, "scalespeculars", ScaleSpecularValues ); export_as_text( Output, "gfxrenderer", GfxRenderer ); diff --git a/utilities/Globals.h b/utilities/Globals.h index b5ff2b3a2..174be4675 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -297,6 +297,9 @@ struct global_settings { // would derail a vehicle (derailment monitor:, once for a vehicle on a track), for the run of a scenery as it was enum class derailment_model { off, old, physical, monitor }; derailment_model derailment = derailment_model::physical; + // physics.trackcheck: the geometry of the rail tracks the criteria of derailment find suspicious, to the log once the + // scenery loaded (trackcheck:, see world/TrackCheck.h) + bool track_check = false; bool control_coupling_engine_check = true; // no multiple-unit control between electric and diesel traction vehicles (eu07/maszyna#520) bool gui_defaultwindows = true; bool gui_showtranscripts = true; diff --git a/world/Track.cpp b/world/Track.cpp index 947a5836c..3f18ee226 100644 --- a/world/Track.cpp +++ b/world/Track.cpp @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "world/Track.h" #include "world/TrackRails.h" +#include "world/TrackCheck.h" #include "simulation/simulation.h" #include "scene/scene.h" #include "utilities/Globals.h" @@ -4164,6 +4165,68 @@ path_table::InitTracks() { TTrack::fetch_default_profiles(); } +namespace { + +// the tightest radius of the curve of a path in the plan [m], from the circles through its design points about 5 m apart +// (without the unevenness, whose short waves would bend it): the curve the axles of a vehicle follow, whether the track +// gives the radius or only its control points. 0 for a straight one; a radius over 15 km is taken for one, as +// TDynamicObject::Update() takes it +double tightest_radius(TSegment const &Segment) { + + auto const length { Segment.GetLength() }; + if( length < 0.5 ) { + return 0.0; + } + auto const intervals { std::max( 2, static_cast( std::ceil( length / 5.0 ) ) ) }; + auto const flat = [&]( int const Index ) { + auto const point { Segment.FastGetPoint( static_cast( Index ) / intervals ) }; + return glm::dvec2 { point.x, point.z }; }; + auto tightest { 0.0 }; + for( int index = 1; index < intervals; ++index ) { + auto const a { flat( index - 1 ) }; + auto const b { flat( index ) }; + auto const c { flat( index + 1 ) }; + auto const ab { b - a }; + auto const ac { c - a }; + auto const area2 { std::abs( ab.x * ac.y - ab.y * ac.x ) }; + if( area2 < 1e-9 ) { + continue; + } + auto const radius { glm::length( ab ) * glm::length( c - b ) * glm::length( ac ) / ( 2.0 * area2 ) }; + if( radius < 15000.0 && ( tightest == 0.0 || radius < tightest ) ) { + tightest = radius; + } + } + return tightest; +} + +} // namespace + +void +path_table::CheckTracks() const { + + std::vector tracks; + for( auto *path : sequence() ) { + if( path == nullptr || ( path->iCategoryFlag & 1 ) == 0 || path->Segment == nullptr ) { + continue; + } + track_check::track track; + track.name = path->name(); + track.velocity = path->VelocityGet(); + track.plain = ( path->eType == tt_Normal ); + track.radius = track.plain ? tightest_radius( *path->Segment ) : 0.0; + float roll1 { 0.f }, roll2 { 0.f }; + path->Segment->GetRolls( roll1, roll2 ); + track.gauge = path->fTrackWidth; + auto const spacing { 1000.0 * derailment::contact_spacing( track.gauge ) }; + track.cant = { spacing * std::sin( roll1 ), spacing * std::sin( roll2 ) }; + track.damage = path->iDamageFlag; + track.uneven = path->m_uneven; + tracks.emplace_back( std::move( track ) ); + } + track_check::scan( tracks, []( std::string const &Line ) { WriteLog( Line ); } ); +} + // legacy method, sends list of occupied paths over network void path_table::TrackBusyList() const { diff --git a/world/Track.h b/world/Track.h index 033bee610..3e03e4011 100644 --- a/world/Track.h +++ b/world/Track.h @@ -523,6 +523,9 @@ public: // legacy method, initializes tracks after deserialization from scenario file void InitTracks(); + // physics.trackcheck: logs the geometry of the rail tracks the checks of world/TrackCheck.h find suspicious + void + CheckTracks() const; // legacy method, sends list of occupied paths over network void TrackBusyList() const; diff --git a/world/TrackCheck.cpp b/world/TrackCheck.cpp new file mode 100644 index 000000000..22bc61861 --- /dev/null +++ b/world/TrackCheck.cpp @@ -0,0 +1,184 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "world/TrackCheck.h" + +#include +#include +#include + +namespace track_check { + +namespace { + +constexpr double kmh{3.6}; + +reference make_reference(std::string const &Name, double const Mass, double const Length, double const AxleBase, double const BodyHeight, derailment::vehicle_class const Class) { + reference result; + result.name = Name; + result.vehicle.mass = Mass; + result.vehicle.axles = 4; + result.vehicle.length = Length; + result.vehicle.axle_base = AxleBase; + result.vehicle.centre_of_gravity = derailment::default_centre_of_gravity(BodyHeight, Class); + return result; +} + +// the cant [rad] of the given height of the outer rail [mm] +double cant_angle(double const Cant, double const Gauge) { + return std::asin(std::clamp(std::abs(Cant) / (1000.0 * derailment::contact_spacing(Gauge)), 0.0, 1.0)); +} + +void append(std::string &Text, std::string const &Part) { + if (false == Text.empty()) { + Text += "; "; + } + Text += Part; +} + +// the values of the unevenness past the range, as "side 40, cross 30" +std::string uneven_excess(track_uneven::attribute const &Uneven, settings const &Settings) { + std::string result; + auto const test = [&](char const *Name, float const Value, double const Most) { + if (Value > Most) { + if (false == result.empty()) { + result += ", "; + } + result += std::format("{} {:g}", Name, Value); + } + }; + test("value", Uneven.value, Settings.most_uneven); + test("up", Uneven.up, Settings.most_uneven); + test("side", Uneven.side, Settings.most_uneven); + test("cross", Uneven.cross, Settings.most_cross); + test("dip", Uneven.dip, Settings.most_uneven); + test("branch", Uneven.branch, Settings.most_uneven); + test("branch up", Uneven.branchup, Settings.most_uneven); + test("branch side", Uneven.branchside, Settings.most_uneven); + return result; +} + +} // namespace + +std::vector const &default_references() { + static std::vector const references{ + make_reference("EU07", 80000.0, 15.915, 3.0, 4.348, derailment::vehicle_class::powered), + make_reference("coach", 40000.0, 24.5, 2.5, 4.05, derailment::vehicle_class::unpowered), + }; + return references; +} + +std::string_view name_of(kind const Kind) { + switch (Kind) { + case kind::overturning: + return "overturning"; + case kind::climbing: + return "flange climbing"; + case kind::overturning_default: + return "overturning at the default speed"; + case kind::climbing_default: + return "flange climbing at the default speed"; + case kind::cant_on_straight: + return "cant on a straight"; + case kind::cant_excess: + return "cant too high"; + case kind::tight_curve: + return "tight curve too fast"; + case kind::uneven: + return "uneven out of range"; + default: + return "?"; + } +} + +findings check(track const &Track, std::vector const &References, settings const &Settings) { + findings result; + auto const found = [&](kind const Kind, std::string const &Text) { + if (std::find(result.kinds.begin(), result.kinds.end(), Kind) == result.kinds.end()) { + result.kinds.push_back(Kind); + } + append(result.text, Text); + }; + auto const curved{Track.radius > 0.0}; + auto const given{Track.velocity >= 0.0}; + auto const velocity{given ? Track.velocity : Settings.default_velocity}; + + if (Track.plain) { + // the speed in the curve, with the cant both ends have at the least + if (curved && velocity > 0.0) { + auto const cant{std::min(std::abs(Track.cant[0]), std::abs(Track.cant[1]))}; + derailment::track_state track; + track.radius = Track.radius; + track.cant = cant_angle(cant, Track.gauge); + track.gauge = Track.gauge; + for (auto const &reference : References) { + auto const overturning{derailment::overturning_speed(track.radius, track.cant, reference.vehicle.centre_of_gravity, track.gauge) * kmh}; + if (overturning > 0.0 && velocity > overturning) { + found(given ? kind::overturning : kind::overturning_default, + std::format("{} {:.0f} km/h over the overturning speed of {} {:.0f} km/h", given ? "speed limit" : "default speed", velocity, reference.name, overturning)); + } + if (auto const climbing{derailment::climbing_speed(reference.vehicle, track)}; climbing.has_value() && velocity > *climbing * kmh) { + found(given ? kind::climbing : kind::climbing_default, + std::format("{} {:.0f} km/h over the flange climbing speed of {} {:.0f} km/h", given ? "speed limit" : "default speed", velocity, reference.name, *climbing * kmh)); + } + } + } + // cant held over the whole of a straight track: a transition has it at one end only + if (false == curved && std::abs(Track.cant[0]) > Settings.straight_cant && std::abs(Track.cant[1]) > Settings.straight_cant && Track.cant[0] * Track.cant[1] > 0.0) { + found(kind::cant_on_straight, std::format("cant {:.0f} / {:.0f} mm on a straight track", Track.cant[0], Track.cant[1])); + } + if (curved && velocity > Settings.tight_velocity && Track.radius < Settings.tight_radius) { + found(kind::tight_curve, std::format("radius {:.0f} m with a {} of {:.0f} km/h", Track.radius, given ? "speed limit" : "default speed", velocity)); + } + } + if (auto const most{std::max(std::abs(Track.cant[0]), std::abs(Track.cant[1]))}; most > Settings.most_cant) { + found(kind::cant_excess, std::format("cant {:.0f} mm over {:.0f} mm", most, Settings.most_cant)); + } + if (auto const excess{uneven_excess(Track.uneven, Settings)}; false == excess.empty()) { + found(kind::uneven, std::format("uneven {} mm out of range", excess)); + } + if (false == result.empty()) { + result.text += std::format(" (radius {:.0f} m, cant {:.0f} / {:.0f} mm, speed limit {}, damage {})", Track.radius, Track.cant[0], Track.cant[1], + given ? std::format("{:.0f} km/h", Track.velocity) : std::string{"none"}, Track.damage); + } + return result; +} + +summary scan(std::vector const &Tracks, sink const &Log, std::vector const &References, settings const &Settings) { + summary result; + for (auto const &track : Tracks) { + ++result.tracks; + if (track.damage != 0) { + ++result.damage[track.damage]; + } + auto const found{check(track, References, Settings)}; + if (found.empty()) { + continue; + } + ++result.suspicious; + for (auto const kind : found.kinds) { + ++result.counts[static_cast(kind)]; + } + Log(std::format("trackcheck: {}: {}", track.name.empty() ? std::string{"(none)"} : track.name, found.text)); + } + std::string counts; + for (std::size_t kind = 0; kind < result.counts.size(); ++kind) { + append(counts, std::format("{} {}", name_of(static_cast(kind)), result.counts[kind])); + } + Log(std::format("trackcheck: {} rail tracks checked, {} suspicious: {}", result.tracks, result.suspicious, counts)); + std::string damage; + for (auto const &[flags, count] : result.damage) { + append(damage, std::format("{} on {}", flags, count)); + } + Log(std::format("trackcheck: damage flags: {}", damage.empty() ? std::string{"none"} : damage)); + return result; +} + +} // namespace track_check diff --git a/world/TrackCheck.h b/world/TrackCheck.h new file mode 100644 index 000000000..d07b3cb49 --- /dev/null +++ b/world/TrackCheck.h @@ -0,0 +1,96 @@ +/* +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 "McZapkie/derailment.h" +#include "world/TrackUneven.h" + +#include +#include +#include +#include +#include +#include + +// the check of the geometry of the rail tracks of a scenery (physics.trackcheck yes in eu07.ini): what the criteria of +// derailment (McZapkie/derailment.h) and the plain rules of the track find suspicious, to the log once the scenery +// loaded, so a run can tell a faulty scenery from a faulty simulation. one line for a track with all it found +// ("trackcheck: : ..."), and a summary with the count of each kind. the damage flags are only counted: sceneries +// set them for the jolts of a worn track (damage 31 on every track of line 107) +namespace track_check { + +// a rail track as the check sees it +struct track { + std::string name; + double velocity{-1.0}; // the speed limit of the track [km/h], negative when it gives none + double radius{0.0}; // the tightest radius of its curve [m], 0 on a straight one + std::array cant{0.0, 0.0}; // at its ends [mm], positive raising the right rail + double gauge{1.435}; // [m] + int damage{0}; // dtrack_* flags + bool plain{true}; // a plain track, its speed and curve checked; a switch or a crossing has the paths and the + // speeds of its position, only its unevenness and its damage are + track_uneven::attribute uneven; +}; + +// a vehicle the speed limit of a curve is checked for +struct reference { + std::string name; + derailment::vehicle_state vehicle; +}; +// the default vehicles of derailment.h: an EU07 (4 axles, 80 t, 15.9 m, bogies of 3 m, the centre of gravity of its +// 4.35 m high body) and a 4-axle coach (40 t, 24.5 m, bogies of 2.5 m, 4.05 m high), alone, without a .fiz +std::vector const &default_references(); + +struct settings { + // the speed limit of a track which gives none [km/h]: the top speed of the EU07, the trains the default vehicles + // make up run no faster + double default_velocity{125.0}; + double most_cant{160.0}; // [mm], 150 the most of the Polish rules (Id-1), and a margin + double straight_cant{5.0}; // the cant both ends of a straight track have, past which it's cant without a curve [mm] + double tight_radius{40.0}; // a curve tighter than this [m] + double tight_velocity{40.0}; // with a speed limit over this [km/h] + double most_uneven{30.0}; // the value, up, side and dip of the unevenness [mm]: Id-14 lets the poorest track 28 mm + double most_cross{25.0}; // the cross level [mm]: 20 mm in class C of Id-14 +}; + +enum class kind { + overturning, // the speed limit is over the speed a reference vehicle overturns at + climbing, // or over the one its flange climbs the rail at + overturning_default, // the same with the default speed limit, of a track which gives none + climbing_default, + cant_on_straight, // both ends of a straight track have the same cant + cant_excess, // over the most cant + tight_curve, // a curve tighter than the tight radius with a speed limit over the tight velocity + uneven, // the unevenness out of the plausible range + count_ +}; +std::string_view name_of(kind Kind); + +// what the check found on a track +struct findings { + std::vector kinds; + std::string text; // what the log line tells after the name of the track, empty when nothing + bool empty() const { return kinds.empty(); } +}; +findings check(track const &Track, std::vector const &References = default_references(), settings const &Settings = {}); + +struct summary { + int tracks{0}; // checked + int suspicious{0}; // with a line of their own + std::array(kind::count_)> counts{}; + std::map damage; // the tracks of each value of the damage flags, none for 0 + int count(kind const Kind) const { return counts[static_cast(Kind)]; } +}; + +using sink = std::function; +// checks the tracks, logs a line for each one found suspicious and the summary +summary scan(std::vector const &Tracks, sink const &Log, std::vector const &References = default_references(), settings const &Settings = {}); + +} // namespace track_check From 0f61567bcb84cc809618ebe5f7e1aeae1ddebded Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 00:26:18 +0100 Subject: [PATCH 028/136] fix(physics): only the energy of a hit past the buffers of EN 15551 crushes the ends Found running every scenario of the install with physics.collisions new: two locomotives (SU45 117 t, SM42 84 t) put down by calkowo_v2_kontenera inside each other crushed both their ends at 5 km/h right after the start, deeper hit after hit, until both overrode (0.60 m); in baltyk_sdm the coaches of a train pushed into a vehicle derailed at the end of the track (a wall) crushed at 5-8 km/h. Some 50 kJ of relative motion, which the buffers take in with room to spare. The crush went by the closing velocity at the stop of the buffers alone: buffers pressed all the way from the start of the contact (put down overlapping, or knocked onto each other by a hit elsewhere) left the whole hit to the underframes, every step anew. Each pair now counts the energy of its contact (collision::contact_energy): what the springs of the buffers take in while they're pressed and the pair closes in, kept down to what they hold once they spring back, reset when they part. A hit may crush only what it brings to the stop past what the buffers of EN 15551 of both ends would take in, by their BufferCategory (the key now also gives that energy) or 30 kJ a buffer by default: budget = 1/2 mu v^2 - max(0, capacity - absorbed) collision::hit() stops the crush once its work reaches the budget, the rest springs back. The crush of a whole hit thus never takes more than the hit brought past the buffers; a train behind pushing the pair on brings in more through the velocity of the next step. The monitor goes by the same budget. The log of a crush tells the energies. Pressing alone, a locomotive pushing a braked train at a stand, and vehicles put down overlapping don't crush. The crash cases keep crushing: the hits of two masses, EU07 into a 430W, the EN 15227 units at 36 km/h and the 15 km/h PoC cases as before; at 25-40 km/h fewer ends deep in the trains crush (the buffers of the couplings there take in their energy). --- McZapkie/MOVER.h | 2 + McZapkie/Mover.cpp | 23 ++- McZapkie/collision.cpp | 74 ++++++- McZapkie/collision.h | 65 +++++- tests/unit/test_collisions.cpp | 354 +++++++++++++++++++++++++++++++++ 5 files changed, 503 insertions(+), 15 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 7e708d5c8..a2ae1368c 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -1304,6 +1304,8 @@ struct TCoupling double hit_duration{0.0}; // physics.collisions monitor: the log told of the crush of this hit of the pair already bool crush_monitored{false}; + // the energy the contact of the pair brought to its buffers, for the budget of the crush + collision::contact_energy contact; int sounds{0}; // sounds emitted by the coupling devices bool Render = false; /*ABu: czy rysowac jak zaczepiony sprzeg*/ diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index f33bbb8ed..1efeb597c 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1623,6 +1623,11 @@ bool TMoverParameters::crush_hit(int const End, double const dt) // the monitor takes the whole hit at once, over a second, longer than the crush of any hit lasts input.dt = monitor ? 1.0 : dt; input.start_velocity = thiscoupler.closing; + // the crush takes only what the hit brings past what the buffers of EN 15551 of both ends take in + auto const reduced{mass * othermass / (mass + othermass)}; + auto const capacity{collision::buffer_capacity(thiscoupler.collision, collision_kind()) + collision::buffer_capacity(othercoupler.collision, othervehicle->collision_kind())}; + auto const hitvelocity{std::max(closing, thiscoupler.closing)}; + input.budget = thiscoupler.contact.budget(reduced, hitvelocity, capacity); auto const hit{collision::hit({firstcurve, thiscoupler.crush}, {secondcurve, othercoupler.crush}, input)}; // the override, by the crush of both ends auto const climbing_of = [&](double const Crush1, double const Crush2) { @@ -1664,7 +1669,6 @@ bool TMoverParameters::crush_hit(int const End, double const dt) { // the steel takes it, the legacy collision follows; its peak, under the force an end gives at, for the push // off the track - auto const reduced{mass * othermass / (mass + othermass)}; auto const weaker{std::min(firstcurve.force(thiscoupler.crush), secondcurve.force(othercoupler.crush))}; auto const peak{std::min(springs + coupler_physics::impact_force(closing, stiffness, mass, othermass), weaker)}; auto const duration{std::min(dt, (1.0 + input.restitution) * std::sqrt(reduced / stiffness))}; @@ -1691,13 +1695,19 @@ bool TMoverParameters::crush_hit(int const End, double const dt) record_hit(thiscoupler, hit.force, hit.duration); record_hit(othercoupler, hit.force, hit.duration); + // the energy the crush took, for both vehicles' count of the contact + thiscoupler.contact.crushed(hit.work); + othercoupler.contact.crushed(hit.work); // what the log tells of the pair, for the analysis of a crush + auto const kinetic{0.5 * reduced * hitvelocity * hitvelocity}; auto const pair = [&]() { return std::format("{} {:.1f} t {}, {} end crushed {:.2f} m, gives at {:.0f} kN; {} {:.1f} t {}, {} end crushed {:.2f} m, gives at {:.0f} kN; force {:.0f} kN, springs {:.0f} kN, " - "closing at {:.1f} km/h at the start of the step", + "closing at {:.1f} km/h at the start of the step; energy {:.0f} kJ of the motion and {:.0f} kJ in the buffers, past the {:.0f} kJ they take in, " + "{:.0f} kJ crushed in the contact", Name, TotalMass / 1000.0, kind_name(collision_kind()), end_name(End), thiscoupler.crush, firstcurve.force(thiscoupler.crush) / 1000.0, othervehicle->Name, othervehicle->TotalMass / 1000.0, kind_name(othervehicle->collision_kind()), end_name(otherend), othercoupler.crush, - secondcurve.force(othercoupler.crush) / 1000.0, hit.force / 1000.0, springs / 1000.0, input.start_velocity * 3.6); + secondcurve.force(othercoupler.crush) / 1000.0, hit.force / 1000.0, springs / 1000.0, input.start_velocity * 3.6, kinetic / 1000.0, + thiscoupler.contact.absorbed() / 1000.0, capacity / 1000.0, thiscoupler.contact.crush_work() / 1000.0); }; auto const crushed = [&](TMoverParameters const &Vehicle, int const VehicleEnd, double const Before, double const After) { if (Before < collision::crush_mark && After >= collision::crush_mark) @@ -5819,9 +5829,15 @@ void TMoverParameters::ComputeTotalForce(double dt) Couplers[end].closing = -CouplerVelocityDifference(end, *Neighbours[end].vehicle->MoverParameters, Neighbours[end].vehicle_end) * DirF(end); Couplers[end].CForce = CouplerForce(end, dt); FTrain += Couplers[end].CForce; + // what the buffers of the pair take in, for the budget of the crush (physics.collisions new and monitor) + auto &coupler{Couplers[end]}; + coupler.contact.update(coupler.Dist < 0.0, coupler.CheckCollision, coupler.closing, compression_at(coupler, end), std::max(0.0, -coupler.Dist), dt); } else + { Couplers[end].CForce = 0; + Couplers[end].contact.reset(); + } } FStand += Fb; @@ -11928,6 +11944,7 @@ void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Inde thiscoupler->physics.buffers = collision::buffer_curve(*category, thiscoupler->physics.buffers.progression); } thiscoupler->collision = collision_definition(line); + thiscoupler->collision.buffers = category; if (Index == 0) { diff --git a/McZapkie/collision.cpp b/McZapkie/collision.cpp index 60bcf4a41..0abdfdd3b 100644 --- a/McZapkie/collision.cpp +++ b/McZapkie/collision.cpp @@ -156,6 +156,51 @@ std::optional buffer_category_of(char const Name) { } } +buffer_category default_buffers(vehicle_kind const Kind) { + return Kind == vehicle_kind::coach ? buffer_category::passenger : buffer_category::A; +} + +double buffer_capacity(end_definition const &Definition, vehicle_kind const Kind) { + // two buffers side by side + return 2.0 * rating(Definition.buffers.value_or(default_buffers(Kind))).energy; +} + +void contact_energy::update(bool const Pressed, bool const Solid, double const Closing, double const Force, double const Compression, double const Dt) { + if (false == Pressed) { + // the buffers apart, the contact is over + reset(); + return; + } + if (Solid) { + // pressed all the way, the buffers take in nothing more + return; + } + auto const force{std::max(Force, 0.0)}; + if (Closing > 0.0) { + m_absorbed += force * Closing * std::max(Dt, 0.0); + } + else if (Closing < 0.0) { + // springing back, they hold no more than their springs pressed in so far + m_absorbed = std::min(m_absorbed, 0.5 * force * std::max(Compression, 0.0)); + } +} + +void contact_energy::crushed(double const Work) { + m_crushed += std::max(Work, 0.0); +} + +double contact_energy::budget(double const Mass, double const Closing, double const Capacity) const { + auto const closing{std::max(Closing, 0.0)}; + // what the buffers of EN 15551 would still take in: the springs of the .fiz taking in more leave no more energy past + // the buffers than the hit has + return 0.5 * std::max(Mass, 0.0) * closing * closing - std::max(0.0, Capacity - m_absorbed); +} + +void contact_energy::reset() { + m_absorbed = 0.0; + m_crushed = 0.0; +} + hit_result hit(end_state const &First, end_state const &Second, hit_input const &Input) { hit_result result; if (Input.velocity <= 0.0 || Input.mass1 <= 0.0 || Input.mass2 <= 0.0 || Input.dt <= 0.0) { @@ -177,7 +222,7 @@ hit_result hit(end_state const &First, end_state const &Second, hit_input const auto const elastic_limit = [&](double const Force) { return std::max(0.0, Force - springs) / root; }; { auto const force{std::min(First.curve.force(crush1), Second.curve.force(crush2))}; - if (false == std::isfinite(force) || velocity <= elastic_limit(force)) { + if (false == std::isfinite(force) || velocity <= elastic_limit(force) || false == (Input.budget > 0.0)) { // the steel takes it all: the legacy elastic exchange return result; } @@ -189,6 +234,8 @@ hit_result hit(end_state const &First, end_state const &Second, hit_input const auto time{0.0}; auto rebound{false}; auto crushtime{0.0}; + auto work{0.0}; + auto cap{0.0}; // the force the crush went at last while (Input.dt - time > 1e-12) { auto const force1{First.curve.force(crush1)}; auto const force2{Second.curve.force(crush2)}; @@ -205,7 +252,19 @@ hit_result hit(end_state const &First, end_state const &Second, hit_input const step = (velocity - limit) * mass / force; change = velocity - limit; } - auto const crush{(velocity - 0.5 * change) * step}; + auto crush{(velocity - 0.5 * change) * step}; + auto spent{false}; + if (work + force * crush > Input.budget) { + // the energy of the hit past the buffers runs out in the slice: the crush goes as far as it takes, the + // buffers of EN 15551 would take in the rest + auto const share{std::clamp((Input.budget - work) / std::max(force * crush, 1e-12), 0.0, 1.0)}; + step *= share; + change *= share; + crush *= share; + spent = true; + } + work += force * crush; + cap = force; // the weaker end gives, both alike when they're alike if (std::abs(force1 - force2) <= 1e-9 * force) { crush1 += 0.5 * crush; @@ -221,14 +280,20 @@ hit_result hit(end_state const &First, end_state const &Second, hit_input const time += step; crushtime += step; result.force = std::max(result.force, force); + if (spent) { + result.spent = true; + rebound = true; + break; + } } auto after{velocity}; auto duration{crushtime}; if (rebound) { // the steel springs back with the restitution, the springs push the pair apart over the rest of the step - // under the force the weaker end gives at, as the slices stopped there - result.force = std::max(result.force, springs + velocity * root); + // under the force the weaker end gives at, as the slices stopped there. a crush stopped at the budget: the + // buffers of EN 15551 would have taken in the rest, its force no more than what crushes the end + result.force = std::max(result.force, result.spent ? std::min(springs + velocity * root, cap) : springs + velocity * root); if (velocity > 0.0) { duration += (1.0 + restitution) * velocity * mass / std::max(velocity * root, 1.0); } @@ -239,6 +304,7 @@ hit_result hit(end_state const &First, end_state const &Second, hit_input const result.duration = std::min(duration, Input.dt); result.crush1 = crush1 - First.crush; result.crush2 = crush2 - Second.crush; + result.work = work; return result; } diff --git a/McZapkie/collision.h b/McZapkie/collision.h index b51fc6561..4964759af 100644 --- a/McZapkie/collision.h +++ b/McZapkie/collision.h @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include #include #include "couplerphysics.h" @@ -17,7 +18,8 @@ http://mozilla.org/MPL/2.0/. // TMoverParameters::CollisionDetect()), as plain functions of the vehicles and the hit: // // crush: once the buffers of the pair are pressed all the way, the underframes carry the rest of the hit, up to the -// force the weaker end gives at. past it the end crushes for good: a short peak of force, then a lower plateau as +// force the weaker end gives at. only the energy the hit brings past what the buffers of EN 15551 of both ends take +// in can crush them (contact_energy): a hit the buffers would take, or the push of a train at a stand, never does. past it the end crushes for good: a short peak of force, then a lower plateau as // the structure folds, then it packs down and stiffens (the force-crush curves of the full scale tests of the FRA: // Tyrell et al., IMECE2002-33247). the hit is an impulse limited to that force over the step, so the force never // goes past it and the depth of the crush is the same with any step; the depth stays with the end @@ -64,6 +66,15 @@ enum class vehicle_kind { // do (2 MN of the crash buffers in service) crush_curve default_crush(vehicle_kind Kind); +// the buffers of EN 15551, by their category +enum class buffer_category { + A, // 105 mm, 30 kJ + B, // 105 mm, 50 kJ + C, // 105 mm, 70 kJ + L, // the long stroke, 150 mm + passenger // 110 mm, of the coaches +}; + // the optional keys of the .fiz for an end (BuffCoupl): what's not given comes from the kind of the vehicle struct end_definition { std::optional peak; // FcrushPeak [N] @@ -75,6 +86,7 @@ struct end_definition { std::optional crash_zone; // CrashZone: built to EN 15227 std::optional anticlimber; // AntiClimber std::optional buffer_height; // BufferHeight, of the empty vehicle above the rail [m] + std::optional buffers; // BufferCategory }; vehicle_kind kind_of(bool Powered, bool Passenger, bool CrashZone); crush_curve crush_of(end_definition const &Definition, vehicle_kind Kind); @@ -85,13 +97,6 @@ double buffer_height(end_definition const &Definition, vehicle_kind Kind, double // ---- the buffers, EN 15551 -enum class buffer_category { - A, // 105 mm, 30 kJ - B, // 105 mm, 50 kJ - C, // 105 mm, 70 kJ - L, // the long stroke, 150 mm - passenger // 110 mm, of the coaches -}; struct buffer_rating { double stroke{0.105}; // [m] double energy{30.0e3}; // dynamic energy of one buffer [J] @@ -101,6 +106,45 @@ buffer_rating rating(buffer_category Category); // over the stroke coupler_physics::spring_curve buffer_curve(buffer_category Category, double Progression); std::optional buffer_category_of(char Name); +// the buffers of an end without the category given: of category A, those of a coach of its own category (EN 15551, +// 30 kJ a buffer either way) +buffer_category default_buffers(vehicle_kind Kind); +// the energy the two buffers of an end take in over their stroke, of the category given or the default of the kind [J] +double buffer_capacity(end_definition const &Definition, vehicle_kind Kind); + +// ---- the energy of a hit, for the crush + +// the energy budget of the crush in a contact of two ends. what a hit brings to the stop of the buffers is the kinetic +// energy of the relative motion of the pair there, and what its buffers took in on the way (the springs of the .fiz, +// which may take less than the buffers of EN 15551 would). the buffers of EN 15551 of both ends take in their +// capacity of it first, the crush may take only the rest: +// budget = 1/2 mu v^2 - max(0, capacity - absorbed) +// over the steps of a crush the crush done already is in neither term, so the crush of the whole hit never takes more +// than the hit brought past the buffers. the train behind the pair pushing it on through the crush brings in more: +// it's in the velocity the pair closes in with in the next step. the buffers take in in the stroke under way: the +// buffers pressed and the pair closing in. springing back they keep what they still hold, so a train pushing at a +// stand never builds up what it feeds into their damping. the buffers pressed all the way from the start of the +// contact took in nothing: vehicles put down inside each other, or knocked onto each other by a hit elsewhere, bring +// in only the kinetic energy they close in with +class contact_energy { +public: + // the step of the pair: whether its buffers press, and all the way; the closing velocity [m/s] and the force + // pressing the buffers [N] at the start of the step; how far they're pressed in [m]; the length of the step [s] + void update(bool Pressed, bool Solid, double Closing, double Force, double Compression, double Dt); + // the crush of the hit took the energy [J] + void crushed(double Work); + // the energy the crush may take now, closing in at the velocity [m/s] with the reduced mass [kg], the buffers of + // both ends taking in the capacity [J]; zero or less, the hit stays elastic + double budget(double Mass, double Closing, double Capacity) const; + // what the buffers took in in the stroke under way [J], and the crush in the contact + double absorbed() const { return m_absorbed; } + double crush_work() const { return m_crushed; } + void reset(); + +private: + double m_absorbed{0.0}; + double m_crushed{0.0}; +}; // ---- the hit past the buffers @@ -121,6 +165,9 @@ struct hit_input { // the closing velocity the pair started the step with, before the forces of the step [m/s]; without it (0), the // velocity with what the springs took off it over the step double start_velocity{0.0}; + // the energy the crush may take at most [J] (contact_energy::budget()); none left, the hit stays elastic, and the + // crush stops once it took it, the rest springs back as the buffers would have taken it + double budget{std::numeric_limits::infinity()}; }; struct hit_result { @@ -131,6 +178,8 @@ struct hit_result { double duration{0.0}; // how long that force acted over the step [s] double crush1{0.0}; // added to the end of the first vehicle [m] double crush2{0.0}; // of the second one + double work{0.0}; // the crush took [J] + bool spent{false}; // the crush stopped at the budget }; // the hit of the step: the steel takes the hit elastically up to the force the weaker end gives at, past that the end diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index c08c714dc..0aa7cb037 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -1,6 +1,7 @@ #include "stdafx.h" #include "doctest.h" #include "consist.h" +#include "drive.h" #include "vehicle.h" #include "McZapkie/collision.h" #include "McZapkie/MOVER.h" @@ -206,6 +207,49 @@ double locomotive_into_wagon(double const Speed, double const Dt) { return wagon->Couplers[end::rear].crush + locomotive->Couplers[end::front].crush; } +// the energy the crush of both ends of the pair took, by their curves [J] +double crush_energy(TMoverParameters const &First, int const FirstEnd, TMoverParameters const &Second, int const SecondEnd) { + return First.crush_curve_at(FirstEnd).energy(0.0, First.Couplers[FirstEnd].crush) + Second.crush_curve_at(SecondEnd).energy(0.0, Second.Couplers[SecondEnd].crush); +} + +// what the buffers of EN 15551 of the two ends take in [J] +double capacity_of(TMoverParameters const &First, int const FirstEnd, TMoverParameters const &Second, int const SecondEnd) { + return cl::buffer_capacity(First.Couplers[FirstEnd].collision, First.collision_kind()) + cl::buffer_capacity(Second.Couplers[SecondEnd].collision, Second.collision_kind()); +} + +// the kinetic energy of the relative motion of two vehicles closing in at the velocity [J] +double relative_energy(TMoverParameters const &First, TMoverParameters const &Second, double const Velocity) { + auto const mass{First.TotalMass * Second.TotalMass / (First.TotalMass + Second.TotalMass)}; + return 0.5 * mass * Velocity * Velocity; +} + +struct contact_outcome { + double crush{0.0}; // of both ends [m] + double energy{0.0}; // the crush took [J] + double available{0.0}; // the kinetic energy of the hit past the buffers of EN 15551 [J] + bool derailed{false}; // either vehicle +}; + +// the second vehicle runs into the rear end of the first one standing, Gap metres short of the hit (negative: the +// buffers pressed that far already), unbraked and alone on the track +contact_outcome contact(definition const &Front, definition const &Back, double const Speed, double const Gap, double const Seconds = 5.0, double const Dt = 0.01) { + consist train; + auto &front{train.add(Front)}; + auto &back{train.add(Back, 0, coupling::faux, Speed, Gap)}; + train.run(Seconds, {}, Dt); + contact_outcome result; + result.crush = front->Couplers[end::rear].crush + back->Couplers[end::front].crush; + result.energy = crush_energy(front.mover(), end::rear, back.mover(), end::front); + result.available = std::max(0.0, relative_energy(front.mover(), back.mover(), Speed * kmh) - capacity_of(front.mover(), end::rear, back.mover(), end::front)); + result.derailed = derailed(front.mover()) || derailed(back.mover()); + return result; +} + +// a coach of data/wagon.json of the given mass without its rotating masses +definition coach(double const Mass) { + return definition::load("wagon").set("Param", "M", Mass); +} + } // namespace // ---- the crush curve @@ -702,3 +746,313 @@ TEST_CASE("collisions: identical units built to EN 15227 at 36 km/h") { CHECK(held.derailed == 0); } } + +// ---- the energy of the hit: what the buffers of EN 15551 take in never crushes (found running every scenario of the +// install: calkowo_v2_kontenera, baltyk_sdm) + +TEST_CASE("collisions: the buffers of EN 15551 of an end take in their energy, of the category given or by the kind") { + CHECK(cl::buffer_capacity({}, cl::vehicle_kind::wagon) == doctest::Approx(60.0e3)); + CHECK(cl::buffer_capacity({}, cl::vehicle_kind::locomotive) == doctest::Approx(60.0e3)); + CHECK(cl::buffer_capacity({}, cl::vehicle_kind::coach) == doctest::Approx(60.0e3)); + CHECK(cl::default_buffers(cl::vehicle_kind::coach) == cl::buffer_category::passenger); + cl::end_definition category_c; + category_c.buffers = cl::buffer_category::C; + CHECK(cl::buffer_capacity(category_c, cl::vehicle_kind::wagon) == doctest::Approx(140.0e3)); + // the key of the .fiz + vehicle wagon{definition::load("wagon").set("BuffCoupl", "BufferCategory", "B")}; + REQUIRE(wagon->Couplers[end::front].collision.buffers.has_value()); + CHECK(*wagon->Couplers[end::front].collision.buffers == cl::buffer_category::B); + CHECK(cl::buffer_capacity(wagon->Couplers[end::rear].collision, wagon->collision_kind()) == doctest::Approx(100.0e3)); +} + +TEST_CASE("collisions: the budget of a contact, by what the hit brings to the buffers") { + cl::contact_energy contact; + // not touching: nothing + contact.update(false, false, 1.0, 0.0, 0.0, 0.01); + CHECK(contact.absorbed() == 0.0); + // pressed in, closing: the springs take in their work + contact.update(true, false, 1.0, 1.0e6, 0.05, 0.01); + CHECK(contact.absorbed() == doctest::Approx(10.0e3)); + // pressed all the way, they take in nothing more + contact.update(true, true, 1.0, 1.4e6, 0.3, 0.01); + CHECK(contact.absorbed() == doctest::Approx(10.0e3)); + // the kinetic energy and what the buffers took, past their capacity + CHECK(contact.budget(40.0e3, 2.0, 60.0e3) == doctest::Approx(0.5 * 40.0e3 * 4.0 + 10.0e3 - 60.0e3)); + // the springs of the .fiz taking in more than the buffers of EN 15551: no more than the kinetic energy + CHECK(contact.budget(40.0e3, 2.0, 5.0e3) == doctest::Approx(0.5 * 40.0e3 * 4.0)); + // springing back they hold no more than their springs pressed in + contact.update(true, false, -0.5, 0.2e6, 0.02, 0.01); + CHECK(contact.absorbed() == doctest::Approx(0.5 * 0.2e6 * 0.02)); + // a train pushing at a stand: the oscillation of the pair never builds the energy up + for (int i = 0; i < 6000; ++i) { + auto const closing{0.05 * std::sin(i * 0.3)}; + contact.update(true, false, closing, 0.3e6 + 1.0e6 * closing, 0.03, 0.01); + } + CHECK(contact.absorbed() < 0.5 * 0.35e6 * 0.03 + 0.35e6 * 0.05 * 0.01 * 12.0); + // parted: a new contact + contact.crushed(5.0e3); + CHECK(contact.crush_work() == doctest::Approx(5.0e3)); + contact.update(false, false, 0.0, 0.0, 0.0, 0.01); + CHECK(contact.absorbed() == 0.0); + CHECK(contact.crush_work() == 0.0); +} + +TEST_CASE("collisions: the crush of a hit takes no more than its energy past the buffers, with any step") { + // two masses at the stop of their buffers from the start (nothing taken in by the springs), the budget of the + // crush taken anew in every step of the hit, as the vehicles take it + struct masses { + double mass1; + double mass2; + }; + constexpr double capacity{120.0e3}; + constexpr double springs{1.2e6}; + for (auto const &[mass1, mass2] : {masses{80.0e3, 80.0e3}, masses{117.0e3, 84.0e3}, masses{300.0e3, 20.0e3}, masses{36.0e3, 41.6e3}}) { + auto const reduced{mass1 * mass2 / (mass1 + mass2)}; + for (auto const speed : {2.0, 5.0, 8.0, 12.0, 20.0, 30.0, 45.0, 60.0}) { + for (auto const dt : {0.001, 0.003, 0.01, 0.02, 0.03}) { + CAPTURE(mass1); + CAPTURE(mass2); + CAPTURE(speed); + CAPTURE(dt); + cl::end_state first{locomotive_curve, 0.0}; + cl::end_state second{wagon_curve, 0.0}; + auto velocity1{speed * kmh}; + auto velocity2{0.0}; + auto work{0.0}; + for (int step = 0; step < 100000; ++step) { + auto const start{velocity1 - velocity2}; + velocity1 -= springs * dt / mass1; + velocity2 += springs * dt / mass2; + auto const closing{velocity1 - velocity2}; + if (closing <= 0.0) { + break; + } + cl::hit_input input; + input.velocity = closing; + input.start_velocity = start; + input.mass1 = mass1; + input.mass2 = mass2; + input.stiffness = 1.4e8; + input.springs = springs; + input.dt = dt; + input.budget = 0.5 * reduced * start * start - capacity; + auto const hit{cl::hit(first, second, input)}; + if (false == hit.crushing) { + break; + } + CHECK(hit.work <= input.budget * (1.0 + 1e-9) + 1e-6); + work += hit.work; + first.crush += hit.crush1; + second.crush += hit.crush2; + velocity1 -= hit.impulse / mass1; + velocity2 += hit.impulse / mass2; + if (hit.velocity <= 0.0) { + break; + } + } + auto const available{std::max(0.0, 0.5 * reduced * (speed * kmh) * (speed * kmh) - capacity)}; + auto const crushed{locomotive_curve.energy(0.0, first.crush) + wagon_curve.energy(0.0, second.crush)}; + CHECK(work <= available + 1.0); + CHECK(crushed <= available * 1.001 + 1.0); + if (available <= 0.0) { + CHECK(first.crush + second.crush == 0.0); + } + } + } + } +} + +TEST_CASE("collisions: the crush of two vehicles takes no more than the energy of the hit past the buffers, with any step") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + struct pair_of { + char const *name; + definition front; + definition back; + }; + for (auto const &[name, front, back] : {pair_of{"EU07 into EU07", definition::fiz("4e_v1/4e"), definition::fiz("4e_v1/4e")}, + pair_of{"SU45 into SM42", definition::fiz("sm42_v1/6d1"), definition::fiz("su45_v2/301d")}, + pair_of{"EU07 into a wagon", definition::fiz("430w_v2/430w"), definition::fiz("4e_v1/4e")}}) { + for (auto const speed : {2.0, 5.0, 10.0, 15.0, 20.0, 30.0, 45.0, 60.0}) { + for (auto const dt : {0.001, 0.01, 0.03}) { + CAPTURE(name); + CAPTURE(speed); + CAPTURE(dt); + auto const result{contact(front, back, speed, 0.5, 4.0, dt)}; + // the explicit steps of the springs before the stop rate what they took in a little off. at 0.03 s, 0.5 m a + // step at 60 km/h, the legacy movement of the vehicles past the stop gives the hit energy of its own (the + // crush goes past what it is at 0.01 s and 0.001 s): the budget doesn't bind there, every step of the hit + // is within it (the test of the hit of two masses above), the same crush as before the budget + CHECK(result.energy <= result.available * (dt > 0.02 ? 1.15 : 1.05) + 5.0e3); + if (result.available <= 0.0) { + CHECK(result.crush == 0.0); + } + } + } + } +} + +TEST_CASE("collisions: two locomotives (117 t and 84 t) touching at walking speed don't crush (calkowo_v2_kontenera)") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + auto const su45{definition::fiz("su45_v2/301d")}; + auto const sm42{definition::fiz("sm42_v1/6d1")}; + { + vehicle check{su45}; + CHECK(check->TotalMass == doctest::Approx(117.0e3).epsilon(0.02)); + } + for (auto const physics : {false, true}) { + CAPTURE(physics); + flag_setting const couplerphysics{Global.coupler_physics, physics}; + flag_setting const everywhere{Global.coupler_physics_all, physics}; + for (auto const speed : {5.0, 5.8, 6.0}) { + CAPTURE(speed); + // a hit from a metre away + { + auto const result{contact(sm42, su45, speed, 1.0)}; + CHECK(result.crush == 0.0); + CHECK_FALSE(result.derailed); + } + // put down by the scenery with the buffers pressed in, up to past their stop, closing in: the log of the run + // had 5.8 km/h at the stop, both ends crushed, deeper hit after hit until both overrode + for (auto const overlap : {0.1, 0.4, 1.0}) { + CAPTURE(overlap); + auto const result{contact(sm42, su45, speed, -overlap, 10.0)}; + CHECK(result.crush == 0.0); + CHECK_FALSE(result.derailed); + } + } + } +} + +TEST_CASE("collisions: two coaches (36 t and 41.6 t) at 8 km/h don't crush, nor run into a wall (baltyk_sdm)") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + auto const light{coach(32.0e3)}; + auto const heavy{coach(37.6e3)}; + { + vehicle check{light}; + MESSAGE("the coaches: ", check->TotalMass / 1000.0, " t and ", vehicle{heavy}->TotalMass / 1000.0, " t"); + } + for (auto const speed : {5.0, 8.0}) { + CAPTURE(speed); + // a hit from a metre away, and one with the buffers pressed all the way already, as the coach knocked onto the + // other one by the hit of the train on the vehicle derailed at the end of the track + for (auto const gap : {1.0, -0.25}) { + CAPTURE(gap); + auto const result{contact(light, heavy, speed, gap)}; + CHECK(result.crush == 0.0); + CHECK_FALSE(result.derailed); + } + } + // the vehicle derailed the legacy way is a wall that the coach runs into + for (auto const gap : {1.0, -0.25}) { + CAPTURE(gap); + consist train; + auto &wall{train.add(light)}; + wall->Derail(END_OF_TRACK); + REQUIRE(derailed(wall.mover())); + auto &running{train.add(heavy, 0, coupling::faux, 5.0, gap)}; + train.run(5.0); + CHECK(wall->Couplers[end::rear].crush + running->Couplers[end::front].crush == 0.0); + CHECK(running->CollisionDerail == NONE); + } +} + +TEST_CASE("collisions: a locomotive pushing a standing braked train at full power doesn't crush") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + test::track const line{0.15, 0.0, test::catenary_3kv}; + // the diesel-electric keeps its full power at a stand (an electric one trips its overload relays there) + for (auto const *path : {"su45_v2/301d"}) { + CAPTURE(path); + consist train; + // four loaded coal wagons, braked in emergency once their brakes are charged + constexpr int wagons{4}; + for (int i = 0; i < wagons; ++i) { + add_mixed(train, 0, consist::full_coupling, 0.0, 0.0).hold_brake_pipe(5.0); + } + train.run(90.0, line); + for (int i = 0; i < wagons; ++i) { + train[i].hold_brake_pipe(0.0); + } + train.run(30.0, line); + // the locomotive behind them, touching, driven forwards into them at full power + auto &locomotive{train.add(definition::fiz(path), 1, coupling::faux, 0.0, 0.0)}; + test::driven const driver{locomotive.mover(), locomotive.mover(), locomotive.mover(), [&train](double const Seconds, test::track const &Track) { train.run(Seconds, Track); }}; + REQUIRE(test::start_up(driver, line)); + test::release_brakes(locomotive.mover()); + for (int i = 0; i < 3 && locomotive->DirActive <= 0; ++i) { + locomotive->DirectionForward(); + } + test::drive(driver, line, 10.0); + auto pushed{0.0}; + auto seconds{0}; // pushing with 100 kN or more + auto const push = [&]() { + auto const force{std::max(0.0, -locomotive->Couplers[end::front].CForce)}; + pushed = std::max(pushed, force); + seconds += force >= 100.0e3; + }; + // the line contactors close at the first position, once their delay and the pressure switch let them + locomotive->IncMainCtrl(1); + for (int i = 0; i < 90 && false == locomotive->StLinFlag; ++i) { + test::drive(driver, line, 1.0); + } + for (int i = 0; i < 60 && false == locomotive->IsMainCtrlMaxPowerPos(); ++i) { + locomotive->IncMainCtrl(1); + test::drive(driver, line, 1.0); + push(); + } + for (int i = 0; i < 60; ++i) { + test::drive(driver, line, 1.0); + push(); + } + MESSAGE(std::format("{}: pushing at up to {:.0f} kN, {} s at 100 kN or more, at {:.1f} km/h at the end", path, pushed / 1000.0, seconds, locomotive.speed())); + CHECK(pushed > 200.0e3); + CHECK(seconds >= 55); + for (std::size_t i = 0; i < train.size(); ++i) { + CAPTURE(i); + CHECK(crush_of(train[i].mover()) == 0.0); + CHECK_FALSE(derailed(train[i].mover())); + } + } +} + +TEST_CASE("collisions: vehicles put down with their buffers pressed in don't crush") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const physics : {false, true}) { + CAPTURE(physics); + flag_setting const couplerphysics{Global.coupler_physics, physics}; + flag_setting const everywhere{Global.coupler_physics_all, physics}; + for (auto const overlap : {0.1, 0.3, 0.6}) { + CAPTURE(overlap); + for (auto const &[front, back] : {std::pair{definition::fiz("sm42_v1/6d1"), definition::fiz("su45_v2/301d")}, std::pair{coach(32.0e3), coach(37.6e3)}, + std::pair{definition::fiz("3wl_v2/3wl"), definition::fiz("4e_v1/4e")}}) { + auto const result{contact(front, back, 0.0, -overlap, 10.0)}; + CHECK(result.crush == 0.0); + CHECK_FALSE(result.derailed); + } + } + } +} + +TEST_CASE("collisions: the monitor goes by the energy of the hit as well") { + flag_setting const crashdamage{Global.crash_damage, true}; + model_setting const monitor{global_settings::collision_model::monitor}; + // a hit the buffers take in: the monitor tells of nothing + for (auto const gap : {1.0, -0.4}) { + CAPTURE(gap); + consist train; + train.add(definition::fiz("sm42_v1/6d1")); + train.add(definition::fiz("su45_v2/301d"), 0, coupling::faux, 5.8, gap); + train.run(5.0); + CHECK(train[0]->crush_reports + train[1]->crush_reports == 0); + } + // one past them it does + consist train; + train.add(definition::fiz("4e_v1/4e")); + train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, 25.0, 20.0); + train.run(10.0); + CHECK(train[0]->crush_reports + train[1]->crush_reports == 1); +} From b5a0a8121d5f93078c415224cb7ff36ba21442ad Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 01:00:36 +0100 Subject: [PATCH 029/136] fix(physics): vehicles put down inside each other don't crush; automatic couplers have no side buffers The rerun of calkowo_v2_kontenera with the energy budget still crushed and overrode its two locomotives, at 9-13 km/h: the scenery puts the SM42 onto the SU45 with their middles 2.7 m apart. The springs at the stops of both ends and the neighbours found at either end shake such a pair up past the energy of the buffers. Pressed past the stop of their buffers and the crush of their ends by more than 0.5 m (more than a hit takes them in a step), the pair is inside each other: no crush, the legacy collision pushes them apart, and the log tells it once (Bad scenery: A and B are inside each other ...). An automatic coupler, or its adapter, has no buffers at the side: its draft gear takes in what its springs of the .fiz do, so the budget leaves no EN 15551 capacity to such a pair. The EN57-2000 hitting a standing one at 20 km/h (en57_2000_crush_new) crushes again. The PoC cases of the energy budget, for the record: 15 km/h straight crushes 3 ends (0.18 m) where it crushed 2 (0.16 m), the same empty pushed off; at 25-40 km/h fewer ends deep in the trains crush on the straight, a few more in the curve, the locomotive overrides in all of them. --- McZapkie/MOVER.h | 2 ++ McZapkie/Mover.cpp | 22 ++++++++++++++++++++-- McZapkie/collision.h | 5 +++++ tests/unit/test_collisions.cpp | 15 +++++++++++++++ 4 files changed, 42 insertions(+), 2 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index a2ae1368c..14eb26224 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -1306,6 +1306,8 @@ struct TCoupling bool crush_monitored{false}; // the energy the contact of the pair brought to its buffers, for the budget of the crush collision::contact_energy contact; + // the log told of the vehicle at this end being inside this one already + bool inside_reported{false}; int sounds{0}; // sounds emitted by the coupling devices bool Render = false; /*ABu: czy rysowac jak zaczepiony sprzeg*/ diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 1efeb597c..f623b933a 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1597,6 +1597,22 @@ bool TMoverParameters::crush_hit(int const End, double const dt) return false; } auto const monitor{Global.collisions == global_settings::collision_model::monitor}; + // put down by the scenery inside each other: pressed past the stop of the buffers and the crush of the ends by more + // than a hit takes them in a step. the legacy collision pushes them apart; their springs, the stops at both ends + // and the neighbours found at either end there make up any closing velocity, not a hit + auto const stop{std::max(thiscoupler.DmaxB + othercoupler.DmaxB, thiscoupler.physics.buffers.travel + othercoupler.physics.buffers.travel) + thiscoupler.crush + othercoupler.crush}; + auto const overlap{-static_cast(Neighbours[End].distance)}; + if (overlap > stop + collision::inside_margin + closing * dt) + { +", Name.c_str(), othervehicle->Name.c_str(), overlap, stop, closing, Neighbours[End].distance, thiscoupler.crush, othercoupler.crush, (int)Derailed, (int)othervehicle->Derailed); + if (false == thiscoupler.inside_reported) + { + thiscoupler.inside_reported = true; + othercoupler.inside_reported = true; + WriteLog(std::format("Bad scenery: {} and {} are inside each other, their buffers pressed {:.2f} m past their stop, no crush", Name, othervehicle->Name, overlap - stop)); + } + return false; + } // a vehicle derailed the legacy way (the end of the track, say) stays where it is, whatever hits it auto const wall{TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none}; auto const otherwall{TestFlag(othervehicle->DamageFlag, dtrain_out) && othervehicle->Derailed == derailment::outcome::none}; @@ -1623,9 +1639,11 @@ bool TMoverParameters::crush_hit(int const End, double const dt) // the monitor takes the whole hit at once, over a second, longer than the crush of any hit lasts input.dt = monitor ? 1.0 : dt; input.start_velocity = thiscoupler.closing; - // the crush takes only what the hit brings past what the buffers of EN 15551 of both ends take in + // the crush takes only what the hit brings past what the buffers of EN 15551 of both ends take in. an automatic + // coupler (or its adapter) has no buffers at the side: its draft gear takes in what its springs of the .fiz do auto const reduced{mass * othermass / (mass + othermass)}; - auto const capacity{collision::buffer_capacity(thiscoupler.collision, collision_kind()) + collision::buffer_capacity(othercoupler.collision, othervehicle->collision_kind())}; + auto const central{thiscoupler.type() == TCouplerType::Automatic || othercoupler.type() == TCouplerType::Automatic || thiscoupler.has_adapter() || othercoupler.has_adapter()}; + auto const capacity{central ? 0.0 : collision::buffer_capacity(thiscoupler.collision, collision_kind()) + collision::buffer_capacity(othercoupler.collision, othervehicle->collision_kind())}; auto const hitvelocity{std::max(closing, thiscoupler.closing)}; input.budget = thiscoupler.contact.budget(reduced, hitvelocity, capacity); auto const hit{collision::hit({firstcurve, thiscoupler.crush}, {secondcurve, othercoupler.crush}, input)}; diff --git a/McZapkie/collision.h b/McZapkie/collision.h index 4964759af..083208d24 100644 --- a/McZapkie/collision.h +++ b/McZapkie/collision.h @@ -112,6 +112,11 @@ buffer_category default_buffers(vehicle_kind Kind); // the energy the two buffers of an end take in over their stroke, of the category given or the default of the kind [J] double buffer_capacity(end_definition const &Definition, vehicle_kind Kind); +// vehicles pressed onto each other past the stop of their buffers and the crush of their ends by more than this, more +// than a hit could have taken them in a step, are inside each other: a scenery put them down overlapping. no hit the +// crush could tell anything of, the legacy collision handles them [m] +inline constexpr double inside_margin{0.5}; + // ---- the energy of a hit, for the crush // the energy budget of the crush in a contact of two ends. what a hit brings to the stop of the buffers is the kinetic diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index 0aa7cb037..803aafa3b 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -925,6 +925,21 @@ TEST_CASE("collisions: two locomotives (117 t and 84 t) touching at walking spee } } +TEST_CASE("collisions: locomotives put down inside each other don't crush, whatever their springs make of them") { + // calkowo_v2_kontenera puts an SM42 on an SU45 with their middles 2.7 m apart: the springs at the stops of both + // ends and the neighbours found at either end shook them up to 9-13 km/h, past the energy of the buffers + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const speed : {0.0, 10.0, 15.0}) { + CAPTURE(speed); + auto const result{contact(definition::fiz("sm42_v1/6d1"), definition::fiz("su45_v2/301d"), speed, -3.0, 10.0)}; + CHECK(result.crush == 0.0); + CHECK_FALSE(result.derailed); + } + // a hit from a distance at the same speeds crushes past the energy of the buffers + CHECK(contact(definition::fiz("sm42_v1/6d1"), definition::fiz("su45_v2/301d"), 20.0, 0.5).crush > 0.0); +} + TEST_CASE("collisions: two coaches (36 t and 41.6 t) at 8 km/h don't crush, nor run into a wall (baltyk_sdm)") { model_setting const physical{global_settings::collision_model::physical}; flag_setting const crashdamage{Global.crash_damage, true}; From 00957a7bb5888fb1c4b67a28939f48669a40d611 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 01:04:05 +0100 Subject: [PATCH 030/136] fix(physics): drop a stray line of a debug print left in crush_hit() It broke the build of b5a0a812. --- McZapkie/Mover.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index f623b933a..ab5a513d0 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1604,7 +1604,6 @@ bool TMoverParameters::crush_hit(int const End, double const dt) auto const overlap{-static_cast(Neighbours[End].distance)}; if (overlap > stop + collision::inside_margin + closing * dt) { -", Name.c_str(), othervehicle->Name.c_str(), overlap, stop, closing, Neighbours[End].distance, thiscoupler.crush, othercoupler.crush, (int)Derailed, (int)othervehicle->Derailed); if (false == thiscoupler.inside_reported) { thiscoupler.inside_reported = true; From c554fff1ae59869e61ba56f024851601ad415d68 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 01:17:08 +0100 Subject: [PATCH 031/136] test(physics): the coaches of the Baltyk case at their masses of the log, 36 t and 41.6 t --- tests/unit/test_collisions.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index 803aafa3b..37d297f9f 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -943,11 +943,12 @@ TEST_CASE("collisions: locomotives put down inside each other don't crush, whate TEST_CASE("collisions: two coaches (36 t and 41.6 t) at 8 km/h don't crush, nor run into a wall (baltyk_sdm)") { model_setting const physical{global_settings::collision_model::physical}; flag_setting const crashdamage{Global.crash_damage, true}; - auto const light{coach(32.0e3)}; - auto const heavy{coach(37.6e3)}; + auto const light{coach(34.3e3)}; + auto const heavy{coach(39.9e3)}; { vehicle check{light}; - MESSAGE("the coaches: ", check->TotalMass / 1000.0, " t and ", vehicle{heavy}->TotalMass / 1000.0, " t"); + CHECK(check->TotalMass == doctest::Approx(36.0e3).epsilon(0.01)); + CHECK(vehicle{heavy}->TotalMass == doctest::Approx(41.6e3).epsilon(0.01)); } for (auto const speed : {5.0, 8.0}) { CAPTURE(speed); @@ -1042,7 +1043,7 @@ TEST_CASE("collisions: vehicles put down with their buffers pressed in don't cru flag_setting const everywhere{Global.coupler_physics_all, physics}; for (auto const overlap : {0.1, 0.3, 0.6}) { CAPTURE(overlap); - for (auto const &[front, back] : {std::pair{definition::fiz("sm42_v1/6d1"), definition::fiz("su45_v2/301d")}, std::pair{coach(32.0e3), coach(37.6e3)}, + for (auto const &[front, back] : {std::pair{definition::fiz("sm42_v1/6d1"), definition::fiz("su45_v2/301d")}, std::pair{coach(34.3e3), coach(39.9e3)}, std::pair{definition::fiz("3wl_v2/3wl"), definition::fiz("4e_v1/4e")}}) { auto const result{contact(front, back, 0.0, -overlap, 10.0)}; CHECK(result.crush == 0.0); From 5ba9876aec334c673ab33eeb5739a438c9c55670 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 01:41:12 +0100 Subject: [PATCH 032/136] fix(physics): count the steps of the search for the climbing speed in whole steps --- McZapkie/derailment.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/McZapkie/derailment.cpp b/McZapkie/derailment.cpp index ed55754b9..01ead60b3 100644 --- a/McZapkie/derailment.cpp +++ b/McZapkie/derailment.cpp @@ -241,7 +241,9 @@ std::optional climbing_speed(vehicle_state const &Vehicle, track_state c } // in steps of 1 m/s up to the first speed it climbs at, which needn't hold above it, then halving the step constexpr double fastest{200.0}; - for (auto low{balancing}; low < fastest; low += 1.0) { + auto const steps{static_cast(std::ceil(fastest - balancing))}; + for (auto step = 0; step < steps; ++step) { + auto low{balancing + step}; auto high{std::min(low + 1.0, fastest)}; if (false == climbs(high)) { continue; From 386a1df9997b5868ba024a9e738d57217607e110 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 07:00:31 +0100 Subject: [PATCH 033/136] test(scenarios): with -j N a case clearing the physicslogs of the game dir runs alone, after the others --- tests/scenarios/README.md | 5 +++-- tests/scenarios/run.py | 29 ++++++++++++++++++++++++----- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index 736e8639a..4dbb7755f 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -143,8 +143,9 @@ Python 3.10+, no extra packages. Options: - `--slow` runs the cases marked `slow` too. Without it, and with no cases named, they are skipped (and listed): each is a whole mission on a big scenery and takes many minutes. A slow case named on the command line always runs. Run them one at a time (`-j 1`): each - simulator loads a whole scenery, and the ones with physicslog on collect every physicslog - written in the game dir meanwhile. + simulator loads a whole scenery. A case on a mission of the base scenery with physicslog on + (`vehicle` given) removes every physicslog written in the game dir meanwhile, so with `-j N` + it runs alone, after the others. - `--seed N` (a number or a word) runs the cases with another seed of the simulator's random numbers (`randomseed`) than the fixed one of the test mode, for a bug that shows up only sometimes: run the case with a few seeds. diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py index cd05866ec..dbe13d869 100644 --- a/tests/scenarios/run.py +++ b/tests/scenarios/run.py @@ -666,6 +666,12 @@ def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool return "XFAIL" +def exclusive_case(case: dict) -> bool: + """A case on a mission of the base scenery with the physicslog on: it removes every physicslog written + while it ran, those of other cases running at the time too, so it has to run alone.""" + return "vehicle" in case and case.get("physicslog", True) + + def _run_case(name: str, case: dict, exe: Path, game_dir: Path, timespeed: float, watch: bool, say, seed: str | None = None) -> bool: say(f"\n=== {name}: {case.get('description', '')}") @@ -719,11 +725,15 @@ def _run_case(name: str, case: dict, exe: Path, game_dir: Path, timespeed: float shutil.move(other, out / other.name) # on a mission of the base scenery every train with a driver logs under its own name, the road vehicles # too (250 files and 740 MB after 900 s of Wrzosy): the ones written in this run are removed, nothing - # checks them (so such a case can't share the game dir with another run at the time) + # checks them (so such a case can't share the game dir with another run at the time: main() runs it + # alone, see exclusive_case()). a file still held open by another simulator is left where it is if own_vehicle and with_physicslog: for other in physicslog.parent.glob("*.dat"): - if other.stat().st_mtime >= started: - other.unlink() + try: + if other.stat().st_mtime >= started: + other.unlink() + except OSError as error: + say(f" left {other.name} in the game dir: {error}") # the black box is named after the case scenery too if result.blackbox: result.blackbox = Path(shutil.move(result.blackbox, out / f"{vehicle}.blackbox")) @@ -834,6 +844,12 @@ def main() -> int: for n in names: results[n] = run_case(n, exe, game_dir, args.timespeed, args.watch, say, args.seed) else: + # a case on a mission of the base scenery removes the physicslogs written while it ran, so it runs + # alone, after the others + alone = [n for n in names if exclusive_case(load_case(n))] + together = [n for n in names if n not in alone] + if alone: + print(f"run alone after the others, they clear the physicslogs of the game dir: {', '.join(alone)}") # each case prints its block when it is done, so parallel output does not interleave def job(n): lines = [] @@ -843,12 +859,15 @@ def main() -> int: status = run_case(n, exe, game_dir, args.timespeed, args.watch, say, args.seed) return n, status, lines with ThreadPoolExecutor(max_workers=args.jobs) as pool: - for n in names: + for n in together: print(f"started {n}", flush=True) - for fut in as_completed([pool.submit(job, n) for n in names]): + for fut in as_completed([pool.submit(job, n) for n in together]): n, status, lines = fut.result() print("\n".join(lines), flush=True) results[n] = status + for n in alone: + results[n] = run_case(n, exe, game_dir, args.timespeed, args.watch, + lambda line, progress=False: print(line, flush=True), args.seed) print(f"\n=== summary ({time.monotonic() - started:.0f}s)") for n in names: From cff1232cce30cd07bf4eb9b597e06a08a6be1c5b Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 07:25:04 +0100 Subject: [PATCH 034/136] refactor: the dates of the scenery wizard and of the editor's backups through std::format, ranges all_of (Sonar S6229, S6197) --- launcher/scenery_wizard.cpp | 4 ++-- scene/scenelayerssave.cpp | 4 ++-- scene/scenenodegroups.cpp | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/launcher/scenery_wizard.cpp b/launcher/scenery_wizard.cpp index 7038415d6..e28c52248 100644 --- a/launcher/scenery_wizard.cpp +++ b/launcher/scenery_wizard.cpp @@ -26,6 +26,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include namespace @@ -400,9 +401,8 @@ bool ui::scenerywizard_panel::create_scenery() return false; } auto const now{std::time(nullptr)}; - char date[32]; std::tm const local{local_tm(now)}; - std::strftime(date, sizeof(date), "%Y-%m-%d", &local); + auto const date{std::format("{:04}-{:02}-{:02}", local.tm_year + 1900, local.tm_mon + 1, local.tm_mday)}; char reference[96]; std::snprintf(reference, sizeof(reference), "//$g PUWG1992 %.3f %.3f", m_map.point().x / 1000.0, m_map.point().y / 1000.0); auto const area{range()}; diff --git a/scene/scenelayerssave.cpp b/scene/scenelayerssave.cpp index 8321c1844..7c0b84241 100644 --- a/scene/scenelayerssave.cpp +++ b/scene/scenelayerssave.cpp @@ -27,6 +27,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/translation.h" #include "editor/editorFormat.hpp" +#include #include #include #include @@ -1667,9 +1668,8 @@ save_result node_layers::save(std::vector const &Rootstatements, st // without the copy nothing is replaced { auto const now{std::time(nullptr)}; - char stamp[32]; std::tm const local{local_tm(now)}; - std::strftime(stamp, sizeof(stamp), "%Y%m%d-%H%M%S", &local); + auto const stamp{std::format("{:04}{:02}{:02}-{:02}{:02}{:02}", local.tm_year + 1900, local.tm_mon + 1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec)}; for (auto const output : written) { auto const filepath{path(output)}; diff --git a/scene/scenenodegroups.cpp b/scene/scenenodegroups.cpp index dd10fc143..e3d1bc463 100644 --- a/scene/scenenodegroups.cpp +++ b/scene/scenenodegroups.cpp @@ -208,7 +208,7 @@ node_groups::update_map() last_switch->track[lastc - 'a'] = track; // all four tracks of the cross switch have to be known before it's assigned - if (!std::all_of(last_switch->track.begin(), last_switch->track.end(), [](TTrack const *Track) { return Track != nullptr; })) + if (!std::ranges::all_of(last_switch->track, [](TTrack const *Track) { return Track != nullptr; })) continue; if (!assign_cross_switch(*last_switch, sw_name, "ac", 0)) From 0e41d27032df27e06c56ba3f4de8fe6ec2787a2e Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 07:44:31 +0100 Subject: [PATCH 035/136] fix(physics): a repaired vehicle is back on the rails, the state of the criteria of derailment cleared resetconsist (Stop and repair consist of the debug panel and of the vehicle window) cleared the damage flags, but kept Derailed, the stretches of the criteria, the distance gathered for them and the report of the monitor. A vehicle once derailed by the criteria and repaired then slid on with their friction after a derailment of the legacy kind, instead of stopping dead, and the friction of the ballast kept holding it whenever it stood. TMoverParameters::rerail() puts a vehicle back on the rails: dtrain_out off, Derailed none, the criteria from scratch, the monitor free to report the track again, a rail vehicle back on the axis of the track. repair_damage() does what resetconsist did to the damage (the flags, the engine damage, the wheel flats, the alarm chain) and rerails it; resetconsist and the road vehicles coming back from the pool of a road point use it. SetDamage taking dtrain_out off rerails the vehicle as well. A vehicle put on a track anew (consistteleport) starts the stretches of the criteria over, they were gathered on the track it left. --- McZapkie/MOVER.h | 5 ++ McZapkie/Mover.cpp | 31 ++++++++ simulation/simulation.cpp | 6 +- tests/unit/test_derailment_vehicle.cpp | 97 ++++++++++++++++++++++++++ vehicle/DynObj.cpp | 3 + world/RoadPoint.cpp | 3 +- 6 files changed, 139 insertions(+), 6 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 1d2280bcc..a6c36168b 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2448,6 +2448,11 @@ class TMoverParameters void derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track, std::string const *TrackName = nullptr); // height of the centre of gravity above the rail with the load [m] double centre_of_gravity() const; + // the vehicle is back on the rails (resetconsist, SetDamage taking dtrain_out off): not derailed any more, and the + // criteria of derailment start from scratch, so a later derailment goes the way its model has it + void rerail(); + // what resetconsist does to a vehicle: no damage of any kind, the alarm chain released, back on the rails + void repair_damage(); // how the vehicle left the rails by the criteria of derailment.h: upright, or on its side. none for any other // derailment, which stops it as the legacy model does derailment::outcome Derailed{derailment::outcome::none}; diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 2dfb8d484..ab42af462 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1584,6 +1584,31 @@ void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::ve ErrorLog("Bad driving: " + Name + " " + derailment::report(Verdict, Vehicle, Track, V, TrackName != nullptr ? *TrackName : std::string{})); } +void TMoverParameters::rerail() +{ + ClearFlag(DamageFlag, dtrain_out); + Derailed = derailment::outcome::none; + derailment_monitor.reset(); + derailment_distance = 0.0; + derailment_reported.reset(); + // back on the axis of the track, which the derailment shifted the vehicle off aside and down (a road vehicle keeps + // its place on the road) + if (TestFlag(CategoryFlag, 1)) + { + OffsetTrackH = 0.0; + OffsetTrackV = 0.0; + } +} + +void TMoverParameters::repair_damage() +{ + DamageFlag = 0; + EngDmgFlag = 0; + WheelFlat = 0.0; + AlarmChainFlag = false; + rerail(); +} + void TMoverParameters::Derail(DerailReason const Reason) { if (SetFlag(DamageFlag, dtrain_out)) @@ -13488,7 +13513,13 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do if (CValue2 == 1) OK = SetFlag(DamageFlag, static_cast(floor(CValue1))); if (CValue2 == -1) + { + auto const derailed{TestFlag(DamageFlag, dtrain_out)}; OK = SetFlag(DamageFlag, static_cast(-floor(CValue1))); + // taking the derailment off puts the vehicle back on the rails, with what the criteria of derailment held + if (derailed && false == TestFlag(DamageFlag, dtrain_out)) + rerail(); + } } else if (Command == "Emergency_brake") { diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp index 87cce81b6..b47bc752b 100644 --- a/simulation/simulation.cpp +++ b/simulation/simulation.cpp @@ -398,12 +398,10 @@ void state_manager::process_commands() { } while (vehicle) { - vehicle->MoverParameters->DamageFlag = 0; - vehicle->MoverParameters->EngDmgFlag = 0; + // no damage, back on the rails with the state of the derailment cleared + vehicle->MoverParameters->repair_damage(); vehicle->MoverParameters->V = 0.000001; // HACK: force vehicle position re-calculation vehicle->MoverParameters->DistCounter = 0.0; - vehicle->MoverParameters->WheelFlat = 0.0; - vehicle->MoverParameters->AlarmChainFlag = false; vehicle->MoverParameters->OffsetTrackH = 0.0; vehicle->MoverParameters->OffsetTrackV = 0.0; diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index 6e8e4661a..d6c94b9b0 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -165,6 +165,103 @@ TEST_CASE("derailment: a stopped derailed vehicle stays put on a gradient") { CHECK(still); } +TEST_CASE("derailment: a repaired vehicle is back on the rails") { + // resetconsist (the debug panel's "Stop and repair consist") clears the damage flags; the state of the criteria + // has to go with them, or a vehicle once derailed by the criteria slides on with their friction after a later + // derailment of any other kind, and the friction of the ballast keeps holding it once it stops + model_setting const physical{global_settings::derailment_model::physical}; + test::track curve; + curve.radius = 300.0; + curve.gradient = 0.02; + vehicle repaired{definition::fiz("4e_v1/4e"), 150.0}; + for (int step = 0; step < 2000; ++step) { + repaired.step(curve); + } + REQUIRE(repaired->Derailed == dr::outcome::overturned); + REQUIRE(repaired->V == 0.0); + repaired->repair_damage(); + CHECK(repaired->DamageFlag == 0); + CHECK(repaired->Derailed == dr::outcome::none); + CHECK(repaired->derailment_distance == 0.0); + CHECK(repaired->OffsetTrackH == 0.0); + CHECK(repaired->OffsetTrackV == 0.0); + + SUBCASE("a derailment of the legacy kind stops it dead, as one never derailed") { + test::track straight; + vehicle fresh{definition::fiz("4e_v1/4e"), 60.0}; + repaired->V = fresh->V; + repaired->AccS = 0.0; + repaired->Derail(TOO_HIGH_SPEED); + fresh->Derail(TOO_HIGH_SPEED); + REQUIRE(repaired->Derailed == dr::outcome::none); + auto const start{fresh->V}; + REQUIRE(start > 10.0); + for (int step = 0; step < 150; ++step) { + repaired.step(straight); + fresh.step(straight); + } + // the legacy model takes g off a derailed vehicle and holds it with a friction 1e20 times its own: 1.1 s from + // 39 km/h. with the friction of the overturned one (half of g on 80 of 96 t) it would still go at 23 km/h + CHECK(fresh->V == doctest::Approx(0.0).epsilon(0.01)); + CHECK(repaired->V == doctest::Approx(fresh->V).epsilon(0.01)); + } + SUBCASE("the friction of the ballast doesn't hold it any more") { + // unbraked on the gradient of 20 per mille it rolls away, at g / 50 less the running resistance + test::track straight; + straight.gradient = 0.02; + for (int step = 0; step < 300; ++step) { + repaired.step(straight); + } + CHECK(std::abs(repaired->V) > 0.4); + CHECK(std::abs(repaired->V) < 3.0 * 0.02 * dr::gravity); + } + SUBCASE("too fast in a curve again it derails again, by the criteria") { + repaired->V = 150.0 * kmh; + curve.gradient = 0.0; + for (int step = 0; step < 20; ++step) { + repaired.step(curve); + } + CHECK(repaired->Derailed == dr::outcome::overturned); + } +} + +TEST_CASE("derailment: SetDamage taking the derailment off puts the vehicle back on the rails") { + model_setting const physical{global_settings::derailment_model::physical}; + test::track curve; + curve.radius = 300.0; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 150.0}; + for (int step = 0; step < 20; ++step) { + eu07vehicle.step(curve); + } + REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned); + // another flag taken off leaves it derailed + eu07vehicle->RunCommand("SetDamage", dtrain_engine, 1); + eu07vehicle->RunCommand("SetDamage", dtrain_engine, -1); + CHECK(eu07vehicle->Derailed == dr::outcome::overturned); + CHECK(eu07vehicle->RunCommand("SetDamage", dtrain_out, -1)); + CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + CHECK(eu07vehicle->Derailed == dr::outcome::none); +} + +TEST_CASE("derailment: monitor tells again on the same track after a repair") { + model_setting const monitor{global_settings::derailment_model::monitor}; + test::track curve; + curve.radius = 300.0; + curve.name = "curve_1"; + auto const critical{dr::overturning_speed(300.0, 0.0, eu07, 1.435) / kmh}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical + 2.0}; + for (int step = 0; step < 100; ++step) { + eu07vehicle.step(curve); + } + REQUIRE(eu07vehicle->derailment_reports == 1); + eu07vehicle->repair_damage(); + CHECK_FALSE(eu07vehicle->derailment_reported.has_value()); + for (int step = 0; step < 100; ++step) { + eu07vehicle.step(curve); + } + CHECK(eu07vehicle->derailment_reports == 2); +} + TEST_CASE("derailment: monitor, the legacy draw decides and the log tells what the criteria would do") { model_setting const monitor{global_settings::derailment_model::monitor}; test::track curve; diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 39ab5c4b6..7f266d099 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -1986,6 +1986,9 @@ void TDynamicObject::place_on_track(TTrack *Track, double fDist, bool Reversed) Axle1.Move((iDirection ? fDist : -fDist) - fAxleDistHalf, false); // false, żeby nie generować eventów break; } + // the stretches the criteria of derailment held over were on the track the vehicle left (consistteleport) + MoverParameters->derailment_monitor.reset(); + MoverParameters->derailment_distance = 0.0; // potrzebne do wyliczenia aktualnej pozycji; nie może być zero, bo nie przeliczy pozycji // teraz jeszcze trzeba przypisać pojazdy do nowego toru, bo przesuwanie początkowe osi nie // zrobiło tego diff --git a/world/RoadPoint.cpp b/world/RoadPoint.cpp index 96eb4814f..ecf39f2ba 100644 --- a/world/RoadPoint.cpp +++ b/world/RoadPoint.cpp @@ -994,8 +994,7 @@ void roadpoint_node::update_spawn(double const Deltatime) auto *vehicle{entry.vehicle}; // it comes back the way it was made: whole, at speed, with the driver told to drive on vehicle->bEnabled = true; - vehicle->MoverParameters->DamageFlag = 0; - vehicle->MoverParameters->EngDmgFlag = 0; + vehicle->MoverParameters->repair_damage(); vehicle->MoverParameters->V = entry.velocity; vehicle->place_on_track(m_lanes.front(), m_offset + 0.5 * vehicle->MoverParameters->Dim.L, false); if (vehicle->Mechanik != nullptr) From 3df78e137ae4bb5cb4bebd227563403620e7f36f Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 07:44:32 +0100 Subject: [PATCH 036/136] fix(physics): trackcheck tells a curve without a speed limit apart from the defects A track without a speed limit of its own was checked at a default 125 km/h and counted as overturning or a tight curve too fast at the default speed: in Tomaszewo 154 such lines, all of them curves with no limit, the tram tracks of the town (29 to 31 m) among them. A curve without a speed limit is no defect: the drivers go by the signals and the timetable there. It now gets a note of its own, "no speed limit set (not a defect): the curve takes at most X km/h, the overturning speed of EU07", only where that is under the top speed of the EU07, and the summary counts these curves apart from the suspicious tracks, with the slowest speed among them. The tight curve too fast needs a speed limit too. Tram tracks have no category of their own (a tram is a vehicle of the trains' category, on their tracks), so they are checked alike. --- tests/unit/test_track_check.cpp | 42 +++++++++-- world/TrackCheck.cpp | 130 +++++++++++++++++++++++--------- world/TrackCheck.h | 24 ++++-- 3 files changed, 144 insertions(+), 52 deletions(-) diff --git a/tests/unit/test_track_check.cpp b/tests/unit/test_track_check.cpp index ce0424d81..f9f015f96 100644 --- a/tests/unit/test_track_check.cpp +++ b/tests/unit/test_track_check.cpp @@ -52,20 +52,35 @@ TEST_CASE("trackcheck: the speed limit of a curve") { SUBCASE("over the overturning speed of the EU07") { auto const found{tc::check(curve(300.0, critical + 5.0))}; CHECK(has(found, tc::kind::overturning)); - CHECK_FALSE(has(found, tc::kind::overturning_default)); + CHECK_FALSE(has(found, tc::kind::unlimited_curve)); + CHECK(found.defective()); CHECK(found.text.find("over the overturning speed of EU07") != std::string::npos); CHECK(found.text.find("speed limit 113 km/h") != std::string::npos); } SUBCASE("the cant raises it") { CHECK(tc::check(curve(300.0, critical + 5.0, 100.0)).empty()); } - SUBCASE("without a speed limit of its own the default one goes, counted apart") { + SUBCASE("without a speed limit of its own it's no defect, the speed it takes is told") { auto const found{tc::check(curve(300.0, -1.0))}; - CHECK(has(found, tc::kind::overturning_default)); + CHECK(has(found, tc::kind::unlimited_curve)); CHECK_FALSE(has(found, tc::kind::overturning)); - CHECK(found.text.find("default speed 125 km/h") != std::string::npos); + CHECK_FALSE(found.defective()); + CHECK_FALSE(tc::is_defect(tc::kind::unlimited_curve)); + CHECK(found.unlimited_speed == doctest::Approx(critical)); + CHECK(found.text.starts_with("no speed limit set (not a defect): the curve takes at most ")); + CHECK(found.text.find(" km/h, the overturning speed of EU07") != std::string::npos); CHECK(found.text.find("speed limit none") != std::string::npos); } + SUBCASE("nor anything when it takes them at the top speed of the EU07") { + CHECK(tc::check(curve(600.0, -1.0)).empty()); + } + SUBCASE("a tram loop of 30 m without a speed limit is no tight curve too fast") { + // the tram tracks of Tomaszewo (tramwaj106...): no category of their own, no speed limit + auto const found{tc::check(curve(30.0, -1.0))}; + CHECK(found.kinds == std::vector{tc::kind::unlimited_curve}); + CHECK(found.unlimited_speed == doctest::Approx(overturning(30.0))); + CHECK(found.unlimited_speed < 40.0); + } SUBCASE("a closed track (speed 0) is not checked") { CHECK(tc::check(curve(100.0, 0.0)).empty()); } @@ -135,23 +150,34 @@ TEST_CASE("trackcheck: the scan of a scenery") { tracks.push_back(curve(0.0, 100.0)); tracks.back().name = "fine"; tracks.back().damage = 2; + tracks.push_back(curve(30.0, -1.0)); + tracks.back().name = "tram_1"; + tracks.push_back(curve(150.0, -1.0)); + tracks.back().name = "siding_1"; std::vector log; auto const summary{tc::scan(tracks, [&](std::string const &Line) { log.push_back(Line); })}; - CHECK(summary.tracks == 4); + CHECK(summary.tracks == 6); + // the curves without a speed limit are told apart from the defects CHECK(summary.suspicious == 2); + CHECK(summary.unlimited == 2); + CHECK(summary.slowest == doctest::Approx(overturning(30.0))); CHECK(summary.count(tc::kind::overturning) == 1); CHECK(summary.count(tc::kind::cant_on_straight) == 1); CHECK(summary.count(tc::kind::tight_curve) == 0); + CHECK(summary.count(tc::kind::unlimited_curve) == 2); // the damage flags are counted, not told track by track CHECK(summary.damage.at(31) == 2); CHECK(summary.damage.at(2) == 1); - REQUIRE(log.size() == 4); + REQUIRE(log.size() == 7); CHECK(log[0].starts_with("trackcheck: fast: speed limit 140 km/h over the overturning speed of EU07")); CHECK(log[1].starts_with("trackcheck: leaning: cant 50 / 50 mm on a straight track")); CHECK(log[1].ends_with("damage 31)")); - CHECK(log[2].starts_with("trackcheck: 4 rail tracks checked, 2 suspicious: overturning 1; flange climbing 0;")); - CHECK(log[3] == "trackcheck: damage flags: 2 on 1; 31 on 2"); + CHECK(log[2].starts_with("trackcheck: tram_1: no speed limit set (not a defect): the curve takes at most ")); + CHECK(log[3].starts_with("trackcheck: siding_1: no speed limit set (not a defect)")); + CHECK(log[4] == "trackcheck: 6 rail tracks checked, 2 suspicious: overturning 1; flange climbing 0; cant on a straight 1; cant too high 0; tight curve too fast 0; uneven out of range 0"); + CHECK(log[5].starts_with("trackcheck: curves without a speed limit: 2 taking the reference vehicles under 125 km/h (not a defect), the slowest at ")); + CHECK(log[6] == "trackcheck: damage flags: 2 on 1; 31 on 2"); for (auto const &line : log) { CHECK(line.starts_with("trackcheck: ")); } diff --git a/world/TrackCheck.cpp b/world/TrackCheck.cpp index 22bc61861..c0661bf2f 100644 --- a/world/TrackCheck.cpp +++ b/world/TrackCheck.cpp @@ -65,6 +65,64 @@ std::string uneven_excess(track_uneven::attribute const &Uneven, settings const return result; } +// what the check of a track found so far +struct collector { + findings &result; + void add(kind const Kind, std::string const &Text) const { + if (std::ranges::find(result.kinds, Kind) == result.kinds.end()) { + result.kinds.push_back(Kind); + } + append(result.text, Text); + } +}; + +derailment::track_state curve_of(track const &Track) { + // with the cant both ends have at the least + auto const cant{std::min(std::abs(Track.cant[0]), std::abs(Track.cant[1]))}; + derailment::track_state result; + result.radius = Track.radius; + result.cant = cant_angle(cant, Track.gauge); + result.gauge = Track.gauge; + return result; +} + +// a speed limit over the speed a reference vehicle overturns or climbs the rail at in the curve +void check_limit(track const &Track, std::vector const &References, collector const &Found) { + auto const curve{curve_of(Track)}; + for (auto const &reference : References) { + auto const overturning{derailment::overturning_speed(curve.radius, curve.cant, reference.vehicle.centre_of_gravity, curve.gauge) * kmh}; + if (overturning > 0.0 && Track.velocity > overturning) { + Found.add(kind::overturning, std::format("speed limit {:.0f} km/h over the overturning speed of {} {:.0f} km/h", Track.velocity, reference.name, overturning)); + } + if (auto const climbing{derailment::climbing_speed(reference.vehicle, curve)}; climbing.has_value() && Track.velocity > *climbing * kmh) { + Found.add(kind::climbing, std::format("speed limit {:.0f} km/h over the flange climbing speed of {} {:.0f} km/h", Track.velocity, reference.name, *climbing * kmh)); + } + } +} + +// a curve without a speed limit: how fast it takes the reference vehicles, when that's under the unlimited velocity +void check_unlimited(track const &Track, std::vector const &References, settings const &Settings, collector const &Found) { + auto const curve{curve_of(Track)}; + auto slowest{Settings.unlimited_velocity}; + std::string what; + for (auto const &reference : References) { + auto const overturning{derailment::overturning_speed(curve.radius, curve.cant, reference.vehicle.centre_of_gravity, curve.gauge) * kmh}; + if (overturning > 0.0 && overturning < slowest) { + slowest = overturning; + what = std::format("the overturning speed of {}", reference.name); + } + if (auto const climbing{derailment::climbing_speed(reference.vehicle, curve)}; climbing.has_value() && *climbing * kmh < slowest) { + slowest = *climbing * kmh; + what = std::format("the flange climbing speed of {}", reference.name); + } + } + if (what.empty()) { + return; + } + Found.result.unlimited_speed = slowest; + Found.add(kind::unlimited_curve, std::format("no speed limit set (not a defect): the curve takes at most {:.0f} km/h, {}", slowest, what)); +} + } // namespace std::vector const &default_references() { @@ -81,10 +139,6 @@ std::string_view name_of(kind const Kind) { return "overturning"; case kind::climbing: return "flange climbing"; - case kind::overturning_default: - return "overturning at the default speed"; - case kind::climbing_default: - return "flange climbing at the default speed"; case kind::cant_on_straight: return "cant on a straight"; case kind::cant_excess: @@ -93,56 +147,48 @@ std::string_view name_of(kind const Kind) { return "tight curve too fast"; case kind::uneven: return "uneven out of range"; + case kind::unlimited_curve: + return "curve without a speed limit"; default: return "?"; } } +bool is_defect(kind const Kind) { + return Kind != kind::unlimited_curve; +} + +bool findings::defective() const { + return std::ranges::any_of(kinds, [](kind const Kind) { return is_defect(Kind); }); +} + findings check(track const &Track, std::vector const &References, settings const &Settings) { findings result; - auto const found = [&](kind const Kind, std::string const &Text) { - if (std::find(result.kinds.begin(), result.kinds.end(), Kind) == result.kinds.end()) { - result.kinds.push_back(Kind); - } - append(result.text, Text); - }; + collector const found{result}; auto const curved{Track.radius > 0.0}; auto const given{Track.velocity >= 0.0}; - auto const velocity{given ? Track.velocity : Settings.default_velocity}; if (Track.plain) { - // the speed in the curve, with the cant both ends have at the least - if (curved && velocity > 0.0) { - auto const cant{std::min(std::abs(Track.cant[0]), std::abs(Track.cant[1]))}; - derailment::track_state track; - track.radius = Track.radius; - track.cant = cant_angle(cant, Track.gauge); - track.gauge = Track.gauge; - for (auto const &reference : References) { - auto const overturning{derailment::overturning_speed(track.radius, track.cant, reference.vehicle.centre_of_gravity, track.gauge) * kmh}; - if (overturning > 0.0 && velocity > overturning) { - found(given ? kind::overturning : kind::overturning_default, - std::format("{} {:.0f} km/h over the overturning speed of {} {:.0f} km/h", given ? "speed limit" : "default speed", velocity, reference.name, overturning)); - } - if (auto const climbing{derailment::climbing_speed(reference.vehicle, track)}; climbing.has_value() && velocity > *climbing * kmh) { - found(given ? kind::climbing : kind::climbing_default, - std::format("{} {:.0f} km/h over the flange climbing speed of {} {:.0f} km/h", given ? "speed limit" : "default speed", velocity, reference.name, *climbing * kmh)); - } - } + // a closed track (speed 0) isn't run on + if (curved && given && Track.velocity > 0.0) { + check_limit(Track, References, found); + } + if (curved && false == given) { + check_unlimited(Track, References, Settings, found); } // cant held over the whole of a straight track: a transition has it at one end only if (false == curved && std::abs(Track.cant[0]) > Settings.straight_cant && std::abs(Track.cant[1]) > Settings.straight_cant && Track.cant[0] * Track.cant[1] > 0.0) { - found(kind::cant_on_straight, std::format("cant {:.0f} / {:.0f} mm on a straight track", Track.cant[0], Track.cant[1])); + found.add(kind::cant_on_straight, std::format("cant {:.0f} / {:.0f} mm on a straight track", Track.cant[0], Track.cant[1])); } - if (curved && velocity > Settings.tight_velocity && Track.radius < Settings.tight_radius) { - found(kind::tight_curve, std::format("radius {:.0f} m with a {} of {:.0f} km/h", Track.radius, given ? "speed limit" : "default speed", velocity)); + if (curved && given && Track.velocity > Settings.tight_velocity && Track.radius < Settings.tight_radius) { + found.add(kind::tight_curve, std::format("radius {:.0f} m with a speed limit of {:.0f} km/h", Track.radius, Track.velocity)); } } if (auto const most{std::max(std::abs(Track.cant[0]), std::abs(Track.cant[1]))}; most > Settings.most_cant) { - found(kind::cant_excess, std::format("cant {:.0f} mm over {:.0f} mm", most, Settings.most_cant)); + found.add(kind::cant_excess, std::format("cant {:.0f} mm over {:.0f} mm", most, Settings.most_cant)); } if (auto const excess{uneven_excess(Track.uneven, Settings)}; false == excess.empty()) { - found(kind::uneven, std::format("uneven {} mm out of range", excess)); + found.add(kind::uneven, std::format("uneven {} mm out of range", excess)); } if (false == result.empty()) { result.text += std::format(" (radius {:.0f} m, cant {:.0f} / {:.0f} mm, speed limit {}, damage {})", Track.radius, Track.cant[0], Track.cant[1], @@ -162,17 +208,27 @@ summary scan(std::vector const &Tracks, sink const &Log, std::vector 0.0) { + ++result.unlimited; + result.slowest = result.slowest > 0.0 ? std::min(result.slowest, found.unlimited_speed) : found.unlimited_speed; + } for (auto const kind : found.kinds) { ++result.counts[static_cast(kind)]; } Log(std::format("trackcheck: {}: {}", track.name.empty() ? std::string{"(none)"} : track.name, found.text)); } std::string counts; - for (std::size_t kind = 0; kind < result.counts.size(); ++kind) { - append(counts, std::format("{} {}", name_of(static_cast(kind)), result.counts[kind])); + for (std::size_t index = 0; index < result.counts.size(); ++index) { + if (auto const kind{static_cast(index)}; is_defect(kind)) { + append(counts, std::format("{} {}", name_of(kind), result.counts[index])); + } } Log(std::format("trackcheck: {} rail tracks checked, {} suspicious: {}", result.tracks, result.suspicious, counts)); + Log(std::format("trackcheck: curves without a speed limit: {} taking the reference vehicles under {:.0f} km/h (not a defect){}", result.unlimited, Settings.unlimited_velocity, + result.unlimited > 0 ? std::format(", the slowest at {:.0f} km/h", result.slowest) : std::string{})); std::string damage; for (auto const &[flags, count] : result.damage) { append(damage, std::format("{} on {}", flags, count)); diff --git a/world/TrackCheck.h b/world/TrackCheck.h index d07b3cb49..e6e99fb2b 100644 --- a/world/TrackCheck.h +++ b/world/TrackCheck.h @@ -23,7 +23,10 @@ http://mozilla.org/MPL/2.0/. // derailment (McZapkie/derailment.h) and the plain rules of the track find suspicious, to the log once the scenery // loaded, so a run can tell a faulty scenery from a faulty simulation. one line for a track with all it found // ("trackcheck: : ..."), and a summary with the count of each kind. the damage flags are only counted: sceneries -// set them for the jolts of a worn track (damage 31 on every track of line 107) +// set them for the jolts of a worn track (damage 31 on every track of line 107). a curve without a speed limit of its +// own is no defect (the drivers go by the signals and the timetable there, the tram loops of a town have none), it is +// only told how fast it takes the reference vehicles, apart from the defects. the rail tracks of trams have no category +// of their own (a tram is a vehicle of the category of the trains, on a track of theirs), so they are checked alike namespace track_check { // a rail track as the check sees it @@ -49,9 +52,9 @@ struct reference { std::vector const &default_references(); struct settings { - // the speed limit of a track which gives none [km/h]: the top speed of the EU07, the trains the default vehicles - // make up run no faster - double default_velocity{125.0}; + // a curve without a speed limit is told of when it takes the reference vehicles slower than this [km/h]: the top + // speed of the EU07, the trains the default vehicles make up run no faster + double unlimited_velocity{125.0}; double most_cant{160.0}; // [mm], 150 the most of the Polish rules (Id-1), and a margin double straight_cant{5.0}; // the cant both ends of a straight track have, past which it's cant without a curve [mm] double tight_radius{40.0}; // a curve tighter than this [m] @@ -63,27 +66,34 @@ struct settings { enum class kind { overturning, // the speed limit is over the speed a reference vehicle overturns at climbing, // or over the one its flange climbs the rail at - overturning_default, // the same with the default speed limit, of a track which gives none - climbing_default, cant_on_straight, // both ends of a straight track have the same cant cant_excess, // over the most cant tight_curve, // a curve tighter than the tight radius with a speed limit over the tight velocity uneven, // the unevenness out of the plausible range + unlimited_curve, // no defect: a curve without a speed limit, which takes the reference vehicles slower than the + // unlimited velocity count_ }; std::string_view name_of(kind Kind); +// whether the kind is a defect of the scenery, rather than a note +bool is_defect(kind Kind); // what the check found on a track struct findings { std::vector kinds; std::string text; // what the log line tells after the name of the track, empty when nothing + double unlimited_speed{0.0}; // the speed a curve without a speed limit takes the reference vehicles at [km/h], 0 when + // not told of bool empty() const { return kinds.empty(); } + bool defective() const; // has a kind which is a defect }; findings check(track const &Track, std::vector const &References = default_references(), settings const &Settings = {}); struct summary { int tracks{0}; // checked - int suspicious{0}; // with a line of their own + int suspicious{0}; // with a defect + int unlimited{0}; // curves without a speed limit told of, defects or not + double slowest{0.0}; // the lowest speed one of them takes the reference vehicles at [km/h], 0 without any std::array(kind::count_)> counts{}; std::map damage; // the tracks of each value of the damage flags, none for 0 int count(kind const Kind) const { return counts[static_cast(Kind)]; } From c774a1ff1c3cff1e2a98de18f848559f6e4fe5a3 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 07:56:12 +0100 Subject: [PATCH 037/136] fix(physics): a pushed wheel climbs the rail over the distance it rolls, not over a time at a stand check_pushed_off() counted the time Y/Q of the leading wheel stayed over the climbing limit, at any speed: a locomotive at its starting effort pressing a braked rake pushed the empty wagon in front of it off the rails in five steps of 0.01 s without it moving, and an 80 t locomotive running onto a free empty 3WL at 9 km/h pushed it off with the half-sine of its buffer springs (565 kN for some 0.06 s, over the climbing limit past about 400 kN in a curve of 150 m). Nadal's limit is that of a wheel rolling under its angle of attack: the creep of the flange contact turns the friction upwards, helping the flange up. A wheel that doesn't roll has the friction against the lift, and with a flange of 70 degrees and a friction over 1 / tan 70 = 0.36 no lateral force gets it up. So the flange now climbs over the distance the wheels roll with Y/Q over the limit without a break, the 2 m window of the criteria of derailment (the window of EN 14363; the climb distance criteria replaced the 50 ms of AAR Chapter XI for the same reason). A hit counts the distance rolled over the time its peak lasted. A push which takes the whole load off the leading wheels lifts them off the rail, rolling or not: that, held for 0.05 s, still derails the vehicle by the time. collision::pushed_forces() gives Y and Q of the wheel (pushed_ratio() their ratio), pushed_monitor counts the climb over the distance and the lift over the time. Tests: both cases of the review stay on the rails (the ST44 pressing at 386 kN, Y/Q 1.29 in a yard curve of 120 m, the 3WL moving 0.11 m; the EU07 at 9 km/h, 565 kN, Y/Q 1.68 for 8 steps), a heavy train propelling an empty 3WL into a braked rake in a curve of 150 m still pushes it off as it slides on. --- McZapkie/MOVER.h | 5 +- McZapkie/Mover.cpp | 34 ++++-- McZapkie/collision.cpp | 37 +++++-- McZapkie/collision.h | 47 +++++--- tests/unit/test_collisions.cpp | 190 +++++++++++++++++++++++++++++++-- 5 files changed, 273 insertions(+), 40 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 8d8ee6e89..3c1b01ec7 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2491,8 +2491,9 @@ class TMoverParameters // velocities took the hit; the legacy collision takes the rest. physics.collisions monitor: the log tells what the // crush of the whole hit would be, once for a hit, nothing changes, and it returns false bool crush_hit(int End, double dt); - // the force pressing the ends pushes the vehicle off the track (physics.collisions new) - void check_pushed_off(double dt); + // the force pressing the ends pushes the vehicle off the track (physics.collisions new), the step travelled the + // Distance [m]: the flange climbs while the wheels roll on + void check_pushed_off(double dt, double Distance); // the vehicle leaves the rails in a collision, the reason told in the log, and slides on as the criteria of // derailment.h have it void derail_in_collision(DerailReason Reason, std::string const &Why); diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 2e5425393..1f6d09875 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1780,7 +1780,7 @@ bool TMoverParameters::crush_hit(int const End, double const dt) return true; } -void TMoverParameters::check_pushed_off(double const dt) +void TMoverParameters::check_pushed_off(double const dt, double const Distance) { if (Global.collisions != global_settings::collision_model::physical || false == Global.crash_damage || TestFlag(DamageFlag, dtrain_out) || false == TestFlag(CategoryFlag, 1) || DebugModeFlag) @@ -1795,7 +1795,9 @@ void TMoverParameters::check_pushed_off(double const dt) vehicle.pivots = BDist; vehicle.axle_base = ADist > 0.0 ? ADist : BDist; - auto holds{false}; + auto climbs{false}; + auto distance{0.0}; + auto lifted{false}; auto duration{0.0}; auto worst{0.0}; auto worstforce{0.0}; @@ -1811,17 +1813,24 @@ void TMoverParameters::check_pushed_off(double const dt) collision::pushed_end pushed; pushed.other_length = other->MoverParameters->Dim.L; pushed.crush = coupler.crush; - // the steady push of the springs over the step, or the peak of a hit for as long as it lasted + // the steady push of the springs over the step, or the peak of a hit for as long as it lasted: the flange climbs + // over the distance the wheels rolled meanwhile, a wheel lifted off the rail goes in a short time, rolling or not for (auto const &[force, time] : {std::pair{compression_at(coupler, end), dt}, std::pair{coupler.hit_force, coupler.hit_duration}}) { pushed.force = force; - auto const ratio{collision::pushed_ratio(vehicle, pushed, RunningShape.R)}; + auto const wheel{collision::pushed_forces(vehicle, pushed, RunningShape.R)}; + auto const ratio{wheel.ratio()}; if (ratio < derailment::climbing_limit) { continue; } - holds = true; - duration = std::max(duration, time); + climbs = true; + distance = std::max(distance, Distance * std::clamp(time / std::max(dt, 1e-9), 0.0, 1.0)); + if (wheel.lifted()) + { + lifted = true; + duration = std::max(duration, time); + } if (ratio > worst) { worst = ratio; @@ -1830,11 +1839,14 @@ void TMoverParameters::check_pushed_off(double const dt) } } } - if (pushed_off_monitor.update(holds, duration)) + if (pushed_off_monitor.update(climbs, distance, lifted, duration)) { - derail_in_collision(COLLISION_PUSHED_OFF, std::format("{:.0f} kN pressing its {} end in for {:.3f} s, at {:.0f} km/h, curve radius {:.0f} m: Y/Q {:.2f} ({:.1f} t {}, {} axles, " + derail_in_collision(COLLISION_PUSHED_OFF, std::format("{:.0f} kN pressing its {} end in, {}, at {:.0f} km/h, curve radius {:.0f} m: Y/Q {:.2f} ({:.1f} t {}, {} axles, " "springs {:.0f} / {:.0f} kN, hits {:.0f} / {:.0f} kN, crushed {:.2f} / {:.2f} m)", - worstforce / 1000.0, end_name(worstend), pushed_off_monitor.time(), Vel, std::abs(RunningShape.R), std::min(worst, 99.0), + worstforce / 1000.0, end_name(worstend), + lifted ? std::format("its wheels lifted off the rail for {:.3f} s", pushed_off_monitor.time()) + : std::format("the flange climbing over {:.2f} m", pushed_off_monitor.distance()), + Vel, std::abs(RunningShape.R), std::min(worst, 99.0), vehicle.mass / 1000.0, kind_name(collision_kind()), vehicle.axles, compression_at(Couplers[end::front], end::front) / 1000.0, compression_at(Couplers[end::rear], end::rear) / 1000.0, Couplers[end::front].hit_force / 1000.0, Couplers[end::rear].hit_force / 1000.0, Couplers[end::front].crush, Couplers[end::rear].crush)); @@ -2135,7 +2147,7 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap for (int b = 0; b < 2; b++) if (Couplers[b].CheckCollision) CollisionDetect(b, dt); // zmienia niejawnie AccS, V !!! - check_pushed_off(dt); + check_pushed_off(dt, std::abs(dL)); } // liczone dL, predkosc i przyspieszenie @@ -2212,7 +2224,7 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh for (int b = 0; b < 2; b++) if (Couplers[b].CheckCollision) CollisionDetect(b, dt); // zmienia niejawnie AccS, V !!! - check_pushed_off(dt); + check_pushed_off(dt, std::abs(dL)); } // liczone dL, predkosc i przyspieszenie auto const d{(EngineType == TEngineType::WheelsDriven ? dL * CabActive : // na chwile dla testu diff --git a/McZapkie/collision.cpp b/McZapkie/collision.cpp index 0abdfdd3b..ef3874b93 100644 --- a/McZapkie/collision.cpp +++ b/McZapkie/collision.cpp @@ -341,9 +341,21 @@ override_result override_of(override_input const &Input) { return result; } +double pushed_wheel::ratio() const { + if (q > 0.0) { + return y / q; + } + return y > 0.0 ? 1e9 : 0.0; +} + double pushed_ratio(pushed_vehicle const &Vehicle, pushed_end const &End, double const Radius) { + return pushed_forces(Vehicle, End, Radius).ratio(); +} + +pushed_wheel pushed_forces(pushed_vehicle const &Vehicle, pushed_end const &End, double const Radius) { + pushed_wheel result; if (Vehicle.mass <= 0.0 || End.force <= 0.0) { - return 0.0; + return result; } auto const axles{static_cast(std::max(Vehicle.axles, 1))}; // the axles of the half of the vehicle at the end: its bogie, or its axle @@ -360,17 +372,24 @@ double pushed_ratio(pushed_vehicle const &Vehicle, pushed_end const &End, double auto const lateral{End.force * angle / half + guiding}; // the force off the height it's carried at pitches the vehicle: the bogie at the end pressed in takes the load off auto const pivots{Vehicle.pivots > 0.0 ? Vehicle.pivots : halflength}; - auto const vertical{wheelload - End.force * eccentricity / (2.0 * half * pivots)}; - return vertical > 0.0 ? lateral / vertical : 1e9; + result.y = lateral; + result.q = wheelload - End.force * eccentricity / (2.0 * half * pivots); + return result; } -bool pushed_monitor::update(bool const Holds, double const Duration) { - if (false == Holds) { - m_time = 0.0; - return false; +bool pushed_monitor::update(bool const Climbs, double const Distance, bool const Lifted, double const Duration) { + auto const climbed{m_climbing.update(Climbs, Distance, climb_distance)}; + if (false == Lifted) { + m_lifted = 0.0; + return climbed; } - m_time += std::max(Duration, 0.0); - return m_time >= pushed_time - 1e-9; + m_lifted += std::max(Duration, 0.0); + return climbed || m_lifted >= lift_time - 1e-9; +} + +void pushed_monitor::reset() { + m_climbing.reset(); + m_lifted = 0.0; } } // namespace collision diff --git a/McZapkie/collision.h b/McZapkie/collision.h index 083208d24..fb719315d 100644 --- a/McZapkie/collision.h +++ b/McZapkie/collision.h @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include #include "couplerphysics.h" +#include "derailment.h" // what a collision of two vehicles does to them past their buffers (physics.collisions new in eu07.ini, see // TMoverParameters::CollisionDetect()), as plain functions of the vehicles and the hit: @@ -29,9 +30,14 @@ http://mozilla.org/MPL/2.0/. // zone of an end is used up // pushed off the track: the force pressing a vehicle's end acts at an angle to it, the more in a curve and the // deeper the end is crushed, which gives a lateral force on its wheels; acting off the height of the centre of the -// vehicle it lifts its leading wheels. Y / Q over Nadal's limit for long enough and the flange climbs the rail -// (the light wagon between heavy ones goes first, in a curve sooner than on a straight track: EN 15566 takes -// 250 kN of the pair of buffers in a curve of 150 m as the safe push) +// vehicle it lifts its leading wheels. Y / Q over Nadal's limit while the wheels roll on over the window of +// EN 14363 and the flange climbs the rail (the light wagon between heavy ones goes first, in a curve sooner than +// on a straight track: EN 15566 takes 250 kN of the pair of buffers in a curve of 150 m as the safe push). a wheel +// which doesn't roll doesn't climb: Nadal's limit is that of a wheel rolling under its angle of attack, the creep of +// the flange contact turning the friction upwards; standing, the friction holds the flange down, and with a flange +// of 70 degrees and a friction over 1 / tan 70 = 0.36 no lateral force gets it up. so a train pushing at a stand, +// or the short peak of the springs of a hit, never pushes a wheel off. a push that takes the whole load off the +// leading wheels lifts them off the rail, rolling or not: that holding for a short time is enough namespace collision { inline constexpr double gravity{9.81}; // [m/s2] @@ -235,8 +241,12 @@ inline constexpr double straight_angle{0.006}; inline constexpr double crush_angle{0.1}; // the height the force acts at off the height it's carried at, the buffers of the pair not at the same height [m] inline constexpr double eccentricity{0.10}; -// the time Y / Q has to stay over the limit for the flange to climb the rail [s] -inline constexpr double pushed_time{0.05}; +// the distance the wheels have to roll with Y / Q over the limit for the flange to climb the rail: the window of the +// criteria of derailment [m] +inline constexpr double climb_distance{derailment::window}; +// the time the push has to hold the leading wheels off the rail, without any load on them, to lift them over the +// rail [s] +inline constexpr double lift_time{0.05}; struct pushed_vehicle { double mass{0.0}; // with the load, without the rotating masses [kg] @@ -250,19 +260,32 @@ struct pushed_end { double other_length{0.0}; // of the vehicle at that end [m] double crush{0.0}; // of the end [m] }; -// Y / Q of the leading wheel at the end pressed in by the force, in a curve of the radius [m] (0 straight) +// the forces of the leading wheel at the end pressed in by the force, in a curve of the radius [m] (0 straight): its +// lateral force, and its vertical one, none or less when the push lifts it off the rail +struct pushed_wheel { + double y{0.0}; // [N] + double q{0.0}; // [N] + double ratio() const; + bool lifted() const { return q <= 0.0 && y > 0.0; } +}; +pushed_wheel pushed_forces(pushed_vehicle const &Vehicle, pushed_end const &End, double Radius); +// Y / Q of that wheel double pushed_ratio(pushed_vehicle const &Vehicle, pushed_end const &End, double Radius); -// the time the condition held, without a break +// the push off the track step by step: how far the wheels rolled with Y / Q over the limit without a break, and how +// long the push held the leading wheels lifted off the rail class pushed_monitor { public: - // true once the condition held for the time it takes the flange to climb, given how long it held in the step [s] - bool update(bool Holds, double Duration); - void reset() { m_time = 0.0; } - double time() const { return m_time; } + // true once the flange climbed the rail, given whether Y / Q held over the limit in the step and the distance the + // wheels rolled while it held [m], and whether the push lifted the wheels and for how long in the step [s] + bool update(bool Climbs, double Distance, bool Lifted, double Duration); + void reset(); + double distance() const { return m_climbing.distance(); } + double time() const { return m_lifted; } private: - double m_time{0.0}; + derailment::stretch m_climbing; + double m_lifted{0.0}; }; } // namespace collision diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index 37d297f9f..53bcd4859 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -250,6 +250,29 @@ definition coach(double const Mass) { return definition::load("wagon").set("Param", "M", Mass); } +// Y / Q of the leading wheel of the vehicle at the end pressed in by its coupling, as check_pushed_off() takes it +double pushed_ratio_of(TMoverParameters const &Vehicle, int const End, double const OtherLength, double const Radius) { + cl::pushed_vehicle pushed; + pushed.mass = Vehicle.TotalMass - Vehicle.Mred; + pushed.axles = Vehicle.NAxles > 0 ? Vehicle.NAxles : 4; + pushed.length = Vehicle.Dim.L; + pushed.pivots = Vehicle.BDist; + pushed.axle_base = Vehicle.ADist > 0.0 ? Vehicle.ADist : Vehicle.BDist; + cl::pushed_end end; + end.force = std::max(0.0, (End == end::front ? -1.0 : 1.0) * Vehicle.Couplers[End].CForce); + end.other_length = OtherLength; + end.crush = Vehicle.Couplers[End].crush; + return cl::pushed_ratio(pushed, end, Radius); +} + +// a loaded 430W coal wagon +vehicle &add_loaded(consist &Train, int const Coupling, double const Velocity, double const Gap) { + auto &wagon{Train.add(definition::fiz("430w_v2/430w"), 0, Coupling, Velocity, Gap)}; + wagon->AssignLoad("coal", 59.5f); + wagon->ComputeMass(); + return wagon; +} + } // namespace // ---- the crush curve @@ -487,12 +510,167 @@ TEST_CASE("collisions: an empty two-axle wagon between loaded ones in a curve of end.force = 600.0e3; CHECK(cl::pushed_ratio(heavy, end, 150.0) < 0.5); - // it has to hold for 0.05 s, however long the steps - cl::pushed_monitor monitor; - CHECK_FALSE(monitor.update(true, 0.03)); - CHECK_FALSE(monitor.update(false, 0.01)); - CHECK_FALSE(monitor.update(true, 0.03)); - CHECK(monitor.update(true, 0.03)); + // past 3 MN on a straight track the push takes the whole load off its leading wheels: they lift off the rail + CHECK_FALSE(cl::pushed_forces(wagon, end, 0.0).lifted()); + end.force = 3.5e6; + CHECK(cl::pushed_forces(wagon, end, 0.0).lifted()); + CHECK(cl::pushed_ratio(wagon, end, 0.0) > 1e8); +} + +TEST_CASE("collisions: the flange climbs while the wheels roll on, a lifted wheel goes in a short time") { + SUBCASE("Y / Q over the limit over 2 m rolled, however long the steps") { + cl::pushed_monitor monitor; + CHECK_FALSE(monitor.update(true, 0.7, false, 0.03)); + CHECK_FALSE(monitor.update(true, 0.7, false, 0.03)); + CHECK(monitor.distance() == doctest::Approx(1.4)); + CHECK(monitor.update(true, 0.7, false, 0.03)); + } + SUBCASE("a break starts it over") { + cl::pushed_monitor monitor; + CHECK_FALSE(monitor.update(true, 1.5, false, 0.03)); + CHECK_FALSE(monitor.update(false, 0.1, false, 0.03)); + CHECK_FALSE(monitor.update(true, 1.5, false, 0.03)); + CHECK(monitor.update(true, 0.5, false, 0.03)); + } + SUBCASE("standing, it never climbs, however long the push holds") { + cl::pushed_monitor monitor; + auto climbed{false}; + for (int step = 0; step < 100000; ++step) { + climbed = climbed || monitor.update(true, 0.0, false, 0.01); + } + CHECK_FALSE(climbed); + CHECK(monitor.distance() == 0.0); + } + SUBCASE("the wheels lifted off the rail for 0.05 s, standing or not") { + cl::pushed_monitor monitor; + CHECK_FALSE(monitor.update(true, 0.0, true, 0.03)); + CHECK_FALSE(monitor.update(false, 0.0, false, 0.01)); + CHECK_FALSE(monitor.update(true, 0.0, true, 0.03)); + CHECK(monitor.update(true, 0.0, true, 0.03)); + } + SUBCASE("a reset clears both") { + cl::pushed_monitor monitor; + monitor.update(true, 1.9, true, 0.04); + monitor.reset(); + CHECK(monitor.distance() == 0.0); + CHECK(monitor.time() == 0.0); + CHECK_FALSE(monitor.update(true, 0.05, true, 0.005)); + } +} + +TEST_CASE("collisions: a locomotive at its starting effort against a braked train doesn't push the empty wagon off at a stand") { + // the reviewer's case: an ST44 pressing a rake with an empty two-axle wagon right in front of it, in a yard curve. + // the push is over the climbing limit of the empty wagon, but nothing rolls: a wheel which doesn't roll doesn't + // climb. the time criterion pushed it off in five steps of 0.01 s. the ST44 gives some 390 kN, at the climbing + // limit of the empty wagon in a curve of 150 m: the yard curve is one of 120 m, to be past it + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + test::track line; + line.radius = 120.0; + consist train; + constexpr int wagons{4}; + for (int i = 0; i < wagons; ++i) { + add_loaded(train, consist::full_coupling, 0.0, 0.0).hold_brake_pipe(5.0); + } + auto &empty{train.add(definition::fiz("3wl_v2/3wl"))}; + empty.hold_brake_pipe(5.0); + train.run(90.0, line); + for (std::size_t i = 0; i < train.size(); ++i) { + train[i].hold_brake_pipe(0.0); + } + train.run(30.0, line); + auto &locomotive{train.add(definition::fiz("st44_v2/m62-1151"), 1, coupling::faux, 0.0, 0.0)}; + test::driven const driver{locomotive.mover(), locomotive.mover(), locomotive.mover(), [&train](double const Seconds, test::track const &Track) { train.run(Seconds, Track); }}; + REQUIRE(test::start_up(driver, line)); + test::release_brakes(locomotive.mover()); + for (int i = 0; i < 3 && locomotive->DirActive <= 0; ++i) { + locomotive->DirectionForward(); + } + test::drive(driver, line, 10.0); + auto const start{empty->DistCounter}; + auto pushed{0.0}; + auto worst{0.0}; + auto const watch = [&]() { + pushed = std::max(pushed, -locomotive->Couplers[end::front].CForce); + worst = std::max(worst, pushed_ratio_of(empty.mover(), end::rear, locomotive->Dim.L, line.radius)); + }; + // the line contactors close at the first position, once their delay and the pressure switch let them + locomotive->IncMainCtrl(1); + for (int i = 0; i < 90 && false == locomotive->StLinFlag; ++i) { + test::drive(driver, line, 1.0); + } + for (int i = 0; i < 60 && false == locomotive->IsMainCtrlMaxPowerPos(); ++i) { + locomotive->IncMainCtrl(1); + test::drive(driver, line, 1.0); + watch(); + } + for (int i = 0; i < 60; ++i) { + test::drive(driver, line, 1.0); + watch(); + } + auto const rolled{(empty->DistCounter - start) * 1000.0}; + MESSAGE(std::format("ST44 pushing at up to {:.0f} kN, the empty 3WL at Y/Q {:.2f}, rolled {:.3f} m", pushed / 1000.0, worst, rolled)); + REQUIRE(worst >= derailment::climbing_limit); + CHECK(rolled < 0.5); + CHECK_FALSE(derailed(empty.mover())); + CHECK(empty->CollisionDerail == NONE); +} + +TEST_CASE("collisions: a locomotive running onto an empty wagon at 9 km/h doesn't push it off with the peak of the springs") { + // the reviewer's case: an 80 t locomotive onto a free empty 3WL in a curve of 150 m. the springs of the buffers + // press past the climbing limit for some 0.06 s, the wagon rolls a few centimetres meanwhile + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + test::track curve; + curve.radius = 150.0; + consist train; + auto &empty{train.add(definition::fiz("3wl_v2/3wl"))}; + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, 9.0, 0.5)}; + auto pushed{0.0}; + auto worst{0.0}; + auto over{0}; // steps past the climbing limit + for (int step = 0; step < 500; ++step) { + train.step(curve); + pushed = std::max(pushed, empty->Couplers[end::rear].CForce); + auto const ratio{pushed_ratio_of(empty.mover(), end::rear, locomotive->Dim.L, curve.radius)}; + worst = std::max(worst, ratio); + over += ratio >= derailment::climbing_limit; + } + MESSAGE(std::format("EU07 at 9 km/h onto the empty 3WL: up to {:.0f} kN, Y/Q {:.2f}, {} steps of 0.01 s past the limit, the wagon at {:.1f} km/h", pushed / 1000.0, worst, over, + empty.speed())); + REQUIRE(worst >= derailment::climbing_limit); + REQUIRE(over >= 5); + CHECK_FALSE(derailed(empty.mover())); + CHECK_FALSE(derailed(locomotive.mover())); +} + +TEST_CASE("collisions: a train propelling an empty wagon into a braked one in a curve pushes it off as it rolls on") { + // the genuine push off: the empty 3WL leading a heavy train at 15 km/h, the train pressing it on into a braked + // rake through the curve while it all slides along + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + test::track curve; + curve.radius = 150.0; + consist train; + constexpr int standing{4}; + for (int i = 0; i < standing; ++i) { + add_loaded(train, consist::full_coupling, 0.0, 0.0).hold_brake_pipe(5.0); + } + train.run(90.0, curve); + for (int i = 0; i < standing; ++i) { + train[i].hold_brake_pipe(0.0); + } + train.run(30.0, curve); + auto &empty{train.add(definition::fiz("3wl_v2/3wl"), 0, coupling::faux, 15.0, 1.0)}; + train.add(definition::fiz("4e_v1/4e"), 0, consist::full_coupling, 15.0, 0.0); + for (int i = 0; i < 6; ++i) { + add_loaded(train, consist::full_coupling, 15.0, 0.0); + } + auto const start{empty->DistCounter}; + train.run(10.0, curve); + MESSAGE(std::format("the empty 3WL: derailed {}, {}, rolled {:.2f} m", derailed(empty.mover()), empty->CollisionDerail == COLLISION_PUSHED_OFF ? "pushed off" : "not pushed off", + (empty->DistCounter - start) * 1000.0)); + CHECK(empty->CollisionDerail == COLLISION_PUSHED_OFF); } // ---- the model of eu07.ini From d9c72e3d7cef083631ff9f7d2c0e804e9eab7171 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 07:56:12 +0100 Subject: [PATCH 038/136] fix(physics): a repaired vehicle has its crushed ends rebuilt and its collision derailment cleared Neither resetconsist nor the repair of a coupler cleared what a collision left: the crush of the ends (which keeps shifting the stop of the buffers in CouplerForce() and in the pair input of the coupler physics, so the next hit of the repaired consist started past it and sooner over the override threshold), the energy of the contact, the hit of the step and the reports of the log; nor the reason of a derailment in a collision and the state of the push off. repair_damage() rebuilds both ends of the vehicle, rerail() clears CollisionDerail and the push off monitor along with the state of the criteria of derailment (so SetDamage taking dtrain_out off does as well), and the repair of a coupler rebuilds its end, the crush past the draw gear having torn it off. --- McZapkie/Mover.cpp | 25 +++++++++++++-- tests/unit/test_collisions.cpp | 58 ++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 2 deletions(-) diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 1f6d09875..14c7fadef 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1856,13 +1856,26 @@ void TMoverParameters::check_pushed_off(double const dt, double const Distance) namespace { -// the coupler as good as new, the vehicle without the coupler damage (and the emergency braking of the torn brake -// hose) once neither of its couplers is broken +// the end as it was built (physics.collisions new): not crushed, and nothing of a contact or a hit kept +void restore_end(TCoupling &Coupler) +{ + Coupler.crush = 0.0; + Coupler.contact.reset(); + Coupler.hit_handled = false; + Coupler.hit_force = 0.0; + Coupler.hit_duration = 0.0; + Coupler.crush_monitored = false; + Coupler.inside_reported = false; +} + +// the coupler as good as new, its end with it (the crush that tore the draw gear off), the vehicle without the coupler +// damage (and the emergency braking of the torn brake hose) once neither of its couplers is broken void repair(TMoverParameters &Vehicle, TCoupling &Coupler) { Coupler.broken = false; Coupler.stretch_duration = 0.f; Coupler.physics_state.couple(); + restore_end(Coupler); if (Vehicle.Couplers[end::front].broken || Vehicle.Couplers[end::rear].broken) { return; @@ -1979,6 +1992,9 @@ void TMoverParameters::rerail() derailment_monitor.reset(); derailment_distance = 0.0; derailment_reported.reset(); + // nor derailed in a collision + CollisionDerail = NONE; + pushed_off_monitor.reset(); // back on the axis of the track, which the derailment shifted the vehicle off aside and down (a road vehicle keeps // its place on the road) if (TestFlag(CategoryFlag, 1)) @@ -1994,6 +2010,11 @@ void TMoverParameters::repair_damage() EngDmgFlag = 0; WheelFlat = 0.0; AlarmChainFlag = false; + // the crushed ends rebuilt + for (auto &coupler : Couplers) + { + restore_end(coupler); + } rerail(); } diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index 53bcd4859..3dead8771 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -673,6 +673,64 @@ TEST_CASE("collisions: a train propelling an empty wagon into a braked one in a CHECK(empty->CollisionDerail == COLLISION_PUSHED_OFF); } +// ---- recovery + +TEST_CASE("collisions: a repaired vehicle has its ends rebuilt and is back on the rails") { + // resetconsist: the crush of the ends shifted the stop of the buffers, the next hit of the repaired consist would + // have started from it; and a vehicle derailed in a collision kept its reason and the state of the push + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + consist train; + auto &wagon{add_loaded(train, coupling::faux, 0.0, 0.0)}; + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, 30.0, 0.5)}; + train.run(3.0); + REQUIRE(wagon->Couplers[end::rear].crush + locomotive->Couplers[end::front].crush > cl::override_crush); + REQUIRE((derailed(wagon.mover()) || derailed(locomotive.mover()))); + for (auto *vehicle : {&wagon, &locomotive}) { + auto &mover{vehicle->mover()}; + mover.repair_damage(); + CHECK(mover.DamageFlag == 0); + CHECK(mover.Derailed == derailment::outcome::none); + CHECK(mover.CollisionDerail == NONE); + CHECK(mover.pushed_off_monitor.distance() == 0.0); + CHECK(mover.pushed_off_monitor.time() == 0.0); + for (auto const &coupler : mover.Couplers) { + CHECK(coupler.crush == 0.0); + CHECK(coupler.contact.absorbed() == 0.0); + CHECK(coupler.contact.crush_work() == 0.0); + CHECK_FALSE(coupler.hit_handled); + CHECK(coupler.hit_force == 0.0); + CHECK_FALSE(coupler.crush_monitored); + CHECK_FALSE(coupler.inside_reported); + } + } +} + +TEST_CASE("collisions: the repair of a coupler torn off by the crush rebuilds its end") { + vehicle wagon{definition::fiz("430w_v2/430w")}; + auto &coupler{wagon->Couplers[end::rear]}; + coupler.crush = 0.3; + coupler.broken = true; + coupler.hit_force = 2.0e6; + SetFlag(wagon->DamageFlag, dtrain_coupling); + REQUIRE(wagon->repair_coupler(end::rear)); + CHECK(coupler.crush == 0.0); + CHECK(coupler.hit_force == 0.0); + CHECK_FALSE(coupler.broken); + CHECK_FALSE(TestFlag(wagon->DamageFlag, dtrain_coupling)); +} + +TEST_CASE("collisions: SetDamage taking the derailment off clears the collision's") { + vehicle wagon{definition::fiz("3wl_v2/3wl")}; + wagon->derail_in_collision(COLLISION_PUSHED_OFF, "test"); + REQUIRE(wagon->CollisionDerail == COLLISION_PUSHED_OFF); + REQUIRE(wagon->Derailed == derailment::outcome::off_rails); + wagon->RunCommand("SetDamage", dtrain_out, -1); + CHECK(wagon->CollisionDerail == NONE); + CHECK(wagon->Derailed == derailment::outcome::none); + CHECK_FALSE(TestFlag(wagon->DamageFlag, dtrain_out)); +} + // ---- the model of eu07.ini TEST_CASE("collisions: the legacy rule with physics.collisions old, the crush with new") { From 3ae8d4e72ed13d9d723ffc4546cfab393eda23d0 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 08:54:00 +0100 Subject: [PATCH 039/136] fix(scripting): typed scenery handles, sandbox keys from eu07.ini only, GCC 13 build - the scenery API (eu07.events) hands out a full userdata of its own locked metatable for each kind of object (event, track, isolated, vehicle, memcell), checked with luaL_checkudata: a handle of another kind, a light userdata or any other value is a Lua error, not an object taken for another. nil stays "no object". one object has one handle while the script holds it, so handles compare and key tables as before. event handlers get their handles built inside lua_cpcall, and nil for no activator - memcell_values keeps its text as a std::string: the text of a number was read from a stack slot popped before use - newproxy is gone from the sandboxed libraries - a config block of a scenery no longer changes what only eu07.ini sets (lua.fulllibraries, execonexit, extcam.cmd/rec, screenshotsdir, network.server/client, zmq.address, motiontelemetry, uart, feedbackmode, feedbackport, python/luascreens/wasm.enabled): kept before its keys are read, put back before FinalizeConfig(), each attempt logged - open_file_library() iterates luaL_Reg instead of a std::pair GCC 13 deduces as a pair of an array and a function --- CMakeLists.txt | 1 + script_screens_doc.md | 13 ++- scripting/lua.cpp | 73 +++++++++----- scripting/lua.h | 4 +- scripting/luasandbox.cpp | 87 ++++++++++++++++- scripting/luasandbox.h | 33 +++++++ simulation/simulationstateserializer.cpp | 5 +- tests/unit/test_ini_only_settings.cpp | 116 +++++++++++++++++++++++ tests/unit/test_lua_sandbox.cpp | 110 ++++++++++++++++++++- utilities/Globals.cpp | 17 +++- utilities/Globals.h | 10 +- utilities/inionlysettings.cpp | 82 ++++++++++++++++ utilities/inionlysettings.h | 55 +++++++++++ 13 files changed, 571 insertions(+), 35 deletions(-) create mode 100644 tests/unit/test_ini_only_settings.cpp create mode 100644 utilities/inionlysettings.cpp create mode 100644 utilities/inionlysettings.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 1b73b0805..eb3e12aff 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -541,6 +541,7 @@ set(CORE_SOURCES "McZapkie/Oerlikon_ESt.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" +"utilities/inionlysettings.cpp" "scripting/ladderlogic.cpp" "scripting/scriptscreenrules.cpp" "scripting/scriptscreenkernels.cpp" diff --git a/script_screens_doc.md b/script_screens_doc.md index 435706fe4..7ebf14caf 100644 --- a/script_screens_doc.md +++ b/script_screens_doc.md @@ -221,7 +221,13 @@ and works with memcells, tracks and vehicles through the table `eu07.events` (`e `os.clock`, `os.difftime` and `os.date` (with the C89 conversions only, `%Y`, `%d`, `%H` and so on). It gets no `io`, the rest of `os`, `ffi`, `debug`, `jit`, `package`, `require`, `dofile`, `load`, `loadfile` or `loadstring`; - a script that fails stops there, the error goes to the log with the file name and line, and the scenery goes on - loading. An event handler that fails is logged with the name of the event, and the simulation goes on. + loading. An event handler that fails is logged with the name of the event, and the simulation goes on; +- the events, tracks, isolated circuits, memcells and vehicles the functions give (`event_find`, `track_find`, + `memcell_find`, the event and the vehicle an event handler gets...) are handles of their kind: equal for the same + object, usable as keys of a table, and taken only where that kind goes. Another kind, or any other value, is an + error (`bad argument #1 to 'memcell_update' (eu07.memcell expected, got userdata)`); `nil`, which the find + functions give for a missing object, is taken as no object, as before. An event run without a vehicle gives its + handler `nil` for the vehicle. Instead of `io`, a scenery script reads and writes files through `eu07`, as the Lua screens read theirs: @@ -257,3 +263,8 @@ again: | key | default | meaning | |---------------------|---------|------------------------------------------------------------------------------------------| | `lua.fulllibraries` | no | yes: the scenery scripts get all of LuaJIT's libraries (`io`, `os`, `ffi`, `require`...), and with them the files and programs of the computer. The Lua screens stay sandboxed | + +Only `eu07.ini` sets it: a `config` block of a scenery doesn't (the log says the key was ignored). Nor does it set +the other keys that would take a scenery out of its sandbox or reach the computer: `execonexit`, `extcam.cmd`, +`extcam.rec`, `screenshotsdir`, `network.server`, `network.client`, `zmq.address`, `motiontelemetry`, `uart`, +`feedbackmode`, `feedbackport`, `python.enabled`, `luascreens.enabled` and `wasm.enabled`. diff --git a/scripting/lua.cpp b/scripting/lua.cpp index 7079bb2c3..2011413b5 100644 --- a/scripting/lua.cpp +++ b/scripting/lua.cpp @@ -18,6 +18,9 @@ lua::lua() // lua.fulllibraries in eu07.ini opens the rest when the scenery loads its first script (interpret()) lua_sandbox::open_safe_libraries(state); lua_sandbox::open_clock_library(state); + // the events, tracks, isolated circuits, vehicles and memcells a script holds: a userdata of a metatable of each + // kind, which the functions check + lua_sandbox::open_handles(state); static constexpr luaL_Reg api[] = { @@ -100,14 +103,33 @@ void lua::unref(lua_State *L, const int ref) luaL_unref(L, LUA_REGISTRYINDEX, ref); } +namespace { + +struct event_call { + int handler; + basic_event *event; + TDynamicObject *activator; +}; + +// calls the handler of the event (event_call) with the handles of the event and its activator (nil when there is none) +int call_handler(lua_State *L) +{ + auto const &call = *static_cast(lua_touserdata(L, 1)); + lua_rawgeti(L, LUA_REGISTRYINDEX, call.handler); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::event, call.event); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::vehicle, call.activator); + lua_call(L, 2, 0); + return 0; +} + +} // namespace + /// Executes the callback function of an event created with `scriptapi_event_create`. void lua::dispatch_event(lua_State *L, const int handler, basic_event *event, const TDynamicObject *activator) { - lua_rawgeti(L, LUA_REGISTRYINDEX, handler); - lua_pushlightuserdata(L, event); - lua_pushlightuserdata(L, const_cast(activator)); - // in protected mode: a handler that fails is logged, and the simulation goes on - if (lua_pcall(L, 2, 0, 0) != 0) { + event_call call{handler, event, const_cast(activator)}; + // in protected mode, the handles made as well: a handler that fails is logged, and the simulation goes on + if (lua_cpcall(L, call_handler, &call) != 0) { auto const *error = lua_tostring(L, -1); ErrorLog("lua: event " + (event ? event->m_name : std::string("?")) + ": " + (error ? error : "unknown error"), logtype::lua); lua_pop(L, 1); @@ -133,12 +155,17 @@ memcell_values lua::get_memcell_values(lua_State *L, int idx) // For negative indices, we need to account for the extra item that is the key name/value extracted from the table. if (idx < 0) idx--; - // no text in the table is an empty one: the memcell and the vehicle take the text as a string + luaL_checktype(L, idx, LUA_TTABLE); + // no text in the table is an empty one: the memcell and the vehicle take the text as a string. copied: the text of + // a number is made on the stack, and gone with it memcell_values mc{"", 0.0, 0.0}; lua_pushstring(L, "str"); lua_gettable(L, idx); - if (lua_isstring(L, -1)) - mc.str = lua_tostring(L, -1); + if (lua_isstring(L, -1)) { + std::size_t length = 0; + auto const *text = lua_tolstring(L, -1, &length); + mc.str.assign(text, length); + } lua_pop(L, 1); lua_pushstring(L, "num1"); lua_gettable(L, idx); @@ -167,7 +194,7 @@ int lua::scriptapi_event_create(lua_State *L) event->m_delayrandom = randomdelay; if (simulation::Events.insert(event)) { - lua_pushlightuserdata(L, event); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::event, event); return 1; } return 0; @@ -179,7 +206,7 @@ int lua::scriptapi_event_find(lua_State *L) basic_event *foundevent = simulation::Events.FindEvent(name); if (foundevent) { - lua_pushlightuserdata(L, foundevent); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::event, foundevent); return 1; } ErrorLog("lua: missing event: " + name); @@ -196,7 +223,7 @@ int lua::scriptapi_event_exists(lua_State *L) int lua::scriptapi_event_getname(lua_State *L) { - auto *event = static_cast(lua_touserdata(L, 1)); + auto *event = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::event); if (event) { lua_pushstring(L, event->m_name.c_str()); @@ -207,8 +234,8 @@ int lua::scriptapi_event_getname(lua_State *L) int lua::scriptapi_event_dispatch(lua_State *L) { - auto *event = static_cast(lua_touserdata(L, 1)); - auto *activator = static_cast(lua_touserdata(L, 2)); + auto *event = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::event); + auto *activator = lua_sandbox::check_handle(L, 2, lua_sandbox::handle_kind::vehicle); double delay = lua_tonumber(L, 3); if (event) simulation::Events.AddToQuery(event, activator, delay); @@ -218,7 +245,7 @@ int lua::scriptapi_event_dispatch(lua_State *L) int lua::scriptapi_event_dispatch_n(lua_State *L) { std::string name = luaL_checkstring(L, 1); - auto *activator = static_cast(lua_touserdata(L, 2)); + auto *activator = lua_sandbox::check_handle(L, 2, lua_sandbox::handle_kind::vehicle); double delay = lua_tonumber(L, 3); basic_event *foundevent = simulation::Events.FindEvent(name); if (foundevent) @@ -234,7 +261,7 @@ int lua::scriptapi_track_find(lua_State *L) TTrack *track = simulation::Paths.find(name); if (track) { - lua_pushlightuserdata(L, track); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::track, track); return 1; } ErrorLog("lua: missing track: " + name); @@ -243,7 +270,7 @@ int lua::scriptapi_track_find(lua_State *L) int lua::scriptapi_track_isoccupied(lua_State *L) { - auto *track = static_cast(lua_touserdata(L, 1)); + auto *track = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::track); if (track) { lua_pushboolean(L, !track->IsEmpty()); @@ -271,7 +298,7 @@ int lua::scriptapi_isolated_find(lua_State *L) TIsolated *isolated = TIsolated::Find(name); if (isolated) { - lua_pushlightuserdata(L, isolated); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::isolated, isolated); return 1; } ErrorLog("lua: missing isolated: " + name); @@ -280,7 +307,7 @@ int lua::scriptapi_isolated_find(lua_State *L) int lua::scriptapi_isolated_isoccupied(lua_State *L) { - auto *isolated = static_cast(lua_touserdata(L, 1)); + auto *isolated = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::isolated); if (isolated) { lua_pushboolean(L, isolated->Busy()); @@ -304,7 +331,7 @@ int lua::scriptapi_isolated_isoccupied_n(lua_State *L) int lua::scriptapi_train_getname(lua_State *L) { - auto *dyn = static_cast(lua_touserdata(L, 1)); + auto *dyn = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::vehicle); if (dyn && dyn->Mechanik) { lua_pushstring(L, dyn->Mechanik->TrainName().c_str()); @@ -315,7 +342,7 @@ int lua::scriptapi_train_getname(lua_State *L) int lua::scriptapi_dynobj_putvalues(lua_State *L) { - auto *dyn = static_cast(lua_touserdata(L, 1)); + auto *dyn = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::vehicle); auto [str, num1, num2] = get_memcell_values(L, 2); if (!dyn) return 0; @@ -333,7 +360,7 @@ int lua::scriptapi_memcell_find(lua_State *L) TMemCell *mc = simulation::Memory.find(str); if (mc) { - lua_pushlightuserdata(L, mc); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::memcell, mc); return 1; } ErrorLog("lua: missing memcell: " + str); @@ -342,7 +369,7 @@ int lua::scriptapi_memcell_find(lua_State *L) int lua::scriptapi_memcell_read(lua_State *L) { - auto *mc = static_cast(lua_touserdata(L, 1)); + auto *mc = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::memcell); push_memcell_values(L, mc); return 1; } @@ -359,7 +386,7 @@ int lua::scriptapi_memcell_read_n(lua_State *L) int lua::scriptapi_memcell_update(lua_State *L) { - auto *mc = static_cast(lua_touserdata(L, 1)); + auto *mc = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::memcell); auto [str, num1, num2] = get_memcell_values(L, 2); if (mc) mc->UpdateValues(str, num1, num2, diff --git a/scripting/lua.h b/scripting/lua.h index a0a2b9333..dc28a01e4 100644 --- a/scripting/lua.h +++ b/scripting/lua.h @@ -3,10 +3,12 @@ #include #include "scripting/luasandbox.h" +#include + class basic_event; class TMemCell; class TDynamicObject; -struct memcell_values { const char *str; double num1; double num2; }; +struct memcell_values { std::string str; double num1; double num2; }; class lua { diff --git a/scripting/luasandbox.cpp b/scripting/luasandbox.cpp index bf6ab3961..16e7f70ba 100644 --- a/scripting/luasandbox.cpp +++ b/scripting/luasandbox.cpp @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "scripting/scriptscreenrules.h" #include +#include #include #include #include @@ -76,8 +77,9 @@ void open_safe_libraries(lua_State *L) open_library(L, luaopen_string, LUA_STRLIBNAME); open_library(L, luaopen_math, LUA_MATHLIBNAME); open_library(L, luaopen_bit, LUA_BITLIBNAME); - // what reaches files or loads code - for (auto const *name : {"dofile", "loadfile", "load", "loadstring", "module", "require"}) + // what reaches files or loads code, and newproxy: a userdata of a metatable of the script's own, whose __gc LuaJIT + // runs without the hooks (the instruction limit of the Lua screens), at any allocation and in lua_close + for (auto const *name : {"dofile", "loadfile", "load", "loadstring", "module", "require", "newproxy"}) { lua_pushnil(L); lua_setglobal(L, name); @@ -430,8 +432,9 @@ void open_file_library(lua_State *L, file_folders const *Folders) lua_pushvalue(L, -1); lua_setglobal(L, "eu07"); } - for (auto const &[name, function] : {std::pair{"read_file", api_read_file}, std::pair{"write_file", api_write_file}, - std::pair{"read_data_file", api_read_data_file}}) + // luaL_Reg, not std::pair: GCC deduces std::pair{"read_file", api_read_file} as a pair of an array and a function + static constexpr luaL_Reg functions[]{{"read_file", api_read_file}, {"write_file", api_write_file}, {"read_data_file", api_read_data_file}}; + for (auto const &[name, function] : functions) { lua_pushlightuserdata(L, const_cast(Folders)); lua_pushcclosure(L, function, 1); @@ -440,4 +443,80 @@ void open_file_library(lua_State *L, file_folders const *Folders) lua_pop(L, 1); } +namespace +{ + +constexpr std::array handle_names{"eu07.event", "eu07.track", "eu07.isolated", "eu07.vehicle", "eu07.memcell"}; +// the addresses are the keys of the handles of each kind in the registry: the objects, to their userdata +constexpr std::array handle_cache_keys{}; + +void *cache_key(handle_kind const Kind) +{ + return const_cast(&handle_cache_keys[static_cast(Kind)]); // NOSONAR: the address is only a key +} + +} // namespace + +char const *handle_name(handle_kind const Kind) +{ + return handle_names[static_cast(Kind)]; +} + +void open_handles(lua_State *L) +{ + for (std::size_t idx = 0; idx < handle_names.size(); ++idx) + { + auto const kind{static_cast(idx)}; + luaL_newmetatable(L, handle_name(kind)); + // getmetatable() of a handle gives this instead of the table + lua_pushboolean(L, 0); + lua_setfield(L, -2, "__metatable"); + lua_pop(L, 1); + // the handles made, weak: a handle the script dropped is collected, and made again when asked for + lua_pushlightuserdata(L, cache_key(kind)); + lua_newtable(L); + lua_createtable(L, 0, 1); + lua_pushliteral(L, "v"); + lua_setfield(L, -2, "__mode"); + lua_setmetatable(L, -2); + lua_rawset(L, LUA_REGISTRYINDEX); + } +} + +void push_handle(lua_State *L, handle_kind const Kind, void *Object) +{ + if (Object == nullptr) + { + lua_pushnil(L); + return; + } + lua_pushlightuserdata(L, cache_key(Kind)); + lua_rawget(L, LUA_REGISTRYINDEX); + lua_pushlightuserdata(L, Object); + lua_rawget(L, -2); + if (false == lua_isnil(L, -1)) + { + // the cache, the handle + lua_remove(L, -2); + return; + } + lua_pop(L, 1); + *static_cast(lua_newuserdata(L, sizeof(void *))) = Object; + luaL_getmetatable(L, handle_name(Kind)); + lua_setmetatable(L, -2); + lua_pushlightuserdata(L, Object); + lua_pushvalue(L, -2); + lua_rawset(L, -4); + lua_remove(L, -2); +} + +void *check_handle(lua_State *L, int const Index, handle_kind const Kind) +{ + if (lua_isnoneornil(L, Index)) + { + return nullptr; + } + return *static_cast(luaL_checkudata(L, Index, handle_name(Kind))); +} + } // namespace lua_sandbox diff --git a/scripting/luasandbox.h b/scripting/luasandbox.h index 5f57c62af..dfb1cd024 100644 --- a/scripting/luasandbox.h +++ b/scripting/luasandbox.h @@ -98,4 +98,37 @@ struct file_folders // Folders, read on every call: Folders is to outlive the state void open_file_library(lua_State *L, file_folders const *Folders); +// the objects of the simulation a scenery script holds (eu07.events): each kind is a userdata of a metatable of its +// own, so a function given the handle of another kind, a light userdata or anything else raises a Lua error, and never +// takes one object for another. the objects outlive the state (the scenery's events, tracks, memcells and isolated +// track circuits, and its vehicles, which the game takes off the tracks but doesn't delete) +enum class handle_kind +{ + event, + track, + isolated, + vehicle, + memcell +}; + +// the name of the metatable of the kind, as the errors give it ("eu07.memcell expected, got userdata") +char const *handle_name(handle_kind Kind); + +// makes the metatables of the handles; once, before the first handle. a script can't reach them (getmetatable gives +// false) +void open_handles(lua_State *L); + +// pushes the handle of Object, of the kind, or nil for nullptr. one object has one handle while the script holds it: +// the handles of an object found twice are equal, and the same key of a table +void push_handle(lua_State *L, handle_kind Kind, void *Object); + +// the object of the handle at Index: nullptr for nil or nothing (what the find functions give for a missing object), +// a Lua error (bad argument) for anything else than a handle of the kind +void *check_handle(lua_State *L, int Index, handle_kind Kind); + +template Type_ *check_handle(lua_State *L, int const Index, handle_kind const Kind) +{ + return static_cast(check_handle(L, Index, Kind)); +} + } // namespace lua_sandbox diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index c39870600..b93c69f2d 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -362,8 +362,9 @@ state_serializer::deserialize_camera( cParser &Input, scene::scratch_data &Scrat void state_serializer::deserialize_config( cParser &Input, scene::scratch_data &Scratchpad ) { - // config parameters (re)definition - Global.ConfigParse( Input ); + // config parameters (re)definition, but for what only eu07.ini sets: programs to run, connections, the sandbox of + // the scripts (utilities/inionlysettings.h) + Global.ConfigParse( Input, config_source::scenery ); if( Global.test.enabled ) { // a scenery doesn't get to turn on what a test keeps off simulation::apply_test_mode_settings(); diff --git a/tests/unit/test_ini_only_settings.cpp b/tests/unit/test_ini_only_settings.cpp new file mode 100644 index 000000000..8ae73fe43 --- /dev/null +++ b/tests/unit/test_ini_only_settings.cpp @@ -0,0 +1,116 @@ +#include "stdafx.h" +#include "doctest.h" + +// the settings only eu07.ini sets (utilities/inionlysettings.h): a config block of a scenery is read by the parser of +// eu07.ini (global_settings::ConfigParse with config_source::scenery), which keeps these as eu07.ini set them, and puts +// them back before FinalizeConfig() acts on any. here the keeping, as ConfigParse does it around the keys of a scenery + +#include "utilities/Globals.h" +#include "utilities/inionlysettings.h" + +#include +#include +#include +#include + +namespace { + +bool listed(std::vector const &Keys, std::string_view const Key) { + return std::ranges::find(Keys, Key) != Keys.end(); +} + +} // namespace + +TEST_CASE("ini only settings: a scenery's config block doesn't give its scripts all libraries") { + auto const settings{std::make_unique()}; + settings->lua_fulllibraries = false; + ini_only_settings const ini{*settings}; + // "config lua.fulllibraries yes endconfig" in the .scn + settings->lua_fulllibraries = true; + auto const changed{ini.restore(*settings)}; + CHECK_FALSE(settings->lua_fulllibraries); + CHECK(changed == std::vector{"lua.fulllibraries"}); +} + +TEST_CASE("ini only settings: what eu07.ini turned on stays on") { + auto const settings{std::make_unique()}; + settings->lua_fulllibraries = true; + settings->python_enabled = false; + ini_only_settings const ini{*settings}; + settings->lua_fulllibraries = false; + settings->python_enabled = true; + auto const changed{ini.restore(*settings)}; + CHECK(settings->lua_fulllibraries); + CHECK_FALSE(settings->python_enabled); + CHECK(changed.size() == 2); +} + +TEST_CASE("ini only settings: a scenery runs no program, opens no connection and switches no runtime back on") { + auto const settings{std::make_unique()}; + settings->luascreens_enabled = false; + settings->wasm_enabled = false; + settings->python_enabled = false; + ini_only_settings const ini{*settings}; + + settings->exec_on_exit = "cmd /c del something"; + settings->extcam_cmd = "evil.exe"; + settings->extcam_rec = "evil.exe"; + settings->screenshot_dir = "C:/Users/Public"; + settings->network_servers.emplace_back("tcp", "0.0.0.0:7424"); + settings->network_client.emplace("tcp", "example.com:7424"); + settings->motiontelemetry_conf.enable = true; + settings->motiontelemetry_conf.address = "example.com"; + settings->iFeedbackMode = 4; + settings->iFeedbackPort = 0x378; + settings->luascreens_enabled = true; + settings->wasm_enabled = true; + settings->python_enabled = true; +#ifdef WITH_UART + settings->uart_conf.enable = true; + settings->uart_conf.port = "COM1"; +#endif +#ifdef WITH_ZMQ + settings->zmq_address = "tcp://*:5555"; +#endif + // and a key a scenery may set + settings->fFriction = 0.5; + + auto const changed{ini.restore(*settings)}; + CHECK(settings->exec_on_exit.empty()); + CHECK(settings->extcam_cmd.empty()); + CHECK(settings->extcam_rec.empty()); + CHECK(settings->screenshot_dir.empty()); + CHECK(settings->network_servers.empty()); + CHECK_FALSE(settings->network_client.has_value()); + CHECK_FALSE(settings->motiontelemetry_conf.enable); + CHECK(settings->motiontelemetry_conf.address.empty()); + CHECK(settings->iFeedbackMode == 1); + CHECK(settings->iFeedbackPort == 0); + CHECK_FALSE(settings->luascreens_enabled); + CHECK_FALSE(settings->wasm_enabled); + CHECK_FALSE(settings->python_enabled); + for (auto const *key : {"execonexit", "extcam.cmd", "extcam.rec", "screenshotsdir", "network.server", "network.client", "motiontelemetry", + "feedbackmode", "feedbackport", "luascreens.enabled", "wasm.enabled", "python.enabled"}) { + CAPTURE(key); + CHECK(listed(changed, key)); + } +#ifdef WITH_UART + CHECK_FALSE(settings->uart_conf.enable); + CHECK(settings->uart_conf.port.empty()); + CHECK(listed(changed, "uart")); +#endif +#ifdef WITH_ZMQ + CHECK(settings->zmq_address.empty()); + CHECK(listed(changed, "zmq.address")); +#endif + // the rest is the scenery's to set + CHECK(settings->fFriction == doctest::Approx(0.5)); +} + +TEST_CASE("ini only settings: nothing changed, nothing to tell") { + auto const settings{std::make_unique()}; + settings->exec_on_exit = "notify.exe"; + ini_only_settings const ini{*settings}; + CHECK(ini.restore(*settings).empty()); + CHECK(settings->exec_on_exit == "notify.exe"); +} diff --git a/tests/unit/test_lua_sandbox.cpp b/tests/unit/test_lua_sandbox.cpp index 344f51c63..bc0753162 100644 --- a/tests/unit/test_lua_sandbox.cpp +++ b/tests/unit/test_lua_sandbox.cpp @@ -65,7 +65,7 @@ bool contains(std::string_view const Text, std::string_view const Part) { TEST_CASE("lua sandbox: no library that reaches files, programs, ffi or the debugger, and nothing that loads code") { sandboxed_state const lua; for (auto const *name : {"io", "ffi", "debug", "package", "jit", "require", "module", "dofile", "loadfile", "load", "loadstring", - "string.dump", "os.execute", "os.exit", "os.remove", "os.rename", "os.getenv", "os.tmpname", + "newproxy", "string.dump", "os.execute", "os.exit", "os.remove", "os.rename", "os.getenv", "os.tmpname", "os.setlocale"}) { CAPTURE(name); CHECK(lua.run(std::format("return {}", name)) == "nil"); @@ -424,4 +424,112 @@ TEST_CASE("lua sandbox: the file functions make eu07 when there is none") { CHECK(lua.run("return eu07.read_file('x.txt')") == "nil"); } +TEST_CASE("lua sandbox: no userdata of the script's own, whose __gc would run without the hooks") { + sandboxed_state const lua; + CHECK(lua.run("return newproxy") == "nil"); + // a table's __gc isn't called (Lua 5.1, LuaJIT): no other way to a finalizer of the script's own + CHECK(lua.run("collected = false setmetatable({}, { __gc = function() collected = true end }) collectgarbage() collectgarbage() return collected") == + "false"); +} + +namespace { + +// two objects of the simulation, of which a script holds handles +int memcell_object{1}; +int track_object{2}; + +// eu07.test_memcell(handle): the number of the memcell object, nil for none; eu07.test_track(handle) likewise +int test_memcell(lua_State *L) { + auto const *object{lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::memcell)}; + if (object == nullptr) { + lua_pushnil(L); + } else { + lua_pushnumber(L, *object); + } + return 1; +} + +int test_track(lua_State *L) { + auto const *object{lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::track)}; + if (object == nullptr) { + lua_pushnil(L); + } else { + lua_pushnumber(L, *object); + } + return 1; +} + +// a state with the handles, the functions above, and the globals memcell, track (handles), memcell2 (the memcell's +// handle pushed again) and light (a light userdata, which a script can't make, as the game gave them before) +class handle_state : public sandboxed_state { + public: + handle_state() { + auto *L{get()}; + lua_sandbox::open_handles(L); + lua_register(L, "test_memcell", test_memcell); + lua_register(L, "test_track", test_track); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::memcell, &memcell_object); + lua_setglobal(L, "memcell"); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::memcell, &memcell_object); + lua_setglobal(L, "memcell2"); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::track, &track_object); + lua_setglobal(L, "track"); + // the address of the memcell as a handle of another kind: told apart all the same + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::track, &memcell_object); + lua_setglobal(L, "memcell_as_track"); + lua_pushlightuserdata(L, &memcell_object); + lua_setglobal(L, "light"); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::event, nullptr); + lua_setglobal(L, "none"); + } +}; + +} // namespace + +TEST_CASE("lua sandbox: a handle of the scenery api reaches the object of its kind") { + handle_state const lua; + CHECK(lua.run("return test_memcell(memcell)") == "1"); + CHECK(lua.run("return test_track(track)") == "2"); + CHECK(lua.run("return type(memcell)") == "userdata"); + // what the find functions give for a missing object, and what the functions take as no object + CHECK(lua.run("return none") == "nil"); + CHECK(lua.run("return test_memcell(nil)") == "nil"); + CHECK(lua.run("return test_memcell()") == "nil"); + // one object, one handle: equal, and the same key of a table + CHECK(lua.run("return rawequal(memcell, memcell2)") == "true"); + CHECK(lua.run("local t = { [memcell] = 'cell' } return t[memcell2]") == "cell"); + CHECK(lua.run("return rawequal(memcell, memcell_as_track)") == "false"); + // the handle of a dropped handle is made again + REQUIRE_FALSE(luaL_dostring(lua.get(), "memcell = nil memcell2 = nil collectgarbage() collectgarbage()")); + lua_sandbox::push_handle(lua.get(), lua_sandbox::handle_kind::memcell, &memcell_object); + lua_setglobal(lua.get(), "memcell"); + CHECK(lua.run("return test_memcell(memcell)") == "1"); +} + +TEST_CASE("lua sandbox: a handle of another kind, or anything else, is a Lua error and not an object") { + handle_state const lua; + // a track where a memcell goes (memcell_update(track_find(...)) once wrote into a track as a memcell). not a tail + // call, which LuaJIT gives no function name in the message + CHECK(contains(lua.run("local r = test_memcell(track) return r"), "bad argument #1 to 'test_memcell' (eu07.memcell expected, got userdata)")); + CHECK(contains(lua.run("local r = test_track(memcell) return r"), "bad argument #1 to 'test_track' (eu07.track expected, got userdata)")); + CHECK(contains(lua.run("return test_memcell(memcell_as_track)"), "eu07.memcell expected")); + CHECK(contains(lua.run("return test_memcell(light)"), "eu07.memcell expected, got userdata")); + for (auto const *value : {"1", "'memcell'", "{}", "true", "false", "print", "coroutine.create(function() end)"}) { + CAPTURE(value); + CHECK(contains(lua.run(std::format("return test_memcell({})", value)), "eu07.memcell expected")); + } + // the error is the script's: caught by pcall, and the state goes on + CHECK(lua.run("return (pcall(test_memcell, track))") == "false"); + CHECK(lua.run("return test_memcell(memcell)") == "1"); +} + +TEST_CASE("lua sandbox: a script can't reach the metatable of a handle") { + handle_state const lua; + CHECK(lua.run("return getmetatable(memcell)") == "false"); + CHECK(contains(lua.run("local r = setmetatable(memcell, {}) return r"), "bad argument #1 to 'setmetatable' (table expected, got userdata)")); + // no field to read or write + CHECK(contains(lua.run("return memcell.x"), "attempt to index")); + CHECK(contains(lua.run("memcell.x = 1"), "attempt to index")); +} + #endif diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 2b5684dab..9ac0f3bff 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationenvironment.h" #include "vehicle/Driver.h" #include "utilities/Logs.h" +#include "utilities/inionlysettings.h" #include "utilities/utilities.h" #include "Console.h" #include "scripting/PyInt.h" @@ -957,7 +958,8 @@ bool global_settings::ConfigParseScriptScreens(cParser& Parser, std::string_view } // the scenery scripts (lua in the .scn) with all of LuaJIT's libraries, for a scenery that needs io, ffi or - // require: they then reach files and programs as the player does + // require: they then reach files and programs as the player does. from eu07.ini only: a config block of the + // scenery doesn't change it (utilities/inionlysettings.h) if (token == "lua.fulllibraries") { ParseOne(Parser, lua_fulllibraries, 1); @@ -1451,8 +1453,10 @@ bool global_settings::ConfigParseDebug(cParser& Parser, const std::string& token return false; } -void global_settings::ConfigParse(cParser& Parser) +void global_settings::ConfigParse(cParser& Parser, config_source const Source) { + // what a scenery doesn't change, kept before its keys are read + std::optional const inionly{Source == config_source::scenery ? std::make_optional(*this) : std::nullopt}; std::string token; do @@ -1507,6 +1511,15 @@ void global_settings::ConfigParse(cParser& Parser) } while (true); + if (inionly.has_value()) + { + // put back before FinalizeConfig() acts on them (feedbackmode) + for (auto const key : inionly->restore(*this)) + { + ErrorLog("scenery config: \"" + std::string(key) + "\" is read from eu07.ini only, ignored"); + } + } + FinalizeConfig(); } diff --git a/utilities/Globals.h b/utilities/Globals.h index 25c7872c8..f77bd65de 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -25,6 +25,12 @@ http://mozilla.org/MPL/2.0/. #include "input/zmq_input.h" #endif +// where the keys global_settings::ConfigParse reads come from +enum class config_source { + ini, // eu07.ini, and the file given with -ini + scenery // a config block of a scenery (.scn, .inc), read as it loads +}; + struct global_settings { // members // data items @@ -403,7 +409,9 @@ struct global_settings { // methods void LoadIniFile( std::string asFileName ); void FinalizeConfig(); - void ConfigParse(cParser &parser); + // the keys of eu07.ini. Source: where they come from, eu07.ini or a config block of a scenery, which doesn't change + // the settings only eu07.ini sets (utilities/inionlysettings.h) + void ConfigParse(cParser &parser, config_source Source = config_source::ini); bool ConfigParseGeneral(cParser& Parser, const std::string& token); bool ConfigParseAudio(cParser& Parser, const std::string& token); bool ConfigParseGraphics(cParser& Parser, const std::string& token); diff --git a/utilities/inionlysettings.cpp b/utilities/inionlysettings.cpp new file mode 100644 index 000000000..836954bf1 --- /dev/null +++ b/utilities/inionlysettings.cpp @@ -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/. +*/ + +#include "stdafx.h" +#include "utilities/inionlysettings.h" + +namespace +{ + +// puts Kept back into Current, and adds Key to Changed when they differed +template void keep(Type_ &Current, Type_ const &Kept, std::string_view const Key, std::vector &Changed) +{ + if (false == (Current == Kept)) + { + Current = Kept; + Changed.push_back(Key); + } +} + +} // namespace + +ini_only_settings::ini_only_settings(global_settings const &Settings) + : m_exec_on_exit{Settings.exec_on_exit}, m_screenshot_dir{Settings.screenshot_dir}, m_extcam_cmd{Settings.extcam_cmd}, + m_extcam_rec{Settings.extcam_rec}, m_network_servers{Settings.network_servers}, m_network_client{Settings.network_client}, +#ifdef WITH_ZMQ + m_zmq_address{Settings.zmq_address}, +#endif + m_motiontelemetry{Settings.motiontelemetry_conf}, +#ifdef WITH_UART + m_uart{Settings.uart_conf}, +#endif + m_feedback_mode{Settings.iFeedbackMode}, m_feedback_port{Settings.iFeedbackPort}, m_python_enabled{Settings.python_enabled}, + m_luascreens_enabled{Settings.luascreens_enabled}, m_lua_fulllibraries{Settings.lua_fulllibraries}, m_wasm_enabled{Settings.wasm_enabled} +{ +} + +std::vector ini_only_settings::restore(global_settings &Settings) const +{ + std::vector changed; + keep(Settings.exec_on_exit, m_exec_on_exit, "execonexit", changed); + keep(Settings.screenshot_dir, m_screenshot_dir, "screenshotsdir", changed); + keep(Settings.extcam_cmd, m_extcam_cmd, "extcam.cmd", changed); + keep(Settings.extcam_rec, m_extcam_rec, "extcam.rec", changed); + keep(Settings.network_servers, m_network_servers, "network.server", changed); + keep(Settings.network_client, m_network_client, "network.client", changed); +#ifdef WITH_ZMQ + keep(Settings.zmq_address, m_zmq_address, "zmq.address", changed); +#endif + // the structures as a whole, told apart by what turns them on and where they lead + { + auto ¤t{Settings.motiontelemetry_conf}; + if (current.enable != m_motiontelemetry.enable || current.proto != m_motiontelemetry.proto || current.address != m_motiontelemetry.address || + current.port != m_motiontelemetry.port) + { + changed.emplace_back("motiontelemetry"); + } + current = m_motiontelemetry; + } +#ifdef WITH_UART + { + auto ¤t{Settings.uart_conf}; + if (current.enable != m_uart.enable || current.port != m_uart.port) + { + changed.emplace_back("uart"); + } + current = m_uart; + } +#endif + keep(Settings.iFeedbackMode, m_feedback_mode, "feedbackmode", changed); + keep(Settings.iFeedbackPort, m_feedback_port, "feedbackport", changed); + keep(Settings.python_enabled, m_python_enabled, "python.enabled", changed); + keep(Settings.luascreens_enabled, m_luascreens_enabled, "luascreens.enabled", changed); + keep(Settings.lua_fulllibraries, m_lua_fulllibraries, "lua.fulllibraries", changed); + keep(Settings.wasm_enabled, m_wasm_enabled, "wasm.enabled", changed); + return changed; +} diff --git a/utilities/inionlysettings.h b/utilities/inionlysettings.h new file mode 100644 index 000000000..eff5c067f --- /dev/null +++ b/utilities/inionlysettings.h @@ -0,0 +1,55 @@ +/* +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 "utilities/Globals.h" + +#include +#include +#include +#include +#include + +// the settings only eu07.ini sets. a scenery's config block is read by the parser of eu07.ini +// (state_serializer::deserialize_config, global_settings::ConfigParse), and with these keys it would run a program +// (execonexit, extcam.cmd, extcam.rec), write the screenshots elsewhere (screenshotsdir), open connections and ports +// (network.server, network.client, zmq.address, motiontelemetry, uart, feedbackmode, feedbackport), switch back on a +// script runtime the player switched off (python.enabled, luascreens.enabled, wasm.enabled) or take its own scripts +// out of the sandbox (lua.fulllibraries). they keep what eu07.ini set +class ini_only_settings +{ + public: + // what Settings holds now, as eu07.ini set it + explicit ini_only_settings(global_settings const &Settings); + + // puts back into Settings what changed since, and gives the keys of eu07.ini whose settings changed + std::vector restore(global_settings &Settings) const; + + private: + std::string m_exec_on_exit; + std::string m_screenshot_dir; + std::string m_extcam_cmd; + std::string m_extcam_rec; + std::vector> m_network_servers; + std::optional> m_network_client; +#ifdef WITH_ZMQ + std::string m_zmq_address; +#endif + motiontelemetry::conf_t m_motiontelemetry; +#ifdef WITH_UART + uart_input::conf_t m_uart; +#endif + int m_feedback_mode; + int m_feedback_port; + bool m_python_enabled; + bool m_luascreens_enabled; + bool m_lua_fulllibraries; + bool m_wasm_enabled; +}; From 8201ccb3b040d4b76247529f74e64b74d4cfd266 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 08:54:29 +0100 Subject: [PATCH 040/136] fix(scripting): hold what runs without the hook in the Lua screens - no newproxy: LuaJIT runs a __gc without the hook, at any allocation and in lua_close, so a looping finalizer hung the worker. a table's __gc isn't run, ffi isn't opened: the screens have no finalizer of their own - render and init of the script's table are read inside the protected, counted call, as is the state table of a refresh: an __index that fails or loops switches the screen off instead of ending the program, and one that gives render works - string.find, match, gmatch and gsub are refused when the steps they may take at worst (script_screens::lua_pattern_cost) are over 1e8, about a tenth of a second of LuaJIT's backtracking - a screen holds at most 128 MB, its heap and the pixels of its images, fonts and sprites: the hook checks it with a full collection, the api reserves pixels before making them, and string.format, table.concat and string.gsub refuse a result over it from the lengths of their arguments. where LuaJIT takes an allocator of the game's (2.1 GC64) the heap gets one that refuses past twice the limit, which also stops a single large concatenation; LuaJIT 2.0 on x64 takes none - xpcall is made in Lua on top of pcall, so a coroutine yields across it - the limits go into limit_libraries(), apart from opening the libraries --- script_screens_doc.md | 30 ++ scripting/luaprogram.cpp | 492 +++++++++++++++++++++---- scripting/scriptscreenprogram.h | 11 + scripting/scriptscreenrules.cpp | 109 ++++++ scripting/scriptscreenrules.h | 15 + tests/unit/test_script_screen_host.cpp | 251 +++++++++++++ tests/unit/test_script_screens.cpp | 42 +++ 7 files changed, 886 insertions(+), 64 deletions(-) diff --git a/script_screens_doc.md b/script_screens_doc.md index 52ccc9ced..3919cda7d 100644 --- a/script_screens_doc.md +++ b/script_screens_doc.md @@ -137,6 +137,36 @@ used: - on the cpu, in the screens' worker, when the renderer can't do it on the gpu (the NVRHI renderer, OpenGL ES, a shader that failed to load) or `screens.gpupost` is 0. A shader that fails is logged once, and the cpu takes over. +### Limits of a Lua script + +Besides the 200 million instructions of a call, a Lua screen is held to what runs in C, where the count doesn't reach: + +- memory: a screen holds at most 128 MB: its Lua heap and the pixels of its images, fonts and sprites (4 bytes a pixel + of an image, 1 of a font or a sprite). An object that would take the screen over is refused (`memory limit + exceeded`), and a screen found holding more stops with that error. Garbage doesn't count: the check collects it + first. Where LuaJIT takes an allocator of the game's (2.1 in its GC64 mode), anything over twice the limit is refused + as it is asked for (`not enough memory`); the game's LuaJIT 2.0 on 64-bit Windows takes none, and there the heap is + checked every thousand instructions and before the calls below, but a single concatenation (`a .. b`) of large + strings is made whole first; +- `string.rep` makes no string over 1 MB; `string.format`, `table.concat` and `string.gsub` (with a string or a table to + replace with) refuse a result that may be over the memory of a screen, counted from the lengths of what they are + given; +- the pattern functions (`string.find`, `match`, `gmatch`, `gsub`) backtrack, and some patterns take hours on a long + subject (`("a"):rep(1e6):find(".-b")`). A call is refused (`the pattern may take too long`) when the steps it may + take at worst are over 100 million, about a tenth of a second at worst: the length of the subject (plus one), times the + length of the pattern, times the subject again for each repetition (`*`, `+`, `-`, `%b`, a back reference `%1`) but + a last one that ends the pattern, times 2 for each `?`, and taken once rather than from every position for a pattern + anchored with `^` (not in `gmatch`). A plain search (`find` with `plain`, or a pattern of no special characters) is + the subject times the pattern. So a pattern ending in its only repetition (`"[^ +]+"`, `"%d+"`) works on any subject, + one more repetition (`"(%w+)=(%w+)"`, `"%s+$"`) on some 3 000 to 5 000 bytes, and each further one divides that + a lot; +- `xpcall` is made of `pcall`: the handler gets the error once it has left the function, and a coroutine may yield + inside either. There is no `newproxy`, so no finalizer (`__gc`) of the script's own: LuaJIT runs those without the + instruction count; +- the game reads `render` and `init` of the script's table in protected mode, so a metatable of the script's + (`__index`) may provide them; one that fails or runs over switches the screen off. + ## WebAssembly modules A module exports: diff --git a/scripting/luaprogram.cpp b/scripting/luaprogram.cpp index 4e3c0eea4..9a5de6c9e 100644 --- a/scripting/luaprogram.cpp +++ b/scripting/luaprogram.cpp @@ -8,14 +8,18 @@ http://mozilla.org/MPL/2.0/. */ // the Lua screens: scripts run by LuaJIT, each screen in a state of its own, with the eu07 table of -// script_screens_doc.md. the state has no io, os, ffi, debug or require, reads files only through eu07 and below the -// script's folder, takes no precompiled code, and runs without the JIT compiler, so that the instruction count hook -// can stop a script stuck in a loop (LuaJIT calls no hooks in compiled code) +// script_screens_doc.md. the state has no io, os, ffi, debug, require or newproxy, reads files only through eu07 and +// below the script's folder, takes no precompiled code, and runs without the JIT compiler, so that the instruction +// count hook can stop a script stuck in a loop (LuaJIT calls no hooks in compiled code). what runs in C without the +// hook is held to limits of its own: the pattern functions to the steps they may take, what makes large strings and +// images to the memory of the screen. the game reads the script's table in protected mode, as its metamethods may +// fail #include "stdafx.h" #include "scripting/scriptscreenprogram.h" #include "scripting/scriptscreendrawing.h" #include "scripting/scriptscreenkernels.h" +#include "scripting/scriptscreenrules.h" #include "utilities/Logs.h" #include "utilities/dictionary.h" @@ -27,9 +31,11 @@ http://mozilla.org/MPL/2.0/. #include #include +#include #include #include #include +#include #include #include #include @@ -50,6 +56,47 @@ constexpr char sprite_metatable[]{"eu07.sprite"}; // the address is the key of the program in the registry of its state constexpr char program_key{0}; +// the memory of a screen: what its Lua heap holds, when the allocator counts it, and the pixels of its images, fonts +// and sprites, which the objects keep outside the heap +struct screen_memory +{ + std::size_t heap{0}; + std::size_t objects{0}; + bool counted{false}; // the state was made with limited_alloc + bool enforced{false}; // a call into the script is in progress: the allocator refuses what goes over the limit + // what the screen holds when it is checked next (lua_program::over_memory) with a full collection + std::size_t collect_at{max_screen_memory}; +}; + +// the allocator of a screen's state (lua_newstate), which refuses a block that would take the screen over twice +// max_screen_memory (what it holds, and its garbage between the collections) while a call into the script is in +// progress: LuaJIT raises "not enough memory" there, in the protected call. the game's own work between the calls isn't +// refused, as it isn't protected +void *limited_alloc(void *Data, void *Block, std::size_t Old, std::size_t New) +{ + auto &memory{*static_cast(Data)}; + if (Block == nullptr) + { + Old = 0; + } + if (New == 0) + { + std::free(Block); + memory.heap -= Old; + return nullptr; + } + if (New > Old && memory.enforced && memory.heap - Old + New + memory.objects > 2 * max_screen_memory) + { + return nullptr; + } + auto *result{std::realloc(Block, New)}; + if (result != nullptr) + { + memory.heap = memory.heap - Old + New; + } + return result; +} + class lua_program final : public program { public: @@ -79,6 +126,13 @@ class lua_program final : public program bool commands_ignored{false}; // a screen outside the cab tried to send a command, and it was logged output_limits output; std::int64_t budget{0}; // instructions left to the call in progress + char const *stopped{nullptr}; // why the call in progress is being stopped: the hook raises it at every instruction + screen_memory memory; + + // true when the screen would hold more than max_screen_memory with Adding bytes more. checked with a full collection + // once it has made a quarter of the limit since the last one, so a screen near its limit isn't collected over and + // over + bool over_memory(lua_State *L, std::size_t Adding); private: // calls what's on the stack, with the instruction limit. logs a failure @@ -99,6 +153,24 @@ lua_program *program_of(lua_State *L) return self; } +bool lua_program::over_memory(lua_State *L, std::size_t const Adding) +{ + auto const used{[this, L] { + auto const heap{memory.counted ? memory.heap + : static_cast(lua_gc(L, LUA_GCCOUNT, 0)) * 1024 + static_cast(lua_gc(L, LUA_GCCOUNTB, 0))}; + return heap + memory.objects; + }}; + if (used() + Adding <= memory.collect_at) + { + return false; + } + // what is garbage doesn't count + lua_gc(L, LUA_GCCOLLECT, 0); + auto const held{used()}; + memory.collect_at = std::max(max_screen_memory, held + max_screen_memory / 4); + return held + Adding > max_screen_memory; +} + void count_hook(lua_State *L, lua_Debug * /*Debug*/) { auto *self{program_of(L)}; @@ -106,27 +178,58 @@ void count_hook(lua_State *L, lua_Debug * /*Debug*/) { return; } - self->budget -= hook_interval; - if (self->budget < 0) + if (self->stopped == nullptr) + { + self->budget -= hook_interval; + if (self->budget < 0) + { + self->stopped = "instruction limit exceeded"; + } + else if (self->over_memory(L, 0)) + { + // what the allocator doesn't refuse (where the screen has none of its own) is caught here + self->stopped = "memory limit exceeded"; + } + } + if (self->stopped != nullptr) { // from now on the hook runs at every instruction, and raises the error again. a script that catches it (pcall, // xpcall, coroutine.resume) gets it again at its next instruction, so the error comes out of every level of the // script in turn, and the call ends. run() sets the interval back for the next call. the hook is the state's, // shared by its coroutines lua_sethook(L, count_hook, LUA_MASKCOUNT, 1); - luaL_error(L, "instruction limit exceeded"); + luaL_error(L, "%s", self->stopped); + } +} + +// raises a Lua error when the screen can't take Bytes more: called before an object of the api is made +void reserve_memory(lua_State *L, std::size_t const Bytes) +{ + if (auto *self{program_of(L)}; self != nullptr && self->over_memory(L, Bytes)) + { + luaL_error(L, "memory limit exceeded (%d MB)", static_cast(max_screen_memory / (1024 * 1024))); } } // objects of the api ------------------------------------------------------------------------------------------------- +// where the userdata of an object keeps the bytes it counts in the screen's memory, after the object +template constexpr std::size_t charge_offset{(sizeof(Type_) + alignof(std::size_t) - 1) / alignof(std::size_t) * alignof(std::size_t)}; + // puts the object in a new userdata with the metatable, left on the stack: an rvalue is moved in, an lvalue copied. -// what's stored is the plain type (no reference, no const), the one collect<> and check_object<> are given -template std::remove_cvref_t *push_object(lua_State *L, Type_ &&Object, char const *Metatable) +// what's stored is the plain type (no reference, no const), the one collect<> and check_object<> are given. Bytes: what +// the object holds outside the heap (its pixels), counted in the screen's memory until it is collected, and checked +// with reserve_memory() before the object was made +template std::remove_cvref_t *push_object(lua_State *L, Type_ &&Object, char const *Metatable, std::size_t const Bytes) { using object_type = std::remove_cvref_t; - auto *memory{lua_newuserdata(L, sizeof(object_type))}; + auto *memory{static_cast(lua_newuserdata(L, charge_offset + sizeof(std::size_t)))}; auto *object{new (memory) object_type(std::forward(Object))}; + std::memcpy(memory + charge_offset, &Bytes, sizeof(Bytes)); + if (auto *self{program_of(L)}; self != nullptr) + { + self->memory.objects += Bytes; + } luaL_getmetatable(L, Metatable); lua_setmetatable(L, -2); return object; @@ -152,9 +255,15 @@ template int collect(lua_State *L) { if (auto *object{test_object(L, 1, Metatable_)}; object != nullptr) { + std::size_t bytes{0}; + std::memcpy(&bytes, reinterpret_cast(object) + charge_offset, sizeof(bytes)); object->~Type_(); lua_pushnil(L); lua_setmetatable(L, 1); + if (auto *self{program_of(L)}; self != nullptr) + { + self->memory.objects -= std::min(bytes, self->memory.objects); + } } return 0; } @@ -217,6 +326,28 @@ struct lua_image } }; +// the pixels an image holds: as drawn, and as its post-processing leaves it +std::size_t image_bytes(int const Width, int const Height, int const Finalwidth, int const Finalheight) +{ + auto const drawn{static_cast(Width) * static_cast(Height)}; + auto const done{Width == Finalwidth && Height == Finalheight ? 0 : static_cast(Finalwidth) * static_cast(Finalheight)}; + return (drawn + done) * 4; +} + +std::size_t image_bytes(lua_image const &Image) +{ + return image_bytes(Image.drawn.width(), Image.drawn.height(), Image.width(), Image.height()); +} + +// a new image, Image a step further, counted in the screen's memory +void push_image_then(lua_State *L, lua_image const &Image, post_step const &Step) +{ + reserve_memory(L, image_bytes(Image.drawn.width(), Image.drawn.height(), width_after(Step, Image.width()), height_after(Step, Image.height()))); + auto next{Image.then(Step)}; + auto const bytes{image_bytes(next)}; + push_object(L, std::move(next), image_metatable, bytes); +} + lua_image &check_lua_image(lua_State *L, int const Index) { return check_object(L, Index, image_metatable); @@ -310,7 +441,9 @@ int api_image(lua_State *L) luaL_argcheck(L, valid_image_side(width), 1, "between 1 and 4096"); luaL_argcheck(L, valid_image_side(height), 2, "between 1 and 4096"); auto const color{lua_isnoneornil(L, 3) ? rgb{0, 0, 0} : check_color(L, 3)}; - push_object(L, lua_image{canvas{width, height, color}, {}}, image_metatable); + auto const bytes{image_bytes(width, height, width, height)}; + reserve_memory(L, bytes); + push_object(L, lua_image{canvas{width, height, color}, {}}, image_metatable, bytes); return 1; } @@ -325,9 +458,12 @@ int api_font(lua_State *L) auto const description{read_screen_file(self->folder, std::string{path} + ".txt")}; if (image.has_value() && description.has_value()) { + // the glyphs keep a bit of each pixel; a byte is counted + auto const bytes{static_cast(image->width) * static_cast(image->height)}; + reserve_memory(L, bytes); if (auto font{bitmap_font::parse(image->pixels, image->width, image->height, *description)}; font.has_value()) { - push_object(L, std::move(*font), font_metatable); + push_object(L, std::move(*font), font_metatable, bytes); loaded = true; } } @@ -348,7 +484,9 @@ int api_sprite(lua_State *L) { if (auto const image{read_png(self->folder, std::string{path} + ".png")}; image.has_value()) { - push_object(L, bitmap_font::sprite(image->pixels, image->width, image->height), sprite_metatable); + auto const bytes{static_cast(image->width) * static_cast(image->height)}; + reserve_memory(L, bytes); + push_object(L, bitmap_font::sprite(image->pixels, image->width, image->height), sprite_metatable, bytes); loaded = true; } } @@ -598,7 +736,7 @@ int image_led_post(lua_State *L) post_step step; step.type = post_step::kind::led; step.bloom = bloom; - push_object(L, image.then(step), image_metatable); + push_image_then(L, image, step); return 1; } @@ -614,14 +752,16 @@ int image_resize(lua_State *L) step.type = post_step::kind::resize; step.width = width; step.height = height; - push_object(L, image.then(step), image_metatable); + push_image_then(L, image, step); return 1; } int image_copy(lua_State *L) { auto const &image{check_lua_image(L, 1)}; - push_object(L, lua_image{image}, image_metatable); + auto const bytes{image_bytes(image)}; + reserve_memory(L, bytes); + push_object(L, lua_image{image}, image_metatable, bytes); return 1; } @@ -715,36 +855,198 @@ int api_repeat(lua_State *L) return 1; } -// xpcall(f, handler, ...). LuaJIT calls the handler where the error was raised, before the stack unwinds: for the error -// of the instruction hook that is while the hook still runs, when no hook is called, so a handler that loops would never -// be stopped. here f runs under pcall (the upvalue), and the handler is called, under pcall as well, once the error -// has left f. a script has no debug library to look at the stack with, so the handler gets what it got before -int api_xpcall(lua_State *L) +// the functions of the libraries that make a string in one call, around the library's own (the upvalue): refused when +// the result may be over the memory of a screen. what they make otherwise is counted with the rest of the heap +int too_large(lua_State *L, char const *Function) +{ + return luaL_error(L, "%s: the result may be over the memory of a screen (%d MB)", Function, static_cast(max_screen_memory / (1024 * 1024))); +} + +// calls the library's own function, the upvalue, with the arguments, and returns what it returns +int call_library(lua_State *L) { - auto const arguments{lua_gettop(L)}; - luaL_checkany(L, 2); lua_pushvalue(L, lua_upvalueindex(1)); - lua_pushvalue(L, 1); - for (int idx = 3; idx <= arguments; ++idx) + lua_insert(L, 1); + lua_call(L, lua_gettop(L) - 1, LUA_MULTRET); + return lua_gettop(L); +} + +// string.format: no longer than the format and its arguments, each string as %q writes it (a character as up to 4, +// "\0" as "\000"), anything else in at most 512 characters +int api_format(lua_State *L) +{ + std::size_t length{0}; + luaL_checklstring(L, 1, &length); + auto total{static_cast(length)}; + for (int idx = 2; idx <= lua_gettop(L); ++idx) { - lua_pushvalue(L, idx); + total += lua_type(L, idx) == LUA_TSTRING ? 4.0 * static_cast(lua_objlen(L, idx)) : 512.0; } - lua_call(L, arguments - 1, LUA_MULTRET); - if (lua_toboolean(L, arguments + 1) != 0) + if (total > static_cast(max_screen_memory)) { - // true and the results of f - return lua_gettop(L) - arguments; + return too_large(L, "string.format"); + } + return call_library(L); +} + +// table.concat: the items and the separators between them. the items are read as the library reads them, up to the +// first one that isn't a string or a number, on which the library raises its error +int api_concat(lua_State *L) +{ + luaL_checktype(L, 1, LUA_TTABLE); + std::size_t separator{0}; + luaL_optlstring(L, 2, "", &separator); + auto const first{luaL_optinteger(L, 3, 1)}; + auto const last{lua_isnoneornil(L, 4) ? static_cast(lua_objlen(L, 1)) : luaL_checkinteger(L, 4)}; + auto total{0.0}; + for (auto idx = first; idx <= last; ++idx) + { + lua_rawgeti(L, 1, static_cast(idx)); + auto const type{lua_type(L, -1)}; + // a number in at most 32 characters + total += (type == LUA_TSTRING ? static_cast(lua_objlen(L, -1)) : 32.0) + (idx > first ? static_cast(separator) : 0.0); + lua_pop(L, 1); + if (type != LUA_TSTRING && type != LUA_TNUMBER) + { + break; + } + if (total > static_cast(max_screen_memory)) + { + return too_large(L, "table.concat"); + } + } + return call_library(L); +} + +// the pattern functions, upvalue 2 telling which +enum class pattern_function +{ + find, + match, + gmatch, + gsub +}; + +constexpr std::array pattern_function_names{"string.find", "string.match", "string.gmatch", "string.gsub"}; + +// the longest text a replacement of gsub puts in place of the matches: a string (or a number) as it is, with each %0-%9 +// as long as a match, a table by its longest value. nothing when it can't be told (a function, a table with a +// metatable): what those give is made in Lua, under the hook +std::optional replacement_length(lua_State *L, int const Index, double const Subject, double const Matches) +{ + if (lua_type(L, Index) == LUA_TSTRING || lua_type(L, Index) == LUA_TNUMBER) + { + std::size_t length{0}; + auto const *text{lua_tolstring(L, Index, &length)}; + auto const captures{static_cast(std::count(text, text + length, '%'))}; + // the matches don't overlap: a capture of each takes at most the subject; a position capture is a number + return Matches * static_cast(length) + captures * (Subject + 24.0 * Matches); + } + if (lua_type(L, Index) == LUA_TTABLE && 0 == lua_getmetatable(L, Index)) + { + auto longest{0.0}; + lua_pushnil(L); + while (lua_next(L, Index) != 0) + { + longest = std::max(longest, lua_type(L, -1) == LUA_TSTRING ? static_cast(lua_objlen(L, -1)) : 32.0); + lua_pop(L, 1); + } + return Matches * longest; + } + return std::nullopt; +} + +// string.find, match, gmatch and gsub, refused for a pattern that may take too long on the subject: they run in C, +// without the instruction hook (see lua_pattern_cost() and max_pattern_cost). gsub with a string or a table is refused +// as well when its result may be over the memory of a screen +int api_pattern(lua_State *L) +{ + auto const function{static_cast(lua_tointeger(L, lua_upvalueindex(2)))}; + auto const *name{pattern_function_names[static_cast(function)]}; + std::size_t subject{0}; + luaL_checklstring(L, 1, &subject); + std::size_t length{0}; + auto const *pattern{luaL_checklstring(L, 2, &length)}; + auto const plain{function == pattern_function::find && lua_toboolean(L, 4) != 0}; + if (lua_pattern_cost({pattern, length}, subject, plain, function != pattern_function::gmatch) > max_pattern_cost) + { + return luaL_error(L, "%s: the pattern may take too long on a subject of %d bytes", name, static_cast(subject)); + } + if (function == pattern_function::gsub) + { + auto const size{static_cast(subject)}; + auto const matches{lua_isnumber(L, 4) ? std::clamp(static_cast(lua_tonumber(L, 4)), 0.0, size + 1.0) : size + 1.0}; + if (auto const replaced{replacement_length(L, 3, size, matches)}; replaced.has_value() && size + *replaced > static_cast(max_screen_memory)) + { + return too_large(L, name); + } + } + return call_library(L); +} + +// xpcall(f, handler, ...), in Lua on top of pcall: LuaJIT calls the handler of its own xpcall where the error was +// raised, before the stack unwinds, which for the error of the instruction hook is while the hook still runs, when no +// hook is called, so a handler that loops would never be stopped. here the handler is called once the error has left +// f, under pcall as well, and a script has no debug library to look at the stack with. made in Lua, a coroutine yields +// across it as across pcall +constexpr std::string_view xpcall_source{R"lua( +local pcall, select, error = pcall, select, error +local function finish(handler, ok, ...) + if ok then + return true, ... + end + local _, handled = pcall(handler, (...)) + return false, handled +end +return function(...) + if select("#", ...) < 2 then + error("bad argument #2 to 'xpcall' (value expected)", 2) + end + local f, handler = ... + return finish(handler, pcall(f, select(3, ...))) +end +)lua"}; + +// what the screens get of the libraries in place of the library's own functions, which run in C without the hook: +// string.rep, string.format and table.concat with a cap on the length of the result, the pattern functions with a cap +// on the steps they take, and xpcall made of pcall. strings share the string table as their methods +void limit_libraries(lua_State *L) +{ + lua_getglobal(L, LUA_STRLIBNAME); + lua_getfield(L, -1, "rep"); + lua_pushcclosure(L, api_repeat, 1); + lua_setfield(L, -2, "rep"); + lua_getfield(L, -1, "format"); + lua_pushcclosure(L, api_format, 1); + lua_setfield(L, -2, "format"); + for (std::size_t idx = 0; idx < pattern_function_names.size(); ++idx) + { + // "string.find": the name in the table is past the dot + auto const *name{pattern_function_names[idx] + sizeof("string.") - 1}; + lua_getfield(L, -1, name); + lua_pushinteger(L, static_cast(idx)); + lua_pushcclosure(L, api_pattern, 2); + lua_setfield(L, -2, name); + } + lua_pop(L, 1); + + lua_getglobal(L, LUA_TABLIBNAME); + lua_getfield(L, -1, "concat"); + lua_pushcclosure(L, api_concat, 1); + lua_setfield(L, -2, "concat"); + lua_pop(L, 1); + + if (0 == luaL_loadbuffer(L, xpcall_source.data(), xpcall_source.size(), "=xpcall") && 0 == lua_pcall(L, 0, 1, 0)) + { + lua_setglobal(L, "xpcall"); + } + else + { + // a script then gets no xpcall rather than the one the hook doesn't reach + lua_pop(L, 1); + lua_pushnil(L); + lua_setglobal(L, "xpcall"); } - // false and what the handler made of the error - auto const error{lua_gettop(L)}; - lua_pushboolean(L, 0); - lua_pushvalue(L, lua_upvalueindex(1)); - lua_pushvalue(L, 2); - lua_pushvalue(L, error); - lua_call(L, 2, 2); - // pcall(handler, error) gave true and the handler's value, or false and the handler's own error - lua_remove(L, -2); - return 2; } template void make_metatable(lua_State *L, char const *Name, std::array const &Methods, lua_CFunction Collect) @@ -825,8 +1127,9 @@ void lua_program::open_libraries() open_library(m_state, luaopen_string, LUA_STRLIBNAME); open_library(m_state, luaopen_math, LUA_MATHLIBNAME); open_library(m_state, luaopen_bit, LUA_BITLIBNAME); - // what reaches files or loads code - for (auto const *name : {"dofile", "loadfile", "load", "loadstring", "module", "require"}) + // what reaches files or loads code, and newproxy: a userdata of a metatable of the script's own, whose __gc LuaJIT + // runs without the hook, at any allocation and in lua_close, where a loop in it would never be stopped + for (auto const *name : {"dofile", "loadfile", "load", "loadstring", "module", "require", "newproxy"}) { lua_pushnil(m_state); lua_setglobal(m_state, name); @@ -834,15 +1137,8 @@ void lua_program::open_libraries() lua_getglobal(m_state, LUA_STRLIBNAME); lua_pushnil(m_state); lua_setfield(m_state, -2, "dump"); - // string.rep with a cap on the length, around the library's own. strings share the table as their methods - lua_getfield(m_state, -1, "rep"); - lua_pushcclosure(m_state, api_repeat, 1); - lua_setfield(m_state, -2, "rep"); lua_pop(m_state, 1); - // xpcall made of pcall, see api_xpcall - lua_getglobal(m_state, "pcall"); - lua_pushcclosure(m_state, api_xpcall, 1); - lua_setglobal(m_state, "xpcall"); + limit_libraries(m_state); } void lua_program::register_api() @@ -875,22 +1171,83 @@ void lua_program::register_api() bool lua_program::run(int const Arguments, int const Results, std::string_view const What) { budget = instruction_limit; + stopped = nullptr; // the interval, which the hook shortens once the budget of a call is spent lua_sethook(m_state, count_hook, LUA_MASKCOUNT, hook_interval); output.start_call(); - if (0 == lua_pcall(m_state, Arguments, Results, 0)) + memory.enforced = true; + auto const status{lua_pcall(m_state, Arguments, Results, 0)}; + memory.enforced = false; + if (0 == status) { return true; } auto const *message{lua_tostring(m_state, -1)}; ErrorLog(std::format("Lua screen \"{}\": {} failed: {}", script, What, message != nullptr ? message : "unknown error")); lua_pop(m_state, 1); + // what the call left behind, a heap run over the limit + lua_gc(m_state, LUA_GCCOLLECT, 0); return false; } +// render and init of the table the script returned (the argument), read in protected mode: the table may have a +// metatable of the script's, whose __index runs the script and may fail +int screen_functions(lua_State *L) +{ + lua_getfield(L, 1, "render"); + lua_getfield(L, 1, "init"); + return 2; +} + +// a refresh: render of the screen's table (its reference, the second argument) called with the state of the refresh +// (the dictionary_source, the first). in protected mode, the reading of render and the making of the state as well +int call_render(lua_State *L) +{ + auto const &input{*static_cast(lua_touserdata(L, 1))}; + auto const screen{static_cast(lua_tointeger(L, 2))}; + lua_settop(L, 0); + lua_rawgeti(L, LUA_REGISTRYINDEX, screen); + lua_getfield(L, 1, "render"); + push_state(L, input); + lua_call(L, 1, 1); + return 1; +} + +// true when a screen's state can be made with an allocator of its own: LuaJIT 2.0 on x64, and 2.1 on x64 without GC64, +// refuse one (lua_newstate gives nullptr, and writes so to stderr: 2.0 isn't asked) +bool custom_allocator_works() +{ +#if LUAJIT_VERSION_NUM < 20100 + if constexpr (sizeof(void *) == 8) + { + return false; + } +#endif + static bool const works{[] { + screen_memory probe; + auto *state{lua_newstate(limited_alloc, &probe)}; + if (state == nullptr) + { + return false; + } + lua_close(state); + return true; + }()}; + return works; +} + bool lua_program::start() { - m_state = luaL_newstate(); + // the screen's own allocator counts its memory, where LuaJIT takes one + if (custom_allocator_works()) + { + m_state = lua_newstate(limited_alloc, &memory); + memory.counted = m_state != nullptr; + } + if (m_state == nullptr) + { + m_state = luaL_newstate(); + } if (m_state == nullptr) { ErrorLog(std::format("Lua screen \"{}\": failed to create the state", script)); @@ -922,19 +1279,22 @@ bool lua_program::start() ErrorLog(std::format("Lua screen \"{}\": the script has to return a table with a render function", script)); return false; } - lua_getfield(m_state, -1, "render"); - auto const renders{lua_isfunction(m_state, -1)}; - lua_pop(m_state, 1); - if (false == renders) + lua_pushcfunction(m_state, screen_functions); + lua_pushvalue(m_state, -2); + if (false == run(1, 2, "reading render and init")) + { + return false; + } + // the table, render, init + if (false == lua_isfunction(m_state, -2)) { ErrorLog(std::format("Lua screen \"{}\": the script has to return a table with a render function", script)); return false; } - m_screen = luaL_ref(m_state, LUA_REGISTRYINDEX); - - lua_rawgeti(m_state, LUA_REGISTRYINDEX, m_screen); - lua_getfield(m_state, -1, "init"); lua_remove(m_state, -2); + lua_insert(m_state, -2); + // init, the table + m_screen = luaL_ref(m_state, LUA_REGISTRYINDEX); if (lua_isfunction(m_state, -1)) { if (false == run(0, 0, "init")) @@ -953,11 +1313,10 @@ bool lua_program::start() bool lua_program::render(render_call &Call) { call = &Call; - lua_rawgeti(m_state, LUA_REGISTRYINDEX, m_screen); - lua_getfield(m_state, -1, "render"); - lua_remove(m_state, -2); - push_state(m_state, Call.input); - auto const rendered{run(1, 1, "render")}; + lua_pushcfunction(m_state, call_render); + lua_pushlightuserdata(m_state, const_cast(&Call.input)); + lua_pushinteger(m_state, m_screen); + auto const rendered{run(2, 1, "render")}; call = nullptr; if (false == rendered) { @@ -999,6 +1358,11 @@ class lua_runtime_host final : public runtime } // namespace +bool lua_screen_memory_allocator() +{ + return custom_allocator_works(); +} + std::unique_ptr make_lua_runtime() { return std::make_unique(); diff --git a/scripting/scriptscreenprogram.h b/scripting/scriptscreenprogram.h index 86e59859b..32fd493ef 100644 --- a/scripting/scriptscreenprogram.h +++ b/scripting/scriptscreenprogram.h @@ -38,6 +38,17 @@ constexpr int max_log_lines_per_call{32}; constexpr std::size_t max_log_line{1024}; // bytes of the text, a longer one is cut // the largest file a screen reads: its script or module, a file below its folder constexpr std::uintmax_t max_screen_file{16 * 1024 * 1024}; +// the memory a Lua screen may hold: its Lua heap, and the pixels of its images, fonts and sprites. checked with a full +// collection, so its garbage doesn't count; between the collections it may take the screen up to twice this +constexpr std::size_t max_screen_memory{128 * 1024 * 1024}; + +// true when the Lua screens count their memory in an allocator of their own, which refuses what goes over +// max_screen_memory as it is asked for: LuaJIT 2.1 in its GC64 mode, a 32-bit build. LuaJIT 2.0 on x64 (the game's on +// Windows) and 2.1 on x64 without GC64 take no allocator; there the memory is checked by the instruction hook every +// so many instructions, and before what makes images and large strings in one call (string.rep, string.format, +// table.concat, string.gsub), but not at the concatenation operator: one concatenation of large strings is made +// whole, as far as LuaJIT's own heap goes (2 GB on x64), and the screen is stopped at the next check +bool lua_screen_memory_allocator(); struct pending_command { diff --git a/scripting/scriptscreenrules.cpp b/scripting/scriptscreenrules.cpp index 6f47565ef..35f918618 100644 --- a/scripting/scriptscreenrules.cpp +++ b/scripting/scriptscreenrules.cpp @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/parser.h" #include +#include namespace script_screens { @@ -134,4 +135,112 @@ std::optional screen_script_path(std::string const &Folder, std::st return path; } +namespace +{ + +// the end of the set that starts at Start ('['), past its ']'; Pattern.size() for a set that doesn't end. as Lua's +// classEnd: a ']' right after '[' or '[^' is in the set, and '%' escapes the character after it +std::size_t set_end(std::string_view const Pattern, std::size_t Start) +{ + auto idx{Start + 1}; + if (idx < Pattern.size() && Pattern[idx] == '^') + { + ++idx; + } + do + { + if (idx >= Pattern.size()) + { + return Pattern.size(); + } + if (Pattern[idx++] == '%') + { + ++idx; + } + } while (idx >= Pattern.size() || Pattern[idx] != ']'); + return idx + 1; +} + +} // namespace + +double lua_pattern_cost(std::string_view const Pattern, std::size_t const Subject, bool const Plain, bool const Anchorable) +{ + auto const length{static_cast(std::max(Pattern.size(), 1))}; + auto const positions{static_cast(Subject) + 1.0}; + // LuaJIT searches plainly for a pattern without the special characters as well + if (Plain || Pattern.find_first_of("^$*+?.([%-") == std::string_view::npos) + { + return positions * length; + } + auto const anchored{Anchorable && Pattern.front() == '^'}; + int repeats{0}; + int optional{0}; + // a repetition that ends the pattern doesn't multiply: past it the match is over + auto last_repeat{false}; + std::size_t idx{anchored ? 1U : 0U}; + while (idx < Pattern.size()) + { + auto const character{Pattern[idx]}; + if (character == '(' || character == ')') + { + ++idx; + // a ')' after the last repetition keeps it last + continue; + } + last_repeat = false; + std::size_t end{idx + 1}; + if (character == '%' && idx + 1 < Pattern.size()) + { + auto const next{Pattern[idx + 1]}; + if (next == 'b') + { + // %bxy goes along the subject to the balancing character + ++repeats; + last_repeat = true; + idx += 4; + continue; + } + if (next == 'f') + { + idx = idx + 2 < Pattern.size() && Pattern[idx + 2] == '[' ? set_end(Pattern, idx + 2) : idx + 2; + continue; + } + if (next >= '0' && next <= '9') + { + // a back reference compares the capture, as long as the subject + ++repeats; + last_repeat = true; + idx += 2; + continue; + } + end = idx + 2; + } + else if (character == '[') + { + end = set_end(Pattern, idx); + } + if (end < Pattern.size() && (Pattern[end] == '*' || Pattern[end] == '+' || Pattern[end] == '-')) + { + ++repeats; + last_repeat = true; + idx = end + 1; + } + else if (end < Pattern.size() && Pattern[end] == '?') + { + ++optional; + idx = end + 1; + } + else + { + idx = end; + } + } + if (last_repeat) + { + --repeats; + } + auto const starts{anchored ? 1.0 : positions}; + return starts * std::pow(positions, repeats) * std::pow(2.0, optional) * length; +} + } // namespace script_screens diff --git a/scripting/scriptscreenrules.h b/scripting/scriptscreenrules.h index 37cf0bd83..8690793e6 100644 --- a/scripting/scriptscreenrules.h +++ b/scripting/scriptscreenrules.h @@ -78,4 +78,19 @@ bool is_safe_relative_path(std::string_view Path); // reads: absolute, with a drive, or with ".."), since the script's folder is the one the screen then reads files from std::optional screen_script_path(std::string const &Folder, std::string const &Script); +// the Lua pattern functions (string.find, match, gmatch, gsub) run in C, where the instruction limit doesn't reach, and +// backtrack: ("a"):rep(1e6):find(".-b") would take hours. a call is refused when the steps it may take at worst, by +// lua_pattern_cost(), are over this: LuaJIT 2.0 goes through the worst patterns that cost as much (a):rep(5770) and +// .-b) in about a tenth of a second +constexpr double max_pattern_cost{1e8}; + +// the steps a Lua pattern function may take at worst on a subject of Subject bytes, Pattern being m bytes long: +// - a plain search (string.find with plain set, or a pattern without special characters): Subject x m; +// - a pattern: tried from every position of the subject (Subject + 1), or from the first only when Anchored (it starts +// with '^', and the function anchors: find, match, gsub, not gmatch), times (Subject + 1) for each repetition ('*', +// '+', '-', %b, a back reference %1-%9) but a last one (followed by nothing but ')', which ends the match where it +// stops), times 2 for each '?', times m for the work of each step (a set is gone through item by item) +// a malformed pattern costs nothing here: the function raises its error itself +double lua_pattern_cost(std::string_view Pattern, std::size_t Subject, bool Plain, bool Anchorable); + } // namespace script_screens diff --git a/tests/unit/test_script_screen_host.cpp b/tests/unit/test_script_screen_host.cpp index 697175c35..8fd4de2f4 100644 --- a/tests/unit/test_script_screen_host.cpp +++ b/tests/unit/test_script_screen_host.cpp @@ -7,6 +7,7 @@ // api; what a call may send, log, read or make is capped. the Lua cases need WITH_LUA, the WebAssembly ones WITH_WASM #include "scripting/scriptscreens.h" +#include "scripting/scriptscreenprogram.h" #include "input/command.h" #include "interfaces/ITexture.h" #include "utilities/Globals.h" @@ -1113,4 +1114,254 @@ TEST_CASE("lua screens: a script larger than the limit isn't loaded") { queue.exit(); } +namespace { + +// white when the script gets no userdata of its own (newproxy), and a table's __gc isn't called: no finalizer of the +// script's, which LuaJIT would run without the hook +constexpr std::string_view finalizer_script{R"( +local collected = false +setmetatable({}, { __gc = function() collected = true end }) +collectgarbage() +collectgarbage() +local good = newproxy == nil and ffi == nil and require == nil and not collected +return { + render = function(state) + return eu07.image(1, 1, good and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// a table whose metatable fails, loops, or gives render: the game reads the table in protected mode +constexpr std::string_view failing_index_script{R"( +return setmetatable({}, { __index = function() error("x") end }) +)"}; + +constexpr std::string_view looping_index_script{R"( +return setmetatable({}, { __index = function() while true do end end }) +)"}; + +constexpr std::string_view inherited_render_script{R"( +local base = { render = function(state) return eu07.image(1, 1, { 255, 255, 255 }) end } +return setmetatable({}, { __index = base }) +)"}; + +// starts, then fails when render is read for a refresh +constexpr std::string_view failing_later_script{R"( +local started = false +return setmetatable({}, { __index = function(t, key) + if key == "init" then return function() started = true end end + if key == "render" then + if started then error("render can't be read any more") end + return function() end + end +end }) +)"}; + +// white when the pattern functions refuse what may take too long, and do what doesn't +constexpr std::string_view pattern_script{R"( +local long = ("a"):rep(1000000) +local function refused(...) + local ok, message = pcall(...) + return not ok and message:find("may take too long", 1, true) ~= nil +end +local slow = refused(string.find, long, ".-b") + and refused(function() return long:find(".-b") end) + and refused(string.match, long, "(a*)b") + and refused(string.gsub, long, "a-b", "") + and refused(function() for x in long:gmatch("a-b") do end end) + and refused(string.find, ("a"):rep(1000), "a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?aaaaaaaaaaaaaaaaaaaaaaaaaaaaaab") + and refused(string.find, long, ("a"):rep(1000) .. "b", 1, true) +-- what a screen does: lines of a file, fields of a line, a plain search, short subjects +local text = ("key=value\n"):rep(10000) +local lines = 0 +for line in text:gmatch("[^\n]+") do lines = lines + 1 end +local key, value = ("speed=120"):match("^(%w+)=(%d+)$") +local spaced = select(2, (("a b c "):rep(100)):gsub("%s+", " ")) +local found = long:find("aaab", 1, true) == nil and (long .. "b"):find("ab", 1, true) == 1000000 +local fast = lines == 10000 and key == "speed" and value == "120" and spaced == 300 and found + and ("x = 1"):find("=") == 3 and ("abc"):gsub("b", "%0%0") == "abbc" +return { + render = function(state) + return eu07.image(1, 1, (slow and fast) and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// white when what makes a large string in one call is refused past the memory of a screen +constexpr std::string_view large_result_script{R"( +local mega = ("x"):rep(1024 * 1024) +local function refused(...) + local ok, message = pcall(...) + return not ok and message:find("over the memory of a screen", 1, true) ~= nil +end +local parts = {} +for i = 1, 200 do parts[i] = mega end +local format = refused(string.format, ("%s"):rep(200), unpack(parts)) +local concat = refused(table.concat, parts) +local gsub = refused(string.gsub, mega, "", ("y"):rep(1000)) +local gsub_table = refused(string.gsub, mega, ".", { x = ("y"):rep(1000) }) +local fits = #table.concat({ mega, mega }, ",") == 2 * 1024 * 1024 + 1 and #string.format("%s%s", mega, mega) == 2 * 1024 * 1024 + and select(2, mega:gsub("x", "yy")) == 1024 * 1024 +return { + render = function(state) + return eu07.image(1, 1, (format and concat and gsub and gsub_table and fits) and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// white when the images a screen holds are held to its memory, and the images it dropped don't count +constexpr std::string_view image_memory_script{R"( +local kept = {} +local ok, message = pcall(function() + for i = 1, 100 do kept[i] = eu07.image(4096, 4096) end +end) +local refused = not ok and message:find("memory limit exceeded", 1, true) ~= nil and #kept < 100 +kept = nil +local dropped = pcall(function() + for i = 1, 20 do local image = eu07.image(4096, 4096) end +end) +return { + render = function(state) + return eu07.image(1, 1, (refused and dropped) and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// holds more and more memory, a little at a time +constexpr std::string_view growing_script{R"( +local kept = {} +for i = 1, 10000000 do kept[i] = ("x"):rep(1000) .. i end +return { render = function(state) return eu07.image(1, 1, { 255, 255, 255 }) end } +)"}; + +// a concatenation of 320 MB in one operation, from a string of 64 MB: only an allocator of the screen's own refuses +// it as it is made +constexpr std::string_view one_concatenation_script{R"( +local a = ("x"):rep(1024 * 1024) +for i = 1, 6 do a = a .. a end +local ok, message = pcall(function() return #(a .. a .. a .. a .. a) end) +local refused = #a == 64 * 1024 * 1024 and not ok and message:find("not enough memory", 1, true) ~= nil +a = nil +return { + render = function(state) + return eu07.image(1, 1, refused and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// white when a coroutine yields across xpcall, and xpcall without a handler is an error +constexpr std::string_view xpcall_yield_script{R"( +local resume = coroutine.wrap(function() + local ok, value = xpcall(function() + coroutine.yield(1) + return 2 + end, function(e) return e end) + coroutine.yield(ok and value) + local caught, handled = xpcall(function() + coroutine.yield(3) + error("boom") + end, function(e) return "handled: " .. e end) + coroutine.yield(not caught and handled:find("handled: .*boom") ~= nil) +end) +local first, second, third, fourth = resume(), resume(), resume(), resume() +local missing = not pcall(xpcall, print) +local good = first == 1 and second == 2 and third == 3 and fourth == true and missing +return { + render = function(state) + return eu07.image(1, 1, good and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// loads the script as a screen next to a working one: the working one draws, the script's screen draws nothing, and +// nothing hangs or ends the program +void check_switched_off(script_folder const &Folder, std::string const &Name, std::string_view const Code) { + auto const painting{Folder.write("paint.lua", paint_script)}; + auto const failing{Folder.write(Name, Code)}; + auto *queue{new script_screen_queue}; // NOSONAR a stuck worker would keep the destructor waiting, see above + REQUIRE(queue->init()); + recording_texture switched_off; + recording_texture working; + auto const first{queue->acquire(request(script_language::lua, failing, Name, &switched_off))}; + 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); + auto const drawn{run_until(*queue, [&working] { return working.uploads > 0; })}; + CHECK(drawn); + if (false == drawn) { + return; + } + run_frames(*queue); + CHECK(switched_off.uploads == 0); + CHECK_FALSE(queue->due(*first)); + queue->exit(); + delete queue; // NOSONAR see above +} + +} // namespace + +TEST_CASE("lua screens: a script makes no finalizer of its own") { + script_folder const folder{"lua_finalizer"}; + CHECK(first_pixel(folder.write("finalizer.lua", finalizer_script), "finalizer") == 255); +} + +TEST_CASE("lua screens: the table of a script is read in protected mode") { + log_capture const log; + script_folder const folder{"lua_index"}; + SUBCASE("a metatable that fails") { + check_switched_off(folder, "failing.lua", failing_index_script); + CHECK_FALSE(log.lines_with("reading render and init failed").empty()); + } + SUBCASE("a metatable that loops") { + check_switched_off(folder, "looping.lua", looping_index_script); + CHECK_FALSE(log.lines_with("instruction limit exceeded").empty()); + } + SUBCASE("a metatable that fails once the screen runs") { + check_switched_off(folder, "later.lua", failing_later_script); + CHECK_FALSE(log.lines_with("render can't be read any more").empty()); + } + SUBCASE("a metatable that gives render") { + CHECK(first_pixel(folder.write("inherited.lua", inherited_render_script), "inherited") == 255); + } +} + +TEST_CASE("lua screens: the pattern functions refuse what may take too long, and do the rest") { + script_folder const folder{"lua_patterns"}; + auto const started{std::chrono::steady_clock::now()}; + CHECK(first_pixel(folder.write("patterns.lua", pattern_script), "patterns") == 255); + // the refused calls take no time, the others little + CHECK(std::chrono::steady_clock::now() - started < std::chrono::seconds(10)); +} + +TEST_CASE("lua screens: what makes a large string in one call is held to the memory of a screen") { + script_folder const folder{"lua_large_result"}; + CHECK(first_pixel(folder.write("large.lua", large_result_script), "large") == 255); +} + +TEST_CASE("lua screens: the images a screen holds are held to its memory") { + script_folder const folder{"lua_image_memory"}; + CHECK(first_pixel(folder.write("images.lua", image_memory_script), "images") == 255); +} + +TEST_CASE("lua screens: a screen holding more than its memory is switched off") { + log_capture const log; + script_folder const folder{"lua_growing"}; + check_switched_off(folder, "growing.lua", growing_script); + CHECK(log.lines_with("memory limit exceeded").size() + log.lines_with("not enough memory").size() > 0); +} + +TEST_CASE("lua screens: with an allocator of the screen's own, a string made over the memory in one operation is refused") { + if (false == script_screens::lua_screen_memory_allocator()) { + MESSAGE("LuaJIT takes no allocator of the game's here (2.0, or 2.1 without GC64 on x64): not tested"); + return; + } + script_folder const folder{"lua_one_concatenation"}; + CHECK(first_pixel(folder.write("concatenation.lua", one_concatenation_script), "concatenation") == 255); +} + +TEST_CASE("lua screens: a coroutine yields across xpcall") { + script_folder const folder{"lua_xpcall_yield"}; + CHECK(first_pixel(folder.write("yield.lua", xpcall_yield_script), "yield") == 255); +} + #endif diff --git a/tests/unit/test_script_screens.cpp b/tests/unit/test_script_screens.cpp index 4fc688928..0b92e7505 100644 --- a/tests/unit/test_script_screens.cpp +++ b/tests/unit/test_script_screens.cpp @@ -117,3 +117,45 @@ TEST_CASE("script screens: the script of a screen is in the vehicle's folder, or CHECK_FALSE(screen_script_path(vehicle, "c:/games/screen.lua").has_value()); CHECK_FALSE(screen_script_path("../outside/", "screen.lua").has_value()); } + +TEST_CASE("script screens: the steps a Lua pattern function may take at worst") { + using script_screens::lua_pattern_cost; + using script_screens::max_pattern_cost; + // a plain search: the subject (and one past it) times the pattern + CHECK(lua_pattern_cost("abc", 999, true, true) == doctest::Approx(1000.0 * 3)); + CHECK(lua_pattern_cost(".-b", 999, true, true) == doctest::Approx(1000.0 * 3)); + // a pattern without special characters is searched plainly as well + CHECK(lua_pattern_cost("abc", 999, false, true) == doctest::Approx(1000.0 * 3)); + CHECK(lua_pattern_cost("", 999, false, true) == doctest::Approx(1000.0)); + // from every position, times the subject for each repetition but a last one + CHECK(lua_pattern_cost(".-b", 999, false, true) == doctest::Approx(1000.0 * 1000 * 3)); + CHECK(lua_pattern_cost("a*", 999, false, true) == doctest::Approx(1000.0 * 2)); + CHECK(lua_pattern_cost("(a+)", 999, false, true) == doctest::Approx(1000.0 * 4)); + CHECK(lua_pattern_cost("a+$", 999, false, true) == doctest::Approx(1000.0 * 1000 * 3)); + CHECK(lua_pattern_cost("(%d+):(%d+)", 999, false, true) == doctest::Approx(1000.0 * 1000 * 11)); + CHECK(lua_pattern_cost("[^\n]+", 999, false, false) == doctest::Approx(1000.0 * 5)); + CHECK(lua_pattern_cost("[%]x]*y", 999, false, true) == doctest::Approx(1000.0 * 1000 * 7)); + CHECK(lua_pattern_cost("%bxyz", 999, false, true) == doctest::Approx(1000.0 * 1000 * 5)); + CHECK(lua_pattern_cost("(a)%1x", 999, false, true) == doctest::Approx(1000.0 * 1000 * 6)); + CHECK(lua_pattern_cost("%f[%w]%w+", 999, false, true) == doctest::Approx(1000.0 * 9)); + // '?' doubles + CHECK(lua_pattern_cost("a?a?b", 999, false, true) == doctest::Approx(1000.0 * 4 * 5)); + // '^' anchors find, match and gsub to the first position; gmatch takes it as a character + CHECK(lua_pattern_cost("^.-b", 999, false, true) == doctest::Approx(1000.0 * 4)); + CHECK(lua_pattern_cost("^.-b", 999, false, false) == doctest::Approx(1000.0 * 1000 * 4)); + // a malformed pattern is the library's to refuse + CHECK(lua_pattern_cost("[a", 999, false, true) > 0.0); + CHECK(lua_pattern_cost("%", 999, false, true) > 0.0); + CHECK(lua_pattern_cost("%b", 999, false, true) > 0.0); + + // the review's case, and what a screen does + CHECK(lua_pattern_cost(".-b", 1'000'000, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("[^\n]+", 1'000'000, false, false) < max_pattern_cost); + CHECK(lua_pattern_cost("^(%w+)=(%d+)$", 1'000, false, true) < max_pattern_cost); + CHECK(lua_pattern_cost("%s+$", 4'000, false, true) < max_pattern_cost); + std::string optional; + for (int idx = 0; idx < 30; ++idx) { + optional += "a?"; + } + CHECK(lua_pattern_cost(optional + std::string(30, 'a'), 100, false, true) > max_pattern_cost); +} From 6ee2cc8eb8207c2303e3781da41f9bdefb0d804e Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 11:53:44 +0100 Subject: [PATCH 041/136] fix: exchange the brake pipe air between vehicles after all of them stepped, in sub-steps The air the brake hoses carry between the vehicles was taken explicitly inside each vehicle's step, at the physics step of 0.01 s. Through the hose between two 14 m freight wagons (Spg 0.792, 11.5 l of pipe) one step moved 11.8 l per bar, 2.06 times the 5.7 l that evens out the two pipes: the pipes overshot each other in turns and settled into a pattern in which every distributor saw the pipe up to 0.28 bar off the pressure left in it after the step. ESt3 valves charged at 5.0 bar saw 4.79 and lapped at the first stage, and the AI of a standing freight train never got its brakes released (the report of eu07/maszyna#368). The exchange now comes after every vehicle has stepped (vehicle_table::update_brake_pipes(), once per physics iteration), for the vehicles which stepped their pipe, in as many sub-steps as keep the air a hose carries in one below what evens out the pipes on its ends (3 for 14 m freight wagons, 2 for passenger cars), each going through the vehicles in the order they step. The distributors see the pressure the pipe holds, and an application reaches the end of the train as with a step of 0.001 s. --- McZapkie/MOVER.h | 4 ++ McZapkie/Mover.cpp | 68 ++++++++++++++++++- McZapkie/hamulce.h | 2 + tests/unit/consist.cpp | 11 ++++ tests/unit/consist.h | 1 + tests/unit/test_brake_pipe.cpp | 117 +++++++++++++++++++++++++++++++++ tests/unit/vehicle.cpp | 2 + vehicle/DynObj.cpp | 15 +++++ vehicle/DynObj.h | 4 ++ 9 files changed, 223 insertions(+), 1 deletion(-) create mode 100644 tests/unit/test_brake_pipe.cpp diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index b619ba7de..0166ba30c 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2078,6 +2078,7 @@ class TMoverParameters double LocBrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych z pomocniczego*/ double PipeBrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych z przewodu*/ double PipePress = 0.0; /*!o cisnienie w przewodzie glownym*/ + bool PipeCouplersPending{false}; // the brake pipe stepped, its air exchange through the hoses is yet to come (UpdatePipeCouplers()) double EqvtPipePress = 0.0; /*!o cisnienie w przewodzie glownym skladu*/ double Volume = 0.0; /*objetosc spr. powietrza w zbiorniku hamulca*/ double CompressedVolume = 0.0; /*objetosc spr. powietrza w ukl. zasilania*/ @@ -2557,6 +2558,9 @@ class TMoverParameters void UpdateScndPipePressure(double dt); void UpdateSpringBrake(double dt); double GetDVc(double dt); + int PipeCouplersSubsteps(double dt) const; + // the air exchange through the brake hoses, after the vehicles stepped + static void UpdatePipeCouplers(std::vector const &Vehicles, double dt); /*funkcje obliczajace sily*/ void ComputeConstans(void); // ABu: wczesniejsze wyznaczenie stalych dla liczenia sil diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 825137675..4e0040deb 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -4958,7 +4958,9 @@ void TMoverParameters::UpdatePipePressure(double dt) temp = 0.0; // odetnij else temp = 1.0; // połącz - Pipe->Flow(temp * Hamulec->GetPF(temp * PipePress, dt, Vel) + GetDVc(dt)); + Pipe->Flow(temp * Hamulec->GetPF(temp * PipePress, dt, Vel)); + // the air the brake hoses carry to and from the neighbours comes once all vehicles have stepped, UpdatePipeCouplers() + PipeCouplersPending = true; if (ASBType == 128) Hamulec->ASB(int(SlippingWheels && Vel > 1) * (1 + 2 * int(nrot_eps < -0.01))); @@ -5125,6 +5127,70 @@ double TMoverParameters::GetDVc(double dt) return dv2 + dv1; } +// ************************************************************************************************* +// the number of sub-steps of dt the air exchange through the brake hoses of the vehicle needs: in one, the air +// a hose carries stays below what evens out the pipes on its ends. taken in a single step of 0.01 s, the hose +// between two 14 m freight wagons carries twice that, their pipes overshoot each other in turns and the +// distributors see the pressure up to 0.28 bar off what's in the pipe (eu07/maszyna#368) +// ************************************************************************************************* +int TMoverParameters::PipeCouplersSubsteps(double const dt) const +{ + auto substeps{1}; + auto const area{Spg / (1.0 + 0.015 / Spg * Dim.L)}; // as in GetDVc() + for (auto const &coupler : Couplers) + { + if (coupler.Connected == nullptr || false == TestFlag(coupler.CouplingFlag, ctrain_pneumatic)) + { + continue; + } + auto const &other{*coupler.Connected}; + // the flow per bar of the difference, at small differences, where it's the largest + auto const pressure{std::max(PipePress, other.PipePress)}; + auto const conductance{std::abs(PF(pressure, pressure - 0.01, area)) / 0.01}; + auto const equalising{Pipe->GetCap() * other.Pipe->GetCap() / (Pipe->GetCap() + other.Pipe->GetCap())}; + substeps = std::max(substeps, static_cast(std::ceil(dt * conductance / equalising))); + } + return std::min(substeps, 10); +} + +// ************************************************************************************************* +// the air exchange through the brake hoses of the vehicles which stepped their brake pipe (UpdatePipePressure()) +// since the last call, in the order they stepped: in as many sub-steps of dt as the vehicle needing the most of +// them takes, each going through the vehicles one after another, as the step of the vehicles does +// ************************************************************************************************* +void TMoverParameters::UpdatePipeCouplers(std::vector const &Vehicles, double const dt) +{ + auto substeps{1}; + for (auto const *vehicle : Vehicles) + { + if (vehicle->PipeCouplersPending) + { + substeps = std::max(substeps, vehicle->PipeCouplersSubsteps(dt)); + } + } + auto const substep{dt / substeps}; + for (auto i = 0; i < substeps; ++i) + { + for (auto *vehicle : Vehicles) + { + if (false == vehicle->PipeCouplersPending) + { + continue; + } + auto &pipe{*vehicle->Pipe}; + pipe.Act(); // what the neighbours have sent in the meantime + vehicle->PipePress = pipe.P(); + pipe.Flow(vehicle->GetDVc(substep)); + pipe.Act(); + vehicle->PipePress = pipe.P(); + } + } + for (auto *vehicle : Vehicles) + { + vehicle->PipeCouplersPending = false; + } +} + // ************************************************************************************************* // Q: 20160713 // Obliczenie stałych potrzebnych do dalszych obliczeń diff --git a/McZapkie/hamulce.h b/McZapkie/hamulce.h index 2fb433a85..7de34ea23 100644 --- a/McZapkie/hamulce.h +++ b/McZapkie/hamulce.h @@ -249,6 +249,8 @@ class TReservoir /// /// Pressure in bar (atm). void CreatePress(double Press); + /// Returns reservoir capacity in liters. + double GetCap() const { return Cap; } /// /// Returns absolute (atmospheric) pressure inside the reservoir. /// diff --git a/tests/unit/consist.cpp b/tests/unit/consist.cpp index a5f10d936..1226c8192 100644 --- a/tests/unit/consist.cpp +++ b/tests/unit/consist.cpp @@ -74,6 +74,7 @@ void consist::step(track const &Track, double Dt) { for (std::size_t i = 0; i < m_vehicles.size(); ++i) { m_positions[i] += m_vehicles[i]->fast_move(Track, Dt, TLocation{m_positions[i], 0.0, 0.0}); } + update_brake_pipes(Dt); } for (auto const &vehicle : m_vehicles) { vehicle->forces(Dt); @@ -90,6 +91,16 @@ void consist::step(track const &Track, double Dt) { for (std::size_t i = 0; i < m_vehicles.size(); ++i) { m_positions[i] += m_vehicles[i]->move(Track, Dt, TLocation{m_positions[i], 0.0, 0.0}, pipe); } + update_brake_pipes(Dt); +} + +void consist::update_brake_pipes(double Dt) { + // vehicle_table::update_brake_pipes() + std::vector movers; + for (auto const &vehicle : m_vehicles) { + movers.push_back(&vehicle->mover()); + } + TMoverParameters::UpdatePipeCouplers(movers, Dt); } void consist::run(double Seconds, track const &Track, double Dt) { diff --git a/tests/unit/consist.h b/tests/unit/consist.h index 02001e042..282c8d07b 100644 --- a/tests/unit/consist.h +++ b/tests/unit/consist.h @@ -45,6 +45,7 @@ public: private: void update_neighbours(); + void update_brake_pipes(double Dt); std::vector> m_vehicles; std::vector m_positions; // of the vehicles' middles along the track diff --git a/tests/unit/test_brake_pipe.cpp b/tests/unit/test_brake_pipe.cpp new file mode 100644 index 000000000..18aa531e8 --- /dev/null +++ b/tests/unit/test_brake_pipe.cpp @@ -0,0 +1,117 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "McZapkie/MOVER.h" +#include "McZapkie/hamulce.h" +#include "consist.h" +#include "vehicle.h" + +// the air exchange through the brake hoses between the vehicles of a train (TMoverParameters::UpdatePipeCouplers()). +// taken in one explicit step of 0.01 s, the hose between two short freight wagons carried twice the air which evens +// out their pipes: the pipes overshot each other in turns, and an ESt3 distributor saw the pipe pressure up to +// 0.28 bar off what was in it, lapped at the first stage of braking and kept the AI's train from leaving +// (eu07/maszyna#368) + +namespace { + +using test::definition; + +// a freight train standing charged: a locomotive and Wagons empty two-axle freight wagons with ESt3, set to G +void freight_train(test::consist &Train, int const Wagons) { + Train.add(definition::fiz("st44_v2/m62-1151")); + for (int i = 0; i < Wagons; ++i) { + auto &wagon{Train.add(definition::fiz("3wl_v2/3wl"))}; + wagon->BrakeDelaySwitch(bdelay_G); + REQUIRE(wagon->BrakeValve == TBrakeValve::ESt3); + REQUIRE(wagon->Spg == doctest::Approx(0.792)); // the pipe of a freight wagon + } + Train[0].hold_brake_pipe(5.0); // the locomotive's driver's valve in the running position +} + +// a passenger train standing charged: a locomotive and Cars passenger cars with ESt4, set to R +void passenger_train(test::consist &Train, int const Cars) { + Train.add(definition::fiz("st44_v2/m62-1151")); + for (int i = 0; i < Cars; ++i) { + auto &car{Train.add(definition::fiz("11xa_v2/93a"))}; + REQUIRE(car->Spg == doctest::Approx(0.507)); // the pipe of a passenger car + } + Train[0].hold_brake_pipe(5.0); +} + +// the time [s] until the brake pipe of the train's last vehicle is 0.5 bar down, once the locomotive holds its pipe +// at Pressure [bar], the physics stepping by Dt +double application_time(test::consist &Train, double const Pressure, double const Dt) { + auto &last{Train[Train.size() - 1]}; + auto const start{last->PipePress}; + Train[0].hold_brake_pipe(Pressure); + auto time{0.0}; + while (last->PipePress > start - 0.5 && time < 60.0) { + Train.step({}, Dt); + time += Dt; + } + return time; +} + +// the same train standing a minute, then braked from the locomotive, all of it in steps of Dt +double application_time(void (*Train)(test::consist &, int), int const Vehicles, double const Pressure, double const Dt) { + test::consist train; + Train(train, Vehicles); + train.run(60.0, {}, Dt); + return application_time(train, Pressure, Dt); +} + +} // namespace + +TEST_CASE("brake pipe: the distributors of a standing freight train see the pressure in the pipe, and none of them brakes") { + test::consist train; + freight_train(train, 37); + // standing a while, the locomotive keeping the pipe charged + train.run(300.0); + for (std::size_t i = 1; i < train.size(); ++i) { + CAPTURE(i); + auto &wagon{train[i].mover()}; + // the distributor's valve chamber follows the pressure the distributor works with: the pipe's own + CHECK(std::abs(wagon.Hamulec->GetVRP() - wagon.PipePress) < 0.005); + CHECK(wagon.PipePress > 4.9); + // released, as the AI wants every vehicle before it starts (TController::CheckVehicles()) + CHECK((wagon.Hamulec->GetBrakeStatus() & (b_on | b_hld)) == 0); + CHECK(wagon.BrakePress < 0.1); + } + // the exchange between the 14 m wagons takes 3 sub-steps of a step of 0.01 s + CHECK(train[1]->PipeCouplersSubsteps(0.01) == 3); +} + +TEST_CASE("brake pipe: an application from the locomotive reaches the end of a freight train as with a short step") { + // a light application, the locomotive's pipe 1 bar down: the last wagon's pipe 0.5 bar down as soon as in the + // step of 0.001 s, at which the exchange through the hoses converges + auto const converged{application_time(freight_train, 37, 4.0, 0.001)}; + auto const usual{application_time(freight_train, 37, 4.0, 0.01)}; + CAPTURE(converged); + CAPTURE(usual); + CHECK(converged < 60.0); + CHECK(usual == doctest::Approx(converged).epsilon(0.1)); + // a full service application + auto const convergedfull{application_time(freight_train, 37, 3.5, 0.001)}; + auto const usualfull{application_time(freight_train, 37, 3.5, 0.01)}; + CAPTURE(convergedfull); + CAPTURE(usualfull); + CHECK(usualfull == doctest::Approx(convergedfull).epsilon(0.1)); +} + +TEST_CASE("brake pipe: a passenger train, whose exchange was stable in one step, brakes as with a short step") { + test::consist train; + passenger_train(train, 10); + train.run(300.0); + for (std::size_t i = 1; i < train.size(); ++i) { + CAPTURE(i); + auto &car{train[i].mover()}; + CHECK(std::abs(car.Hamulec->GetVRP() - car.PipePress) < 0.005); + CHECK((car.Hamulec->GetBrakeStatus() & (b_on | b_hld)) == 0); + CHECK(car.BrakePress < 0.1); + } + auto const converged{application_time(passenger_train, 10, 3.5, 0.001)}; + auto const usual{application_time(passenger_train, 10, 3.5, 0.01)}; + CAPTURE(converged); + CAPTURE(usual); + CHECK(usual == doctest::Approx(converged).epsilon(0.05)); +} diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp index e38999f7d..743f3f266 100644 --- a/tests/unit/vehicle.cpp +++ b/tests/unit/vehicle.cpp @@ -332,6 +332,8 @@ void pair::step(track const &Track, double Dt) { auto const &mover{placed.owner->mover()}; placed.position += placed.heading * placed.owner->move(Track, Dt, TLocation{placed.position, 0.0, 0.0}, mover.PipePress); } + // vehicle_table::update_brake_pipes() + TMoverParameters::UpdatePipeCouplers({&m_vehicles[0].owner->mover(), &m_vehicles[1].owner->mover()}, Dt); } void pair::run(double Seconds, track const &Track, double Dt) { diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 24810a2e7..67f0d516c 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -9023,6 +9023,7 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { for( auto *vehicle : m_items ) { vehicle->FastUpdate( Deltatime ); } + update_brake_pipes( Deltatime ); } } for( auto *vehicle : m_items ) { @@ -9035,6 +9036,7 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { // Ra 2015-01: tylko tu przelicza sieć trakcyjną vehicle->Update( Deltatime, totaltime ); } + update_brake_pipes( Deltatime ); // jeśli jest coś do usunięcia z listy, to trzeba na końcu erase_disabled(); @@ -9046,6 +9048,19 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { } } +// the air exchange through the brake hoses of the vehicles which stepped their physics, after all of them did +void +vehicle_table::update_brake_pipes( double const Deltatime ) { + + m_brakepipes.clear(); + for( auto *vehicle : m_items ) { + if( true == vehicle->MoverParameters->PipeCouplersPending ) { + m_brakepipes.push_back( vehicle->MoverParameters ); + } + } + TMoverParameters::UpdatePipeCouplers( m_brakepipes, Deltatime ); +} + // records the odometer states of the vehicles and saves them for the next sessions (eu07/maszyna#72) void vehicle_table::save_odometers() { diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index 49b23c959..8771146c5 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -948,8 +948,12 @@ private: // the trains it closes in on void update_coupler_physics() const; + // the air exchange through the brake hoses of the vehicles which stepped their physics, after all of them did + void + update_brake_pipes( double const Deltatime ); double m_odometersavetimer { 0.0 }; // simulation time since the odometers were last saved + std::vector m_brakepipes; // the vehicles of update_brake_pipes(), kept for the memory }; From c0bcdc23c7b7360d7692611a12069e03739052e1 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 17:35:42 +0100 Subject: [PATCH 042/136] fix: Sonar on the brake pipe sub-steps: no shadowed enumerator, const test helper, template callback --- McZapkie/Mover.cpp | 6 +++--- tests/unit/consist.cpp | 2 +- tests/unit/consist.h | 2 +- tests/unit/test_brake_pipe.cpp | 3 ++- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 4e0040deb..949a11dc4 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -5137,13 +5137,13 @@ int TMoverParameters::PipeCouplersSubsteps(double const dt) const { auto substeps{1}; auto const area{Spg / (1.0 + 0.015 / Spg * Dim.L)}; // as in GetDVc() - for (auto const &coupler : Couplers) + for (auto const &hose : Couplers) { - if (coupler.Connected == nullptr || false == TestFlag(coupler.CouplingFlag, ctrain_pneumatic)) + if (hose.Connected == nullptr || false == TestFlag(hose.CouplingFlag, ctrain_pneumatic)) { continue; } - auto const &other{*coupler.Connected}; + auto const &other{*hose.Connected}; // the flow per bar of the difference, at small differences, where it's the largest auto const pressure{std::max(PipePress, other.PipePress)}; auto const conductance{std::abs(PF(pressure, pressure - 0.01, area)) / 0.01}; diff --git a/tests/unit/consist.cpp b/tests/unit/consist.cpp index 1226c8192..1f22632e6 100644 --- a/tests/unit/consist.cpp +++ b/tests/unit/consist.cpp @@ -94,7 +94,7 @@ void consist::step(track const &Track, double Dt) { update_brake_pipes(Dt); } -void consist::update_brake_pipes(double Dt) { +void consist::update_brake_pipes(double Dt) const { // vehicle_table::update_brake_pipes() std::vector movers; for (auto const &vehicle : m_vehicles) { diff --git a/tests/unit/consist.h b/tests/unit/consist.h index 282c8d07b..2c982e446 100644 --- a/tests/unit/consist.h +++ b/tests/unit/consist.h @@ -45,7 +45,7 @@ public: private: void update_neighbours(); - void update_brake_pipes(double Dt); + void update_brake_pipes(double Dt) const; std::vector> m_vehicles; std::vector m_positions; // of the vehicles' middles along the track diff --git a/tests/unit/test_brake_pipe.cpp b/tests/unit/test_brake_pipe.cpp index 18aa531e8..664f7262d 100644 --- a/tests/unit/test_brake_pipe.cpp +++ b/tests/unit/test_brake_pipe.cpp @@ -53,7 +53,8 @@ double application_time(test::consist &Train, double const Pressure, double cons } // the same train standing a minute, then braked from the locomotive, all of it in steps of Dt -double application_time(void (*Train)(test::consist &, int), int const Vehicles, double const Pressure, double const Dt) { +template +double application_time(Builder Train, int const Vehicles, double const Pressure, double const Dt) { test::consist train; Train(train, Vehicles); train.run(60.0, {}, Dt); From 8a185ee9807a31ee17a9d92482005b15301116d1 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 18:03:03 +0100 Subject: [PATCH 043/136] fix: exchange the main reservoir pipe air between vehicles after all of them stepped, in sub-steps The main reservoir hoses (ctrain_scndpneumatic) exchanged the air explicitly inside each vehicle's step at the physics step of 0.01 s, as the brake hoses did before eu07/maszyna#387. One step through the hose (0.38 of area, whatever the vehicles) moves about 1.5 times the air which evens out the pipes on its ends (EN57 cars 8.3 l per bar against 5.5 l, SM40 8.6 against 5.7, passenger cars 9.3 against 6.3), and the vehicles with a main reservoir of their own feed the pipe from it in the same step. Where a vehicle has both, and hoses on both ends, the pipe can't settle: with all the main reservoirs held at 7.0 bar, the middle cars of a three unit EN57 kept jumping 0.8 bar to and fro between the steps for good (6.6/7.4), three SM40s in multiple traction the same, a two unit Impuls 1.7 bar. Freely evening out, the reservoirs of a three unit EN57 took 13.9 s at 0.01 s against 7.6 s at 0.001 s. A locomotive with passenger cars, whose pipe only it feeds, was stable already. The main reservoir pipe now goes through the brake pipe's mechanism: UpdateScndPipePressure() leaves the hose exchange to UpdatePipeCouplers() (GetScndDVc(), ScndPipeCouplersSubsteps(), 2 sub-steps for these vehicles), which vehicle_table::update_brake_pipes() calls after every vehicle stepped. The two pipes share the code and take their sub-steps apart, so the brake pipe's exchange is as it was. With it the EN57 pipes stand at 7.000, and its reservoirs even out in 7.0 s against 7.5 s at 0.001 s. --- McZapkie/MOVER.h | 5 +- McZapkie/Mover.cpp | 182 +++++++++++++++++++++++----------- tests/unit/test_feed_pipe.cpp | 173 ++++++++++++++++++++++++++++++++ vehicle/DynObj.cpp | 5 +- vehicle/DynObj.h | 2 +- 5 files changed, 305 insertions(+), 62 deletions(-) create mode 100644 tests/unit/test_feed_pipe.cpp diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 0166ba30c..030c3f2ed 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2074,6 +2074,7 @@ class TMoverParameters double EmergencyValveFlow = 0.0; // air flow through alerter valve during last simulation step /*! przyrosty cisnienia w kroku czasowym*/ double ScndPipePress = 0.0; /*cisnienie w przewodzie zasilajacym*/ + bool ScndPipeCouplersPending{false}; // the main reservoir pipe stepped, its air exchange through the hoses is yet to come (UpdatePipeCouplers()) double BrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych*/ double LocBrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych z pomocniczego*/ double PipeBrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych z przewodu*/ @@ -2559,7 +2560,9 @@ class TMoverParameters void UpdateSpringBrake(double dt); double GetDVc(double dt); int PipeCouplersSubsteps(double dt) const; - // the air exchange through the brake hoses, after the vehicles stepped + double GetScndDVc(double dt); + int ScndPipeCouplersSubsteps(double dt) const; + // the air exchange through the brake and main reservoir hoses, after the vehicles stepped static void UpdatePipeCouplers(std::vector const &Vehicles, double dt); /*funkcje obliczajace sily*/ diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 949a11dc4..5e8c57ff9 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -4997,50 +4997,19 @@ void TMoverParameters::UpdateScndPipePressure(double dt) } const double Spz = 0.5067; - TMoverParameters *c; - double dv1; - double dv2; - double dV; UpdateSpringBrake(dt); - dv1 = 0; - dv2 = 0; - - // sprzeg 1 - if (Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic)) - { - c = Couplers[0].Connected; // skrot - dv1 = 0.5 * dt * PF(ScndPipePress, c->ScndPipePress, Spz * 0.75); - if (dv1 * dv1 > 0.00000000000001) - c->switch_physics(true); - c->Pipe2->Flow(-dv1); - } - // sprzeg 2 - if (Couplers[1].Connected != nullptr && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) - { - c = Couplers[1].Connected; // skrot - dv2 = 0.5 * dt * PF(ScndPipePress, c->ScndPipePress, Spz * 0.75); - if (dv2 * dv2 > 0.00000000000001) - c->switch_physics(true); - c->Pipe2->Flow(-dv2); - } - if (Couplers[1].Connected != nullptr && Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic) && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) - { - dV = 0.00025 * dt * PF(Couplers[0].Connected->ScndPipePress, Couplers[1].Connected->ScndPipePress, Spz * 0.25); - Couplers[0].Connected->Pipe2->Flow(+dV); - Couplers[1].Connected->Pipe2->Flow(-dV); - } - Pipe2->Flow(Hamulec->GetHPFlow(ScndPipePress, dt)); // NOTE: condition disabled to allow the air flow from the main hose to the main tank as well if (/* ( ( Compressor > ScndPipePress ) && ( */ VeselVolume > 0.0 /* ) ) || ( TrainType == dt_EZT ) || ( TrainType == dt_DMU ) */) { - dV = PF(Compressor, ScndPipePress, Spz) * dt; + double const dV = PF(Compressor, ScndPipePress, Spz) * dt; CompressedVolume += dV / 1000.0; Pipe2->Flow(-dV); } - Pipe2->Flow(dv1 + dv2); + // the air the main reservoir hoses carry to and from the neighbours comes once all vehicles have stepped, UpdatePipeCouplers() + ScndPipeCouplersPending = true; Pipe2->Act(); ScndPipePress = Pipe2->P(); @@ -5128,44 +5097,107 @@ double TMoverParameters::GetDVc(double dt) } // ************************************************************************************************* -// the number of sub-steps of dt the air exchange through the brake hoses of the vehicle needs: in one, the air -// a hose carries stays below what evens out the pipes on its ends. taken in a single step of 0.01 s, the hose -// between two 14 m freight wagons carries twice that, their pipes overshoot each other in turns and the -// distributors see the pressure up to 0.28 bar off what's in the pipe (eu07/maszyna#368) +// the air the main reservoir hoses carry between the vehicle's pipe and the neighbours' in dt: the neighbours' +// share is sent to them, the vehicle's own returned // ************************************************************************************************* -int TMoverParameters::PipeCouplersSubsteps(double const dt) const +double TMoverParameters::GetScndDVc(double dt) +{ + const double Spz = 0.5067; + TMoverParameters *c; + double dv1 = 0; + double dv2 = 0; + + // sprzeg 1 + if (Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic)) + { + c = Couplers[0].Connected; // skrot + dv1 = 0.5 * dt * PF(ScndPipePress, c->ScndPipePress, Spz * 0.75); + if (dv1 * dv1 > 0.00000000000001) + c->switch_physics(true); + c->Pipe2->Flow(-dv1); + } + // sprzeg 2 + if (Couplers[1].Connected != nullptr && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) + { + c = Couplers[1].Connected; // skrot + dv2 = 0.5 * dt * PF(ScndPipePress, c->ScndPipePress, Spz * 0.75); + if (dv2 * dv2 > 0.00000000000001) + c->switch_physics(true); + c->Pipe2->Flow(-dv2); + } + if (Couplers[1].Connected != nullptr && Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic) && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) + { + double const dV = 0.00025 * dt * PF(Couplers[0].Connected->ScndPipePress, Couplers[1].Connected->ScndPipePress, Spz * 0.25); + Couplers[0].Connected->Pipe2->Flow(+dV); + Couplers[1].Connected->Pipe2->Flow(-dV); + } + return dv1 + dv2; +} + +namespace +{ + +// a pipe along the train, whose air the hoses between the vehicles carry (TMoverParameters::UpdatePipeCouplers()) +struct train_pipe +{ + std::shared_ptr TMoverParameters::*reservoir; + double TMoverParameters::*pressure; + bool TMoverParameters::*pending; // the vehicle stepped the pipe, the exchange through its hoses is yet to come + int hose; // the coupling flag of the pipe's hose + double (TMoverParameters::*exchange)(double); // the air the hoses carry in a step, the neighbours' share sent to them + double (*area)(TMoverParameters const &); // the cross-section of the hose, as the exchange takes it +}; + +// the brake pipe, GetDVc() +train_pipe const brake_pipe{&TMoverParameters::Pipe, + &TMoverParameters::PipePress, + &TMoverParameters::PipeCouplersPending, + ctrain_pneumatic, + &TMoverParameters::GetDVc, + [](TMoverParameters const &Vehicle) { return Vehicle.Spg / (1.0 + 0.015 / Vehicle.Spg * Vehicle.Dim.L); }}; +// the main reservoir pipe, GetScndDVc() +train_pipe const main_reservoir_pipe{&TMoverParameters::Pipe2, + &TMoverParameters::ScndPipePress, + &TMoverParameters::ScndPipeCouplersPending, + ctrain_scndpneumatic, + &TMoverParameters::GetScndDVc, + [](TMoverParameters const &) { return 0.5067 * 0.75; }}; + +// the number of sub-steps of dt the air exchange through the hoses of the vehicle's pipe needs: in one, the air a +// hose carries stays below what evens out the pipes on its ends +int hose_substeps(TMoverParameters const &Vehicle, train_pipe const &Pipe, double const dt) { auto substeps{1}; - auto const area{Spg / (1.0 + 0.015 / Spg * Dim.L)}; // as in GetDVc() - for (auto const &hose : Couplers) + auto const area{Pipe.area(Vehicle)}; + auto const capacity{(Vehicle.*Pipe.reservoir)->GetCap()}; + for (auto const &hose : Vehicle.Couplers) { - if (hose.Connected == nullptr || false == TestFlag(hose.CouplingFlag, ctrain_pneumatic)) + if (hose.Connected == nullptr || false == TestFlag(hose.CouplingFlag, Pipe.hose)) { continue; } auto const &other{*hose.Connected}; + auto const othercapacity{(other.*Pipe.reservoir)->GetCap()}; // the flow per bar of the difference, at small differences, where it's the largest - auto const pressure{std::max(PipePress, other.PipePress)}; + auto const pressure{std::max(Vehicle.*Pipe.pressure, other.*Pipe.pressure)}; auto const conductance{std::abs(PF(pressure, pressure - 0.01, area)) / 0.01}; - auto const equalising{Pipe->GetCap() * other.Pipe->GetCap() / (Pipe->GetCap() + other.Pipe->GetCap())}; + auto const equalising{capacity * othercapacity / (capacity + othercapacity)}; substeps = std::max(substeps, static_cast(std::ceil(dt * conductance / equalising))); } return std::min(substeps, 10); } -// ************************************************************************************************* -// the air exchange through the brake hoses of the vehicles which stepped their brake pipe (UpdatePipePressure()) -// since the last call, in the order they stepped: in as many sub-steps of dt as the vehicle needing the most of -// them takes, each going through the vehicles one after another, as the step of the vehicles does -// ************************************************************************************************* -void TMoverParameters::UpdatePipeCouplers(std::vector const &Vehicles, double const dt) +// the air exchange through the hoses of the pipe, for the vehicles which stepped it since the last call, in the order +// they stepped: in as many sub-steps of dt as the vehicle needing the most of them takes, each going through the +// vehicles one after another, as the step of the vehicles does +void exchange_through_hoses(std::vector const &Vehicles, train_pipe const &Pipe, double const dt) { auto substeps{1}; for (auto const *vehicle : Vehicles) { - if (vehicle->PipeCouplersPending) + if (vehicle->*Pipe.pending) { - substeps = std::max(substeps, vehicle->PipeCouplersSubsteps(dt)); + substeps = std::max(substeps, hose_substeps(*vehicle, Pipe, dt)); } } auto const substep{dt / substeps}; @@ -5173,24 +5205,58 @@ void TMoverParameters::UpdatePipeCouplers(std::vector const { for (auto *vehicle : Vehicles) { - if (false == vehicle->PipeCouplersPending) + if (false == vehicle->*Pipe.pending) { continue; } - auto &pipe{*vehicle->Pipe}; + auto &pipe{*(vehicle->*Pipe.reservoir)}; pipe.Act(); // what the neighbours have sent in the meantime - vehicle->PipePress = pipe.P(); - pipe.Flow(vehicle->GetDVc(substep)); + vehicle->*Pipe.pressure = pipe.P(); + pipe.Flow((vehicle->*Pipe.exchange)(substep)); pipe.Act(); - vehicle->PipePress = pipe.P(); + vehicle->*Pipe.pressure = pipe.P(); } } for (auto *vehicle : Vehicles) { - vehicle->PipeCouplersPending = false; + vehicle->*Pipe.pending = false; } } +} // namespace + +// ************************************************************************************************* +// the number of sub-steps of dt the air exchange through the brake hoses of the vehicle needs. taken in a single +// step of 0.01 s, the hose between two 14 m freight wagons carries twice the air which evens out their pipes, the +// pipes overshoot each other in turns and the distributors see the pressure up to 0.28 bar off what's in the pipe +// (eu07/maszyna#368) +// ************************************************************************************************* +int TMoverParameters::PipeCouplersSubsteps(double const dt) const +{ + return hose_substeps(*this, brake_pipe, dt); +} + +// ************************************************************************************************* +// the number of sub-steps of dt the air exchange through the main reservoir hoses of the vehicle needs. taken in a +// single step of 0.01 s, the hose carries about 1.5 times the air which evens out the pipes on its ends; along with +// the vehicles' own main reservoirs feeding the pipe in the same step, the pipes of the middle vehicles of a +// multiple unit or of locomotives in multiple traction kept jumping 0.8 bar to and fro between the steps +// ************************************************************************************************* +int TMoverParameters::ScndPipeCouplersSubsteps(double const dt) const +{ + return hose_substeps(*this, main_reservoir_pipe, dt); +} + +// ************************************************************************************************* +// the air exchange through the brake and the main reservoir hoses of the vehicles which stepped their pipes +// (UpdatePipePressure(), UpdateScndPipePressure()) since the last call, each pipe in its own sub-steps +// ************************************************************************************************* +void TMoverParameters::UpdatePipeCouplers(std::vector const &Vehicles, double const dt) +{ + exchange_through_hoses(Vehicles, brake_pipe, dt); + exchange_through_hoses(Vehicles, main_reservoir_pipe, dt); +} + // ************************************************************************************************* // Q: 20160713 // Obliczenie stałych potrzebnych do dalszych obliczeń diff --git a/tests/unit/test_feed_pipe.cpp b/tests/unit/test_feed_pipe.cpp new file mode 100644 index 000000000..00e7596c4 --- /dev/null +++ b/tests/unit/test_feed_pipe.cpp @@ -0,0 +1,173 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "McZapkie/MOVER.h" +#include "McZapkie/hamulce.h" +#include "consist.h" +#include "vehicle.h" + +// the air exchange through the main reservoir hoses between the vehicles of a train (TMoverParameters::UpdatePipeCouplers()). +// taken in one explicit step of 0.01 s, a hose carried about 1.5 times the air which evens out the pipes on its ends, +// and the vehicles' own main reservoirs fed the pipe in the same step: the pipes of the middle vehicles of a multiple +// unit, or of locomotives in multiple traction, kept jumping 0.8 bar to and fro between the steps, with the main +// reservoirs all at the same pressure + +namespace { + +using test::definition; + +// an EN57 of Units units, driven from the front cab +void en57(test::consist &Train, int const Units) { + for (int i = 0; i < Units; ++i) { + Train.add(definition::fiz("en57_v1/5bgb"), i == 0 ? 1 : 0); + Train.add(definition::fiz("en57_v1/6ba_840")); + Train.add(definition::fiz("en57_v1/5bgb")); + } +} + +// Count SM40 shunters in multiple traction, driven from the first +void sm40(test::consist &Train, int const Count) { + for (int i = 0; i < Count; ++i) { + Train.add(definition::fiz("sm40_v1/sm40"), i == 0 ? 1 : 0); + } +} + +// a locomotive and Cars passenger cars, whose main reservoir pipe only the locomotive feeds +void passenger_train(test::consist &Train, int const Cars) { + Train.add(definition::fiz("ep09_v2/104e")); + for (int i = 0; i < Cars; ++i) { + Train.add(definition::fiz("11xa_v2/93a")); + } + Train[0].hold_brake_pipe(5.0); +} + +// the largest difference [bar] of a main reservoir pipe of the train from Pressure, over Seconds of steps of Dt +double off_pressure(test::consist &Train, double const Pressure, double const Seconds, double const Dt = 0.01) { + auto off{0.0}; + for (auto time = 0.0; time < Seconds; time += Dt) { + Train.step({}, Dt); + for (std::size_t i = 0; i < Train.size(); ++i) { + off = std::max(off, std::abs(Train[i]->ScndPipePress - Pressure)); + } + } + return off; +} + +struct evening_out { + double time{60.0}; // [s] until the main reservoirs of the train's ends are within 0.05 bar + double zigzag{0.0}; // [bar] the largest step of a main reservoir pipe back and forth, between steps the other way +}; + +// the train standing, the main reservoir of its first vehicle Pressure [bar], those of the rest 1 bar below, stepping +// by Dt until they even out through the main reservoir pipe +template +evening_out even_out(Builder Train, int const Count, double const Pressure, double const Dt) { + test::consist train; + Train(train, Count); + for (std::size_t i = 0; i < train.size(); ++i) { + auto &mover{train[i].mover()}; + REQUIRE(mover.VeselVolume > 0.0); + auto const pressure{i == 0 ? Pressure : Pressure - 1.0}; + mover.CompressedVolume = pressure * mover.VeselVolume; + mover.Compressor = pressure; + mover.Pipe2->CreatePress(pressure); + mover.Pipe2->Act(); + mover.ScndPipePress = pressure; + } + evening_out result; + auto &first{train[0].mover()}; + auto &last{train[train.size() - 1].mover()}; + std::vector previous(train.size()), change(train.size()); + for (std::size_t i = 0; i < train.size(); ++i) { + previous[i] = train[i]->ScndPipePress; + } + auto time{0.0}; + while (time < 60.0) { + train.step({}, Dt); + time += Dt; + for (std::size_t i = 0; i < train.size(); ++i) { + auto const step{train[i]->ScndPipePress - previous[i]}; + if (step * change[i] < 0.0) { + // turned back + result.zigzag = std::max(result.zigzag, std::min(std::abs(step), std::abs(change[i]))); + } + change[i] = step; + previous[i] = train[i]->ScndPipePress; + } + if (std::abs(first.Compressor - last.Compressor) < 0.05) { + result.time = time; + break; + } + } + return result; +} + +// the time [s] until the main reservoir pipe of the train's last vehicle, emptied with all the others which have no +// main reservoir of their own, is within 0.2 bar of the first vehicle's, which holds its main reservoir at Pressure [bar] +template +double charging_time(Builder Train, int const Count, double const Pressure, double const Dt) { + test::consist train; + Train(train, Count); + train[0].hold_main_reservoir(Pressure); + for (std::size_t i = 1; i < train.size(); ++i) { + auto &mover{train[i].mover()}; + REQUIRE(mover.VeselVolume == 0.0); + mover.Pipe2->CreatePress(0.0); + mover.Pipe2->Act(); + mover.ScndPipePress = 0.0; + } + auto &first{train[0].mover()}; + auto &last{train[train.size() - 1].mover()}; + auto time{0.0}; + while ((last.ScndPipePress < 1.0 || std::abs(last.ScndPipePress - first.ScndPipePress) > 0.2) && time < 60.0) { + train.step({}, Dt); + time += Dt; + } + return time; +} + +} // namespace + +TEST_CASE("main reservoir pipe: the pipes of a three unit EN57 stand at the pressure of its main reservoirs") { + test::consist train; + en57(train, 3); + for (std::size_t i = 0; i < train.size(); ++i) { + train[i].hold_main_reservoir(7.0); + } + // the pipes filling up from the reservoirs + train.run(60.0); + CHECK(off_pressure(train, 7.0, 1.0) < 0.01); + // the exchange through the hoses of the 21 m cars takes 2 sub-steps of a step of 0.01 s + CHECK(train[1]->ScndPipeCouplersSubsteps(0.01) == 2); +} + +TEST_CASE("main reservoir pipe: the pipes of locomotives in multiple traction stand at the pressure of their main reservoirs") { + test::consist train; + sm40(train, 3); + for (std::size_t i = 0; i < train.size(); ++i) { + train[i].hold_main_reservoir(7.5); + } + train.run(60.0); + CHECK(off_pressure(train, 7.5, 1.0) < 0.01); +} + +TEST_CASE("main reservoir pipe: the main reservoirs of a multiple unit even out as with a short step") { + auto const converged{even_out(en57, 3, 7.0, 0.001)}; + auto const usual{even_out(en57, 3, 7.0, 0.01)}; + CAPTURE(converged.time); + CAPTURE(usual.time); + CAPTURE(usual.zigzag); + CHECK(converged.time < 60.0); + CHECK(usual.time == doctest::Approx(converged.time).epsilon(0.1)); + // the pipes go along with the reservoirs, without jumping to and fro between the steps + CHECK(usual.zigzag < 0.05); +} + +TEST_CASE("main reservoir pipe: a passenger train, whose exchange was stable in one step, fills its pipe as with a short step") { + auto const converged{charging_time(passenger_train, 10, 9.0, 0.001)}; + auto const usual{charging_time(passenger_train, 10, 9.0, 0.01)}; + CAPTURE(converged); + CAPTURE(usual); + CHECK(converged < 60.0); + CHECK(usual == doctest::Approx(converged).epsilon(0.05)); +} diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 67f0d516c..64354d774 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -9048,13 +9048,14 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { } } -// the air exchange through the brake hoses of the vehicles which stepped their physics, after all of them did +// the air exchange through the brake and main reservoir hoses of the vehicles which stepped their physics, after all of them did void vehicle_table::update_brake_pipes( double const Deltatime ) { m_brakepipes.clear(); for( auto *vehicle : m_items ) { - if( true == vehicle->MoverParameters->PipeCouplersPending ) { + if( ( true == vehicle->MoverParameters->PipeCouplersPending ) + || ( true == vehicle->MoverParameters->ScndPipeCouplersPending ) ) { m_brakepipes.push_back( vehicle->MoverParameters ); } } diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index 8771146c5..7e2fb6e37 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -948,7 +948,7 @@ private: // the trains it closes in on void update_coupler_physics() const; - // the air exchange through the brake hoses of the vehicles which stepped their physics, after all of them did + // the air exchange through the brake and main reservoir hoses of the vehicles which stepped their physics, after all of them did void update_brake_pipes( double const Deltatime ); From c8f52c8b03b6d45ffaa060ed8070408a5101778a Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 20:22:53 +0100 Subject: [PATCH 044/136] test: Sonar on the main reservoir pipe test: an integer step counter, const references, one declaration a line --- tests/unit/test_feed_pipe.cpp | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/tests/unit/test_feed_pipe.cpp b/tests/unit/test_feed_pipe.cpp index 00e7596c4..55816af43 100644 --- a/tests/unit/test_feed_pipe.cpp +++ b/tests/unit/test_feed_pipe.cpp @@ -44,7 +44,8 @@ void passenger_train(test::consist &Train, int const Cars) { // the largest difference [bar] of a main reservoir pipe of the train from Pressure, over Seconds of steps of Dt double off_pressure(test::consist &Train, double const Pressure, double const Seconds, double const Dt = 0.01) { auto off{0.0}; - for (auto time = 0.0; time < Seconds; time += Dt) { + auto const steps{static_cast(std::lround(Seconds / Dt))}; + for (int step = 0; step < steps; ++step) { Train.step({}, Dt); for (std::size_t i = 0; i < Train.size(); ++i) { off = std::max(off, std::abs(Train[i]->ScndPipePress - Pressure)); @@ -75,9 +76,10 @@ evening_out even_out(Builder Train, int const Count, double const Pressure, doub mover.ScndPipePress = pressure; } evening_out result; - auto &first{train[0].mover()}; - auto &last{train[train.size() - 1].mover()}; - std::vector previous(train.size()), change(train.size()); + auto const &first{train[0].mover()}; + auto const &last{train[train.size() - 1].mover()}; + std::vector previous(train.size()); + std::vector change(train.size()); for (std::size_t i = 0; i < train.size(); ++i) { previous[i] = train[i]->ScndPipePress; } @@ -116,8 +118,8 @@ double charging_time(Builder Train, int const Count, double const Pressure, doub mover.Pipe2->Act(); mover.ScndPipePress = 0.0; } - auto &first{train[0].mover()}; - auto &last{train[train.size() - 1].mover()}; + auto const &first{train[0].mover()}; + auto const &last{train[train.size() - 1].mover()}; auto time{0.0}; while ((last.ScndPipePress < 1.0 || std::abs(last.ScndPipePress - first.ScndPipePress) > 0.2) && time < 60.0) { train.step({}, Dt); From dda38b6c0d03fe39b6da38e1c26f9b115f93d9ce Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 21:37:58 +0100 Subject: [PATCH 045/136] feat: the cruise control apart from the field shunting (eu07/maszyna#69) The secondary controller (ScndCtrl) is the switch of the cruise control (SpeedCtrl) on the vehicles which have one: its first position switches it on (IncScndCtrl), zero off (DecScndCtrl), and the speed buttons and steps work only off its zero position. On the 6Dg, the ST45 and the BR285, diesel-electrics with SpeedCtrl=Yes, the same controller shunts the field of the traction motors by itself (AutoRelay), refuses the driver's moves, and nothing could switch the cruise control on. Now the cruise control has a switch of its own wherever the secondary controller shunts the field (ElectricSeriesMotor, DieselElectric) or there's none: - IsSpeedCtrlSeparate(): which vehicles; IsSpeedCtrlEngaged(): on or off, SpeedCtrlUnit.IsActive for those, ScndCtrlPos > 0 for the rest; - SpeedCtrlSwitch(): the driver's switch, on at the speed of the moment or off; on the others IncScndCtrl(1) / DecScndCtrl(2), as before; - the buttons, the steps and the power limit go by IsSpeedCtrlEngaged(), the automatic turning off (SpeedCtrlATOF) by SpeedCtrlSwitch(false); - the cab's tempomat_sw / tempomatoff_sw toggle it, and follow its state rather than the secondary controller's; the AI's SpeedCntrl() uses it. The .fiz and .mmd formats are unchanged, with no new keys: the SpeedControl section and the cab's scndctrl and tempomat_sw entries stay as they are and now work side by side. Nothing changes for the vehicles with only one of the two: the whole unit test suite matches golden traces recorded before the change bit for bit. Tests (test_speed_control.cpp): the field shunting of the EU07, SM42 and SU45 and the cruise control of the Impuls and EU47 as before, the 6Dg's and ST45's shunting as before, the 6Dg's and ST45's cruise control on its own switch holding and changing the speed with the shunting going on by itself, the 214M railbus switched by the secondary controller through SpeedCtrlSwitch(). The 6Dg's definition joins tests/unit/data/fiz as on test/6dg-power-steps-real-data. --- McZapkie/MOVER.h | 9 + McZapkie/Mover.cpp | 54 +++- tests/unit/data/fiz/6dg_v1/6dg.json | 55 ++++ tests/unit/data/fiz/README.md | 3 +- tests/unit/test_speed_control.cpp | 395 ++++++++++++++++++++++++++++ vehicle/Driver.cpp | 13 +- vehicle/Train.cpp | 24 +- 7 files changed, 530 insertions(+), 23 deletions(-) create mode 100644 tests/unit/data/fiz/6dg_v1/6dg.json create mode 100644 tests/unit/test_speed_control.cpp diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index b619ba7de..7cdf004f4 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2498,6 +2498,7 @@ class TMoverParameters // ScndCtrlResistiveLock: the shunt controller drops to 0 once the master controller is at zero or on a resistive position, so it // can't stay engaged there, locked in place (eu07/maszyna#402) void ScndCtrlResistiveLockCheck(); + // NOTE: with the cruise control, either end of the secondary controller, as before the split of the two (eu07/maszyna#69) bool IsScndCtrlNoPowerPos() const; bool IsScndCtrlMaxPowerPos() const; @@ -2743,6 +2744,14 @@ class TMoverParameters void CheckEIMIC(double dt); // sprawdzenie i zmiana nastawy zintegrowanego nastawnika jazdy/hamowania void CheckSpeedCtrl(double dt); + // whether the cruise control has a switch of its own: the secondary controller doubles as its switch unless it + // shunts the field of the traction motors already, or there's none (the 6Dg, the ST45; eu07/maszyna#69) + bool IsSpeedCtrlSeparate() const; + // whether the cruise control is switched on: by its own switch, or by the secondary controller off its zero position + bool IsSpeedCtrlEngaged() const; + // the driver's switch of the cruise control: on, to hold the speed of the moment, or off. its own switch, or the + // secondary controller doubling as one (first position on, back to zero off); returns whether it did anything + bool SpeedCtrlSwitch(bool State); void SpeedCtrlButton(int button); void SpeedCtrlInc(); void SpeedCtrlDec(); diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 825137675..dacb9dd34 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -2577,7 +2577,7 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) OK = true; if (EIMCtrlType == 0 && ( SpeedCtrlAutoTurnOffFlag & 1 ) == 1 && MainCtrlActualPos != MainCtrlPos) { - DecScndCtrl(2); + SpeedCtrlSwitch(false); SpeedCtrlUnit.IsActive = false; } break; @@ -2755,7 +2755,7 @@ bool TMoverParameters::DecMainCtrl(int CtrlSpeed) OK = true; if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1 && MainCtrlActualPos != MainCtrlPos) { - DecScndCtrl(2); + SpeedCtrlSwitch(false); SpeedCtrlUnit.IsActive = false; } } @@ -8043,7 +8043,7 @@ void TMoverParameters::CheckSpeedCtrl(double dt) } if ((SpeedCtrlAutoTurnOffFlag & 2) == 2 && Hamulec->GetEDBCP() > 0.25) { - DecScndCtrl(2); + SpeedCtrlSwitch(false); SpeedCtrlUnit.IsActive = false; } } @@ -8056,9 +8056,47 @@ void TMoverParameters::CheckSpeedCtrl(double dt) } } +bool TMoverParameters::IsSpeedCtrlSeparate() const +{ + // no secondary controller, or one of these engines', which shunts the field of the traction motors (eu07/maszyna#69) + return SpeedCtrl && (ScndCtrlPosNo == 0 || EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric); +} + +bool TMoverParameters::IsSpeedCtrlEngaged() const +{ + return IsSpeedCtrlSeparate() ? SpeedCtrlUnit.IsActive : ScndCtrlPos > 0; +} + +bool TMoverParameters::SpeedCtrlSwitch(bool const State) +{ + if (false == IsSpeedCtrlSeparate()) + { + return State ? IncScndCtrl(1) : DecScndCtrl(2); + } + // its own switch, the secondary controller left to the field shunting + if (State) + { + if (CabActive == 0 || SpeedCtrlUnit.IsActive) + { + return false; + } + SpeedCtrlValue = static_cast(Round(Vel)); + SpeedCtrlUnit.IsActive = true; + return true; + } + auto const wasactive{SpeedCtrlUnit.IsActive}; + SpeedCtrlValue = 0; + SpeedCtrlUnit.IsActive = false; + if (wasactive && SpeedCtrlUnit.ManualStateOverride) + { + eimic = 0.0; + } + return wasactive; +} + void TMoverParameters::SpeedCtrlButton(int button) { - if (SpeedCtrl && ScndCtrlPos > 0) + if (SpeedCtrl && IsSpeedCtrlEngaged()) { SpeedCtrlValue = SpeedCtrlButtons[button]; } @@ -8066,7 +8104,7 @@ void TMoverParameters::SpeedCtrlButton(int button) void TMoverParameters::SpeedCtrlInc() { - if (SpeedCtrl && ScndCtrlPos > 0) + if (SpeedCtrl && IsSpeedCtrlEngaged()) { double x = floor(SpeedCtrlValue / SpeedCtrlUnit.VelocityStep) + 1.0; SpeedCtrlValue = std::min(x * SpeedCtrlUnit.VelocityStep, SpeedCtrlUnit.MaxVelocity); @@ -8075,7 +8113,7 @@ void TMoverParameters::SpeedCtrlInc() void TMoverParameters::SpeedCtrlDec() { - if (SpeedCtrl && ScndCtrlPos > 0) + if (SpeedCtrl && IsSpeedCtrlEngaged()) { double x = ceil(SpeedCtrlValue / SpeedCtrlUnit.VelocityStep) - 1.0; SpeedCtrlValue = std::max(x * SpeedCtrlUnit.VelocityStep, SpeedCtrlUnit.MinVelocity); @@ -8084,7 +8122,7 @@ void TMoverParameters::SpeedCtrlDec() bool TMoverParameters::SpeedCtrlPowerInc() { - if (!(SpeedCtrl && ScndCtrlPos > 0)) + if (!(SpeedCtrl && IsSpeedCtrlEngaged())) return false; if (SpeedCtrlUnit.DesiredPower == SpeedCtrlUnit.MaxPower) @@ -8096,7 +8134,7 @@ bool TMoverParameters::SpeedCtrlPowerInc() bool TMoverParameters::SpeedCtrlPowerDec() { - if (!(SpeedCtrl && ScndCtrlPos > 0)) + if (!(SpeedCtrl && IsSpeedCtrlEngaged())) return false; if (SpeedCtrlUnit.DesiredPower == SpeedCtrlUnit.MinPower) diff --git a/tests/unit/data/fiz/6dg_v1/6dg.json b/tests/unit/data/fiz/6dg_v1/6dg.json new file mode 100644 index 000000000..9ad99dec4 --- /dev/null +++ b/tests/unit/data/fiz/6dg_v1/6dg.json @@ -0,0 +1,55 @@ +{ + "_source": "pkp/6dg_v1/6dg.fiz", + "_comment": "converted by test_fiz.cpp from the game's definition with the files it includes, keeping what the game's loader reads", + "Param": {"Category": "train", "M": "70000", "Mred": "10000", "Vmax": "90", "PWR": "708", "SandCap": "300"}, + "Dimensions": {"L": "14.24", "H": "4.285", "W": "3.170", "Cx": "0.2"}, + "Wheels": {"D": "1.100", "AIM": "4000", "Tw": "1.435", "Axle": "Bo'Bo'", "Ad": "2.6", "Bd": "7.524", "Rmin": "80"}, + "Brake": {"BrakeValve": "LSt", "NBpA": "4", "MBF": "85.0", "MaxBP": "6.2", "MaxASBP": "2.0", "BCN": "4", "BCR": "0.1143", "BCD": "0.05", "BCM": "6.68", "HiPP": "5.0", "LoPP": "3.5", "Vv": "0.8", "MinCP": "7.5", "MaxCP": "8.5", "CompressorSpeed": "0.05", "CompressorPower": "Converter", "BVV": "200", "BRE": "0.9", "UBB1": "1", "UBB2": "12", "UBB3": "16", "HandlePipeUnlockPos": "-0.5", "LPOn": "2.75", "LPOff": "4.5"}, + "BuffCoupl": {"ControlType": "6Dg", "CType": "Screw", "kB": "9200", "DmaxB": "0.15", "FmaxB": "740", "kC": "4800", "DmaxC": "0.15", "FmaxC": "780", "beta": "0.58", "AllowedFlag": "39"}, + "Cntrl": {"BrakeSystem": "Pneumatic", "BCPN": "10", "BDelay1": "15", "BDelay2": "3", "BDelay3": "35", "BDelay4": "36", "ASB": "Manual", "LocalBrake": "PneumaticBrake", "MCPN": "6", "SCPN": "1", "AutoRelay": "Yes", "IniCDelay": "0.5", "SCDelay": "0.1", "BrakeDelays": "GP", "BrakeHandle": "MHZ_K8P", "LocBrakeHandle": "FD1", "ConverterStart": "Automatic", "ConverterStartDelay": "10", "FuelStart": "Automatic", "OilStart": "Automatic", "BrakeOpModes": "PN", "EIMCtrlType": "3", "DirChangeMaxPos": "3", "HAO": "No", "HMO": "Yes", "HGDP1": "2", "rows": [ + ["-1","0.7","-1","15","Pneumatic"], + ["0","0.5","-1","9","Pneumatic"], + ["1","0.46","-1","9","Pneumatic"], + ["2","0.42","-1","9","Pneumatic"], + ["3","0.38","-1","9","Pneumatic"], + ["4","0.34","-1","9","Pneumatic"], + ["5","0.29","-1","9","Pneumatic"], + ["6","0","-1","15","Pneumatic"] + ]}, + "Security": {"AwareSystem": "Active,CabSignal", "AwareDelay": "60", "SoundSignalDelay": "5", "MaxHoldTime": "1.0", "EmergencyBrakeDelay": "6", "RadioStop": "Yes"}, + "Light": {"Light": "Generator", "LGeneratorEngine": "ElectricSeriesMotor", "LMaxVoltage": "110", "LMaxCurrent": "91"}, + "Engine": {"AIM": "0.55", "EngineType": "DumbDE", "Trans": "17:75", "Ftmax": "219000", "Vhyp": "7", "Vadd": "5.5", "Cr": "1", "ShuntMode": "0", "WaterCoolingTemperature": "81", "WaterCoolingFanSpeed": "-1200", "WaterMaxTemperature": "85", "OilMinPressure": "0.15", "OilMinTemperature": "25", "OilMaxTemperature": "90", "HeaterMinTemperature": "55", "HeaterMaxTemperature": "60", "HeatKFS": "35", "HeatKFO": "30", "HeatKFE": "7", "HeatKW": "0.01", "HeatKV": "0.3", "HeatKFO2": "100"}, + "MotorParamTable": {"rows": [ + ["0","17.567","64","1500","15","800","1320"], + ["1","15","183.3","2000","49","800","1320"] + ]}, + "SpringBrake": {"Volume": "8", "MBF": "5", "MaxSP": "6", "ResetP": "4.0", "MinFP": "3.5", "PressOff": "4.5", "PressOn": "3.5", "ValveOnArea": "0.0002", "ValveOffArea": "0.0002", "ValvePNBArea": "0.002", "MTC": "4"}, + "WWList": {"Size": "6", "rows": [ + ["596","0","0","0"], + ["840","120","324","1150"], + ["1080","240","468","1350"], + ["1320","360","612","1550"], + ["1560","480","756","1750"], + ["1800","600","900","2000"], + ["1800","600","900","2000"] + ]}, + "SpeedControl": {"SpeedCtrl": "Yes", "OverrideManual": "Yes", "InitPwr": "0.3", "MaxPwrVel": "5", "StartVel": "2", "MinPwr": "0.3", "MaxPwr": "1.0", "MinVel": "0", "MaxVel": "120", "Offset": "-0.5", "kPpos": "0.1", "kPneg": "0.4", "kIpos": "0.06", "kIneg": "0.06", "BrakeIntervention": "Yes"}, + "LightsList": {"Size": "7", "Wrap": "no", "Default": "1", "rows": [ + ["0","0"], + ["34","34"], + ["38","34"], + ["22","34"], + ["16","1"], + ["1","16"], + ["21","34"] + ]}, + "UCList": {"Size": "6", "IntegratedBrakePN": "no", "IntegratedLocBrake": "yes", "IntegratedBrake": "no", "CtrlValStep": "0.05", "rows": [ + ["0","0","-1","0","-1","0.15","0.15","0","1","1"], + ["1","0","-1","0","0","0.00","0.00","1","3","1"], + ["2","0","-1","0","0","0.15","0.00","1","3","1"], + ["3","0","0","0","0","0.00","0.00","1","5","3"], + ["4","0","0","1","0","0.00","0.15","3","5","5"], + ["5","0","0","1","0","0.00","0.00","3","6","5"], + ["6","0","0","1","1","0.15","0.15","5","6","5"] + ]} +} diff --git a/tests/unit/data/fiz/README.md b/tests/unit/data/fiz/README.md index 514fb6287..e29a85dbb 100644 --- a/tests/unit/data/fiz/README.md +++ b/tests/unit/data/fiz/README.md @@ -20,6 +20,7 @@ Every `.json` here is a vehicle picked up by `test_fiz.cpp`: record the paramete | `3wl_v2/3wl.fiz` | 3WL | - | ESt3 | - | ManualBrake | Screw | | `430w_v2/430w.fiz` | 430W | - | ESt3AL2HBG300 | - | ManualBrake | Screw | | `4e_v1/4e.fiz` | 4E | ElectricSeriesMotor | LSt | FV4a | PneumaticBrake | Screw | +| `6dg_v1/6dg.fiz` | 6Dg | DumbDE | LSt | MHZ_K8P | PneumaticBrake | Screw | | `bdhpumn_v3/bdhpumn.fiz` | BDHPUMN | - | KE | - | ManualBrake | Screw | | `bhp_v1/bhp-b.fiz` | BHP | - | ESt3AL2 | - | ManualBrake | Articulated | | `br285_v1/br285.fiz` | BR285 | DieselElectric | KE | MHZ_6P | PneumaticBrake | Screw | @@ -63,4 +64,4 @@ Every `.json` here is a vehicle picked up by `test_fiz.cpp`: record the paramete | `wmb10_v1/wmb10.fiz` | WMB10 | DieselEngine | LSt | FV4a | PneumaticBrake | Screw | | `z1_v2/152a.fiz` | Z1 | - | KE | - | ManualBrake | Screw | -The paths are those of the game's `.fiz` files. `elf_v1/inverter.fiz` is a part the Elf units include, not a vehicle. The 218M (V2NList), the SA134 (HTCList) and the 22WEc (ffBrakeList) are there for lists the others lack, the EP05 for its camshaft. The 214MA stands for the 214M railbus, whose own file repeats a section (TurboPos and MotorParamTable twice), which the definitions here can't hold. +The paths are those of the game's `.fiz` files. `elf_v1/inverter.fiz` is a part the Elf units include, not a vehicle. The 218M (V2NList), the SA134 (HTCList) and the 22WEc (ffBrakeList) are there for lists the others lack, the EP05 for its camshaft. The 6Dg is there for its universal controller (UCList) setting the power in steps (CtrlValStep), converted alone from the game data of 2026-11 (SVN r9630, which added the key), the others staying as they were. The 214MA stands for the 214M railbus, whose own file repeats a section (TurboPos and MotorParamTable twice), which the definitions here can't hold. diff --git a/tests/unit/test_speed_control.cpp b/tests/unit/test_speed_control.cpp new file mode 100644 index 000000000..a141f41a6 --- /dev/null +++ b/tests/unit/test_speed_control.cpp @@ -0,0 +1,395 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scenario.h" +#include "drive.h" + +#include + +// the cruise control (tempomat, SpeedCtrl) and the secondary controller (ScndCtrl) of the vehicles which have one +// of them or both (eu07/maszyna#69). on the vehicles with the cruise control alone the secondary controller is +// its switch, as it always was; on those whose secondary controller shunts the field of the traction motors +// (the 6Dg, the ST45 and the BR285 among them) the cruise control has a switch of its own, apart from it + +using test::scenario; +using namespace test::channels; + +namespace { + +std::vector cruise() { + return { + {"SpeedCtrlActive", [](auto const &M) { return M.SpeedCtrlUnit.IsActive ? 1.0 : 0.0; }}, + {"SpeedCtrlStandby", [](auto const &M) { return M.SpeedCtrlUnit.Standby ? 1.0 : 0.0; }}, + {"SpeedCtrlValue", [](auto const &M) { return M.SpeedCtrlValue; }}, + {"eimic", [](auto const &M) { return M.eimic; }}, + {"eimicSpeedCtrl", [](auto const &M) { return M.eimicSpeedCtrl; }}, + {"eimic_real", [](auto const &M) { return M.eimic_real; }}, + }; +} + +// the universal controller (EIMCtrlType 3) of the 6Dg: 3 no power, 4 lowers the demand, 5 holds it, 6 raises it +constexpr int dg_no_power{3}; +constexpr int dg_lower{4}; +constexpr int dg_hold{5}; +constexpr int dg_raise{6}; + +void move_to(TMoverParameters &Vehicle, int const Position) { + while (Vehicle.MainCtrlPos < Position && Vehicle.IncMainCtrl(1)) { + ; + } + while (Vehicle.MainCtrlPos > Position && Vehicle.DecMainCtrl(1)) { + ; + } + REQUIRE(Vehicle.MainCtrlPos == Position); +} + +// the 6Dg started up, its brakes released, its controller through the no power and lowering positions to holding, +// for the line contactors to close +void get_6dg_going(scenario &Scenario) { + auto &loco{Scenario.cab()}; + REQUIRE(Scenario.start_up()); + Scenario.get_going(); + move_to(loco, dg_no_power); + for (int second = 0; second < 180 && loco.BrakePress > 0.1; ++second) { + Scenario.wait(1.0); + } + REQUIRE(loco.BrakePress <= 0.1); + move_to(loco, dg_lower); + Scenario.wait(1.0); + move_to(loco, dg_hold); + Scenario.wait(5.0); + REQUIRE(loco.StLinFlag); +} + +} // namespace + +// the vehicles with the field shunting alone, and those with the cruise control alone: as before the split + +TEST_CASE("speed control: the field shunting of the vehicles without a cruise control, as before") { + // the EU07's and the SM42's shunting by hand, the SU45's by itself (RelayType 45, from position 11 of its + // controller on); none has a cruise control, and the secondary controller shunts the field + SUBCASE("EU07 and SM42, by hand") { + for (auto const *path : {"4e_v1/4e", "sm42_v1/6d1"}) { + CAPTURE(path); + scenario scenario{std::string{"speed control/shunting/"} + path, motion() + traction() + cruise()}; + scenario.add(path, 1); + auto &loco{scenario.cab()}; + REQUIRE_FALSE(loco.SpeedCtrl); + REQUIRE_FALSE(loco.AutoRelayFlag); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(60.0); + auto const speed{loco.Vel}; + scenario.act("shunt"); + CHECK(loco.IncScndCtrl(1)); + CHECK(loco.ScndCtrlPos == 1); + scenario.wait(10.0); + CHECK(loco.Vel > speed); + CHECK(loco.ScndCtrlPos == 1); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + CHECK(loco.SpeedCtrlValue == 0.0); + scenario.act("shunt off"); + CHECK(loco.DecScndCtrl(2)); + CHECK(loco.ScndCtrlPos == 0); + scenario.wait(5.0); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + scenario.check(); + } + } + SUBCASE("SU45, by itself") { + scenario scenario{"speed control/shunting/su45_v2/301d", motion() + traction() + cruise()}; + scenario.add("su45_v2/301d", 1); + auto &loco{scenario.cab()}; + REQUIRE_FALSE(loco.SpeedCtrl); + REQUIRE(loco.AutoRelayFlag); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(5.0); + auto most{0}; + for (int i = 0; i < 18; ++i) { + scenario.wait(10.0); + most = std::max(most, loco.ScndCtrlPos); + } + CHECK(most == loco.ScndCtrlPosNo); + // the driver can't move it + CHECK_FALSE(loco.DecScndCtrl(2)); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + scenario.act("notch back"); + scenario.notch_back(0); + scenario.wait(5.0); + CHECK(loco.ScndCtrlPos == 0); + scenario.check(); + } +} + +TEST_CASE("speed control: the vehicles whose secondary controller is the cruise control's switch, as before") { + SUBCASE("Impuls: on at the speed of the moment, off by the controller") { + scenario scenario{"speed control/cruise/impuls_v1/31we-a_pr", motion() + traction() + cruise()}; + scenario.add("impuls_v1/31we-a_pr", 1).add("impuls_v1/31we-b_pr").add("impuls_v1/31we-c_pr").add("impuls_v1/31we-d_pr"); + auto &unit{scenario.cab()}; + REQUIRE(unit.SpeedCtrl); + REQUIRE(unit.ScndCtrlPosNo == 1); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(40.0); + scenario.act("cruise control on"); + CHECK(unit.IncScndCtrl(1)); + CHECK(unit.ScndCtrlPos == 1); + CHECK(unit.SpeedCtrlUnit.IsActive); + CHECK(unit.SpeedCtrlValue == doctest::Approx(unit.Vel)); + auto const held{unit.SpeedCtrlValue}; + scenario.wait(60.0); + CHECK(unit.Vel == doctest::Approx(held).epsilon(0.05)); + scenario.act("cruise control off"); + CHECK(unit.DecScndCtrl(2)); + CHECK(unit.ScndCtrlPos == 0); + CHECK_FALSE(unit.SpeedCtrlUnit.IsActive); + CHECK(unit.SpeedCtrlValue == 0.0); + scenario.wait(5.0); + scenario.check(); + } + SUBCASE("EU47: the speed raised by tens while the controller is held up, set when it's let go") { + scenario scenario{"speed control/cruise/e186_v2/eu47", motion() + traction() + cruise()}; + scenario.add("e186_v2/eu47", 1); + auto &loco{scenario.cab()}; + REQUIRE(loco.SpeedCtrl); + REQUIRE(loco.SpeedCtrlTypeTime); + REQUIRE(loco.ScndCtrlPosNo == 4); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.act("raise"); + while (loco.ScndCtrlPos < 3 && loco.IncScndCtrl(1)) { + ; + } + REQUIRE(loco.ScndCtrlPos == 3); + scenario.wait(10.0); + CHECK(loco.NewSpeed > 0.0); + scenario.act("set"); + CHECK(loco.DecScndCtrl(1)); + scenario.wait(1.0); + CHECK(loco.SpeedCtrlValue == doctest::Approx(loco.NewSpeed)); + CHECK(loco.SpeedCtrlUnit.IsActive); + scenario.full_power(60.0); + CHECK(loco.Vel == doctest::Approx(loco.SpeedCtrlValue).epsilon(0.1)); + scenario.act("off"); + CHECK(loco.DecScndCtrl(2)); + scenario.wait(1.0); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + scenario.check(); + } +} + +// the vehicles with both: the field shunting as before, the cruise control on a switch of its own + +TEST_CASE("speed control: the field shunting of the vehicles with a cruise control besides, as before") { + SUBCASE("6Dg") { + scenario scenario{"speed control/both/6dg_v1/6dg", motion() + traction() + cruise(), test::track{}}; + scenario.add("6dg_v1/6dg", 1); + auto &loco{scenario.cab()}; + REQUIRE(loco.SpeedCtrl); + REQUIRE(loco.AutoRelayFlag); + REQUIRE(loco.ScndCtrlPosNo == 1); + get_6dg_going(scenario); + scenario.act("raise"); + move_to(loco, dg_raise); + // the shunt engages by itself at about 40 km/h (RelayType 0, by the current of the motors) + scenario.wait(10.0); + CHECK(loco.Vel < 35.0); + CHECK(loco.ScndCtrlPos == 0); + scenario.wait(110.0); + CHECK(loco.Vel > 100.0); + CHECK(loco.ScndCtrlPos == 1); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + CHECK(loco.eimic_real == doctest::Approx(loco.eimic)); + // the driver can't move the shunt + CHECK_FALSE(loco.IncScndCtrl(1)); + CHECK_FALSE(loco.DecScndCtrl(2)); + scenario.check(); + } + SUBCASE("ST45") { + scenario scenario{"speed control/both/st45_v2/301dd", motion() + traction() + cruise(), test::track{}}; + scenario.add("st45_v2/301dd", 1); + auto &loco{scenario.cab()}; + REQUIRE(loco.SpeedCtrl); + REQUIRE(loco.AutoRelayFlag); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(5.0); + // its relays (RelayType 45) engage the shunt from position 11 of the controller on, which the universal + // controller of the ST45, of 4 positions, never gets to: the shunt stays off + auto most{0}; + for (int i = 0; i < 9; ++i) { + scenario.wait(10.0); + most = std::max(most, loco.ScndCtrlPos); + } + CHECK(loco.Vel > 130.0); + CHECK(most == 0); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + CHECK(loco.eimic_real == doctest::Approx(loco.eimic)); + // the speed buttons do nothing with the cruise control off + loco.SpeedCtrlButton(4); + loco.SpeedCtrlInc(); + CHECK(loco.SpeedCtrlValue == 0.0); + CHECK_FALSE(loco.IncScndCtrl(1)); + scenario.check(); + } +} + +TEST_CASE("speed control apart: which vehicles' cruise control has a switch of its own") { + struct kind { + char const *path; + bool separate; + }; + for (auto const &[path, separate] : { + // the secondary controller shunts the field: a switch of its own + kind{"6dg_v1/6dg", true}, kind{"st45_v2/301dd", true}, kind{"br285_v1/br285", true}, + // the secondary controller is the switch, the speed setter or the gears' selector of the automatic gearbox + kind{"21xm_v1/214ma", false}, kind{"21xm_v1/218ma_a_kd", false}, kind{"sa134_v1/218mc_a", false}, kind{"impuls_v1/31we-a_pr", false}, + kind{"elf_v1/21we-a", false}, kind{"e186_v2/eu47", false}, kind{"e6act_v2/e6acta", false}, kind{"en57akl_v1/akl_ra", false}, + // no cruise control + kind{"4e_v1/4e", false}, kind{"sm42_v1/6d1", false}, kind{"su45_v2/301d", false}, kind{"ep09_v2/104e", false}}) { + CAPTURE(path); + test::vehicle vehicle{test::definition::fiz(path)}; + CHECK(vehicle->IsSpeedCtrlSeparate() == separate); + CHECK_FALSE(vehicle->IsSpeedCtrlEngaged()); + } + // with a cruise control and no secondary controller, the switch is its own too + test::vehicle eu07{test::definition::fiz("4e_v1/4e").set("Cntrl", "SCPN", 0).set("SpeedControl", "SpeedCtrl", "Yes")}; + CHECK(eu07->IsSpeedCtrlSeparate()); +} + +TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the field shunting going on by itself") { + scenario scenario{"speed control apart/6dg_v1/6dg", motion() + traction() + cruise(), test::track{}}; + scenario.add("6dg_v1/6dg", 1); + auto &loco{scenario.cab()}; + get_6dg_going(scenario); + scenario.act("raise"); + move_to(loco, dg_raise); + scenario.wait(30.0); + REQUIRE(loco.Vel > 50.0); + REQUIRE(loco.ScndCtrlPos == 1); // the shunt in + // the shunt is no cruise control: its buttons do nothing yet, the secondary controller can't switch it on + CHECK_FALSE(loco.IsSpeedCtrlEngaged()); + loco.SpeedCtrlButton(2); + CHECK(loco.SpeedCtrlValue == 0.0); + CHECK_FALSE(loco.IncScndCtrl(1)); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + + scenario.act("cruise control on"); + CHECK(loco.SpeedCtrlSwitch(true)); + CHECK_FALSE(loco.SpeedCtrlSwitch(true)); // on already + CHECK(loco.SpeedCtrlUnit.IsActive); + CHECK(loco.IsSpeedCtrlEngaged()); + CHECK(loco.SpeedCtrlValue == doctest::Approx(std::round(loco.Vel)).epsilon(0.02)); + CHECK(loco.ScndCtrlPos == 1); // the shunt as it was + auto const held{loco.SpeedCtrlValue}; + // the shunt goes by itself all the while, by the current of the motors, which the cruise control's demand sets + auto shunted{0}; + auto unshunted{0}; + auto const run{[&](int const Seconds) { + for (int second = 0; second < Seconds; ++second) { + scenario.wait(1.0); + ++(loco.ScndCtrlPos > 0 ? shunted : unshunted); + } + }}; + run(60); + CHECK(loco.Vel == doctest::Approx(held).epsilon(0.03)); + CHECK_FALSE(loco.SpeedCtrlUnit.Standby); + CHECK(loco.eimic_real < loco.eimic); // the cruise control holding the power back + + scenario.act("two steps up"); + loco.SpeedCtrlInc(); + loco.SpeedCtrlInc(); + auto const higher{loco.SpeedCtrlValue}; + CHECK(higher == doctest::Approx(held + 10.0).epsilon(0.1)); + run(60); + CHECK(loco.Vel == doctest::Approx(higher).epsilon(0.03)); + CHECK(loco.StLinFlag); + CHECK(shunted > 0); + CHECK(unshunted > 0); + CHECK_FALSE(loco.IncScndCtrl(1)); // still not the driver's + + scenario.act("button 30"); + loco.SpeedCtrlButton(0); + CHECK(loco.SpeedCtrlValue == doctest::Approx(30.0)); + scenario.wait(60.0); + // it brakes down with the air (BrakeIntervention), which opens the line contactors (the pressure switch), and + // they close again only through the first power position of the controller, as without the cruise control + CHECK(loco.Vel < 35.0); + CHECK_FALSE(loco.StLinFlag); + scenario.act("controller to the first power position and back up"); + move_to(loco, dg_lower); + scenario.wait(2.0); + move_to(loco, dg_raise); + scenario.wait(60.0); + CHECK(loco.StLinFlag); + CHECK(loco.Vel == doctest::Approx(30.0).epsilon(0.05)); + CHECK(loco.ScndCtrlPos == 0); // out at this speed + + scenario.act("cruise control off"); + CHECK(loco.SpeedCtrlSwitch(false)); + CHECK_FALSE(loco.SpeedCtrlSwitch(false)); // off already + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + CHECK(loco.SpeedCtrlValue == 0.0); + scenario.wait(5.0); + CHECK(loco.eimic_real == doctest::Approx(loco.eimic)); // the controller's demand again + scenario.check(); +} + +TEST_CASE("speed control apart: the ST45's cruise control on its own switch, with its buttons and the power limit") { + scenario scenario{"speed control apart/st45_v2/301dd", motion() + traction() + cruise(), test::track{}}; + scenario.add("st45_v2/301dd", 1); + auto &loco{scenario.cab()}; + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(0.0); + REQUIRE(loco.Vel < 50.0); + scenario.act("cruise control on, button 60"); + CHECK(loco.SpeedCtrlSwitch(true)); + CHECK(loco.SpeedCtrlUnit.IsActive); + loco.SpeedCtrlButton(4); + CHECK(loco.SpeedCtrlValue == doctest::Approx(60.0)); + scenario.wait(90.0); + CHECK(loco.Vel == doctest::Approx(60.0).epsilon(0.03)); + CHECK(loco.StLinFlag); + scenario.act("step up, power down"); + loco.SpeedCtrlInc(); + CHECK(loco.SpeedCtrlValue == doctest::Approx(65.0)); + CHECK(loco.SpeedCtrlPowerDec()); + CHECK(loco.SpeedCtrlUnit.DesiredPower == doctest::Approx(0.9)); + scenario.wait(60.0); + CHECK(loco.Vel == doctest::Approx(65.0).epsilon(0.03)); + CHECK(loco.eimic_real <= 0.9 + 1e-9); + scenario.act("cruise control off"); + CHECK(loco.SpeedCtrlSwitch(false)); + // off, its buttons do nothing + loco.SpeedCtrlButton(6); + loco.SpeedCtrlInc(); + CHECK_FALSE(loco.SpeedCtrlPowerInc()); + CHECK(loco.SpeedCtrlValue == 0.0); + scenario.wait(5.0); + CHECK(loco.ScndCtrlPos == 0); + scenario.check(); +} + +TEST_CASE("speed control apart: the switch of a cruise control without one of its own is the secondary controller, as before") { + // the 214M railbus: on, its first position; off, back to zero + scenario scenario{"speed control apart/21xm_v1/214ma", motion() + traction() + cruise(), test::track{}}; + scenario.add("21xm_v1/214ma", 1); + auto &railbus{scenario.cab()}; + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(20.0); + scenario.act("cruise control on"); + CHECK(railbus.SpeedCtrlSwitch(true)); + CHECK(railbus.ScndCtrlPos == 1); + CHECK(railbus.SpeedCtrlUnit.IsActive); + CHECK(railbus.IsSpeedCtrlEngaged()); + scenario.wait(10.0); + scenario.act("cruise control off"); + CHECK(railbus.SpeedCtrlSwitch(false)); + CHECK(railbus.ScndCtrlPos == 0); + CHECK_FALSE(railbus.SpeedCtrlUnit.IsActive); + CHECK_FALSE(railbus.IsSpeedCtrlEngaged()); + scenario.wait(5.0); + scenario.check(); +} diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index eb74344bf..594f660ce 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -4474,7 +4474,16 @@ void TController::SpeedCntrl(double DesiredSpeed) { if( false == mvControlling->SpeedCtrl ) { return; } - if (mvControlling->EngineType == TEngineType::DieselEngine) + if (mvControlling->IsSpeedCtrlSeparate()) + { + // a switch of its own, the secondary controller left to the field shunting (eu07/maszyna#69) + if (DesiredSpeed < 0.1) { + DesiredSpeed = 0; + } + mvControlling->SpeedCtrlSwitch(DesiredSpeed > 0); + mvControlling->RunCommand("SpeedCntrl", DesiredSpeed, mvControlling->CabActive); + } + else if (mvControlling->EngineType == TEngineType::DieselEngine) { if (DesiredSpeed < 0.1) { mvControlling->DecScndCtrl(2); @@ -4498,7 +4507,7 @@ void TController::SpeedCntrl(double DesiredSpeed) while( mvControlling->ScndCtrlPos < DesiredPos && true == mvControlling->IncScndCtrl(1) ) { ; } // all work is done in the condition loop } - if( mvControlling->SpeedCtrlUnit.PowerStep > 0 && mvControlling->ScndCtrlPos > 0 ) { + if( mvControlling->SpeedCtrlUnit.PowerStep > 0 && mvControlling->IsSpeedCtrlEngaged() ) { while (mvControlling->SpeedCtrlUnit.DesiredPower < mvControlling->SpeedCtrlUnit.MaxPower) { mvControlling->SpeedCtrlPowerInc(); diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 50659934c..72aa6b480 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -1447,8 +1447,8 @@ void TTrain::OnCommand_secondcontrollerincrease(TTrain *Train, command_data cons auto const neutralposition{Train->ggScndCtrl.is_toggle() ? 0.5f : 0.f}; Train->ggScndCtrl.UpdateValue(Command.action == GLFW_RELEASE ? neutralposition : activeposition, Train->dsbSwitch); } - // potentially animate tempomat button - if (Train->ggScndCtrlButton.is_push() && Train->mvControlled->ScndCtrlPos <= 1) + // potentially animate tempomat button, unless the cruise control has its own + if (Train->ggScndCtrlButton.is_push() && Train->mvControlled->ScndCtrlPos <= 1 && false == Train->mvControlled->IsSpeedCtrlSeparate()) { Train->ggScndCtrlButton.UpdateValue(Command.action == GLFW_RELEASE ? 0.f : 1.f, Train->dsbSwitch); } @@ -1511,17 +1511,17 @@ void TTrain::OnCommand_tempomattoggle(TTrain *Train, command_data const &Command return; } // glfw_press - if (Train->mvControlled->ScndCtrlPos == 0) + if (false == Train->mvControlled->IsSpeedCtrlEngaged()) { // turn on if it's not active - Train->mvControlled->IncScndCtrl(1); + Train->mvControlled->SpeedCtrlSwitch(true); // visual feedback Train->ggScndCtrlButton.UpdateValue(1.0, Train->dsbSwitch); } else { // otherwise turn off - Train->mvControlled->DecScndCtrl(2); + Train->mvControlled->SpeedCtrlSwitch(false); // visual feedback if (Train->m_controlmapper.contains("tempomatoff_sw:")) { @@ -1541,17 +1541,17 @@ void TTrain::OnCommand_tempomattoggle(TTrain *Train, command_data const &Command return; } - if (Train->mvControlled->ScndCtrlPos == 0) + if (false == Train->mvControlled->IsSpeedCtrlEngaged()) { // turn on - Train->mvControlled->IncScndCtrl(1); + Train->mvControlled->SpeedCtrlSwitch(true); // visual feedback Train->ggScndCtrlButton.UpdateValue(1.0, Train->dsbSwitch); } else { // turn off - Train->mvControlled->DecScndCtrl(2); + Train->mvControlled->SpeedCtrlSwitch(false); // visual feedback Train->ggScndCtrlButton.UpdateValue(0.0, Train->dsbSwitch); } @@ -1653,8 +1653,8 @@ void TTrain::OnCommand_secondcontrollerdecrease(TTrain *Train, command_data cons auto const neutralposition{Train->ggScndCtrl.is_toggle() ? 0.5f : 0.f}; Train->ggScndCtrl.UpdateValue(Command.action == GLFW_RELEASE ? neutralposition : activeposition, Train->dsbSwitch); } - // potentially animate tempomat button - if (Train->ggScndCtrlButton.is_push() && Train->mvControlled->ScndCtrlPos <= 1) + // potentially animate tempomat button, unless the cruise control has its own + if (Train->ggScndCtrlButton.is_push() && Train->mvControlled->ScndCtrlPos <= 1 && false == Train->mvControlled->IsSpeedCtrlSeparate()) { if (Train->m_controlmapper.contains("tempomatoff_sw:")) { @@ -9725,7 +9725,7 @@ bool TTrain::Update(double const Deltatime) { if (ggScndCtrlButton.is_toggle()) { - ggScndCtrlButton.UpdateValue(mvControlled->ScndCtrlPos > 0 ? 1.f : 0.f, dsbSwitch); + ggScndCtrlButton.UpdateValue(mvControlled->IsSpeedCtrlEngaged() ? 1.f : 0.f, dsbSwitch); } ggScndCtrlButton.Update(lowvoltagepower); } @@ -11993,7 +11993,7 @@ void TTrain::set_cab_controls(int const Cab) // tempomat if (false == ggScndCtrlButton.is_push()) { - ggScndCtrlButton.PutValue(mvControlled->ScndCtrlPos > 0 ? 1.f : 0.f); + ggScndCtrlButton.PutValue(mvControlled->IsSpeedCtrlEngaged() ? 1.f : 0.f); } // sandbox if (ggAutoSandButton.type() != TGaugeType::push) From 611dc365ebae82a3ad588b2763c81756e0394b9f Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 22:37:04 +0100 Subject: [PATCH 046/136] test: Sonar on the cruise control test: no empty statements, the lambda's captures named --- tests/unit/test_speed_control.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/unit/test_speed_control.cpp b/tests/unit/test_speed_control.cpp index a141f41a6..7b0f7fc52 100644 --- a/tests/unit/test_speed_control.cpp +++ b/tests/unit/test_speed_control.cpp @@ -34,10 +34,10 @@ constexpr int dg_raise{6}; void move_to(TMoverParameters &Vehicle, int const Position) { while (Vehicle.MainCtrlPos < Position && Vehicle.IncMainCtrl(1)) { - ; + // all the work is done in the condition } while (Vehicle.MainCtrlPos > Position && Vehicle.DecMainCtrl(1)) { - ; + // all the work is done in the condition } REQUIRE(Vehicle.MainCtrlPos == Position); } @@ -158,7 +158,7 @@ TEST_CASE("speed control: the vehicles whose secondary controller is the cruise scenario.get_going(); scenario.act("raise"); while (loco.ScndCtrlPos < 3 && loco.IncScndCtrl(1)) { - ; + // all the work is done in the condition } REQUIRE(loco.ScndCtrlPos == 3); scenario.wait(10.0); @@ -285,7 +285,7 @@ TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the // the shunt goes by itself all the while, by the current of the motors, which the cruise control's demand sets auto shunted{0}; auto unshunted{0}; - auto const run{[&](int const Seconds) { + auto const run{[&scenario, &loco, &shunted, &unshunted](int const Seconds) { for (int second = 0; second < Seconds; ++second) { scenario.wait(1.0); ++(loco.ScndCtrlPos > 0 ? shunted : unshunted); From 88383c0903ef2452a5fa037e0145d5c8c2c9f86d Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 22:45:06 +0100 Subject: [PATCH 047/136] feat: dynamic brake of the diesel-electric vehicles (#82) The drive of a diesel-electric vehicle is computed from the power of its generator, not from a circuit, so neither the EP09's resistor brake (Current()) nor the inverter model of the induction motors has anything to work on, and a negative setting of the integrated controller did nothing: the BR285's TRAXX controller has its braking range (EB+, EB, EB-) and brakes nothing. A vehicle opts in with keys of its Engine section, read only for the diesel-electric ones; without EDBrake nothing changes: - EDBrake=Controller: the negative range of the integrated controller (EIMCtrlType > 0) sets the effort, which goes to the vehicles in multiple with the EIMIC command; EDBrake=Lever: a lever of its own, the one of SplitEDPneumaticBrake (DBPN steps, the dynamicbrakecontroller commands), working with the master controller at zero. - EDBrakeFmax [kN], EDBrakePmax [kW]: the force at the wheels, limited by the power of the resistors at speed; EDBrakeV0, EDBrakeV1 [km/h]: no force below V0, the whole above V1. An inverter's brake fades only at the stop, a resistor brake of direct current motors grows with the speed from 0. - EDBrakeRate [1/s]: how fast the effort follows (0.5). - EDBrakeBlending=Yes: the locomotive's train brake lets off by the share of the force (Hamulec->SetED, LSt and EStED valves). The brake works while the engine runs, with the direction set, the overload relay closed, the wheels rolling and no power asked for. Its force takes the place of the drive's in TractionForce(), the ammeter shows the motors' current, DynamicBrakeFlag lights the dynamic brake lamp. The traces of all 615 test cases recorded before the change compare bit for bit after it (EU07_UNIT_TESTS_GOLDEN_EXACT=1). --- McZapkie/MOVER.h | 30 +++ McZapkie/Mover.cpp | 131 ++++++++++++- tests/unit/test_dynamic_brake_diesel.cpp | 234 +++++++++++++++++++++++ 3 files changed, 390 insertions(+), 5 deletions(-) create mode 100644 tests/unit/test_dynamic_brake_diesel.cpp diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index b619ba7de..1411ff4bd 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -1842,6 +1842,29 @@ class TMoverParameters int DynamicBrakeAmpmeters = 2; /*liczba amperomierzy przy hamowaniu ED*/ bool SplitEDPneumaticBrake = false; /*czy hamulec ED i pneumatyczny pomocniczy są rozdzielone na osobne nastawniki*/ int DynamicBrakeCtrlPosNo = 10; /*ilosc pozycji nastawnika hamulca ED (DBPN, domyslnie 10)*/ + // the dynamic brake of a diesel-electric vehicle (Engine: EDBrake=...): the traction motors brake into resistors while + // the engine runs, with the force of the definition rather than from a circuit, as the drive of these vehicles is + // computed from the generator's power. no definition, no dynamic brake (MaSzyna-EU07/maszyna#82) + struct diesel_electric_dynamic_brake + { + enum class control + { + none, + controller, // the negative range of the integrated controller (EIMCtrlType > 0), as the TRAXX one of the BR285 + lever // a lever of its own (the SplitEDPneumaticBrake one, DBPN steps), with the master controller at zero + }; + control source{control::none}; + double max_force{0.0}; // [N] at the wheel rims of the whole vehicle, EDBrakeFmax [kN] + double max_power{0.0}; // [W] the resistors take, EDBrakePmax [kW]; 0: no limit + double fade_low{0.0}; // [km/h] EDBrakeV0: no force below + double fade_high{0.0}; // [km/h] EDBrakeV1: the whole force above, rising in between + double rate{0.5}; // [1/s] EDBrakeRate: how fast the effort follows the demand + bool blending{false}; // EDBrakeBlending: the locomotive's train brake lets off while the dynamic brake works (Hamulec->SetED) + // state + double level{0.0}; // the effort, 0..1 + double force{0.0}; // [N] the braking force, against the motion + }; + diesel_electric_dynamic_brake DEDynamicBrake; double DynamicBrakeRes = 5.8; /*rezystancja oporników przy hamowaniu ED*/ double DynamicBrakeRes1 = 5.8; /*rezystancja oporników przy hamowaniu ED - 1 tryb*/ double DynamicBrakeRes2 = 5.8; /*rezystancja oporników przy hamowaniu ED - 2 tryb*/ @@ -2564,6 +2587,12 @@ class TMoverParameters void ComputeTotalForce(double dt); double Adhesive(double staticfriction) const; double TractionForce(double dt); + // the dynamic brake of a diesel-electric vehicle: the effort following the demand, the force it gives at the speed + void update_dieselelectric_dynamic_brake(double dt); + double dieselelectric_dynamic_brake_demand() const; // 0..1, the effort the driver asks for + double dieselelectric_dynamic_brake_limit() const; // [N] the force at full effort at the speed + void apply_dieselelectric_dynamic_brake(); // the force in place of the drive's one + double dieselelectric_motor_current(double Moment) const; // the current of the motors giving the moment double FrictionForce() const; double BrakeForceR(double ratio, double velocity) const; double BrakeForceP(double press, double velocity) const; @@ -2815,6 +2844,7 @@ class TMoverParameters void LoadFIZ_AI(std::string const &Input); void LoadFIZ_RList(std::string const &Input); void LoadFIZ_UCList(std::string const &Input); + void LoadFIZ_DieselElectricDynamicBrake(std::string const &Input); void LoadFIZ_DList(std::string const &Input); void LoadFIZ_FFList(std::string const &Input); void LoadFIZ_FFEDList(std::string const &Input); diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 825137675..9c0b6b881 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -6119,6 +6119,11 @@ double TMoverParameters::TractionForce(double dt) } } + if (EngineType == TEngineType::DieselElectric && DEDynamicBrake.source != diesel_electric_dynamic_brake::control::none) + { + update_dieselelectric_dynamic_brake(dt); + } + if (DirActive != 0) switch (EngineType) { @@ -6361,11 +6366,7 @@ double TMoverParameters::TractionForce(double dt) Mw = Fw * WheelDiameter / 2.0; // moment na osi kola Mm = Mw / Transmision.Ratio; // moment silnika trakcyjnego - // with MotorParam[ScndCtrlPos] do - if (abs(Mm) > motor_param(ScndCtrlPos).fi) - Im = NPoweredAxles * abs(abs(Mm) / motor_param(ScndCtrlPos).mfi + motor_param(ScndCtrlPos).mIsat); - else - Im = NPoweredAxles * sqrt(abs(Mm * motor_param(ScndCtrlPos).Isat)); + Im = dieselelectric_motor_current(Mm); if (ShuntMode) { @@ -6611,6 +6612,11 @@ double TMoverParameters::TractionForce(double dt) } } } + if (DEDynamicBrake.level > 0.0) + { + // braking: no power asked for, so the drive above gave no force + apply_dieselelectric_dynamic_brake(); + } break; } // DieselElectric @@ -6940,6 +6946,91 @@ double TMoverParameters::TractionForce(double dt) return Ft; } +// the current of a diesel-electric vehicle's traction motors giving the moment [N m] of one motor +double TMoverParameters::dieselelectric_motor_current(double const Moment) const +{ + // with MotorParam[ScndCtrlPos] do + if (abs(Moment) > motor_param(ScndCtrlPos).fi) + return NPoweredAxles * abs(abs(Moment) / motor_param(ScndCtrlPos).mfi + motor_param(ScndCtrlPos).mIsat); + else + return NPoweredAxles * sqrt(abs(Moment * motor_param(ScndCtrlPos).Isat)); +} + +// the effort of a diesel-electric vehicle's dynamic brake the driver asks for, 0..1 +double TMoverParameters::dieselelectric_dynamic_brake_demand() const +{ + switch (DEDynamicBrake.source) + { + case diesel_electric_dynamic_brake::control::controller: + return std::clamp(-eimic_real, 0.0, 1.0); + case diesel_electric_dynamic_brake::control::lever: + return DynamicBrakeRatio(); + default: + return 0.0; + } +} + +// the force [N] of a diesel-electric vehicle's dynamic brake at full effort at the speed: the most the motors take +// (the current), above the speed where the resistors' power takes over, the power; under EDBrakeV1 it fades, down to +// nothing at EDBrakeV0. a brake of direct current motors, whose force grows with the speed (the voltage they generate +// into the resistors), fades from 0 to the speed of its whole force; an inverter's only at the stop +double TMoverParameters::dieselelectric_dynamic_brake_limit() const +{ + auto const &brake{DEDynamicBrake}; + auto limit{brake.max_force}; + if (brake.max_power > 0.0 && std::abs(V) > 0.0) + { + limit = std::min(limit, brake.max_power / std::abs(V)); + } + if (brake.fade_high > brake.fade_low) + { + limit *= std::clamp((Vel - brake.fade_low) / (brake.fade_high - brake.fade_low), 0.0, 1.0); + } + else if (Vel < brake.fade_low) + { + limit = 0.0; + } + return limit; +} + +// the dynamic brake of a diesel-electric vehicle, before the drive's force: the effort follows the demand, the force +// is the share of the most at the speed. the motors brake while the engine runs (it excites them, or keeps the +// control of the inverters going), with the direction set, the overload relay closed, no power asked for and the +// wheels rolling; otherwise there's no brake at once +void TMoverParameters::update_dieselelectric_dynamic_brake(double const dt) +{ + auto &brake{DEDynamicBrake}; + auto const nopower{brake.source == diesel_electric_dynamic_brake::control::controller ? eimic_real <= 0.0 : IsMainCtrlNoPowerPos()}; + if (Mains && DirActive != 0 && false == FuseFlag && false == SlippingWheels && nopower) + { + brake.level += std::clamp(dieselelectric_dynamic_brake_demand() - brake.level, -brake.rate * dt, brake.rate * dt); + } + else + { + brake.level = 0.0; + } + brake.force = brake.level * dieselelectric_dynamic_brake_limit(); + DynamicBrakeFlag = brake.force > 0.0; + if (brake.blending) + { + // the train brake of the locomotive lets off by the share of the dynamic brake's force (LSt, EStED) + Hamulec->SetED(brake.max_force > 0.0 ? brake.force / brake.max_force : 0.0); + } +} + +// the force of a diesel-electric vehicle's dynamic brake, against the motion, in place of the drive's one: the motors +// work as generators into the resistors, the ammeter shows their current, the main generator gives nothing +void TMoverParameters::apply_dieselelectric_dynamic_brake() +{ + Ft = V > 0.0 ? -DEDynamicBrake.force : V < 0.0 ? DEDynamicBrake.force : 0.0; + Fw = Ft / NPoweredAxles; + Mw = Fw * WheelDiameter / 2.0; + Mm = Mw / Transmision.Ratio; + Im = dieselelectric_motor_current(Mm); + EngineVoltage = 0.0; + EnginePower = 0.0; +} + // ************************************************************************************************* // Q: 20160713 // Obliczenie predkości obrotowej kół??? @@ -12021,6 +12112,7 @@ void TMoverParameters::LoadFIZ_Engine(std::string const &Input) extract_value(EngineHeatingRPM, "HeatingRPM", Input, ""); extract_value(dizel_AIM, "AIM", Input, "1.25"); extract_value(dizel_RevolutionsDecreaseRate, "RPMDecRate", Input, ""); + LoadFIZ_DieselElectricDynamicBrake(Input); break; } case TEngineType::ElectricInductionMotor: @@ -12229,6 +12321,35 @@ void TMoverParameters::LoadFIZ_RList(std::string const &Input) extract_value(DynamicBrakeRes2, "DynBrakeRes2", Input, ""); } +// the dynamic brake of a diesel-electric vehicle, from its Engine section: none without EDBrake +void TMoverParameters::LoadFIZ_DieselElectricDynamicBrake(std::string const &Input) +{ + using enum diesel_electric_dynamic_brake::control; + std::map> const sources{{"Controller", controller}, {"Lever", lever}}; + auto const lookup{sources.find(extract_value("EDBrake", Input))}; + if (lookup == sources.end()) + { + return; + } + auto &brake{DEDynamicBrake}; + brake.source = lookup->second; + auto force{0.0}; // [kN] + auto power{0.0}; // [kW] + extract_value(force, "EDBrakeFmax", Input, ""); + extract_value(power, "EDBrakePmax", Input, ""); + brake.max_force = force * 1000.0; + brake.max_power = power * 1000.0; + extract_value(brake.fade_low, "EDBrakeV0", Input, ""); + extract_value(brake.fade_high, "EDBrakeV1", Input, ""); + extract_value(brake.rate, "EDBrakeRate", Input, ""); + extract_value(brake.blending, "EDBrakeBlending", Input, ""); + if (brake.source == lever) + { + // the lever of its own, which the commands of the dynamic brake controller move + SplitEDPneumaticBrake = true; + } +} + void TMoverParameters::LoadFIZ_UCList(std::string const &Input) { diff --git a/tests/unit/test_dynamic_brake_diesel.cpp b/tests/unit/test_dynamic_brake_diesel.cpp new file mode 100644 index 000000000..f0851d061 --- /dev/null +++ b/tests/unit/test_dynamic_brake_diesel.cpp @@ -0,0 +1,234 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scenario.h" +#include "drive.h" +#include "real_vehicles.h" + +#include "McZapkie/hamulce.h" + +// the dynamic brake of the diesel-electric vehicles (Engine: EDBrake=, MaSzyna-EU07/maszyna#82): the traction motors +// brake into resistors while the engine runs, with the force of the definition (EDBrakeFmax, the power limit +// EDBrakePmax, the fade below EDBrakeV1 down to EDBrakeV0), set either by the negative range of the integrated +// controller (EDBrake=Controller, the BR285's TRAXX controller) or by a lever of its own (EDBrake=Lever, the +// SplitEDPneumaticBrake one, with the master controller at zero) + +using test::definition; +using test::scenario; +using namespace test::channels; + +namespace { + +std::vector dynamic_brake() { + return { + {"EDLevel", [](auto const &M) { return M.DEDynamicBrake.level; }}, + {"EDForce", [](auto const &M) { return M.DEDynamicBrake.force; }}, + {"DynamicBrakeFlag", [](auto const &M) { return M.DynamicBrakeFlag ? 1.0 : 0.0; }}, + {"eimic_real", [](auto const &M) { return M.eimic_real; }}, + {"DynamicBrakeCtrlPos", [](auto const &M) { return M.DynamicBrakeCtrlPos; }}, + }; +} + +// the BR285 with its dynamic brake: 150 kN up to the power limit of 2000 kW (48 km/h), fading out under 6 km/h +definition br285_braking() { + return definition::fiz("br285_v1/br285") + .set("Engine", "EDBrake", "Controller") + .set("Engine", "EDBrakeFmax", 150) + .set("Engine", "EDBrakePmax", 2000) + .set("Engine", "EDBrakeV0", 2) + .set("Engine", "EDBrakeV1", 6); +} + +// a resistor brake of a locomotive with direct current motors, on the ST44 (M62): a lever of 8 steps, the force +// growing with the speed up to 120 kN at 40 km/h, the resistors taking 1200 kW +definition st44_braking() { + return definition::fiz("st44_v2/m62-1151") + .set("Cntrl", "DBPN", 8) + .set("Engine", "EDBrake", "Lever") + .set("Engine", "EDBrakeFmax", 120) + .set("Engine", "EDBrakePmax", 1200) + .set("Engine", "EDBrakeV0", 0) + .set("Engine", "EDBrakeV1", 40); +} + +// the force of the brakes above at full effort at the speed of the vehicle +double br285_limit(TMoverParameters const &Vehicle) { + return std::min(150000.0, 2000000.0 / std::abs(Vehicle.V)) * std::clamp((Vehicle.Vel - 2.0) / 4.0, 0.0, 1.0); +} +double st44_limit(TMoverParameters const &Vehicle) { + return std::min(120000.0, 1200000.0 / std::abs(Vehicle.V)) * std::clamp(Vehicle.Vel / 40.0, 0.0, 1.0); +} + +// the controller of the BR285 down to the given position, a step a time +void controller_to(TMoverParameters &Locomotive, int Position) { + while (Locomotive.MainCtrlPos > Position && Locomotive.DecMainCtrl(1)) {} + while (Locomotive.MainCtrlPos < Position && Locomotive.IncMainCtrl(1)) {} +} + +} // namespace + +TEST_CASE("diesel-electric dynamic brake: none without its definition") { + // no game vehicle defines it: the diesel-electric ones load without, the BR285's braking positions brake nothing + for (auto const &path : test::real_vehicles()) { + CAPTURE(path); + test::vehicle vehicle{definition::fiz(path)}; + CHECK(vehicle->DEDynamicBrake.source == TMoverParameters::diesel_electric_dynamic_brake::control::none); + } + scenario scenario{"dynamic brake/diesel electric/br285 without", motion() + traction() + dynamic_brake()}; + scenario.add("br285_v1/br285", 1); + REQUIRE(scenario.start_up()); + auto &locomotive{scenario.cab()}; + scenario.get_going(); + scenario.full_power(40.0); + auto const speed{locomotive.Vel}; + REQUIRE(speed > 30.0); + scenario.act("braking range"); + controller_to(locomotive, 0); + scenario.wait(15.0); + CHECK(locomotive.eimic_real == doctest::Approx(-1.0)); + CHECK(locomotive.Ft == doctest::Approx(0.0)); + CHECK_FALSE(locomotive.DynamicBrakeFlag); + // coasting: braking with the power of the resistors above, it would lose more than 30 km/h + CHECK(locomotive.Vel > speed - 12.0); + scenario.check(); +} + +TEST_CASE("diesel-electric dynamic brake: the BR285's controller") { + // the braking positions of the TRAXX controller: EB+ raises the braking effort, EB holds it, EB- lowers it. + // the force is limited by the power of the resistors at speed, holds below that, fades out at the stop; the + // air brake stays off + scenario scenario{"dynamic brake/diesel electric/br285", motion() + traction() + brakes() + dynamic_brake()}; + scenario.train().add(br285_braking(), 1); + auto &locomotive{scenario.cab()}; + REQUIRE(locomotive.DEDynamicBrake.source == TMoverParameters::diesel_electric_dynamic_brake::control::controller); + CHECK(locomotive.DEDynamicBrake.max_force == doctest::Approx(150000.0)); + CHECK(locomotive.DEDynamicBrake.max_power == doctest::Approx(2000000.0)); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(60.0); + REQUIRE(locomotive.Vel > 60.0); + + scenario.act("EB+"); + controller_to(locomotive, 0); + scenario.wait(10.0); + CHECK(locomotive.eimic_real == doctest::Approx(-1.0)); + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); + CHECK(locomotive.DynamicBrakeFlag); + REQUIRE(locomotive.Vel > 6.0); + CHECK(-locomotive.Ft == doctest::Approx(br285_limit(locomotive)).epsilon(0.01)); + CHECK(locomotive.Im > 0.0); + CHECK(locomotive.EngineVoltage == doctest::Approx(0.0)); + CHECK(locomotive.BrakePress < 0.1); + + scenario.act("EB- to half"); + controller_to(locomotive, 2); + for (int i = 0; i < 20 && locomotive.eimic_real < -0.5; ++i) { + scenario.wait(1.0); + } + scenario.act("EB"); + controller_to(locomotive, 1); + scenario.wait(2.0); + auto const held{locomotive.eimic_real}; + CHECK(held == doctest::Approx(-0.5).epsilon(0.35)); + scenario.wait(5.0); + CHECK(locomotive.eimic_real == doctest::Approx(held)); + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(-held).epsilon(0.01)); + + scenario.act("EB+ to the stop"); + controller_to(locomotive, 0); + for (int i = 0; i < 120 && locomotive.Vel > 20.0; ++i) { + scenario.wait(1.0); + } + // under the power limit the force holds + REQUIRE(locomotive.Vel < 40.0); + REQUIRE(locomotive.Vel > 6.0); + CHECK(-locomotive.Ft == doctest::Approx(150000.0).epsilon(0.01)); + for (int i = 0; i < 120 && locomotive.Vel > 4.0; ++i) { + scenario.wait(1.0); + } + // fading out + CHECK(-locomotive.Ft < 150000.0 * 0.6); + for (int i = 0; i < 120 && locomotive.Vel > 1.5; ++i) { + scenario.wait(1.0); + } + CHECK(locomotive.Ft == doctest::Approx(0.0)); + CHECK_FALSE(locomotive.DynamicBrakeFlag); + // it doesn't hold the train: the air brake does + CHECK(locomotive.Vel > 0.1); + scenario.check(); +} + +TEST_CASE("diesel-electric dynamic brake: a resistor brake with its own lever") { + // on a locomotive with direct current motors the lever sets the excitation of the motors: the force grows with + // the speed, up to the limit of the current, then of the resistors' power. it works only with the master + // controller at zero and the engine running + scenario scenario{"dynamic brake/diesel electric/st44 lever", motion() + traction() + brakes() + dynamic_brake()}; + scenario.train().add(st44_braking(), 1); + auto &locomotive{scenario.cab()}; + REQUIRE(locomotive.DEDynamicBrake.source == TMoverParameters::diesel_electric_dynamic_brake::control::lever); + CHECK(locomotive.SplitEDPneumaticBrake); + CHECK(locomotive.DynamicBrakeCtrlPosNo == 8); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(90.0); + REQUIRE(locomotive.Vel > 50.0); + + scenario.act("lever with power on"); + CHECK(locomotive.DynamicBrakeLevelSet(1.0)); + scenario.wait(5.0); + // the master controller at a power position keeps it off + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(0.0)); + CHECK(locomotive.Ft > 0.0); + CHECK_FALSE(locomotive.DynamicBrakeFlag); + + scenario.act("power off"); + scenario.notch_back(0); + scenario.wait(4.0); + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); + CHECK(locomotive.DynamicBrakeFlag); + CHECK(-locomotive.Ft == doctest::Approx(st44_limit(locomotive)).epsilon(0.01)); + CHECK(locomotive.ShowCurrent(0) > 0.0); + + scenario.act("half the lever"); + locomotive.DecDynamicBrakeLevel(4.0f); + CHECK(locomotive.DynamicBrakeCtrlPos == doctest::Approx(0.5)); + for (int i = 0; i < 300 && locomotive.Vel > 20.0; ++i) { + scenario.wait(1.0); + } + REQUIRE(locomotive.Vel < 21.0); + REQUIRE(locomotive.Vel > 10.0); + // on the rising part, half the excitation + CHECK(-locomotive.Ft == doctest::Approx(0.5 * st44_limit(locomotive)).epsilon(0.01)); + + scenario.act("engine off"); + locomotive.MainSwitch(false); + scenario.wait(1.0); + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(0.0)); + CHECK(locomotive.Ft == doctest::Approx(0.0)); + CHECK_FALSE(locomotive.DynamicBrakeFlag); + scenario.check(); +} + +TEST_CASE("diesel-electric dynamic brake: blended with the locomotive's air brake") { + // EDBrakeBlending: the LSt valve lets the train brake off the locomotive while the dynamic brake takes over + // (Hamulec->SetED with the share of the force it gives); without, both brake + for (auto const blending : {false, true}) { + CAPTURE(blending); + scenario scenario{std::format("dynamic brake/diesel electric/st44 blending {}", blending), motion() + traction() + brakes() + dynamic_brake()}; + scenario.train().add(st44_braking().set("Engine", "EDBrakeBlending", blending ? "Yes" : "No"), 1); + auto &locomotive{scenario.cab()}; + REQUIRE(locomotive.DEDynamicBrake.blending == blending); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(150.0); + scenario.notch_back(0); + scenario.act("dynamic and train brake"); + locomotive.DynamicBrakeLevelSet(1.0); + locomotive.BrakeLevelSet(locomotive.Handle->GetPos(bh_FB)); + scenario.wait(6.0); + REQUIRE(locomotive.Vel > 15.0); + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); + CHECK(locomotive.PipePress < 4.6); + CHECK((locomotive.BrakePress < 0.2) == blending); + scenario.check(); + } +} From 8d2d9badb5723da49a7b4a7769f359b2817221fc Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 23:36:26 +0100 Subject: [PATCH 048/136] feat: own kind of animation for a door wing in the .mmd (eu07/maszyna#70) A vehicle can now have door wings of different kinds on one side, e.g. 111Ainw (Bdhinu) with folding doors at one end and wider ones at the other. A new optional entry in the models section of the .mmd: animdoor: { type: range: rangeout: } gives one wing (door1, door2... of animdoorprefix) its own kind of animation and range; the keys left out keep the values of the .fiz. The wing still follows the door of its side: it is as far along its own range as the door is along DoorMaxShift. The entry may come before or after animdoorprefix; a faulty one is logged and the wing keeps the .fiz kind. Wings without an entry get the same update functions as before, so the existing vehicles, .mmd and .fiz files are unchanged. The door state, the physics, AI, cab controls, sounds and exports are not touched. The parsing and the wing position live in vehicle/doorwings.h, tested in test_door_wings.cpp. --- tests/unit/test_door_wings.cpp | 117 +++++++++++++++++++++++++++ vehicle/DynObj.cpp | 102 ++++++++++++++++++++---- vehicle/DynObj.h | 7 ++ vehicle/doorwings.h | 139 +++++++++++++++++++++++++++++++++ 4 files changed, 348 insertions(+), 17 deletions(-) diff --git a/tests/unit/test_door_wings.cpp b/tests/unit/test_door_wings.cpp index 290260f6a..e049d6c61 100644 --- a/tests/unit/test_door_wings.cpp +++ b/tests/unit/test_door_wings.cpp @@ -2,6 +2,7 @@ #include "doctest.h" #include "vehicle/doorwings.h" +#include "utilities/parser.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 @@ -52,3 +53,119 @@ TEST_CASE("door wings: a folding wing turns one way and its larger wing twice as CHECK(closed.larger == 0.f); CHECK(closed.step == 0.f); } + +// a wing with its own kind of animation (eu07/maszyna#70): animdoor: in the .mmd, for vehicles whose doors on one side +// aren't all alike, e.g. 111Ainw with folding doors at one end and wider ones at the other + +namespace { + +// the spec of the .fiz the entries start from: folding doors which turn by 80 degrees +door_wings::wing_spec const fizdoors{0, door_wings::fold_type, 80.f, 0.f}; + +// reads the entry after animdoor: from the text, starting from the spec of the .fiz +std::string read(std::string const &Entry, door_wings::wing_spec &Spec) { + Spec = fizdoors; + cParser parser(Entry, cParser::buffer_TEXT); + return door_wings::read_spec(parser, Spec); +} + +} // namespace + +TEST_CASE("door wings: the kinds of animation are named as DoorOpenMethod of the .fiz") { + CHECK(door_wings::type_from_name("Shift") == door_wings::shift_type); + CHECK(door_wings::type_from_name("Rotate") == door_wings::rotate_type); + CHECK(door_wings::type_from_name("Fold") == door_wings::fold_type); + CHECK(door_wings::type_from_name("Plug") == door_wings::plug_type); + // in any letter case + CHECK(door_wings::type_from_name("plug") == door_wings::plug_type); + CHECK(door_wings::type_from_name("SHIFT") == door_wings::shift_type); + // the same numbers as TMoverParameters::door_data::type + CHECK(door_wings::shift_type == 1); + CHECK(door_wings::rotate_type == 2); + CHECK(door_wings::fold_type == 3); + CHECK(door_wings::plug_type == 4); + CHECK_FALSE(door_wings::type_from_name("Roll").has_value()); + CHECK_FALSE(door_wings::type_from_name("").has_value()); +} + +TEST_CASE("door wings: an animdoor entry gives the wing its own kind, range and plug shift") { + door_wings::wing_spec spec; + CHECK(read("3 { type: Plug range: 0.9 rangeout: 0.06 } endmodels", spec).empty()); + CHECK(spec.number == 3); + CHECK(spec.type == door_wings::plug_type); + CHECK(spec.range == doctest::Approx(0.9f)); + CHECK(spec.range_out == doctest::Approx(0.06f)); +} + +TEST_CASE("door wings: the keys an animdoor entry leaves out keep the values of the .fiz") { + door_wings::wing_spec spec; + SUBCASE("only the kind") { + CHECK(read("2 { type: Rotate }", spec).empty()); + CHECK(spec.number == 2); + CHECK(spec.type == door_wings::rotate_type); + CHECK(spec.range == 80.f); + CHECK(spec.range_out == 0.f); + } + SUBCASE("only the range, keys in any letter case and order") { + CHECK(read("1 { Range: -95 }", spec).empty()); + CHECK(spec.type == door_wings::fold_type); + CHECK(spec.range == -95.f); + } + SUBCASE("nothing") { + CHECK(read("4 { }", spec).empty()); + CHECK(spec.number == 4); + CHECK(spec.type == fizdoors.type); + CHECK(spec.range == fizdoors.range); + } +} + +TEST_CASE("door wings: a faulty animdoor entry says what is wrong with it") { + door_wings::wing_spec spec; + CHECK(read("3 type: Shift range: 0.65", spec) == "no { after the wing number"); + CHECK(read("3 { type: Roll range: 0.65 }", spec) == "unknown door type \"Roll\""); + CHECK(read("3 { type: Shift range: 0,65 }", spec) == "bad number \"0,65\" for \"range:\""); + CHECK(read("3 { type: Shift range: wide }", spec) == "bad number \"wide\" for \"range:\""); + CHECK(read("3 { kind: Shift }", spec) == "unknown key \"kind:\""); + CHECK(read("3 { type: Shift range: }", spec) == "no value for \"range:\""); + CHECK(read("3 { type: Shift range: 0.65", spec) == "no } after the keys"); +} + +TEST_CASE("door wings: the parsed keys go into the spec, pairs of a key and its value") { + door_wings::wing_spec spec{fizdoors}; + CHECK(door_wings::parse_spec({"type:", "Shift", "range:", "0.65"}, spec).empty()); + CHECK(spec.type == door_wings::shift_type); + CHECK(spec.range == doctest::Approx(0.65f)); + CHECK(door_wings::parse_spec({"rangeout:"}, spec) == "no value for \"rangeout:\""); + CHECK(door_wings::parse_spec({}, spec).empty()); +} + +TEST_CASE("door wings: only the wings with an entry animate in their own way, the latest entry counts") { + std::vector specs; + CHECK(door_wings::find(specs, 1) == nullptr); + door_wings::store(specs, {3, door_wings::shift_type, 0.65f, 0.f}); + door_wings::store(specs, {4, door_wings::shift_type, 0.65f, 0.f}); + door_wings::store(specs, {3, door_wings::plug_type, 0.9f, 0.06f}); + CHECK(specs.size() == 2); + CHECK(door_wings::find(specs, 1) == nullptr); + CHECK(door_wings::find(specs, 2) == nullptr); + REQUIRE(door_wings::find(specs, 3) != nullptr); + CHECK(door_wings::find(specs, 3)->type == door_wings::plug_type); + CHECK(door_wings::find(specs, 3)->range == 0.9f); + REQUIRE(door_wings::find(specs, 4) != nullptr); + CHECK(door_wings::find(specs, 4)->type == door_wings::shift_type); +} + +TEST_CASE("door wings: a wing with its own range is as far along it as the door of its side") { + // folding doors of the .fiz turn by 80 degrees; the wide wing slides by 0.9 m + CHECK(door_wings::wing_position(0.f, 80.f, 0.9f) == 0.f); + CHECK(door_wings::wing_position(40.f, 80.f, 0.9f) == doctest::Approx(0.45f)); + CHECK(door_wings::wing_position(80.f, 80.f, 0.9f) == doctest::Approx(0.9f)); + // a wing turning the other way + CHECK(door_wings::wing_position(20.f, 80.f, -100.f) == doctest::Approx(-25.f)); + // no doors in the .fiz: the wing stays closed + CHECK(door_wings::wing_position(0.f, 0.f, 0.9f) == 0.f); + // the pose of the plug wing at the end of its range + auto const open{door_wings::plug(door_wings::wing_position(80.f, 80.f, 0.9f), 0.06f)}; + CHECK(open.x == doctest::Approx(0.06f)); + CHECK(open.z == doctest::Approx(0.87f)); +} diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 24810a2e7..0bfcdac75 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -700,6 +700,62 @@ void TDynamicObject::UpdateDoorPlug(TAnim *pAnim) { } } +// a wing animated in its own way (animdoor: of the .mmd): as far along its own range as the door of its side is +void TDynamicObject::UpdateDoorWing( TAnim *pAnim, door_wings::wing_spec const &Spec ) { + + if( pAnim->smAnimated == nullptr ) { return; } + + auto const position { door_wings::wing_position( door_position( *MoverParameters, pAnim ), MoverParameters->Doors.range, Spec.range ) }; + for( auto *wing : wing_parts( pAnim ) ) { + if( wing == nullptr ) { continue; } + switch( Spec.type ) { + case door_wings::shift_type: { + wing->SetTranslate( door_wings::slide( position ) ); + break; + } + case door_wings::rotate_type: { + wing->SetRotate( float3( 1, 0, 0 ), position ); + break; + } + case door_wings::fold_type: { + fold_wing( wing, door_wings::fold( position ) ); + break; + } + case door_wings::plug_type: { + wing->SetTranslate( door_wings::plug( position, Spec.range_out ) ); + break; + } + default: { + break; + } + } + } +} + +void TDynamicObject::bind_door_animation( TAnim &Animation ) { + + if( auto const *spec { door_wings::find( m_doorwings, Animation.iNumber ) } ) { + Animation.yUpdate = [ this, spec = *spec ]( TAnim *pAnim ) { UpdateDoorWing( pAnim, spec ); }; + return; + } + switch( MoverParameters->Doors.type ) { // od razu zapinamy potrzebny typ animacji + case 1: + Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorTranslate, this, std::placeholders::_1 ); + break; + case 2: + Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorRotate, this, std::placeholders::_1 ); + break; + case 3: + Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorFold, this, std::placeholders::_1 ); + break; // obrót 3 kolejnych submodeli + case 4: + Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorPlug, this, std::placeholders::_1 ); + break; + default: + break; + } +} + void TDynamicObject::UpdatePant(TAnim *pAnim) { // animacja pantografu - 4 obracane ramiona, ślizg piąty float a, b, c; @@ -5882,24 +5938,8 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co if (pAnimations[i + j].smAnimated) { //++iAnimatedDoors; pAnimations[i + j].smAnimated->WillBeAnimated(); // wyłączenie optymalizacji transformu - switch( MoverParameters->Doors.type ) - { // od razu zapinamy potrzebny typ animacji - case 1: - pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdateDoorTranslate, this, std::placeholders::_1 ); - break; - case 2: - pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdateDoorRotate, this, std::placeholders::_1 ); - break; - case 3: - pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdateDoorFold, this, std::placeholders::_1 ); - break; // obrót 3 kolejnych submodeli - case 4: - pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdateDoorPlug, this, std::placeholders::_1 ); - break; - default: - break; - } pAnimations[i + j].iNumber = i + 1; // parzyste działają inaczej niż nieparzyste + bind_door_animation( pAnimations[ i + j ] ); // od razu zapinamy potrzebny typ animacji pAnimations[i + j].fMaxDist = 300 * 300; // drzwi to z daleka widać /* // NOTE: no longer used @@ -5910,6 +5950,34 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co } } + else if( token == "animdoor:" ) { + // own kind of animation of one door wing, in place of the one of the .fiz (eu07/maszyna#70): + // animdoor: { type: range: rangeout: } + // the keys left out keep the values of the .fiz. the wing still follows the door of its side + door_wings::wing_spec spec { + 0, + MoverParameters->Doors.type, + MoverParameters->Doors.range, + MoverParameters->Doors.range_out }; + auto error { door_wings::read_spec( parser, spec ) }; + if( error.empty() + && ( spec.number < 1 || spec.number > iAnimType[ ANIM_DOORS ] ) ) { + error = "no door wing " + std::to_string( spec.number ) + " among the door animations"; + } + if( false == error.empty() ) { + ErrorLog( "Bad model: " + asFileName + " - animdoor: " + error, logtype::model ); + } + else { + door_wings::store( m_doorwings, spec ); + // a wing animdoorprefix has found already gets the new kind of animation now; the ones it + // finds later get it then + auto const index { static_cast( std::accumulate( std::begin( iAnimType ), std::begin( iAnimType ) + ANIM_DOORS, 0 ) + spec.number - 1 ) }; + if( index < pAnimations.size() && pAnimations[ index ].yUpdate ) { + bind_door_animation( pAnimations[ index ] ); + } + } + } + else if( token == "animstepprefix:" ) { // animated doorstep submodel name prefix int i, j; diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index 49b23c959..c0a7bc1cf 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -22,6 +22,7 @@ http://mozilla.org/MPL/2.0/. #include "audio/sound.h" #include "world/Spring.h" #include "vehicle/mirrors.h" +#include "vehicle/doorwings.h" #include "scripting/scriptscreenrules.h" #include @@ -305,6 +306,12 @@ private: void UpdateDoorRotate(TAnim *pAnim); // animacja drzwi - obrót void UpdateDoorFold(TAnim *pAnim); // animacja drzwi - składanie void UpdateDoorPlug(TAnim *pAnim); // animacja drzwi - odskokowo-przesuwne + // a wing with its own kind of animation, given in the .mmd (animdoor:), in place of the one of the .fiz + void UpdateDoorWing( TAnim *pAnim, door_wings::wing_spec const &Spec ); + // sets the update of a door wing animation, for its own kind if the .mmd gives one, otherwise for the .fiz + void bind_door_animation( TAnim &Animation ); + // door wings animated in their own way, from the .mmd (eu07/maszyna#70) + std::vector m_doorwings; void UpdatePant(TAnim *pAnim); // animacja pantografu void UpdatePlatformTranslate(TAnim *pAnim); // doorstep animation, shift void UpdatePlatformRotate(TAnim *pAnim); // doorstep animation, rotate diff --git a/vehicle/doorwings.h b/vehicle/doorwings.h index 07286aac8..1266dafec 100644 --- a/vehicle/doorwings.h +++ b/vehicle/doorwings.h @@ -10,6 +10,13 @@ http://mozilla.org/MPL/2.0/. #pragma once #include +#include +#include +#include +#include +#include +#include +#include #include @@ -17,6 +24,12 @@ http://mozilla.org/MPL/2.0/. // in the main model and, when the low poly interior has a submodel of the same name, in the interior as well namespace door_wings { +// the kinds of wing animation, numbered as DoorOpenMethod of the .fiz (TMoverParameters::door_data::type) +inline constexpr int shift_type{1}; +inline constexpr int rotate_type{2}; +inline constexpr int fold_type{3}; +inline constexpr int plug_type{4}; + // whether the animation with the given flags (TAnim::iFlags, the kind of animation in bits 4-7) moves a door wing inline bool is_wing(int const Flags) { return (Flags & 0xF0) == 0x10; @@ -49,4 +62,130 @@ inline fold_angles fold(float const Position) { return {Position, -Position - Position, Position}; } +// the animation of one wing given in the .mmd, in place of the one the .fiz sets for all door wings of the vehicle +// (eu07/maszyna#70). the wing still follows the door of its side, over its own range: +// animdoor: { type: range: rangeout: } +// every key is optional; a key left out keeps the value of the .fiz +struct wing_spec { + int number{0}; // of the wing, as in animdoorprefix: door1 is 1 + int type{rotate_type}; + float range{0.f}; // shift or angle of the wing when the door is fully open + float range_out{0.f}; // how far a plug wing is pushed out +}; + +// the kind of wing animation with the given name of DoorOpenMethod, in any letter case +inline std::optional type_from_name(std::string_view const Name) { + std::string name{Name}; + std::transform(name.begin(), name.end(), name.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + if (name == "shift") { + return shift_type; + } + if (name == "rotate") { + return rotate_type; + } + if (name == "fold") { + return fold_type; + } + if (name == "plug") { + return plug_type; + } + return std::nullopt; +} + +// the number written in the whole of the text, or nothing +inline std::optional number_from_text(std::string const &Text) { + if (Text.empty()) { + return std::nullopt; + } + char *end{nullptr}; + auto const value{std::strtof(Text.c_str(), &end)}; + if (end != Text.c_str() + Text.size() || false == std::isfinite(value)) { + return std::nullopt; + } + return value; +} + +// applies the keys and values of the block of an animdoor entry (the tokens between the braces) to the spec, which +// comes filled with the values of the .fiz. returns what is wrong with the block, or an empty text when nothing is; +// the keys before the fault are applied +inline std::string parse_spec(std::vector const &Tokens, wing_spec &Spec) { + for (std::size_t index = 0; index < Tokens.size(); index += 2) { + std::string key{Tokens[index]}; + std::transform(key.begin(), key.end(), key.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + if (index + 1 >= Tokens.size()) { + return "no value for \"" + key + "\""; + } + auto const &value{Tokens[index + 1]}; + if (key == "type:") { + auto const type{type_from_name(value)}; + if (false == type.has_value()) { + return "unknown door type \"" + value + "\""; + } + Spec.type = *type; + } + else if (key == "range:" || key == "rangeout:") { + auto const number{number_from_text(value)}; + if (false == number.has_value()) { + return "bad number \"" + value + "\" for \"" + key + "\""; + } + (key == "range:" ? Spec.range : Spec.range_out) = *number; + } + else { + return "unknown key \"" + key + "\""; + } + } + return {}; +} + +// reads an animdoor entry after its key: the wing number and the block in braces, into the spec filled with the values +// of the .fiz. returns what is wrong with the entry, or an empty text when nothing is. the parser is a cParser +template +std::string read_spec(Parser_ &Parser, wing_spec &Spec) { + Parser.getTokens(1, false); + Parser >> Spec.number; + std::string token; + Parser.getTokens(1, false); + Parser >> token; + if (token != "{") { + return "no { after the wing number"; + } + std::vector block; + while (true) { + token.clear(); + Parser.getTokens(1, false); + Parser >> token; + if (token.empty()) { + return "no } after the keys"; + } + if (token == "}") { + break; + } + block.emplace_back(token); + } + return parse_spec(block, Spec); +} + +// the spec given for the wing with the given number, or null when the wing animates as the .fiz says +inline wing_spec const *find(std::vector const &Specs, int const Number) { + auto const lookup{std::find_if(Specs.begin(), Specs.end(), [Number](wing_spec const &Spec) { return Spec.number == Number; })}; + return lookup != Specs.end() ? &(*lookup) : nullptr; +} + +// keeps the spec of a wing; a later entry for the same wing replaces the earlier one +inline void store(std::vector &Specs, wing_spec const &Spec) { + auto lookup{std::find_if(Specs.begin(), Specs.end(), [&Spec](wing_spec const &Stored) { return Stored.number == Spec.number; })}; + if (lookup != Specs.end()) { + *lookup = Spec; + } + else { + Specs.emplace_back(Spec); + } +} + +// the shift or angle of a wing which opens over Wingrange, while the door of its side opens over Doorrange: the wing +// is as far along its range as the door is along the door range +inline float wing_position(float const Doorposition, float const Doorrange, float const Wingrange) { + return Doorrange != 0.f ? Doorposition / Doorrange * Wingrange : 0.f; +} + } // namespace door_wings From aa84e41f0984e38b26a4f0e663ba77e2111748d8 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 00:17:22 +0100 Subject: [PATCH 049/136] feat: timetable service flags for the AI driver (eu07/maszyna#95) A timetable can now tell the AI how the train is served, for trams, underground trains and the like. The whole train gets them from a new row of the first box of the header: [ Flagi AI | drzwi_centralne=tak,stopien=nie,kierownik=nie,proba_hamulca=nie ] and a station changes them from there on with entries of its station ware (the second line of the station, next to R2, ph, @): [ | | po,kierownik=nie 1 12.54 | ] - drzwi_centralne=tak: the driver opens all the doors from the cab, those of mixed control too (otherwise left to the passengers) - stopien=tak/nie: the doorsteps switched on/off before the doors open (the AI didn't touch them before; new driver hints for it) - kierownik=nie: no conductor, so no departure signal (direct or by radio) and no first door kept open for him before the departure - proba_hamulca=nie: no running brake test A flag left out keeps today's behaviour, so a timetable without flags drives as before. Old builds skip the header row and keep the station entries as station ware text (none starts with R or holds @, po, pt). The reader moves out of TTrainParameters::LoadTTfile into world/timetablereader.cpp (eu07_core) unchanged, so the tests can run it; the flags come out of the station ware there. It now ends at the end of the file with an error where the old one spun forever (a truncated file, a missing number), and stops at 100 stations instead of writing past the table. Every .txt of the game's sceneries and of the SVN data reads the same as with the old reader (compared field by field against a verbatim copy of it); EU07_UNIT_TESTS_TIMETABLES= reads them in the unit tests and EU07_UNIT_TESTS_TIMETABLES_DUMP writes what was read. --- CMakeLists.txt | 3 + application/driverhints.cpp | 23 +++ application/driverhints_def.h | 2 + tests/unit/test_timetable.cpp | 321 ++++++++++++++++++++++++++++++++++ vehicle/Driver.cpp | 26 ++- vehicle/Driver.h | 1 + vehicle/timetableservice.cpp | 49 ++++++ vehicle/timetableservice.h | 37 ++++ world/mtable.cpp | 307 +++----------------------------- world/mtable.h | 25 +-- world/timetableflags.cpp | 103 +++++++++++ world/timetableflags.h | 59 +++++++ world/timetablereader.cpp | 321 ++++++++++++++++++++++++++++++++++ world/timetablereader.h | 66 +++++++ 14 files changed, 1038 insertions(+), 305 deletions(-) create mode 100644 tests/unit/test_timetable.cpp create mode 100644 vehicle/timetableservice.cpp create mode 100644 vehicle/timetableservice.h create mode 100644 world/timetableflags.cpp create mode 100644 world/timetableflags.h create mode 100644 world/timetablereader.cpp create mode 100644 world/timetablereader.h diff --git a/CMakeLists.txt b/CMakeLists.txt index e97e41d03..7fb845ba3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -553,6 +553,9 @@ set(CORE_SOURCES "vehicle/linebreaker.cpp" "vehicle/smoke.cpp" "vehicle/odometer.cpp" +"vehicle/timetableservice.cpp" +"world/timetableflags.cpp" +"world/timetablereader.cpp" ) add_library(eu07_core STATIC ${CORE_SOURCES}) target_link_libraries(eu07_core PUBLIC eu07_settings) diff --git a/application/driverhints.cpp b/application/driverhints.cpp index 0c6f02cc8..2c3fbd66b 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -1150,6 +1150,29 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) return IsAnyDoorPermitActive[side::left] == false; } ); break; } + // doorsteps, as the timetable asks (eu07/maszyna#95) + case driver_hint::doorstepon: { + if( AIControllFlag ) { + mvOccupied->PermitDoorStep( true ); + } + remove_hint( driver_hint::doorstepoff ); + hint( + Action, + [this](float const /*Parameter*/) { + return mvOccupied->Doors.step_enabled == true; } ); + break; + } + case driver_hint::doorstepoff: { + if( AIControllFlag ) { + mvOccupied->PermitDoorStep( false ); + } + remove_hint( driver_hint::doorstepon ); + hint( + Action, + [this](float const /*Parameter*/) { + return mvOccupied->Doors.step_enabled == false; } ); + break; + } // consist lights case driver_hint::consistlightson: { if( AIControllFlag ) { diff --git a/application/driverhints_def.h b/application/driverhints_def.h index 2ce896679..6f5c86474 100644 --- a/application/driverhints_def.h +++ b/application/driverhints_def.h @@ -72,6 +72,8 @@ DRIVER_HINT_DEF(doorrightpermiton, STRN("Grant permit to open doors")) DRIVER_HINT_DEF(doorrightpermitoff, STRN("Revoke permit to open doors")) DRIVER_HINT_DEF(doorleftpermiton, STRN("Grant permit to open doors")) DRIVER_HINT_DEF(doorleftpermitoff, STRN("Revoke permit to open doors")) +DRIVER_HINT_DEF(doorstepon, STRN("Switch on doorsteps")) +DRIVER_HINT_DEF(doorstepoff, STRN("Switch off doorsteps")) DRIVER_HINT_DEF(hornon, STRN("Sound the horn")) DRIVER_HINT_DEF(hornoff, STRN("Switch off horn")) DRIVER_HINT_DEF(consistlightson, STRN("Switch on consist lights")) diff --git a/tests/unit/test_timetable.cpp b/tests/unit/test_timetable.cpp new file mode 100644 index 000000000..f4387e7f8 --- /dev/null +++ b/tests/unit/test_timetable.cpp @@ -0,0 +1,321 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +#include "McZapkie/MOVER.h" +#include "utilities/utilities.h" +#include "vehicle/timetableservice.h" +#include "world/timetablereader.h" + +#include +#include +#include +#include +#include + +// the timetables of the trains (.txt next to the scenery, world/timetablereader.cpp) and the service flags they +// give the AI driver (eu07/maszyna#95): the reader as it was, the flags of the header and of the stations, and what +// the driver does with them + +using timetable::service_flags; +using timetable::tristate; + +namespace { + +// a timetable the way the game's sceneries have them: the header, three stations, a speed change at the second one +std::string const timetable_text{ + " ___________________________________________________________________\n" + "[ Rodzaj i numer pociagu | Os1234 ]\n" + "[ Kategoria | Os ]\n" + "%FLAGS%" + "[________________________________________________|__________________]\n" + "[ | Gorna ]\n" + "[ Relacja pociagu | Dolna ]\n" + "[________________________________________________|__________________]\n" + "[ Wymagany % ciezaru hamujacego | 60% ]\n" + "[________________________________________________|__________________]\n" + "[ Seria i obciazenie lokomotywy | EN57 120 ]\n" + "[________________________________________________|__________________]\n" + "[ 1.13 | 60 | Gorna 1 | | ]\n" + "[ | | %WARE1% 1 12.47 | ]\n" + "[ | |----------------------------------1---------|--------]\n" + "[ 5.06 |_____| Srodkowa 1 12.54 | 7 ]\n" + "[ | 40 | %WARE2% 1 12.55 | ]\n" + "[ | |----------------------------------1---------|--------]\n" + "[ 9.16 | | Dolna 2 13.01 | 6 ]\n" + "[ | | %WARE3% 2 | | ]\n" + "[_______|_____|__________________________________2_________|________]\n"}; + +std::string replaced(std::string Text, std::string const &Key, std::string const &Value) { + for (auto at{Text.find(Key)}; at != std::string::npos; at = Text.find(Key, at + Value.size())) { + Text.replace(at, Key.size(), Value); + } + return Text; +} + +std::string timetable_with(std::string const &Flags, std::string const &Ware1, std::string const &Ware2, std::string const &Ware3) { + return replaced(replaced(replaced(replaced(timetable_text, "%FLAGS%", Flags), "%WARE1%", Ware1), "%WARE2%", Ware2), "%WARE3%", Ware3); +} + +struct read_result { + int error; + Mtable::timetable_data data; +}; + +read_result read(std::string const &Text) { + std::istringstream input{Text}; + read_result result; + result.data.TrainName = "file"; + result.error = Mtable::read_timetable(input, result.data); + return result; +} + +service_flags flags(tristate const Doors, tristate const Doorstep, tristate const Conductor, tristate const Braketest) { + return {Doors, Doorstep, Conductor, Braketest}; +} + +auto const unset{tristate::unset}; +auto const yes{tristate::yes}; +auto const no{tristate::no}; + +// what the timetable gives, but for the service flags: to compare a timetable with flags to one without +std::string contents(Mtable::timetable_data const &Data) { + auto text{std::format("{}|{}|{}|{}|{}|{}|{}|{}|{}\n", Data.TrainName, Data.TrainCategory, Data.TrainLabel, Data.Relation1, Data.Relation2, Data.BrakeRatio, + Data.LocSeries, Data.LocLoad, Data.StationCount)}; + for (auto i{0}; i <= Data.StationCount; ++i) { + auto const &row{Data.TimeTable[i]}; + text += std::format("{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}\n", i, row.km, row.vmax, row.StationName, row.StationWare, row.TrackNo, row.Ah, row.Am, row.Dh, row.Dm, + row.tm, row.is_maintenance, row.radio_channel); + } + return text; +} + +std::string flags_text(service_flags const &Flags) { + auto const one{[](tristate const Flag) { return Flag == tristate::unset ? '-' : Flag == tristate::yes ? 'y' : 'n'; }}; + return {one(Flags.central_doors), one(Flags.doorstep), one(Flags.conductor), one(Flags.brake_test)}; +} + +} // namespace + +TEST_CASE("timetable: the reader reads a timetable the way it always did") { + auto const [error, data]{read(timetable_with("", "R2,H", "po", "R3"))}; + + CHECK(error == 0); + CHECK(data.TrainName == "Os1234"); + CHECK(data.TrainCategory == "Os"); + CHECK(data.Relation1 == "Gorna"); + CHECK(data.Relation2 == "Dolna"); + CHECK(data.BrakeRatio == 60.0); + CHECK(data.LocSeries == "EN57"); + CHECK(data.LocLoad == 120.0); + REQUIRE(data.StationCount == 3); + + auto const &first{data.TimeTable[1]}; + CHECK(first.StationName == "Gorna"); + CHECK(first.km == doctest::Approx(1.13)); + CHECK(first.Ah == -1); // no arrival: LoadTTfile makes it a stop, the first station being the start of the relation + CHECK(first.Dh == 12); + CHECK(first.Dm == 47.f); + CHECK(first.StationWare == "R2,H"); + CHECK(first.radio_channel == 2); + + auto const &second{data.TimeTable[2]}; + CHECK(second.StationName == "Srodkowa"); + CHECK(second.Ah == 12); + CHECK(second.Am == 54.f); + CHECK(second.Dm == 55.f); + CHECK(second.tm == 7.f); + CHECK(second.StationWare == "po"); + CHECK(second.radio_channel == -1); + + auto const &last{data.TimeTable[3]}; + CHECK(last.StationName == "Dolna"); + CHECK(last.TrackNo == 2); + CHECK(last.Ah == 13); + CHECK(last.Dh == 13); // departure as the arrival, for the delay + CHECK(last.radio_channel == 3); + // 60 km/h up to the change at the second station, 40 km/h after it + CHECK(data.TimeTable[1].vmax == 60.f); + CHECK(data.TimeTable[2].vmax == 60.f); + CHECK(data.TimeTable[3].vmax == 40.f); + // a timetable without flags leaves all of them to the vehicles + CHECK(data.Flags.empty()); + for (auto i{0}; i <= data.StationCount; ++i) { + CHECK(data.TimeTable[i].flags.empty()); + } +} + +TEST_CASE("timetable: the row Flagi of the header sets the flags of the whole train") { + auto const [error, data]{read(timetable_with("[ Flagi AI | kierownik=nie, proba_hamulca=nie ]\n", "R2,H", "po", "R3"))}; + + CHECK(error == 0); + CHECK(data.Flags == flags(unset, unset, no, no)); + // every station has them + for (auto i{0}; i <= data.StationCount; ++i) { + CAPTURE(i); + CHECK(data.TimeTable[i].flags == data.Flags); + } + // and the rest of the header reads as before + CHECK(data.TrainName == "Os1234"); + CHECK(data.TrainCategory == "Os"); + CHECK(data.Relation1 == "Gorna"); + CHECK(data.StationCount == 3); +} + +TEST_CASE("timetable: a station's flags hold from that station on") { + auto const [error, data]{read(timetable_with("[ Flagi AI | proba_hamulca=nie ]\n", "R2,H", "po,stopien=nie,drzwi_centralne=tak", "R3,stopien=tak"))}; + + CHECK(error == 0); + CHECK(data.TimeTable[1].flags == flags(unset, unset, unset, no)); + CHECK(data.TimeTable[2].flags == flags(yes, no, unset, no)); + CHECK(data.TimeTable[3].flags == flags(yes, yes, unset, no)); + // the flags are taken out of the station ware, the rest of it stays + CHECK(data.TimeTable[2].StationWare == "po"); + CHECK(data.TimeTable[3].StationWare == "R3"); + CHECK(data.TimeTable[3].radio_channel == 3); +} + +TEST_CASE("timetable: the flags change nothing else the timetable gives") { + auto const plain{read(timetable_with("", "R2,H", "po", "R3"))}; + auto const flagged{read(timetable_with("[ Flagi AI | kierownik=nie ]\n", "kierownik=tak,R2,H", "po,drzwi_centralne=tak", "R3,stopien=nie,proba_hamulca=nie"))}; + + CHECK(flagged.error == plain.error); + CHECK(contents(flagged.data) == contents(plain.data)); +} + +TEST_CASE("timetable: entries which aren't flags stay in the station ware") { + service_flags read_flags; + SUBCASE("no flags: the list as it was, empty entries too") { + CHECK(timetable::extract_flags("po,,R2", read_flags) == "po,,R2"); + CHECK(timetable::extract_flags("", read_flags).empty()); + CHECK(read_flags.empty()); + } + SUBCASE("an unknown key stays, a known one with an unknown value is dropped") { + CHECK(timetable::extract_flags("po,foo=1,kierownik=moze,R2", read_flags) == "po,foo=1,R2"); + CHECK(read_flags.empty()); + } + SUBCASE("keys and values in either case, 1 and 0 for tak and nie") { + CHECK(timetable::extract_flags("Kierownik=NIE,STOPIEN=1,ph", read_flags) == "ph"); + CHECK(read_flags == flags(unset, yes, no, unset)); + } +} + +TEST_CASE("timetable: a truncated timetable is an error, not a hang") { + auto const text{timetable_with("", "R2,H", "po", "R3")}; + // cut in the middle of a station, in the middle of the header, right after the top line: the reader used to go + // on reading past the end of the file forever + for (auto const cut : {text.find("Srodkowa"), text.find("Wymagany"), text.find("Rodzaj")}) { + CAPTURE(cut); + auto const [error, data]{read(text.substr(0, cut))}; + CHECK(error == Mtable::timetable_truncated); + } + // cut between two stations: the row the reader expects isn't there + auto const [error, data]{read(text.substr(0, text.find("[ 9.16")))}; + CHECK(error == -4); + CHECK(data.StationCount == 3); +} + +TEST_CASE("timetable: a timetable longer than the table is an error") { + auto const text{timetable_with("", "R2,H", "po", "R3")}; + auto const begin{text.find("[ 5.06")}; + auto const end{text.find("[ 9.16")}; + auto const station{text.substr(begin, end - begin)}; + std::string stations; + for (auto i{0}; i < Mtable::MaxTTableSize; ++i) { + stations += station; + } + auto const [error, data]{read(text.substr(0, begin) + stations + text.substr(end))}; + CHECK(error == Mtable::timetable_too_long); + CHECK(data.StationCount == Mtable::MaxTTableSize); +} + +TEST_CASE("timetable: the entry whose flags hold at the stop and on the way") { + // before the timetable is loaded, and with none + CHECK(timetable::stop_flags_entry(0, 0) == 0); + CHECK(timetable::run_flags_entry(0, 0) == 0); + CHECK(timetable::run_flags_entry(1, 0) == 0); + // making for (or standing at) the first station: its flags at the stop, the header's on the way + CHECK(timetable::stop_flags_entry(1, 3) == 1); + CHECK(timetable::run_flags_entry(1, 3) == 0); + // after the departure from the second station + CHECK(timetable::stop_flags_entry(3, 3) == 3); + CHECK(timetable::run_flags_entry(3, 3) == 2); + // past the end of the timetable + CHECK(timetable::stop_flags_entry(4, 3) == 3); + CHECK(timetable::run_flags_entry(5, 3) == 3); +} + +TEST_CASE("timetable: the AI opens the doors from the cab as the vehicle and the timetable say") { + test::vehicle unit{test::definition::load("wagon")}; + auto const central{flags(yes, unset, unset, unset)}; + auto const notcentral{flags(no, unset, unset, unset)}; + + unit->Doors.open_control = control_t::driver; + CHECK(timetable::opens_doors(unit.mover(), {})); + CHECK(timetable::opens_doors(unit.mover(), notcentral)); // the driver's doors open only from the cab + unit->Doors.open_control = control_t::conductor; + CHECK(timetable::opens_doors(unit.mover(), {})); + // doors of mixed control are left to the passengers, unless the timetable has the driver open them all + unit->Doors.open_control = control_t::mixed; + CHECK_FALSE(timetable::opens_doors(unit.mover(), {})); + CHECK_FALSE(timetable::opens_doors(unit.mover(), notcentral)); + CHECK(timetable::opens_doors(unit.mover(), central)); + // the passengers' own doors and the automatic ones can't be opened from the cab + unit->Doors.open_control = control_t::passenger; + CHECK_FALSE(timetable::opens_doors(unit.mover(), central)); + unit->Doors.open_control = control_t::autonomous; + CHECK_FALSE(timetable::opens_doors(unit.mover(), central)); +} + +TEST_CASE("timetable: the doorsteps, the conductor and the brake test as the timetable says") { + // no flags: the doorsteps as they are, the conductor and the brake test as before + CHECK_FALSE(timetable::doorstep({}).has_value()); + CHECK(timetable::has_conductor({})); + CHECK(timetable::makes_brake_test({})); + + CHECK(timetable::doorstep(flags(unset, no, unset, unset)) == false); + CHECK(timetable::doorstep(flags(unset, yes, unset, unset)) == true); + CHECK_FALSE(timetable::has_conductor(flags(unset, unset, no, unset))); + CHECK(timetable::has_conductor(flags(unset, unset, yes, unset))); + CHECK_FALSE(timetable::makes_brake_test(flags(unset, unset, unset, no))); + CHECK(timetable::makes_brake_test(flags(unset, unset, unset, yes))); +} + +// reads every .txt file under the folder given in EU07_UNIT_TESTS_TIMETABLES (the scenery/ of the game), the way the +// game reads a timetable, and checks none of them has flags; EU07_UNIT_TESTS_TIMETABLES_DUMP names a file to write +// what was read to, to compare the reading of two builds +TEST_CASE("timetable: the timetables of the game, when asked for") { + auto const *source{std::getenv("EU07_UNIT_TESTS_TIMETABLES")}; + if (source == nullptr) { + return; + } + std::vector files; + for (auto const &entry : std::filesystem::recursive_directory_iterator{source}) { + if (entry.is_regular_file() && ToLower(entry.path().extension().string()) == ".txt") { + files.push_back(entry.path()); + } + } + std::ranges::sort(files); + std::string dump; + auto timetables{0}; + for (auto const &file : files) { + auto const name{std::filesystem::relative(file, source).generic_string()}; + CAPTURE(name); + std::ifstream input{file}; + Mtable::timetable_data data; + data.TrainName = file.stem().string(); + auto const error{Mtable::read_timetable(input, data)}; + if (error == 0 && data.StationCount > 0) { + ++timetables; + } + CHECK(data.Flags.empty()); + for (auto i{0}; i <= data.StationCount; ++i) { + CHECK(data.TimeTable[i].flags.empty()); + } + dump += std::format("== {} error {}\n", name, error) + contents(data); + } + MESSAGE(std::format("{} files, {} read as timetables", files.size(), timetables)); + if (auto const *output{std::getenv("EU07_UNIT_TESTS_TIMETABLES_DUMP")}; output != nullptr) { + std::ofstream{output, std::ios::binary} << dump; + } +} diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index eb74344bf..6ff904431 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -21,6 +21,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Train.h" #include "vehicle/brakesetting.h" #include "vehicle/handover.h" +#include "vehicle/timetableservice.h" #include "world/mtable.h" #include "vehicle/DynObj.h" #include "world/Event.h" @@ -1345,6 +1346,8 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub if (TrainParams.UpdateMTable( simulation::Time, asNextStop) ) { // to się wykona tylko raz po zatrzymaniu na W4 record_station( Point, blackbox::station_kinds::stopped ); + // the service flags of this stop hold for its doors and departure + m_stopflags = TrainParams.stop_flags(); if( TrainParams.StationIndex < TrainParams.StationCount ) { // jeśli są dalsze stacje, bez trąbienia przed odjazdem // also ignore any horn cue that may be potentially set below 1 km/h and before the actual full stop @@ -1443,7 +1446,8 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub if( Command == TCommandType::cm_Unknown ) { // jeśli nie było komendy wcześniej Command = TCommandType::cm_Ready; // gotów do odjazdu z W4 (semafor może zatrzymać) } - if( false == tsGuardSignal.empty() ) { + if( false == tsGuardSignal.empty() + && true == timetable::has_conductor( m_stopflags ) ) { // jeśli mamy głos kierownika, to odegrać iDrivigFlags |= moveGuardSignal; } @@ -1451,7 +1455,8 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub } // koniec startu z zatrzymania else { cue_action(driver_hint::waitdeparturetime); - if (TrainParams.IsTimeToGo(simulation::Time.data().wHour, simulation::Time.data().wMinute + simulation::Time.data().wSecond*0.0167 + 0.1)) { //if is less than 6 sec to departure + if (timetable::has_conductor(m_stopflags) // no conductor, no door kept open for him + && TrainParams.IsTimeToGo(simulation::Time.data().wHour, simulation::Time.data().wMinute + simulation::Time.data().wSecond*0.0167 + 0.1)) { //if is less than 6 sec to departure iDrivigFlags |= moveGuardOpenDoor; GuardOpenDoor(); } @@ -4790,6 +4795,11 @@ void TController::Doors( bool const Open, int const Side ) { auto const lewe = pVehicle->DirectionGet() > 0 ? 1 : 2; auto const prawe = 3 - lewe; + // doorsteps as the timetable asks, before the doors open (eu07/maszyna#95) + if( auto const doorstep { timetable::doorstep( m_stopflags ) }; + doorstep.has_value() && mvOccupied->Doors.step_enabled != *doorstep ) { + cue_action( *doorstep ? driver_hint::doorstepon : driver_hint::doorstepoff ); + } // grant door control permission if it's not automatic // TBD: stricter requirements? if( true == pVehicle->MoverParameters->Doors.permit_needed ) { @@ -4801,10 +4811,9 @@ void TController::Doors( bool const Open, int const Side ) { } } // consist-wide remote signals to open doors doors - if( pVehicle->MoverParameters->Doors.open_control == control_t::conductor - || pVehicle->MoverParameters->Doors.open_control == control_t::driver - // NOTE: disabled for mixed controls, leave it up to passengers to open doors by themselves -/* || ( pVehicle->MoverParameters->Doors.open_control == control_t::mixed ) */ ) { + // NOTE: mixed controls are left up to passengers to open doors by themselves, unless the timetable has + // the driver open all the doors + if( true == timetable::opens_doors( *pVehicle->MoverParameters, m_stopflags ) ) { if( Side & prawe ) { cue_action( driver_hint::doorrightopen ); } @@ -4954,6 +4963,7 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N TrainParams = TTrainParameters(NewCommand); // rozkład jazdy tsGuardSignal = sound_source { sound_placement::internal, 2 * EU07_SOUND_CABCONTROLSCUTOFFRANGE }; // wywalenie kierownika m_lastexchangestop.clear(); + m_stopflags = {}; if (NewCommand != "none") { if (false == TrainParams.LoadTTfile( @@ -4988,6 +4998,8 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N TrainParams.StationIndexInc(); // przejście do następnej TrainParams.StationStart = TrainParams.StationIndex; asNextStop = TrainParams.NextStop(); + // the flags of the first station until the train stops there + m_stopflags = TrainParams.stop_flags(); m_lastannouncement = announcement_t::idle; iDrivigFlags |= movePrimary; // skoro dostał rozkład, to jest teraz głównym // NewCommand = Global.asCurrentSceneryPath + NewCommand; @@ -8588,6 +8600,8 @@ TController::adjust_desired_speed_for_braking_test() { // if( false == Global.DynamicBrakeTest ) { return; } if( DynamicBrakeTest >= 5 ) { return; } // all done + if( ( DynamicBrakeTest == 0 ) + && ( false == timetable::makes_brake_test( TrainParams.run_flags() ) ) ) { return; } // the timetable says there's none (eu07/maszyna#95) if( false == is_train() ) { return; } // not applicable if( mvOccupied->BrakeHandle == TBrakeHandle::FVel6 ) { return; } // leads to bugs in DecBrake, disable for now if( false == TestFlag( OrderCurrentGet(), Obey_train ) ) { return; } // not applicable diff --git a/vehicle/Driver.h b/vehicle/Driver.h index cfa27757e..2ed51b6a1 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -663,6 +663,7 @@ private: std::string m_lastexchangestop; // HACK: safeguard to prevent multiple load exchanges per station int m_lastexchangeplatforms { 0 }; // cached station platforms for last exchange int m_lastexchangedirection { 0 }; // + timetable::service_flags m_stopflags; // service flags of the timetable at the stop the train is at or left last double fLastStopExpDist = -1.0; // odległość wygasania ostateniego przystanku int iRadioChannel = 1; // numer aktualnego kanału radiowego int iGuardRadio = 0; // numer kanału radiowego kierownika (0, gdy nie używa radia) diff --git a/vehicle/timetableservice.cpp b/vehicle/timetableservice.cpp new file mode 100644 index 000000000..913e9d2d4 --- /dev/null +++ b/vehicle/timetableservice.cpp @@ -0,0 +1,49 @@ +/* +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/timetableservice.h" + +#include "McZapkie/MOVER.h" + +namespace timetable { + +bool opens_doors(TMoverParameters const &Vehicle, service_flags const &Flags) { + switch (Vehicle.Doors.open_control) { + case control_t::conductor: + case control_t::driver: + return true; + case control_t::mixed: + // left to the passengers, unless the timetable has the driver open them all + return Flags.central_doors == tristate::yes; + default: + return false; + } +} + +std::optional doorstep(service_flags const &Flags) { + switch (Flags.doorstep) { + case tristate::yes: + return true; + case tristate::no: + return false; + default: + return std::nullopt; + } +} + +bool has_conductor(service_flags const &Flags) { + return Flags.conductor != tristate::no; +} + +bool makes_brake_test(service_flags const &Flags) { + return Flags.brake_test != tristate::no; +} + +} // namespace timetable diff --git a/vehicle/timetableservice.h b/vehicle/timetableservice.h new file mode 100644 index 000000000..b5c72adf7 --- /dev/null +++ b/vehicle/timetableservice.h @@ -0,0 +1,37 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include + +#include "world/timetableflags.h" + +class TMoverParameters; + +// what the AI driver does at a stop and on the way, as the service flags of the timetable ask (eu07/maszyna#95). with +// no flags each answer is the one the AI gave before the flags +namespace timetable { + +// whether the driver opens the doors of the consist from the cab at a stop, Vehicle being the one he drives: the doors +// the conductor or the driver opens, and with the central door opening also the ones of mixed control, which are +// otherwise left to the passengers +bool opens_doors(TMoverParameters const &Vehicle, service_flags const &Flags); + +// the state the driver sets the doorsteps to before he opens the doors at a stop, none when he leaves them as they are +std::optional doorstep(service_flags const &Flags); + +// whether a conductor serves the train: gives the departure signal (by radio or by voice) and keeps the first door +// open for himself until the departure +bool has_conductor(service_flags const &Flags); + +// whether the driver makes the running brake test after the departure +bool makes_brake_test(service_flags const &Flags); + +} // namespace timetable diff --git a/world/mtable.cpp b/world/mtable.cpp index 123ae00f6..daf7b6637 100644 --- a/world/mtable.cpp +++ b/world/mtable.cpp @@ -109,6 +109,16 @@ sound_source TTrainParameters::current_stop_sound() const { return { sound_placement::engine }; } +timetable::service_flags const &TTrainParameters::stop_flags() const { + + return TimeTable[ timetable::stop_flags_entry( StationIndex, StationCount ) ].flags; +} + +timetable::service_flags const &TTrainParameters::run_flags() const { + + return TimeTable[ timetable::run_flags_entry( StationIndex, StationCount ) ].flags; +} + bool TTrainParameters::UpdateMTable( scenario_time const &Time, std::string const &NewName ) { return UpdateMTable( Time.data().wHour, Time.data().wMinute + Time.data().wSecond * 0.0167, NewName ); @@ -257,21 +267,16 @@ void TTrainParameters::UpdateVelocity(int /*Stationcount*/, double vActual) bool TTrainParameters::LoadTTfile(std::string const &scnpath, int iPlus, double vmax) // wczytanie pliku-tabeli z rozkładem przesuniętym o (fPlus); (vMax) nie ma znaczenia { - std::string lines; std::string s; std::ifstream fin; - bool EndTable; - double vActual; int conversionerror = 0; - EndTable = false; if (TrainName == "") { // jeśli pusty rozkład // UpdateVelocity(StationCount,vMax); //ograniczenie do prędkości startowej } else { - vActual = -1; s = scnpath + TrainName + ".txt"; replace_slashes(s); // Ra 2014-09: ustalić zasady wyznaczenia pierwotnego pliku przy przesuniętych rozkładach @@ -293,284 +298,22 @@ bool TTrainParameters::LoadTTfile(std::string const &scnpath, int iPlus, double } else { /*analiza rozkładu jazdy*/ - conversionerror = 0; - while (fin.good() && !(conversionerror != 0 || EndTable)) - { - std::getline(fin, lines); /*wczytanie linii*/ - if (contains( lines, "___________________") ) /*linia pozioma górna*/ - { - fin >> s; - if (s == "[") /*lewy pion*/ - { - fin >> s; - if (s == "Rodzaj") /*"Rodzaj i numer pociagu"*/ - do - { - fin >> s; - } while (!(s == "|") || fin.eof()); /*środkowy pion*/ - } - } - else if (lines == "") - { - fin.close(); - break; - } - fin >> s; /*nazwa pociągu*/ - // if LowerCase(s)<>ExtractFileName(TrainName) then {musi być taka sama, jak nazwa - // pliku} - // ConversionError:=-7 {błąd niezgodności} - TrainName = s; // nadanie nazwy z pliku TXT (bez ścieżki do pliku) - while (fin >> s || fin.bad()) - { - if (contains( s,"_______|") ) - { - break; - } - if (s == "Kategoria") - { - do - { - fin >> s; - } while (!(s == "|" || fin.bad())); - fin >> TrainCategory; - continue; - } - if (s == "Nazwa") - { - do - { - fin >> s; - } while (!(s == "|" || fin.bad())); - fin >> TrainLabel; - continue; - } - } // while (!(s == "Seria")); - // else - { /*czytaj naglowek*/ - while (fin >> s || !fin.bad()) - { - if (s == "[") - break; - } // while (!() || (fin.eof())); /*pierwsza linia z relacją*/ - while (fin >> s || !fin.bad()) - { - if (s != "|") - break; - } // while (!(() || fin.eof())); - if( s != "|" ) { - Relation1 = s; - win1250_to_ascii( Relation1 ); - } - else - conversionerror = -5; - while (fin >> s || !fin.bad()) - { - if (s == "Relacja") - break; - } // while ( - // !( || (fin.eof()))); /*druga linia z relacją*/ - while (fin >> s || !fin.bad()) - { - if (s == "|") - break; - } // while (!( || (fin.eof()))); - fin >> Relation2; - win1250_to_ascii( Relation2 ); - while (fin >> s || !fin.bad()) - { - if (s == "Wymagany") - break; - } // while (!(); - while (fin >> s || !fin.bad()) - { - if (s == "|" || s == "\n") - break; - } // while (!()); - fin >> s; - s = s.substr(0, s.find("%")); - BrakeRatio = atof(s.c_str()); - while (fin >> s || fin.bad()) - { - if (s == "Seria") - break; - } // while (!(s == "Seria")); - do - { - fin >> s; - } while (!(s == "|" || fin.bad())); - fin >> LocSeries; - fin >> LocLoad; // = s2rE(ReadWord(fin)); - do - { - fin >> s; - } while (!(contains( s,"[______________" ) || fin.bad())); - auto activeradiochannel{ -1 }; - while (!fin.bad() && !EndTable) - { - ++StationCount; - do - { - fin >> s; - } while (!(s == "[" || fin.bad())); - TMTableLine *record = &TimeTable[StationCount]; - { - if (s == "[") - fin >> s; - else - conversionerror = -4; - if (false == contains( s,"|") ) - { - record->km = static_cast(atof(s.c_str())); - fin >> s; - } - if (contains( s,"|_____|")) /*zmiana predkosci szlakowej*/ - UpdateVelocity(StationCount, vActual); - else - { - fin >> s; - if (false == contains(s,"|")) - vActual = atof(s.c_str()); - } - while (false == contains( s,"|")) - fin >> s; - fin >> record->StationName; - // get rid of non-ascii chars. TODO: run correct version based on locale - win1250_to_ascii( record->StationName ); - do - { - fin >> s; - } while (!(s == "1" || s == "2" || fin.bad())); - record->TrackNo = atoi(s.c_str()); - fin >> s; - if (s != "|") - { - if (contains( s, hrsd) ) - { - record->Ah = atoi( s.substr(0, s.find(hrsd)).c_str()); // godzina przyjazdu - record->Am = static_cast(atof(s.substr(s.find(hrsd) + 1, s.length()).c_str())); // minuta przyjazdu - } - else - { - record->Ah = TimeTable[StationCount - 1].Ah; // godzina z poprzedniej pozycji - record->Am = static_cast(atof(s.c_str())); // bo tylko minuty podane - } - } - do - { - fin >> s; - } while (!(s != "|" || fin.bad())); - if (s != "]") - record->tm = static_cast(atof(s.c_str())); - do - { - fin >> s; - } while (!(s == "[" || fin.bad())); - fin >> s; - if (false == contains(s,"|")) - { - /*tu s moze byc miejscem zmiany predkosci szlakowej*/ - fin >> s; - } - if (s.find("|_____|") != - std::string::npos) /*zmiana predkosci szlakowej*/ - UpdateVelocity(StationCount, vActual); - else - { - fin >> s; - if (false == contains(s,"|")) - vActual = atof(s.c_str()); - } - while (false == contains(s,"|")) - fin >> s; - // stationware. added fix for empty entry - fin >> s; - while( false == ( s == "1" - || s == "2" - || fin.bad() ) ) { - record->StationWare += s; - fin >> s; - } - // cache relevant station data - record->is_maintenance = contains(s, "pt"); - { - auto const stationware { Split( record->StationWare, ',' ) }; - for( auto const &entry : stationware ) { - if( entry.front() != 'R' ) { - continue; - } - auto const [entrytype, entrynumber]{ split_string_and_number( entry ) }; - if( entrytype == "R" - && entrynumber <= 10 ) { - auto const radiochannel { entrynumber }; - if( record->radio_channel == -1 - || radiochannel != activeradiochannel ) { - // if the station has more than one radiochannel listed, - // it generally means we should switch to the one we weren't using so far - // TODO: reverse this behaviour (keep the channel used so far) once W28 signs are included in the system - record->radio_channel = radiochannel; - } - } - } - if( record->radio_channel != -1 ) { - activeradiochannel = record->radio_channel; - } - } - record->TrackNo = atoi(s.c_str()); - fin >> s; - if (s != "|") - { - if (contains( s, hrsd) ) - { - record->Dh = atoi(s.substr(0, s.find(hrsd)).c_str()); // godzina odjazdu - record->Dm = static_cast(atof(s.substr(s.find(hrsd) + 1, s.length()).c_str())); // minuta odjazdu - } - else - { - record->Dh = TimeTable[StationCount - 1].Dh; // godzina z poprzedniej pozycji - record->Dm = static_cast(atof(s.c_str())); // bo tylko minuty podane - } - } - else - { - record->Dh = record->Ah; // odjazd o tej samej, co przyjazd (dla ostatniego też) - record->Dm = record->Am; // bo są używane do wyliczenia opóźnienia po dojechaniu - } - do - { - fin >> s; - } while (!(s != "|" || fin.bad())); - if (s != "]") - record->tm = static_cast(atof(s.c_str())); - do - { - fin >> s; - } while (!(contains( s, "[" ) || fin.bad())); - if (false == contains( s, "_|_")) - fin >> s; - if (false == contains( s, "|")) - { - /*tu s moze byc miejscem zmiany predkosci szlakowej*/ - fin >> s; - } - if (contains( s, "|_____|") ) /*zmiana predkosci szlakowej*/ - UpdateVelocity(StationCount, vActual); - else - { - fin >> s; - if (false == contains( s, "|")) - vActual = atof(s.c_str()); - } - while (false == contains( s, "|" ) ) - fin >> s; - while (false == contains(s, "]")) - fin >> s; - if (contains( s,"_|_") ) - EndTable = true; - } /*timetableline*/ - } - } - } /*while eof*/ + timetable_data data; + data.TrainName = TrainName; + conversionerror = read_timetable( fin, data ); fin.close(); + TrainName = data.TrainName; + TrainCategory = data.TrainCategory; + TrainLabel = data.TrainLabel; + Relation1 = data.Relation1; + Relation2 = data.Relation2; + BrakeRatio = data.BrakeRatio; + LocSeries = data.LocSeries; + LocLoad = data.LocLoad; + StationCount = data.StationCount; + for( auto i = 0; i <= MaxTTableSize; ++i ) { + static_cast( TimeTable[ i ] ) = data.TimeTable[ i ]; + } } } // jeśli nazwa pierwszego zgodna z relacją diff --git a/world/mtable.h b/world/mtable.h index 841fea815..31fdd8810 100644 --- a/world/mtable.h +++ b/world/mtable.h @@ -13,32 +13,19 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Classes.h" #include "audio/sound.h" +#include "world/timetablereader.h" namespace Mtable { -static int const MaxTTableSize = 100; // można by to robić dynamicznie static char const *const hrsd = "."; // Ra: pozycja zerowa rozkładu chyba nie ma sensu // Ra: numeracja przystanków jest 1..StationCount -struct TMTableLine +// a station of the timetable as the file gives it (TMTableEntry, world/timetablereader.h), with its name announcement +struct TMTableLine : TMTableEntry { - float km{ 0.f }; // kilometraz linii - float vmax{ -1.f }; // predkosc rozkladowa przed przystankiem - // StationName:string[32]; //nazwa stacji ('_' zamiast spacji) - // StationWare:string[32]; //typ i wyposazenie stacji, oddz. przecinkami} - std::string StationName{ "nowhere" }; // nazwa stacji ('_' zamiast spacji) - std::string StationWare; // typ i wyposazenie stacji, oddz. przecinkami} - int TrackNo{ 1 }; // ilosc torow szlakowych - int Ah{ -1 }; - float Am{ -1.f }; // godz. i min. przyjazdu, -1 gdy bez postoju - int Dh{ -1 }; - float Dm{ -1.f }; // godz. i min. odjazdu - float tm{ 0.f }; // czas jazdy do tej stacji w min. (z kolumny) - bool is_maintenance{ false }; - int radio_channel{ -1 }; sound_source name_sound{ sound_placement::engine }; }; @@ -58,7 +45,7 @@ class TTrainParameters double BrakeRatio; std::string LocSeries; // seria (typ) pojazdu double LocLoad; - TMTable TimeTable; + TMTable TimeTable; // TimeTable[0].flags holds the service flags of the whole train int StationCount; // ilość przystanków (0-techniczny) int StationIndex; // numer najbliższego (aktualnego) przystanku int StationStart; // numer pierwszej stacji pokazywanej na podglądzie rozkładu @@ -95,6 +82,10 @@ class TTrainParameters int radio_channel() const; // returns: sound file associated with current station, or -1 sound_source current_stop_sound() const; + // service flags (eu07/maszyna#95) which hold at the stop the train makes for or stands at + timetable::service_flags const &stop_flags() const; + // service flags which hold on the way, since the stop the train left last + timetable::service_flags const &run_flags() const; private: void load_sounds(); }; diff --git a/world/timetableflags.cpp b/world/timetableflags.cpp new file mode 100644 index 000000000..5c7d6ae9e --- /dev/null +++ b/world/timetableflags.cpp @@ -0,0 +1,103 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "world/timetableflags.h" + +#include "utilities/Logs.h" +#include "utilities/utilities.h" + +namespace timetable { + +namespace { + +void apply_one(tristate &Flag, tristate const Other) { + if (Other != tristate::unset) { + Flag = Other; + } +} + +tristate *flag_named(std::string_view const Key, service_flags &Flags) { + if (Key == "drzwi_centralne") { + return &Flags.central_doors; + } + if (Key == "stopien") { + return &Flags.doorstep; + } + if (Key == "kierownik") { + return &Flags.conductor; + } + if (Key == "proba_hamulca") { + return &Flags.brake_test; + } + return nullptr; +} + +} // namespace + +void service_flags::apply(service_flags const &Other) { + apply_one(central_doors, Other.central_doors); + apply_one(doorstep, Other.doorstep); + apply_one(conductor, Other.conductor); + apply_one(brake_test, Other.brake_test); +} + +bool read_flag(std::string_view const Entry, service_flags &Flags) { + auto const separator{Entry.find('=')}; + if (separator == std::string_view::npos) { + return false; + } + auto const key{ToLower(std::string{Entry.substr(0, separator)})}; + auto *flag{flag_named(key, Flags)}; + if (flag == nullptr) { + return false; + } + auto const value{ToLower(std::string{Entry.substr(separator + 1)})}; + if (value == "tak" || value == "1") { + *flag = tristate::yes; + } + else if (value == "nie" || value == "0") { + *flag = tristate::no; + } + else { + ErrorLog("Bad timetable: unknown value of " + key + " in \"" + std::string{Entry} + "\", expected tak or nie"); + } + return true; +} + +std::string extract_flags(std::string const &Ware, service_flags &Flags) { + if (false == contains(Ware, '=')) { + // no flags, the list as it was + return Ware; + } + std::string rest; + for (auto const &entry : Split(Ware, ',')) { + if (read_flag(entry, Flags)) { + continue; + } + if (contains(entry, '=')) { + ErrorLog("Bad timetable: unknown flag \"" + entry + "\" in station ware \"" + Ware + "\""); + } + if (false == rest.empty()) { + rest += ','; + } + rest += entry; + } + return rest; +} + +int stop_flags_entry(int const StationIndex, int const StationCount) { + return std::clamp(StationIndex, 0, std::max(StationCount, 0)); +} + +int run_flags_entry(int const StationIndex, int const StationCount) { + return std::clamp(StationIndex - 1, 0, std::max(StationCount, 0)); +} + +} // namespace timetable diff --git a/world/timetableflags.h b/world/timetableflags.h new file mode 100644 index 000000000..8c463d3f3 --- /dev/null +++ b/world/timetableflags.h @@ -0,0 +1,59 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include + +// the way a train is served, set by its timetable for the AI driver (eu07/maszyna#95): trams and underground trains +// open all the doors from the cab, have no doorstep, no conductor, no running brake test. each flag the timetable +// leaves out keeps the behaviour of the vehicles, as before the flags. +// +// the whole train: a row of the first box of the header +// [ Flagi AI | kierownik=nie,proba_hamulca=nie ] +// from a station on: entries of its station ware (the second line of the station, with R2, ph, @...) +// [ | | R2,ph,drzwi_centralne=tak,stopien=nie 1 12.47 | ] +// a station's entry holds from that station on, until another station changes it +namespace timetable { + +enum class tristate : std::uint8_t { + unset, // left to the vehicles, as before the flags + yes, + no +}; + +struct service_flags { + tristate central_doors{tristate::unset}; // drzwi_centralne: the driver opens all the doors, of mixed control too + tristate doorstep{tristate::unset}; // stopien: the doorsteps on (tak) or off (nie) before the doors open + tristate conductor{tristate::unset}; // kierownik: no conductor (nie), no departure signal, no door kept open for him + tristate brake_test{tristate::unset}; // proba_hamulca: no running brake test (nie) + + bool operator==(service_flags const &) const = default; + bool empty() const { return *this == service_flags{}; } + // the flags Other sets explicitly override these + void apply(service_flags const &Other); +}; + +// reads one entry, key=value (tak/nie, 1/0), into Flags. returns false for an entry which isn't a flag, so the caller +// keeps it; a flag with a value it doesn't know is reported to the log and taken as handled +bool read_flag(std::string_view Entry, service_flags &Flags); + +// reads the flags out of a station ware list (comma separated entries) into Flags. returns the list without them: the +// list as it was when it had none +std::string extract_flags(std::string const &Ware, service_flags &Flags); + +// the timetable entry whose flags hold at the stop the train makes for or stands at: the current one (StationIndex), +// within 0 (the header's flags) and the last station +int stop_flags_entry(int StationIndex, int StationCount); +// the entry whose flags hold on the way: the station the train left last, 0 (the header's flags) before the first one +int run_flags_entry(int StationIndex, int StationCount); + +} // namespace timetable diff --git a/world/timetablereader.cpp b/world/timetablereader.cpp new file mode 100644 index 000000000..3d340e8bd --- /dev/null +++ b/world/timetablereader.cpp @@ -0,0 +1,321 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "world/timetablereader.h" + +#include "utilities/Logs.h" +#include "utilities/utilities.h" + +namespace Mtable { + +namespace { + +char const *const hrsd = "."; + +// the rest of the row "Flagi" of the header after its label: flag entries up to the closing bracket. returns true when +// a row with no closing bracket ran into the line under the box +bool read_header_flags(std::istream &fin, timetable_data &Data) { + std::string s; + do { + fin >> s; + } while (!(s == "|" || fin.fail())); + while (fin >> s) { + if (s.starts_with('[')) { + // the next row, or the line under the box + ErrorLog("Bad timetable: row \"Flagi\" of " + Data.TrainName + " without the closing bracket"); + return contains(s, "_______|"); + } + auto const closing{s.ends_with(']')}; + for (auto const &entry : Split(closing ? std::string_view{s}.substr(0, s.size() - 1) : std::string_view{s}, ',')) { + if (false == entry.empty() && false == timetable::read_flag(entry, Data.Flags)) { + ErrorLog("Bad timetable: unknown flag \"" + entry + "\" in row \"Flagi\" of " + Data.TrainName); + } + } + if (closing) { + break; + } + } + return false; +} + +} // namespace + +// the reader as TTrainParameters::LoadTTfile had it, but for: the row "Flagi" of the header and the flags of the +// station ware; the loops end with the end of the file, where they used to spin forever (on a truncated file, or one +// with a number where the reader expects it which isn't one). a file the old reader read gets read the same +int read_timetable(std::istream &fin, timetable_data &Data) { + std::string lines; + std::string s; + bool EndTable{false}; + double vActual{-1}; + int conversionerror{0}; + auto &TimeTable{Data.TimeTable}; + auto &StationCount{Data.StationCount}; + // zapisywanie prędkości maksymalnej do wcześniejszych odcinków + auto const UpdateVelocity{[&TimeTable, &StationCount](double const Velocity) { + int i = StationCount; + while (i >= 0 && TimeTable[i].vmax == -1) { + TimeTable[i].vmax = static_cast(Velocity); // prędkość dojazdu do przystanku i + --i; // ewentualnie do poprzedniego też + } + }}; + + while (fin.good() && !(conversionerror != 0 || EndTable)) { + std::getline(fin, lines); /*wczytanie linii*/ + if (contains(lines, "___________________")) /*linia pozioma górna*/ + { + fin >> s; + if (s == "[") /*lewy pion*/ + { + fin >> s; + if (s == "Rodzaj") /*"Rodzaj i numer pociagu"*/ + do { + fin >> s; + } while (!(s == "|" || fin.fail())); /*środkowy pion*/ + } + } + else if (lines == "") { + break; + } + fin >> s; /*nazwa pociągu*/ + Data.TrainName = s; // nadanie nazwy z pliku TXT (bez ścieżki do pliku) + while (fin >> s) { + if (contains(s, "_______|")) { + break; + } + if (s == "Kategoria") { + do { + fin >> s; + } while (!(s == "|" || fin.fail())); + fin >> Data.TrainCategory; + continue; + } + if (s == "Nazwa") { + do { + fin >> s; + } while (!(s == "|" || fin.fail())); + fin >> Data.TrainLabel; + continue; + } + if (s == "Flagi") { + // service flags of the whole train (eu07/maszyna#95) + if (read_header_flags(fin, Data)) { + break; + } + continue; + } + } + { /*czytaj naglowek*/ + while (fin >> s) { + if (s == "[") + break; + } /*pierwsza linia z relacją*/ + while (fin >> s) { + if (s != "|") + break; + } + if (s != "|") { + Data.Relation1 = s; + win1250_to_ascii(Data.Relation1); + } + else + conversionerror = -5; + while (fin >> s) { + if (s == "Relacja") + break; + } /*druga linia z relacją*/ + while (fin >> s) { + if (s == "|") + break; + } + fin >> Data.Relation2; + win1250_to_ascii(Data.Relation2); + while (fin >> s) { + if (s == "Wymagany") + break; + } + while (fin >> s) { + if (s == "|" || s == "\n") + break; + } + fin >> s; + s = s.substr(0, s.find("%")); + Data.BrakeRatio = atof(s.c_str()); + while (fin >> s) { + if (s == "Seria") + break; + } + do { + fin >> s; + } while (!(s == "|" || fin.fail())); + fin >> Data.LocSeries; + fin >> Data.LocLoad; // = s2rE(ReadWord(fin)); + do { + fin >> s; + } while (!(contains(s, "[______________") || fin.fail())); + // the header's flags hold from the start, entry 0 keeps them for the stations to inherit + TimeTable[0].flags = Data.Flags; + auto activeradiochannel{-1}; + while (!fin.fail() && !EndTable) { + ++StationCount; + if (StationCount > MaxTTableSize) { + --StationCount; + conversionerror = timetable_too_long; + break; + } + do { + fin >> s; + } while (!(s == "[" || fin.fail())); + TMTableEntry *record = &TimeTable[StationCount]; + { + if (s == "[") + fin >> s; + else + conversionerror = -4; + if (false == contains(s, "|")) { + record->km = static_cast(atof(s.c_str())); + fin >> s; + } + if (contains(s, "|_____|")) /*zmiana predkosci szlakowej*/ + UpdateVelocity(vActual); + else { + fin >> s; + if (false == contains(s, "|")) + vActual = atof(s.c_str()); + } + while (false == contains(s, "|") && false == fin.fail()) + fin >> s; + fin >> record->StationName; + // get rid of non-ascii chars. TODO: run correct version based on locale + win1250_to_ascii(record->StationName); + do { + fin >> s; + } while (!(s == "1" || s == "2" || fin.fail())); + record->TrackNo = atoi(s.c_str()); + fin >> s; + if (s != "|") { + if (contains(s, hrsd)) { + record->Ah = atoi(s.substr(0, s.find(hrsd)).c_str()); // godzina przyjazdu + record->Am = static_cast(atof(s.substr(s.find(hrsd) + 1, s.length()).c_str())); // minuta przyjazdu + } + else { + record->Ah = TimeTable[StationCount - 1].Ah; // godzina z poprzedniej pozycji + record->Am = static_cast(atof(s.c_str())); // bo tylko minuty podane + } + } + do { + fin >> s; + } while (!(s != "|" || fin.fail())); + if (s != "]") + record->tm = static_cast(atof(s.c_str())); + do { + fin >> s; + } while (!(s == "[" || fin.fail())); + fin >> s; + if (false == contains(s, "|")) { + /*tu s moze byc miejscem zmiany predkosci szlakowej*/ + fin >> s; + } + if (s.find("|_____|") != std::string::npos) /*zmiana predkosci szlakowej*/ + UpdateVelocity(vActual); + else { + fin >> s; + if (false == contains(s, "|")) + vActual = atof(s.c_str()); + } + while (false == contains(s, "|") && false == fin.fail()) + fin >> s; + // stationware. added fix for empty entry + fin >> s; + while (false == (s == "1" || s == "2" || fin.fail())) { + record->StationWare += s; + fin >> s; + } + // cache relevant station data + record->is_maintenance = contains(s, "pt"); + // service flags (eu07/maszyna#95): the ones of the station before, changed by the ones given here + record->flags = TimeTable[StationCount - 1].flags; + record->StationWare = timetable::extract_flags(record->StationWare, record->flags); + { + auto const stationware{Split(record->StationWare, ',')}; + for (auto const &entry : stationware) { + if (entry.front() != 'R') { + continue; + } + auto const [entrytype, entrynumber]{split_string_and_number(entry)}; + if (entrytype == "R" && entrynumber <= 10) { + auto const radiochannel{entrynumber}; + if (record->radio_channel == -1 || radiochannel != activeradiochannel) { + // if the station has more than one radiochannel listed, + // it generally means we should switch to the one we weren't using so far + // TODO: reverse this behaviour (keep the channel used so far) once W28 signs are included in the system + record->radio_channel = radiochannel; + } + } + } + if (record->radio_channel != -1) { + activeradiochannel = record->radio_channel; + } + } + record->TrackNo = atoi(s.c_str()); + fin >> s; + if (s != "|") { + if (contains(s, hrsd)) { + record->Dh = atoi(s.substr(0, s.find(hrsd)).c_str()); // godzina odjazdu + record->Dm = static_cast(atof(s.substr(s.find(hrsd) + 1, s.length()).c_str())); // minuta odjazdu + } + else { + record->Dh = TimeTable[StationCount - 1].Dh; // godzina z poprzedniej pozycji + record->Dm = static_cast(atof(s.c_str())); // bo tylko minuty podane + } + } + else { + record->Dh = record->Ah; // odjazd o tej samej, co przyjazd (dla ostatniego też) + record->Dm = record->Am; // bo są używane do wyliczenia opóźnienia po dojechaniu + } + do { + fin >> s; + } while (!(s != "|" || fin.fail())); + if (s != "]") + record->tm = static_cast(atof(s.c_str())); + do { + fin >> s; + } while (!(contains(s, "[") || fin.fail())); + if (false == contains(s, "_|_")) + fin >> s; + if (false == contains(s, "|")) { + /*tu s moze byc miejscem zmiany predkosci szlakowej*/ + fin >> s; + } + if (contains(s, "|_____|")) /*zmiana predkosci szlakowej*/ + UpdateVelocity(vActual); + else { + fin >> s; + if (false == contains(s, "|")) + vActual = atof(s.c_str()); + } + while (false == contains(s, "|") && false == fin.fail()) + fin >> s; + while (false == contains(s, "]") && false == fin.fail()) + fin >> s; + if (contains(s, "_|_")) + EndTable = true; + } /*timetableline*/ + } + if (false == EndTable && conversionerror == 0) { + // the old reader went on reading past the end of the file here, forever + conversionerror = timetable_truncated; + } + } + } /*while eof*/ + return conversionerror; +} + +} // namespace Mtable diff --git a/world/timetablereader.h b/world/timetablereader.h new file mode 100644 index 000000000..aaf43e34c --- /dev/null +++ b/world/timetablereader.h @@ -0,0 +1,66 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include + +#include "world/timetableflags.h" + +// the reader of the timetable files (.txt next to the scenery), without the parts of the engine the timetable +// of a running train needs (sounds, scenario time), so it can be tested on its own +namespace Mtable { + +static int const MaxTTableSize = 100; // można by to robić dynamicznie + +// one station of a timetable, as the file gives it +struct TMTableEntry { + float km{0.f}; // kilometraz linii + float vmax{-1.f}; // predkosc rozkladowa przed przystankiem + std::string StationName{"nowhere"}; // nazwa stacji ('_' zamiast spacji) + std::string StationWare; // typ i wyposazenie stacji, oddz. przecinkami, bez flag obsługi + int TrackNo{1}; // ilosc torow szlakowych + int Ah{-1}; + float Am{-1.f}; // godz. i min. przyjazdu, -1 gdy bez postoju + int Dh{-1}; + float Dm{-1.f}; // godz. i min. odjazdu + float tm{0.f}; // czas jazdy do tej stacji w min. (z kolumny) + bool is_maintenance{false}; + int radio_channel{-1}; + // the service flags which hold from this station on: the header's, changed by this and the earlier stations. + // entry 0 holds the header's + timetable::service_flags flags; +}; + +// what a timetable file holds +struct timetable_data { + std::string TrainName; // the name the file is looked up by, then the one the file gives + std::string TrainCategory; + std::string TrainLabel; + std::string Relation1; + std::string Relation2; + double BrakeRatio{0.0}; + std::string LocSeries; + double LocLoad{0.0}; + timetable::service_flags Flags; // of the whole train, the row "Flagi" of the header + int StationCount{0}; // stations 1..StationCount, entry 0 is the technical one + std::array TimeTable; +}; + +// conversion errors of read_timetable, besides the ones it always had (-4: no station row where expected, -5: no +// first station of the relation) +int const timetable_truncated{-9}; // the file ends before the bottom line of the table (the reader used to hang) +int const timetable_too_long{-10}; // more stations than MaxTTableSize (the reader used to write past the table) + +// reads the timetable from Input into Data. returns the conversion error, 0 when read +int read_timetable(std::istream &Input, timetable_data &Data); + +} // namespace Mtable From a3df3a07c8a19ae4260577dcc401e1abb96c8899 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 00:48:28 +0100 Subject: [PATCH 050/136] test: count the shunting seconds in a function of its own, not a lambda holding the vehicle --- tests/unit/test_speed_control.cpp | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/tests/unit/test_speed_control.cpp b/tests/unit/test_speed_control.cpp index 7b0f7fc52..3f8a9a9ec 100644 --- a/tests/unit/test_speed_control.cpp +++ b/tests/unit/test_speed_control.cpp @@ -257,6 +257,18 @@ TEST_CASE("speed control apart: which vehicles' cruise control has a switch of i CHECK(eu07->IsSpeedCtrlSeparate()); } +namespace { + +// Seconds of the scenario going on, a second at a time, counting the seconds with the field shunted and not +void count_shunting(scenario &Scenario, TMoverParameters const &Vehicle, int const Seconds, int &Shunted, int &Unshunted) { + for (int second = 0; second < Seconds; ++second) { + Scenario.wait(1.0); + ++(Vehicle.ScndCtrlPos > 0 ? Shunted : Unshunted); + } +} + +} // namespace + TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the field shunting going on by itself") { scenario scenario{"speed control apart/6dg_v1/6dg", motion() + traction() + cruise(), test::track{}}; scenario.add("6dg_v1/6dg", 1); @@ -285,13 +297,7 @@ TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the // the shunt goes by itself all the while, by the current of the motors, which the cruise control's demand sets auto shunted{0}; auto unshunted{0}; - auto const run{[&scenario, &loco, &shunted, &unshunted](int const Seconds) { - for (int second = 0; second < Seconds; ++second) { - scenario.wait(1.0); - ++(loco.ScndCtrlPos > 0 ? shunted : unshunted); - } - }}; - run(60); + count_shunting(scenario, loco, 60, shunted, unshunted); CHECK(loco.Vel == doctest::Approx(held).epsilon(0.03)); CHECK_FALSE(loco.SpeedCtrlUnit.Standby); CHECK(loco.eimic_real < loco.eimic); // the cruise control holding the power back @@ -301,7 +307,7 @@ TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the loco.SpeedCtrlInc(); auto const higher{loco.SpeedCtrlValue}; CHECK(higher == doctest::Approx(held + 10.0).epsilon(0.1)); - run(60); + count_shunting(scenario, loco, 60, shunted, unshunted); CHECK(loco.Vel == doctest::Approx(higher).epsilon(0.03)); CHECK(loco.StLinFlag); CHECK(shunted > 0); From 81bae7cdd44b5421f7f9008af5c117c091afb524 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 01:42:49 +0100 Subject: [PATCH 051/136] feat: drag universal cab controls to any position with the mouse (#62) A universal control (window, door, sun blind) whose definition in the .mmd has the new optional key drag: can be dragged with the left mouse button to any position between its ends, and stays where it is let go: universal1: { okno_p mov -0.71 0 0.3 drag: left soundinc: ... } The value is the direction the mouse moves to open the control: up, down, left or right (yes = up, no = off). The drag works like the sliders of the controllers: the cursor is hidden, its move over 0.6 of the window height takes the control from one end to the other. A click without dragging toggles the control as before, and so do the keys: to the end farther from where it is. Push controls aren't dragged. Without the key every universal works as it did; none of the cab definitions has it yet. New commands genericset0..29 set universal N to the position in param1 (0-1); the mouse sends them, and they can be bound to a gamepad axis. The rules (the key's values, the move of the cursor along the direction, the ends, click or drag, the keys) are in vehicle/universaldrag.h, with unit tests. --- input/command.cpp | 60 ++++++++++++ input/command.h | 31 +++++++ input/drivermouseinput.cpp | 87 +++++++++++++++++- input/drivermouseinput.h | 24 ++++- tests/unit/test_universal_drag.cpp | 143 +++++++++++++++++++++++++++++ vehicle/Gauge.cpp | 14 ++- vehicle/Gauge.h | 7 ++ vehicle/Train.cpp | 86 ++++++++++++++--- vehicle/Train.h | 6 ++ vehicle/universaldrag.h | 138 ++++++++++++++++++++++++++++ 10 files changed, 576 insertions(+), 20 deletions(-) create mode 100644 tests/unit/test_universal_drag.cpp create mode 100644 vehicle/universaldrag.h diff --git a/input/command.cpp b/input/command.cpp index 32ba02e94..add272473 100644 --- a/input/command.cpp +++ b/input/command.cpp @@ -416,6 +416,36 @@ commanddescription_sequence Commands_descriptions = { {"linebreakeropenc", command_target::vehicle, command_mode::oneoff}, {"linebreakerclosec", command_target::vehicle, command_mode::oneoff}, {"repaircoupler", command_target::simulation, command_mode::oneoff}, + {"genericset0", command_target::vehicle, command_mode::oneoff}, + {"genericset1", command_target::vehicle, command_mode::oneoff}, + {"genericset2", command_target::vehicle, command_mode::oneoff}, + {"genericset3", command_target::vehicle, command_mode::oneoff}, + {"genericset4", command_target::vehicle, command_mode::oneoff}, + {"genericset5", command_target::vehicle, command_mode::oneoff}, + {"genericset6", command_target::vehicle, command_mode::oneoff}, + {"genericset7", command_target::vehicle, command_mode::oneoff}, + {"genericset8", command_target::vehicle, command_mode::oneoff}, + {"genericset9", command_target::vehicle, command_mode::oneoff}, + {"genericset10", command_target::vehicle, command_mode::oneoff}, + {"genericset11", command_target::vehicle, command_mode::oneoff}, + {"genericset12", command_target::vehicle, command_mode::oneoff}, + {"genericset13", command_target::vehicle, command_mode::oneoff}, + {"genericset14", command_target::vehicle, command_mode::oneoff}, + {"genericset15", command_target::vehicle, command_mode::oneoff}, + {"genericset16", command_target::vehicle, command_mode::oneoff}, + {"genericset17", command_target::vehicle, command_mode::oneoff}, + {"genericset18", command_target::vehicle, command_mode::oneoff}, + {"genericset19", command_target::vehicle, command_mode::oneoff}, + {"genericset20", command_target::vehicle, command_mode::oneoff}, + {"genericset21", command_target::vehicle, command_mode::oneoff}, + {"genericset22", command_target::vehicle, command_mode::oneoff}, + {"genericset23", command_target::vehicle, command_mode::oneoff}, + {"genericset24", command_target::vehicle, command_mode::oneoff}, + {"genericset25", command_target::vehicle, command_mode::oneoff}, + {"genericset26", command_target::vehicle, command_mode::oneoff}, + {"genericset27", command_target::vehicle, command_mode::oneoff}, + {"genericset28", command_target::vehicle, command_mode::oneoff}, + {"genericset29", command_target::vehicle, command_mode::oneoff}, }; // Maps of command and coresponding strings @@ -811,6 +841,36 @@ std::unordered_map const commandMap = { {"linebreakeropenc", user_command::linebreakeropenc}, {"linebreakerclosec", user_command::linebreakerclosec}, {"repaircoupler", user_command::repaircoupler}, + {"genericset0", user_command::genericset0}, + {"genericset1", user_command::genericset1}, + {"genericset2", user_command::genericset2}, + {"genericset3", user_command::genericset3}, + {"genericset4", user_command::genericset4}, + {"genericset5", user_command::genericset5}, + {"genericset6", user_command::genericset6}, + {"genericset7", user_command::genericset7}, + {"genericset8", user_command::genericset8}, + {"genericset9", user_command::genericset9}, + {"genericset10", user_command::genericset10}, + {"genericset11", user_command::genericset11}, + {"genericset12", user_command::genericset12}, + {"genericset13", user_command::genericset13}, + {"genericset14", user_command::genericset14}, + {"genericset15", user_command::genericset15}, + {"genericset16", user_command::genericset16}, + {"genericset17", user_command::genericset17}, + {"genericset18", user_command::genericset18}, + {"genericset19", user_command::genericset19}, + {"genericset20", user_command::genericset20}, + {"genericset21", user_command::genericset21}, + {"genericset22", user_command::genericset22}, + {"genericset23", user_command::genericset23}, + {"genericset24", user_command::genericset24}, + {"genericset25", user_command::genericset25}, + {"genericset26", user_command::genericset26}, + {"genericset27", user_command::genericset27}, + {"genericset28", user_command::genericset28}, + {"genericset29", user_command::genericset29}, {"none", user_command::none}}; } // namespace simulation diff --git a/input/command.h b/input/command.h index 664f6a3ba..9fb6021d0 100644 --- a/input/command.h +++ b/input/command.h @@ -414,6 +414,37 @@ enum class user_command linebreakeropenc, linebreakerclosec, repaircoupler, // the broken coupler of the vehicle (payload) at the end (param1) + // sets universal control N to the position given in param1, 0-1 (MaSzyna-EU07/maszyna#62) + genericset0, + genericset1, + genericset2, + genericset3, + genericset4, + genericset5, + genericset6, + genericset7, + genericset8, + genericset9, + genericset10, + genericset11, + genericset12, + genericset13, + genericset14, + genericset15, + genericset16, + genericset17, + genericset18, + genericset19, + genericset20, + genericset21, + genericset22, + genericset23, + genericset24, + genericset25, + genericset26, + genericset27, + genericset28, + genericset29, none = -1 }; diff --git a/input/drivermouseinput.cpp b/input/drivermouseinput.cpp index 222c58a62..d8d389f44 100644 --- a/input/drivermouseinput.cpp +++ b/input/drivermouseinput.cpp @@ -28,6 +28,8 @@ void mouse_slider::bind( user_command const &Command ) { m_command = Command; + m_universal.reset(); + m_universaldrag.reset(); auto const *train { simulation::Train }; TMoverParameters const *vehicle { nullptr }; @@ -124,18 +126,47 @@ mouse_slider::bind( user_command const &Command ) { m_analogue ? controledge - m_value * controlsize : controledge - m_value * stepsize - 0.5 * stepsize ); } +void +mouse_slider::bind_universal( int const Index, universal_drag::direction const Drag, float const Position ) { + + m_command = static_cast( static_cast( user_command::genericset0 ) + Index ); + m_universal = Index; + m_universaldrag.emplace( Drag, Position ); + m_value = m_universaldrag->position(); + m_valuerange = 1.0; + m_analogue = true; + m_invertrange = false; + // the cursor is hidden for the drag and put back where it was when the drag ends; the drag follows its moves + // from wherever it is, so it isn't placed anywhere + m_cursorposition = glm::dvec2( Global.cursor_pos ); + Application.set_cursor( GLFW_CURSOR_DISABLED ); +} + void mouse_slider::release() { m_command = user_command::none; + m_universal.reset(); + m_universaldrag.reset(); Application.set_cursor_pos( m_cursorposition.x, m_cursorposition.y ); Application.set_cursor( GLFW_CURSOR_NORMAL ); } -void -mouse_slider::on_move( double const /*Mousex*/, double const Mousey ) { +bool +mouse_slider::on_move( double const Mousex, double const Mousey ) { auto const controlsize { Global.window_size.y * EU07_CONTROLLER_MOUSESLIDERSIZE }; + + if( m_universaldrag ) { + // a universal control, dragged the same way as the controllers: the move of the cursor over the size of the + // slider takes it from one end to the other + if( false == m_universaldrag->move( Mousex, Mousey, controlsize ) ) { + return false; + } + m_value = m_universaldrag->position(); + return true; + } + auto const controledge { Global.window_size.y * 0.5 + controlsize * 0.5 }; auto const stepsize { controlsize / m_valuerange }; @@ -143,6 +174,7 @@ mouse_slider::on_move( double const /*Mousex*/, double const Mousey ) { m_value = m_analogue ? (controledge - mousey) / controlsize : std::floor((controledge - mousey) / stepsize); if( m_invertrange ) { m_value = ( m_analogue ? 1.0 : m_valuerange ) - m_value; } + return true; } @@ -246,8 +278,8 @@ drivermouse_input::move( double Mousex, double Mousey ) { } else { // control picking mode - if( m_slider.command() != user_command::none ) { - m_slider.on_move( Mousex, Mousey ); + if( m_slider.command() != user_command::none + && true == m_slider.on_move( Mousex, Mousey ) ) { m_relay.post( m_slider.command(), m_slider.value(), @@ -341,7 +373,14 @@ drivermouse_input::button( int const Button, int const Action ) { else { m_pickwaiting = false; if (Button == GLFW_MOUSE_BUTTON_LEFT && m_slider.command() != user_command::none) { - m_relay.post( m_slider.command(), 0, 0, Action, 0 ); + if( auto const universal { m_slider.universal() }; + universal && m_slider.is_click() ) { + // a universal control clicked rather than dragged goes to its end, as a click on any universal does + toggle_universal( *universal ); + } + else { + m_relay.post( m_slider.command(), 0, 0, Action, 0 ); + } m_slider.release(); } // if it's the right mouse button that got released and we had no command active, we were potentially in view panning mode; stop it @@ -392,6 +431,25 @@ drivermouse_input::button( int const Button, int const Action ) { default: { break; } } } + // a universal control with drag: in its definition is dragged to any position between its ends, + // and a click without dragging toggles it as before (MaSzyna-EU07/maszyna#62) + if( Button == GLFW_MOUSE_BUTTON_LEFT ) { + auto const universal { universal_index( mousecommand ) }; + auto const drag { + universal ? + simulation::Train->universal_drag_direction( *universal ) : + universal_drag::direction::none }; + if( drag != universal_drag::direction::none ) { + mousecommand = none; + if( false == pickwaiting ) { + // the button was let go before the control was found under the cursor: a click + toggle_universal( *universal ); + return; + } + m_slider.bind_universal( *universal, drag, simulation::Train->universal_position( *universal ) ); + return; + } + } switch( mousecommand ) { case mastercontrollerincrease: @@ -1162,4 +1220,23 @@ drivermouse_input::adjust_command( user_command Command ) const { return Command; } +std::optional +drivermouse_input::universal_index( user_command const Command ) { + + auto const index { static_cast( Command ) - static_cast( user_command::generictoggle0 ) }; + if( index < 0 + || index > static_cast( user_command::generictoggle29 ) - static_cast( user_command::generictoggle0 ) ) { + return std::nullopt; + } + return index; +} + +void +drivermouse_input::toggle_universal( int const Index ) const { + + auto const toggle { static_cast( static_cast( user_command::generictoggle0 ) + Index ) }; + m_relay.post( toggle, 0, 0, GLFW_PRESS, 0 ); + m_relay.post( toggle, 0, 0, GLFW_RELEASE, 0 ); +} + //--------------------------------------------------------------------------- diff --git a/input/drivermouseinput.h b/input/drivermouseinput.h index 180e0335c..aa2ac0ca3 100644 --- a/input/drivermouseinput.h +++ b/input/drivermouseinput.h @@ -9,8 +9,10 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include #include #include "input/command.h" +#include "vehicle/universaldrag.h" // virtual slider; value determined by position of the mouse class mouse_slider { @@ -21,9 +23,14 @@ public: // methods void bind( user_command const &Command ); + // binds the slider to universal control Index, which the mouse drags in the Drag direction from its Position + // to any position between its ends (MaSzyna-EU07/maszyna#62) + void + bind_universal( int const Index, universal_drag::direction const Drag, float const Position ); void release(); - void + // returns whether the value changed + bool on_move( double const Mousex, double const Mousey ); inline user_command @@ -32,10 +39,19 @@ public: double value() const { return m_value; } + // the universal control the slider drags, if any, and whether letting it go now is a click rather than a drag + std::optional + universal() const { + return m_universal; } + bool + is_click() const { + return m_universaldrag && m_universaldrag->is_click(); } private: // members user_command m_command { user_command::none }; + std::optional m_universal; // the universal control dragged, if any + std::optional m_universaldrag; double m_value { 0.0 }; double m_valuerange { 0.0 }; bool m_analogue { false }; @@ -92,6 +108,12 @@ private: // potentially replaces supplied command with a more relevant one user_command adjust_command( user_command Command ) const; + // the universal control a command toggles, if it toggles one + static std::optional + universal_index( user_command const Command ); + // toggles universal control Index, as a click on it does + void + toggle_universal( int const Index ) const; // members command_relay m_relay; diff --git a/tests/unit/test_universal_drag.cpp b/tests/unit/test_universal_drag.cpp new file mode 100644 index 000000000..f520b694f --- /dev/null +++ b/tests/unit/test_universal_drag.cpp @@ -0,0 +1,143 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/universaldrag.h" + +// smooth regulation of the universal cab controls (MaSzyna-EU07/maszyna#62): a universal with "drag: " +// in its definition is dragged with the mouse to any position between its ends and stays there when let go; a click +// and the keys move it to its ends. the mouse and TGauge are not part of the core library, the rules they follow are + +using universal_drag::direction; + +TEST_CASE("universal drag: the values of the drag key") { + CHECK(universal_drag::parse("up") == direction::up); + CHECK(universal_drag::parse("down") == direction::down); + CHECK(universal_drag::parse("left") == direction::left); + CHECK(universal_drag::parse("right") == direction::right); + // yes drags it up, as the sliders of the controllers + CHECK(universal_drag::parse("yes") == direction::up); + CHECK(universal_drag::parse("true") == direction::up); + CHECK(universal_drag::parse("1") == direction::up); + CHECK(universal_drag::parse("no") == direction::none); + CHECK(universal_drag::parse("false") == direction::none); + CHECK(universal_drag::parse("0") == direction::none); + CHECK(universal_drag::parse("none") == direction::none); + // a value it doesn't know is reported, and the control can't be dragged + CHECK_FALSE(universal_drag::parse("sideways").has_value()); + CHECK_FALSE(universal_drag::parse("").has_value()); + CHECK_FALSE(universal_drag::parse("Up").has_value()); +} + +TEST_CASE("universal drag: a push universal can't be dragged, it springs back when let go") { + CHECK(universal_drag::effective(direction::up, true) == direction::none); + CHECK(universal_drag::effective(direction::left, true) == direction::none); + CHECK(universal_drag::effective(direction::up, false) == direction::up); + CHECK(universal_drag::effective(direction::none, false) == direction::none); +} + +TEST_CASE("universal drag: the move of the cursor along the direction") { + auto const size{600.0}; + // the cursor's y grows downwards + CHECK(universal_drag::along(direction::up, 0.0, -60.0, size) == doctest::Approx(0.1)); + CHECK(universal_drag::along(direction::up, 0.0, 60.0, size) == doctest::Approx(-0.1)); + CHECK(universal_drag::along(direction::down, 0.0, 60.0, size) == doctest::Approx(0.1)); + CHECK(universal_drag::along(direction::left, -150.0, 0.0, size) == doctest::Approx(0.25)); + CHECK(universal_drag::along(direction::right, -150.0, 0.0, size) == doctest::Approx(-0.25)); + // the move across the direction doesn't count + CHECK(universal_drag::along(direction::up, 300.0, 0.0, size) == 0.0); + CHECK(universal_drag::along(direction::left, 0.0, 300.0, size) == 0.0); + // nothing to drag + CHECK(universal_drag::along(direction::none, 100.0, 100.0, size) == 0.0); + CHECK(universal_drag::along(direction::up, 0.0, -60.0, 0.0) == 0.0); +} + +TEST_CASE("universal drag: the position is kept between the ends") { + CHECK(universal_drag::clamp(-0.5) == 0.f); + CHECK(universal_drag::clamp(1.5) == 1.f); + CHECK(universal_drag::clamp(0.25) == doctest::Approx(0.25f)); +} + +TEST_CASE("universal drag: the keys and a click move the control to the end farther from its position") { + CHECK(universal_drag::toggled(0.f) == 1.f); + CHECK(universal_drag::toggled(1.f) == 0.f); + // a control left in between + CHECK(universal_drag::toggled(0.3f) == 1.f); + CHECK(universal_drag::toggled(0.7f) == 0.f); + // half way, as the two-state universals always did + CHECK(universal_drag::toggled(0.5f) == 0.f); +} + +TEST_CASE("universal drag: a drag takes the control to a position between its ends, where it stays") { + auto const size{600.0}; + universal_drag::drag drag{direction::up, 0.f}; + // the first position of the cursor is where the drag starts from, even if the hidden cursor was moved + CHECK_FALSE(drag.move(400.0, 500.0, size)); + CHECK(drag.position() == 0.f); + CHECK(drag.is_click()); + // up by a quarter of the size + CHECK(drag.move(400.0, 350.0, size)); + CHECK(drag.position() == doctest::Approx(0.25f)); + // sideways it stays + CHECK_FALSE(drag.move(700.0, 350.0, size)); + CHECK(drag.position() == doctest::Approx(0.25f)); + // back down a little + CHECK(drag.move(700.0, 380.0, size)); + CHECK(drag.position() == doctest::Approx(0.2f)); + CHECK_FALSE(drag.is_click()); + // let go: the position is what the drag left, the control keeps it + CHECK(drag.start() == 0.f); + CHECK(drag.position() == doctest::Approx(0.2f)); +} + +TEST_CASE("universal drag: the control stops at its ends, and moving back takes it back at once") { + auto const size{100.0}; + universal_drag::drag drag{direction::right, 0.9f}; + drag.move(0.0, 0.0, size); + CHECK(drag.move(50.0, 0.0, size)); + CHECK(drag.position() == 1.f); + // further on it stays at the end + CHECK_FALSE(drag.move(200.0, 0.0, size)); + CHECK(drag.position() == 1.f); + // back: from the end, not from where the cursor went past it + CHECK(drag.move(190.0, 0.0, size)); + CHECK(drag.position() == doctest::Approx(0.9f)); + // and the other end + CHECK(drag.move(0.0, 0.0, size)); + CHECK(drag.position() == 0.f); +} + +TEST_CASE("universal drag: a press let go with the cursor barely moved is a click") { + auto const size{600.0}; + universal_drag::drag drag{direction::down, 0.4f}; + drag.move(10.0, 10.0, size); + // a jitter of the hand, under the travel of a click + drag.move(11.0, 13.0, size); + drag.move(10.0, 11.0, size); + CHECK(drag.is_click()); + // the click moves it to the end farther from it, as the key does + CHECK(universal_drag::toggled(drag.position()) == 1.f); + // a drag there and back is a drag, though it ends where it started + universal_drag::drag back{direction::down, 0.4f}; + back.move(0.0, 0.0, size); + back.move(0.0, 60.0, size); + back.move(0.0, 0.0, size); + CHECK_FALSE(back.is_click()); + CHECK(back.position() == doctest::Approx(0.4f)); +} + +TEST_CASE("universal drag: a drag starts from the position the control is set to") { + universal_drag::drag drag{direction::up, 0.6f}; + CHECK(drag.start() == doctest::Approx(0.6f)); + CHECK(drag.position() == doctest::Approx(0.6f)); + // a position out of the range is brought into it + CHECK(universal_drag::drag{direction::up, 3.f}.position() == 1.f); + CHECK(universal_drag::drag{direction::up, -1.f}.position() == 0.f); +} + +TEST_CASE("universal drag: a control which can't be dragged doesn't move") { + universal_drag::drag drag{direction::none, 0.f}; + drag.move(0.0, 0.0, 600.0); + CHECK_FALSE(drag.move(300.0, -300.0, 600.0)); + CHECK(drag.position() == 0.f); + CHECK(drag.is_click()); +} diff --git a/vehicle/Gauge.cpp b/vehicle/Gauge.cpp index 52bf7795d..6289fe5a2 100644 --- a/vehicle/Gauge.cpp +++ b/vehicle/Gauge.cpp @@ -121,8 +121,9 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu Parser.getTokens(); if( Parser.peek() != "{" ) { // old fixed size config - // it has no scaletable:, drop the one of an earlier definition of the same control + // it has no scaletable: nor drag:, drop the ones of an earlier definition of the same control m_scaletable.clear(); + m_drag = universal_drag::direction::none; Parser >> submodelname; gaugetypename = Parser.getToken( true ); Parser.getTokens( 3, false ); @@ -168,6 +169,7 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu } gauge_scale::sort( scratchpad.scaletable ); m_scaletable = std::move( scratchpad.scaletable ); + m_drag = scratchpad.drag; // post-deserialization cleanup // set provided custom soundproofing to assigned sounds (for sounds without their own custom soundproofing) if( scratchpad.soundproofing ) { @@ -308,6 +310,16 @@ TGauge::Load_mapping( cParser &Input, TGauge::scratch_data &Scratchpad ) { >> soundproofing[ 5 ]; Scratchpad.soundproofing = soundproofing; } + else if( key == "drag:" ) { + // the mouse drags the control to any position between its ends, moving in the given direction to open it + // (MaSzyna-EU07/maszyna#62) + auto const value { Input.getToken( true, "\n\r\t ,;" ) }; + auto const drag { universal_drag::parse( value ) }; + if( false == drag.has_value() ) { + ErrorLog( "Bad model: unknown drag direction \"" + value + "\" of a cab control, it takes up, down, left, right, yes or no", logtype::model ); + } + Scratchpad.drag = drag.value_or( universal_drag::direction::none ); + } else if( key == "scaletable:" ) { // non-uniform scale in format [ value1 scaled1, value2 scaled2, ... ] return Load_scaletable( Input, Scratchpad ); diff --git a/vehicle/Gauge.h b/vehicle/Gauge.h index c16509f79..18ddf373a 100644 --- a/vehicle/Gauge.h +++ b/vehicle/Gauge.h @@ -12,6 +12,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Classes.h" #include "audio/sound.h" #include "vehicle/gaugescale.h" +#include "vehicle/universaldrag.h" enum class TGaugeAnimation { // typ ruchu @@ -86,6 +87,10 @@ public: // true if the gauge was given a non-uniform scale (scaletable:) bool has_scaletable() const { return false == m_scaletable.empty(); } + // the direction the mouse drags the control in to any position between its ends (drag:, MaSzyna-EU07/maszyna#62), + // none for a control set only to its ends. a push control springs back, so it isn't dragged + universal_drag::direction drag() const { + return universal_drag::effective( m_drag, is_push() ); } // members TSubModel *SubModel { nullptr }; // McZapkie-310302: zeby mozna bylo sprawdzac czy zainicjowany poprawnie TSubModel *SubModelOn { nullptr }; // optional submodel visible when the state input is set @@ -96,6 +101,7 @@ private: std::optional< std::array > soundproofing; bool duplicate { false }; // the definition is a duplicate submodel of the control defined before std::vector scaletable; // as read, in the units of the config + universal_drag::direction drag { universal_drag::direction::none }; }; // methods // imports member data pair from the config file @@ -127,6 +133,7 @@ private: float m_endvalue { -1.f }; // end value of accepted value range bool m_interpolatescale { false }; std::vector m_scaletable; // optional non-uniform scale, sorted by value; replaces scale and offset + universal_drag::direction m_drag { universal_drag::direction::none }; // the mouse drags the control smoothly, drag: char m_datatype { '\0' }; // typ zmiennej parametru: f-float, d-double, i-int, b-bool; none until one is assigned union { diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 50659934c..f2766a265 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -537,6 +537,36 @@ TTrain::commandhandler_map const TTrain::m_commandhandlers = { {user_command::generictoggle27, &TTrain::OnCommand_generictoggle}, {user_command::generictoggle28, &TTrain::OnCommand_generictoggle}, {user_command::generictoggle29, &TTrain::OnCommand_generictoggle}, + {user_command::genericset0, &TTrain::OnCommand_genericset}, + {user_command::genericset1, &TTrain::OnCommand_genericset}, + {user_command::genericset2, &TTrain::OnCommand_genericset}, + {user_command::genericset3, &TTrain::OnCommand_genericset}, + {user_command::genericset4, &TTrain::OnCommand_genericset}, + {user_command::genericset5, &TTrain::OnCommand_genericset}, + {user_command::genericset6, &TTrain::OnCommand_genericset}, + {user_command::genericset7, &TTrain::OnCommand_genericset}, + {user_command::genericset8, &TTrain::OnCommand_genericset}, + {user_command::genericset9, &TTrain::OnCommand_genericset}, + {user_command::genericset10, &TTrain::OnCommand_genericset}, + {user_command::genericset11, &TTrain::OnCommand_genericset}, + {user_command::genericset12, &TTrain::OnCommand_genericset}, + {user_command::genericset13, &TTrain::OnCommand_genericset}, + {user_command::genericset14, &TTrain::OnCommand_genericset}, + {user_command::genericset15, &TTrain::OnCommand_genericset}, + {user_command::genericset16, &TTrain::OnCommand_genericset}, + {user_command::genericset17, &TTrain::OnCommand_genericset}, + {user_command::genericset18, &TTrain::OnCommand_genericset}, + {user_command::genericset19, &TTrain::OnCommand_genericset}, + {user_command::genericset20, &TTrain::OnCommand_genericset}, + {user_command::genericset21, &TTrain::OnCommand_genericset}, + {user_command::genericset22, &TTrain::OnCommand_genericset}, + {user_command::genericset23, &TTrain::OnCommand_genericset}, + {user_command::genericset24, &TTrain::OnCommand_genericset}, + {user_command::genericset25, &TTrain::OnCommand_genericset}, + {user_command::genericset26, &TTrain::OnCommand_genericset}, + {user_command::genericset27, &TTrain::OnCommand_genericset}, + {user_command::genericset28, &TTrain::OnCommand_genericset}, + {user_command::genericset29, &TTrain::OnCommand_genericset}, {user_command::vehiclemoveforwards, &TTrain::OnCommand_vehiclemoveforwards}, {user_command::vehiclemovebackwards, &TTrain::OnCommand_vehiclemovebackwards}, {user_command::vehicleboost, &TTrain::OnCommand_vehicleboost}, @@ -6994,19 +7024,9 @@ void TTrain::OnCommand_generictoggle(TTrain *Train, command_data const &Command) } else { - // two-state switch - if (item.GetDesiredValue() < 0.5) - { - // turn on - // visual feedback - item.UpdateValue(1.0); - } - else - { - // turn off - // visual feedback - item.UpdateValue(0.0); - } + // two-state switch, or one dragged in between its ends with the mouse: to the end farther from it + // visual feedback + item.UpdateValue(universal_drag::toggled(item.GetDesiredValue())); } } else if (Command.action == GLFW_RELEASE && item.type() == TGaugeType::push) @@ -7018,6 +7038,46 @@ void TTrain::OnCommand_generictoggle(TTrain *Train, command_data const &Command) } } +// sets a universal control to the position given in param1, from 0 to 1 (MaSzyna-EU07/maszyna#62): the mouse drags +// the ones with drag: in their definition, and it can be bound to an axis of a gamepad. it stays where it is set +void TTrain::OnCommand_genericset(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_RELEASE) + { + return; + } + auto const itemindex = static_cast(Command.command) - static_cast(user_command::genericset0); + auto &item = Train->ggUniversals[itemindex]; + if (item.is_push()) + { + // an impulse switch springs back, it has no position to be left in + return; + } + // visual feedback + item.UpdateValue(universal_drag::clamp(Command.param1)); +} + +universal_drag::direction TTrain::universal_drag_direction(int const Index) const +{ + + if (Index < 0 || Index >= static_cast(ggUniversals.size()) || ggUniversals[Index].SubModel == nullptr) + { + return universal_drag::direction::none; + } + return ggUniversals[Index].drag(); +} + +float TTrain::universal_position(int const Index) const +{ + + if (Index < 0 || Index >= static_cast(ggUniversals.size())) + { + return 0.f; + } + return ggUniversals[Index].GetDesiredValue(); +} + void TTrain::OnCommand_springbraketoggle(TTrain *Train, command_data const &Command) { diff --git a/vehicle/Train.h b/vehicle/Train.h index a547eef72..e6cc0f3ba 100644 --- a/vehicle/Train.h +++ b/vehicle/Train.h @@ -172,6 +172,11 @@ class TTrain { inline std::string GetLabel( TSubModel const *Control ) const { return m_controlmapper.find( Control ); } + // the direction the mouse drags universal control Index in to any position between its ends, none if the control + // is only set to its ends (MaSzyna-EU07/maszyna#62) + universal_drag::direction universal_drag_direction( int const Index ) const; + // the position universal control Index is set to, from 0 to 1 + float universal_position( int const Index ) const; void UpdateCab(); bool Update( double const Deltatime ); void UpdateDirectionRelays(); @@ -518,6 +523,7 @@ class TTrain { static void OnCommand_cabchangeforward( TTrain *Train, command_data const &Command ); static void OnCommand_cabchangebackward( TTrain *Train, command_data const &Command ); static void OnCommand_generictoggle( TTrain *Train, command_data const &Command ); + static void OnCommand_genericset( TTrain *Train, command_data const &Command ); static void OnCommand_vehiclemoveforwards( TTrain *Train, command_data const &Command ); static void OnCommand_vehiclemovebackwards( TTrain *Train, command_data const &Command ); static void OnCommand_vehicleboost( TTrain *Train, command_data const &Command ); diff --git a/vehicle/universaldrag.h b/vehicle/universaldrag.h new file mode 100644 index 000000000..d25f93c57 --- /dev/null +++ b/vehicle/universaldrag.h @@ -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/. +*/ + +#pragma once + +#include +#include +#include +#include + +// smooth regulation of the universal cab controls (MaSzyna-EU07/maszyna#62): a universal whose definition in the +// .mmd has "drag: " can be dragged with the mouse to any position between its ends (0 and 1), and stays +// where it is let go, like a window opened a crack or a sun blind pulled half way down. a click without dragging and +// the keys still move it to its ends, as they do any universal. universals without the key work as they always did +namespace universal_drag { + +// the way the mouse moves to take the control towards its end 1 (to open it); none: the control can't be dragged +enum class direction { none, up, down, left, right }; + +// the direction the value of the drag: key gives, nothing for a value it doesn't know +inline std::optional parse(std::string_view const Value) { + if (Value == "yes" || Value == "true" || Value == "1" || Value == "up") { + return direction::up; + } + if (Value == "down") { + return direction::down; + } + if (Value == "left") { + return direction::left; + } + if (Value == "right") { + return direction::right; + } + if (Value == "no" || Value == "false" || Value == "0" || Value == "none") { + return direction::none; + } + return std::nullopt; +} + +// a push (impulse) universal springs back when it is let go, so it can't be left anywhere in between +inline direction effective(direction const Drag, bool const Push) { + return Push ? direction::none : Drag; +} + +// the position of the control, kept between its ends +inline float clamp(double const Position) { + return static_cast(std::clamp(Position, 0.0, 1.0)); +} + +// how far the cursor moving by Dx, Dy pixels (y grows downwards, as the cursor's does) takes the control along the +// Drag direction, as a fraction of its full travel; Size is the move in pixels which takes it from one end to the other +inline double along(direction const Drag, double const Dx, double const Dy, double const Size) { + if (Size <= 0.0) { + return 0.0; + } + switch (Drag) { + case direction::up: + return -Dy / Size; + case direction::down: + return Dy / Size; + case direction::left: + return -Dx / Size; + case direction::right: + return Dx / Size; + default: + return 0.0; + } +} + +// the position the keys and a click move the control to: the end farther from the position it is set to, as for +// the two-state universals: a control open less than half way opens fully, one open half way or more closes +inline float toggled(float const Desired) { + return Desired < 0.5f ? 1.f : 0.f; +} + +// the travel of the cursor along the direction of the drag, as a fraction of the full travel of the control, under +// which letting the button go counts as a click rather than a drag +inline constexpr double click_travel{0.02}; + +// one drag of a control, from the press of the mouse button to its release +class drag { + + public: + drag(direction const Drag, float const Position) : m_direction{Drag}, m_position{clamp(Position)}, m_start{m_position} {} + + // the cursor moved to X, Y; Size is the move in pixels which takes the control from one end to the other. + // the first position of the cursor is only where the drag starts from: when the cursor gets hidden for the drag + // it can be put elsewhere. returns whether the position of the control changed + bool move(double const X, double const Y, double const Size) { + if (false == m_started) { + m_started = true; + m_x = X; + m_y = Y; + return false; + } + auto const step{along(m_direction, X - m_x, Y - m_y, Size)}; + m_x = X; + m_y = Y; + m_travel += std::abs(step); + // the position follows each move from where it is, so after the control reached its end, moving the cursor + // back takes it back at once rather than after the overshoot is undone + auto const position{clamp(m_position + step)}; + if (position == m_position) { + return false; + } + m_position = position; + return true; + } + // the position the control is dragged to + float position() const { + return m_position; + } + // the position the control was in when the drag started + float start() const { + return m_start; + } + // whether letting the button go now is a click rather than a drag: the cursor barely moved along the direction + bool is_click() const { + return m_travel < click_travel; + } + + private: + direction m_direction; + float m_position; + float m_start; + bool m_started{false}; + double m_x{0.0}; + double m_y{0.0}; + double m_travel{0.0}; // the moves of the cursor along the direction, either way, as fractions of the full travel +}; + +} // namespace universal_drag From 795883335dc3c04e4c896a093613576c21b151c0 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 02:30:55 +0100 Subject: [PATCH 052/136] feat: orbit, shunting, coupling and trackside views of the train (eu07/maszyna#551) [Shift]+[F4] goes on after the four views it had (front of the train, its rear, a bogie, drive-by) to four views that go with one vehicle of the train: - orbit: around the middle of the vehicle. Left/right arrows (and the mouse) turn the camera around it, up/down arrows bring it closer and further (from outside the body to 250 m), PgUp/PgDn (and the mouse) raise and lower it; it never goes below 0.5 m above the rails. It turns with the vehicle. - shunting: straight down from above the vehicle, the way the user drives up the screen, going with it. Arrows move it along and across the train, PgUp/PgDn up and down (from above the roof to 300 m). - coupling: low beside a coupler, looking at it. At an end of the train with another vehicle (not coupled) closer than 150 m, it starts at that end and steps back from the track as the gap grows, looking between the two couplers. Left/right arrows pick the side of the track, up/down the distance, PgUp/PgDn the height. - trackside: a railfan beside the line ahead of the train, looking at the vehicle picked as the train comes and goes by. Once its tail is 40 m past (or the train is 1 km away) the railfan walks to a new spot ahead, 15 s of the train's run away (80-500 m, along the curve of the line), on the other side of the track. [ and ] pick the vehicle the view goes with (the coupling, in the coupling view), towards the front and the rear of the train; the view starts with the vehicle the user drives. [ and ] are bound to nothing by default nor in the shipped eu07_input-keyboard.ini; [Ctrl]+[ / ] stay the debug train moves. The camera follows from pure functions in vehicle/cameraviews.cpp (eu07_core), tested in tests/unit/test_camera_views.cpp; application/consistviews.cpp hands them the vehicles of the train and keeps what the user set. The four older views and their order don't change. "consistviews no" in eu07.ini keeps the cycle of [Shift]+[F4] to the four older views. The black box writes the new views as 4-7 (blackbox_doc.md). --- CMakeLists.txt | 2 + application/consistviews.cpp | 311 +++++++++++++++++++++++++ application/consistviews.h | 74 ++++++ application/drivermode.cpp | 44 +++- application/drivermode.h | 11 + blackbox_doc.md | 2 +- tests/unit/test_camera_views.cpp | 386 +++++++++++++++++++++++++++++++ utilities/Globals.cpp | 8 + utilities/Globals.h | 1 + vehicle/blackbox.h | 2 +- vehicle/cameraviews.cpp | 281 ++++++++++++++++++++++ vehicle/cameraviews.h | 182 +++++++++++++++ 12 files changed, 1300 insertions(+), 4 deletions(-) create mode 100644 application/consistviews.cpp create mode 100644 application/consistviews.h create mode 100644 tests/unit/test_camera_views.cpp create mode 100644 vehicle/cameraviews.cpp create mode 100644 vehicle/cameraviews.h diff --git a/CMakeLists.txt b/CMakeLists.txt index e97e41d03..1374a587e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -182,6 +182,7 @@ set(SOURCES "rendering/screenshot.cpp" "input/driverkeyboardinput.cpp" "application/drivermode.cpp" +"application/consistviews.cpp" "application/driveruilayer.cpp" "application/driveruipanels.cpp" "input/editorkeyboardinput.cpp" @@ -550,6 +551,7 @@ set(CORE_SOURCES "vehicle/brakesetting.cpp" "vehicle/handover.cpp" "vehicle/horn.cpp" +"vehicle/cameraviews.cpp" "vehicle/linebreaker.cpp" "vehicle/smoke.cpp" "vehicle/odometer.cpp" diff --git a/application/consistviews.cpp b/application/consistviews.cpp new file mode 100644 index 000000000..15762d437 --- /dev/null +++ b/application/consistviews.cpp @@ -0,0 +1,311 @@ +/* +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 "application/consistviews.h" + +#include +#include + +#include "vehicle/Camera.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" + +namespace { + +// more vehicles than any train has: a guard against a loop in the couplings +std::size_t constexpr train_limit{1000}; +// metres the vehicle picked moves before the trackside view takes the way it went for the way of the train +double constexpr direction_step{0.5}; + +cameraviews::vehicle_pose pose_of(TDynamicObject const *Vehicle) { + cameraviews::vehicle_pose pose; + pose.position = Vehicle->GetPosition(); + pose.front = Vehicle->VectorFront(); + pose.length = Vehicle->MoverParameters->Dim.L; + pose.width = Vehicle->MoverParameters->Dim.W; + pose.height = Vehicle->MoverParameters->Dim.H; + return pose; +} + +// the end of the Vehicle the Other vehicle is beyond, -1 when it's beyond neither +int end_towards(TDynamicObject const *Vehicle, TDynamicObject const *Other) { + for (auto const side : {end::front, end::rear}) { + if (Vehicle->MoverParameters->Neighbours[side].vehicle == Other) { + return side; + } + } + return -1; +} + +// the end of the Vehicle at an end of the train, away from the Inner vehicle next to it (nullptr when it's alone) +int outer_end(TDynamicObject const *Vehicle, TDynamicObject const *Inner, int const Alone) { + if (Inner == nullptr) { + return Alone; + } + auto const inner{end_towards(Vehicle, Inner)}; + return inner < 0 ? Alone : 1 - inner; +} + +cameraviews::coupler coupler_of(TDynamicObject const *Vehicle, int const End) { + cameraviews::coupler coupler; + coupler.position = Vehicle->CouplerPosition(static_cast(End)); + coupler.outward = Vehicle->VectorFront() * (End == end::front ? 1.0 : -1.0); + coupler.width = Vehicle->MoverParameters->Dim.W; + return coupler; +} + +// the driver's way: the front (1) or the rear (-1) of the Driven vehicle, as the user drives it +int driven_way(TDynamicObject const *Driven) { + auto const cab{Driven->MoverParameters->CabOccupied < 0 ? -1 : 1}; + auto const direction{Driven->MoverParameters->DirActive < 0 ? -1 : 1}; + return cab * direction; +} + +// the coupler of the Vehicle furthest along the Way (or furthest back, with a negative Way) +glm::dvec3 end_along(TDynamicObject const *Vehicle, glm::dvec3 const &Way) { + auto const front{Vehicle->CouplerPosition(end::front)}; + auto const rear{Vehicle->CouplerPosition(end::rear)}; + return glm::dot(front - rear, Way) >= 0.0 ? front : rear; +} + +// the front of the Vehicle, or its rear when that faces the Way +glm::dvec3 facing_along(TDynamicObject const *Vehicle, glm::dvec3 const &Way) { + auto const front{cameraviews::flat_front(Vehicle->VectorFront())}; + return glm::dot(front, Way) < 0.0 ? -front : front; +} + +bool usable(cameraviews::placement const &Place) { + auto const finite{[](glm::dvec3 const &Value) { return std::isfinite(Value.x) && std::isfinite(Value.y) && std::isfinite(Value.z); }}; + if (false == (finite(Place.eye) && finite(Place.target) && finite(Place.up))) { + return false; + } + auto const look{Place.target - Place.eye}; + if (glm::length(look) < 0.01 || glm::length(Place.up) < 0.5) { + return false; + } + // a camera looking along its own up has no way to tell left from right + return std::abs(glm::dot(glm::normalize(look), glm::normalize(Place.up))) < 0.999; +} + +} // namespace + +std::vector consist_views::train_of(TDynamicObject *Driven) { + std::vector train; + if (Driven == nullptr) { + return train; + } + auto const *controller{Driven->Mechanik != nullptr ? Driven->Mechanik : Driven->ctOwner}; + auto *first{controller != nullptr ? controller->Vehicle(end::front) : nullptr}; + if (first == nullptr) { + first = Driven; + } + for (auto *vehicle{first}; vehicle != nullptr && train.size() < train_limit; vehicle = vehicle->Next()) { + if (std::ranges::find(train, vehicle) != train.end()) { + break; + } + train.push_back(vehicle); + } + if (std::ranges::find(train, Driven) == train.end()) { + // the controller's list is behind the couplings: the driven vehicle alone, until it catches up + train.assign(1, Driven); + } + return train; +} + +TDynamicObject *consist_views::pick(std::vector const &Train, TDynamicObject *Driven) { + auto picked{std::ranges::find(Train, m_vehicle)}; + if (m_vehicle == nullptr || picked == Train.end()) { + picked = std::ranges::find(Train, Driven); + } + if (picked == Train.end()) { + picked = Train.begin(); + } + auto index{static_cast(picked - Train.begin())}; + if (m_view != kind::coupling) { + index = cameraviews::step_index(index, static_cast(Train.size()), m_step); + m_step = 0; + } + m_vehicle = Train[index]; + return m_vehicle; +} + +double consist_views::gap_beyond(TDynamicObject const *Vehicle, int const End) { + auto const &neighbour{Vehicle->MoverParameters->Neighbours[End]}; + if (neighbour.vehicle == nullptr || Vehicle->MoverParameters->Couplers[End].CouplingFlag != 0) { + return -1.0; + } + if (neighbour.distance > cameraviews::coupler_watch_range) { + return -1.0; + } + return std::max(0.0, static_cast(neighbour.distance)); +} + +consist_views::coupling_place consist_views::coupling_at(std::vector const &Train, int const Index) { + auto const count{static_cast(Train.size())}; + coupling_place place; + if (Index > 0 && Index < count) { + // between two vehicles of the train + auto *ahead{Train[Index - 1]}; + auto const *behind{Train[Index]}; + auto const aheadend{end_towards(ahead, behind)}; + auto const behindend{end_towards(behind, ahead)}; + place.vehicle = ahead; + place.coupler = coupler_of(ahead, aheadend < 0 ? end::rear : aheadend); + place.other = true; + place.otherposition = behind->CouplerPosition(static_cast(behindend < 0 ? end::front : behindend)); + return place; + } + // an end of the train, perhaps with another vehicle coming closer to it + auto const front{Index <= 0}; + auto *vehicle{front ? Train.front() : Train.back()}; + auto const *inner{count > 1 ? Train[front ? 1 : count - 2] : nullptr}; + auto const outer{outer_end(vehicle, inner, front ? end::front : end::rear)}; + place.vehicle = vehicle; + place.coupler = coupler_of(vehicle, outer); + auto const &neighbour{vehicle->MoverParameters->Neighbours[outer]}; + place.gap = gap_beyond(vehicle, outer); + if (place.gap >= 0.0 && (neighbour.vehicle_end == end::front || neighbour.vehicle_end == end::rear)) { + place.other = true; + place.otherposition = neighbour.vehicle->CouplerPosition(static_cast(neighbour.vehicle_end)); + } + return place; +} + +cameraviews::train_motion consist_views::motion_of(std::vector const &Train, TDynamicObject const *Driven) { + auto const position{m_vehicle->GetPosition()}; + if (false == m_moved) { + // standing, the train is to go the way the user drives + m_direction = cameraviews::flat_front(m_vehicle->VectorFront()) * + static_cast(cameraviews::driving_facing(m_vehicle->VectorFront(), Driven->VectorFront(), driven_way(Driven))); + m_lastposition = position; + m_moved = true; + } + else if (std::hypot(position.x - m_lastposition.x, position.z - m_lastposition.z) > direction_step) { + m_direction = cameraviews::flat_front(position - m_lastposition); + m_lastposition = position; + } + std::vector positions; + positions.reserve(Train.size()); + for (auto const *vehicle : Train) { + positions.emplace_back(vehicle->GetPosition()); + } + auto const [head, tail]{cameraviews::train_ends(positions, m_direction)}; + cameraviews::train_motion motion; + motion.direction = m_direction; + motion.head = end_along(Train[head], m_direction); + motion.tail = end_along(Train[tail], -m_direction); + motion.speed = std::abs(m_vehicle->GetVelocity()) / 3.6; + motion.width = m_vehicle->MoverParameters->Dim.W; + if (Train.size() > 1) { + auto const *behind{Train[head == 0 ? 1 : head - 1]}; + motion.curvature = cameraviews::line_curvature(Train[head]->GetPosition(), facing_along(Train[head], m_direction), behind->GetPosition(), facing_along(behind, m_direction)); + } + return motion; +} + +cameraviews::placement consist_views::place_orbit(TCamera &Camera, double const Seconds) { + auto const pose{pose_of(m_vehicle)}; + if (m_orbit.radius <= 0.0) { + m_orbit = cameraviews::orbit_start(pose); + } + // the mouse turns the camera around the vehicle rather than the view away from it + glm::dvec2 const turn{Camera.Angle.x, Camera.Angle.y}; + Camera.Angle = {}; + m_orbit = cameraviews::orbit_moved(m_orbit, Camera.Velocity, turn, Seconds, pose); + return cameraviews::orbit_placement(m_orbit, pose); +} + +cameraviews::placement consist_views::place_shunting(TCamera const &Camera, std::vector const &Train, TDynamicObject const *Driven, double const Seconds) { + auto const pose{pose_of(m_vehicle)}; + auto length{0.0}; + for (auto const *vehicle : Train) { + length += vehicle->MoverParameters->Dim.L; + } + m_topdown = cameraviews::topdown_moved(m_topdown, Camera.Velocity, Seconds, pose, 0.5 * length + 50.0); + auto const facing{cameraviews::driving_facing(m_vehicle->VectorFront(), Driven->VectorFront(), Driven->MoverParameters->CabOccupied)}; + return cameraviews::topdown_placement(m_topdown, pose, facing); +} + +cameraviews::placement consist_views::place_coupling(TCamera const &Camera, std::vector const &Train, double const Seconds) { + auto const count{static_cast(Train.size())}; + if (m_coupling < 0) { + auto const front{coupling_at(Train, 0)}; + auto const rear{coupling_at(Train, count)}; + m_coupling = cameraviews::first_coupling(front.gap, rear.gap, count); + } + m_coupling = cameraviews::step_index(std::min(m_coupling, count), count + 1, m_step); + m_step = 0; + auto const place{coupling_at(Train, m_coupling)}; + m_vehicle = place.vehicle; + m_coupler = cameraviews::coupler_moved(m_coupler, Camera.Velocity, Seconds); + return cameraviews::coupler_placement(m_coupler, place.coupler, place.other ? &place.otherposition : nullptr); +} + +cameraviews::placement consist_views::place_trackside(std::vector const &Train, TDynamicObject const *Driven) { + auto const motion{motion_of(Train, Driven)}; + if (cameraviews::trackside_expired(m_trackside, motion)) { + m_trackside = cameraviews::trackside_next(m_trackside, motion); + } + return cameraviews::trackside_placement(m_trackside, cameraviews::orbit_centre(pose_of(m_vehicle))); +} + +TDynamicObject *consist_views::enter(kind const View, TDynamicObject *Driven) { + m_view = View; + m_step = 0; + if (View == kind::coupling) { + // each time the view starts at the end of the train something comes closer to, or at its front + m_coupling = -1; + } + if (View == kind::trackside) { + // and the railfan finds a new spot ahead of the train + m_trackside.placed = false; + m_moved = false; + } + auto const train{train_of(Driven)}; + if (train.empty()) { + return nullptr; + } + return pick(train, Driven); +} + +void consist_views::select(int const Step) { + m_step += Step; +} + +TDynamicObject *consist_views::update(TCamera &Camera, TDynamicObject *Driven, double const Seconds) { + auto const train{train_of(Driven)}; + if (train.empty()) { + return nullptr; + } + pick(train, Driven); + cameraviews::placement place; + switch (m_view) { + case kind::orbit: + place = place_orbit(Camera, Seconds); + break; + case kind::shunting: + // straight down, the mouse would only tilt it off the train + Camera.Angle = {}; + place = place_shunting(Camera, train, Driven, Seconds); + break; + case kind::coupling: + place = place_coupling(Camera, train, Seconds); + break; + case kind::trackside: + place = place_trackside(train, Driven); + break; + } + if (usable(place)) { + Camera.Pos = place.eye; + Camera.LookAt = place.target; + Camera.vUp = place.up; + } + return m_vehicle; +} diff --git a/application/consistviews.h b/application/consistviews.h new file mode 100644 index 000000000..1c86345c0 --- /dev/null +++ b/application/consistviews.h @@ -0,0 +1,74 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include + +#include "vehicle/cameraviews.h" + +class TCamera; +class TDynamicObject; + +// The outside views of the user's train that go with one of its vehicles (eu07/maszyna#551), after the four views +// [Shift]+[F4] had before: the orbit around a vehicle, the shunting view from above, the view beside a coupling +// and the trackside view of a railfan. [ and ] pick the vehicle (the coupling) the view goes with. The camera +// follows from cameraviews.h; this class hands over the vehicles of the train and keeps what the user set. +class consist_views { + +public: + enum class kind { orbit, shunting, coupling, trackside }; + + // starts the View of the train of the Driven vehicle, with the vehicle (or the coupling) picked before when it's + // still in the train; returns the vehicle the camera goes with, nullptr when there's no train + TDynamicObject *enter(kind View, TDynamicObject *Driven); + // picks the vehicle Step places towards the rear of the train (towards its front for a negative Step); the + // coupling in the coupling view + void select(int Step); + // places the Camera for this frame of Seconds (real time): the movement keys come from its Velocity, the mouse of + // the orbit from its Angle. returns the vehicle the camera goes with, nullptr when the train is gone + TDynamicObject *update(TCamera &Camera, TDynamicObject *Driven, double Seconds); + +private: + struct coupling_place { + TDynamicObject *vehicle{nullptr}; // the vehicle the coupler is on + cameraviews::coupler coupler; + bool other{false}; + glm::dvec3 otherposition{}; // the facing coupler of the vehicle beyond, coupled or coming closer + double gap{-1.0}; // at an end of the train: the distance to a vehicle coming closer, negative for none + }; + + // the vehicles of the train of the Driven vehicle, from its front to its rear + static std::vector train_of(TDynamicObject *Driven); + // the vehicle the camera goes with in the Train: the one picked before, or the Driven one + TDynamicObject *pick(std::vector const &Train, TDynamicObject *Driven); + // the Index coupling of the Train, 0 its front end, Train.size() its rear end + static coupling_place coupling_at(std::vector const &Train, int Index); + // the distance to a vehicle not coupled beyond the End of the Vehicle, negative for none + static double gap_beyond(TDynamicObject const *Vehicle, int End); + // keeps up the way the train goes and works out where its ends are, for the trackside view + cameraviews::train_motion motion_of(std::vector const &Train, TDynamicObject const *Driven); + + cameraviews::placement place_orbit(TCamera &Camera, double Seconds); + cameraviews::placement place_shunting(TCamera const &Camera, std::vector const &Train, TDynamicObject const *Driven, double Seconds); + cameraviews::placement place_coupling(TCamera const &Camera, std::vector const &Train, double Seconds); + cameraviews::placement place_trackside(std::vector const &Train, TDynamicObject const *Driven); + + kind m_view{kind::orbit}; + TDynamicObject *m_vehicle{nullptr}; // the vehicle picked; only compared with the vehicles of the train, never followed + int m_step{0}; // vehicles to step over in the next update, from [ and ] + int m_coupling{-1}; // the coupling picked in the coupling view, -1 not yet + cameraviews::orbit m_orbit; + cameraviews::topdown m_topdown; + cameraviews::coupler_view m_coupler; + cameraviews::trackside m_trackside; + glm::dvec3 m_lastposition{}; // of the vehicle picked, where the trackside view last saw it move + glm::dvec3 m_direction{0.0, 0.0, -1.0}; // the way the train goes, for the trackside view + bool m_moved{false}; // m_lastposition is known +}; diff --git a/application/drivermode.cpp b/application/drivermode.cpp index cde7e80d7..47ab3ae0c 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -739,7 +739,12 @@ void driver_mode::update_camera(double const Deltatime) // reset window state, it'll be set again if applicable in a check below Global.CabWindowOpen = false; - if (simulation::Train != nullptr && controlled != nullptr && Camera.m_owner != nullptr && false == DebugCameraFlag) + if (consist_view_active()) + { + // the orbit, shunting, coupling and trackside views place the camera themselves + update_consist_view(Deltatime); + } + else if (simulation::Train != nullptr && controlled != nullptr && Camera.m_owner != nullptr && false == DebugCameraFlag) { // jeśli jazda w kabinie, przeliczyć trzeba parametry kamery /* @@ -1102,6 +1107,17 @@ void driver_mode::OnKeyDown(int cKey) } break; } + case GLFW_KEY_LEFT_BRACKET: + case GLFW_KEY_RIGHT_BRACKET: + { + // in the orbit, shunting, coupling and trackside views: the vehicle (coupling) towards the front, or the rear, + // of the train. [Ctrl] with them moves the train in the debug mode, bound in the keyboard settings + if (false == Global.ctrlState && consist_view_active()) + { + m_consistviews.select(cKey == GLFW_KEY_LEFT_BRACKET ? -1 : 1); + } + break; + } default: { break; @@ -1111,6 +1127,18 @@ void driver_mode::OnKeyDown(int cKey) return; // nie są przekazywane do pojazdu wcale } +bool driver_mode::consist_view_active() const +{ + return FreeFlyModeFlag && m_externalview && m_externalviewmode >= view::orbit && Camera.m_owner != nullptr && false == DebugCameraFlag; +} + +void driver_mode::update_consist_view(double const Deltatime) +{ + auto *controlled{simulation::Train != nullptr ? simulation::Train->Dynamic() : nullptr}; + // the camera goes with the vehicle picked, or stays where it is once the train is gone + Camera.m_owner = m_consistviews.update(Camera, controlled, Deltatime); +} + // places camera outside the controlled vehicle, or nearest if nothing is under control // depending on provided switch the view is placed right outside, or at medium distance void driver_mode::DistantView(bool const Near) @@ -1159,7 +1187,8 @@ void driver_mode::ExternalView() if (true == m_externalview) { // we're already in some external view mode, so select next one on the list - m_externalviewmode = clamp_circular(++m_externalviewmode, static_cast(view::count_)); + // the views of the train's vehicles come after the four older ones, unless they're turned off in eu07.ini + m_externalviewmode = clamp_circular(++m_externalviewmode, static_cast(Global.ConsistViews ? view::count_ : view::orbit)); } FreeFlyModeFlag = true; @@ -1262,6 +1291,17 @@ void driver_mode::ExternalView() DistantView(false); break; } + case view::orbit: + case view::shunting: + case view::coupling: + case view::trackside: + { + // the camera goes with a vehicle of the train, placed by update_consist_view() from the next frame on + auto const kind{static_cast(m_externalviewmode - view::orbit)}; + Camera.m_owner = m_consistviews.enter(kind, vehicle); + Camera.m_owneroffset = {}; + break; + } default: { break; diff --git a/application/drivermode.h b/application/drivermode.h index e0406043d..7e86e99f6 100644 --- a/application/drivermode.h +++ b/application/drivermode.h @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "input/gamepadinput.h" #include "Console.h" #include "vehicle/Camera.h" +#include "application/consistviews.h" #include "utilities/Classes.h" #ifdef WITH_UART #include "utilities/uart.h" @@ -55,6 +56,11 @@ private: consistrear, bogie, driveby, + // the views of consist_views (eu07/maszyna#551), left out of the cycle with consistviews off in eu07.ini + orbit, + shunting, + coupling, + trackside, count_ }; @@ -97,6 +103,10 @@ private: void CabView(); void ExternalView(); void DistantView( bool const Near = false ); + // whether the camera shows one of the views of consist_views now + bool consist_view_active() const; + // places the camera of the view of consist_views for the frame + void update_consist_view( double const Deltatime ); void set_picking( bool const Picking ); // members @@ -107,6 +117,7 @@ private: int m_externalviewmode { view::consistfront }; // selected external view mode bool m_externalview { true }; std::array m_externalviewconfigs; + consist_views m_consistviews; // the orbit, shunting, coupling and trackside views TDynamicObject *pDynamicNearest { nullptr }; // vehicle nearest to the active camera. TODO: move to camera double fTime50Hz { 0.0 }; // bufor czasu dla komunikacji z PoKeys double const m_primaryupdaterate { 1.0 / 100.0 }; diff --git a/blackbox_doc.md b/blackbox_doc.md index c58cae100..ab330dc2e 100644 --- a/blackbox_doc.md +++ b/blackbox_doc.md @@ -388,7 +388,7 @@ moved more than 0.5 m or turned more than 0.05 rad. |---------|------------------------------------------------------------------------------| | `f64` | t | | `u8` | mode: 0 from the cab, 1 an outside view of the user's train, 2 the free camera, 3 the debug camera | -| `u8` | the outside view: 0 the front of the train, 1 its rear, 2 a bogie, 3 drive-by; 0 in the other modes | +| `u8` | the outside view: 0 the front of the train, 1 its rear, 2 a bogie, 3 drive-by, 4 the orbit around a vehicle, 5 the shunting view from above, 6 beside a coupling, 7 trackside; 0 in the other modes | | `u32` | number of the vehicle the camera goes with, 0 for none | | `dvec3` | position | | `f32` | heading [rad] of where it looks, as that of a vehicle: towards (sin, cos) in (x, z) | diff --git a/tests/unit/test_camera_views.cpp b/tests/unit/test_camera_views.cpp new file mode 100644 index 000000000..2529efbb9 --- /dev/null +++ b/tests/unit/test_camera_views.cpp @@ -0,0 +1,386 @@ +#include "stdafx.h" +#include "doctest.h" + +#include +#include + +#include "vehicle/cameraviews.h" + +// the outside views of the train that go with one of its vehicles (eu07/maszyna#551): orbit, shunting from above, +// beside a coupling, trackside. The camera follows from the place of the vehicle and the keys alone. + +namespace { + +using cameraviews::move_keys; + +// a 20 m coach standing at Position, facing Front +cameraviews::vehicle_pose coach(glm::dvec3 const &Position = {100.0, 50.0, 200.0}, glm::dvec3 const &Front = {0.0, 0.0, -1.0}) { + cameraviews::vehicle_pose pose; + pose.position = Position; + pose.front = Front; + pose.length = 20.0; + pose.width = 3.0; + pose.height = 4.0; + return pose; +} + +double flat_distance(glm::dvec3 const &A, glm::dvec3 const &B) { + return std::hypot(A.x - B.x, A.z - B.z); +} + +// a key held, as TCamera::Velocity has it outside the cab +double constexpr key{1.0}; + +} // namespace + +TEST_CASE("camera views: the orbit starts outside the vehicle, ahead of it on its left, above the rails") { + auto const pose{coach()}; + auto const orbit{cameraviews::orbit_start(pose)}; + auto const place{cameraviews::orbit_placement(orbit, pose)}; + auto const centre{cameraviews::orbit_centre(pose)}; + + CHECK(place.target == centre); + CHECK(glm::distance(place.eye, centre) == doctest::Approx(orbit.radius)); + CHECK(orbit.radius >= cameraviews::orbit_min_radius(pose)); + auto const offset{place.eye - centre}; + CHECK(glm::dot(offset, pose.front) > 0.0); // ahead + CHECK(glm::dot(offset, glm::dvec3{-1.0, 0.0, 0.0}) > 0.0); // on the left of a vehicle facing -z + CHECK(place.eye.y > pose.position.y + pose.height); +} + +TEST_CASE("camera views: the orbit radius stays between the body of the vehicle and its limit") { + auto const pose{coach()}; + auto orbit{cameraviews::orbit_start(pose)}; + // the up arrow held for a minute brings the camera as close as the body lets it + for (int frame = 0; frame < 600; ++frame) { + orbit = cameraviews::orbit_moved(orbit, move_keys{0.0, 0.0, -key}, {}, 0.1, pose); + } + CHECK(orbit.radius == doctest::Approx(cameraviews::orbit_min_radius(pose))); + // the diagonal of the body, so it's outside at any angle + CHECK(orbit.radius > 0.5 * std::hypot(pose.length, pose.width)); + + for (int frame = 0; frame < 600; ++frame) { + orbit = cameraviews::orbit_moved(orbit, move_keys{0.0, 0.0, key}, {}, 0.1, pose); + } + CHECK(orbit.radius == doctest::Approx(cameraviews::orbit_max_radius)); + + // a radius not set yet becomes the default one of the vehicle + cameraviews::orbit unset; + CHECK(cameraviews::orbit_clamped(unset, pose).radius == doctest::Approx(cameraviews::orbit_start(pose).radius)); +} + +TEST_CASE("camera views: the orbit keeps above the rails however low it goes") { + auto const pose{coach()}; + for (auto const radius : {12.0, 25.0, 100.0, 250.0}) { + CAPTURE(radius); + auto orbit{cameraviews::orbit_start(pose)}; + orbit.radius = radius; + for (int frame = 0; frame < 300; ++frame) { + orbit = cameraviews::orbit_moved(orbit, move_keys{0.0, -key, 0.0}, {}, 0.1, pose); + } + auto const place{cameraviews::orbit_placement(orbit, pose)}; + CHECK(place.eye.y >= pose.position.y + cameraviews::rail_clearance - 1e-9); + CHECK(orbit.elevation >= cameraviews::orbit_min_elevation - 1e-9); + } + // up to its highest it doesn't go over the top + auto orbit{cameraviews::orbit_start(pose)}; + for (int frame = 0; frame < 300; ++frame) { + orbit = cameraviews::orbit_moved(orbit, move_keys{0.0, key, 0.0}, {}, 0.1, pose); + } + CHECK(orbit.elevation == doctest::Approx(cameraviews::orbit_max_elevation)); + // the mouse moved up a lot at once is held the same way + orbit = cameraviews::orbit_moved(orbit, {}, {10.0, 0.0}, 0.0, pose); + CHECK(orbit.elevation == doctest::Approx(cameraviews::orbit_lowest_elevation(pose, orbit.radius))); +} + +TEST_CASE("camera views: the left key takes the orbit clockwise around the vehicle, as a step to the left") { + auto const pose{coach()}; + cameraviews::orbit orbit; + orbit.radius = 30.0; + orbit = cameraviews::orbit_clamped(orbit, pose); + auto const ahead{cameraviews::orbit_placement(orbit, pose)}; + CHECK(glm::dot(ahead.eye - ahead.target, pose.front) > 0.0); + + // a little to the left from in front of the vehicle: the camera comes round to its right side + auto const moved{cameraviews::orbit_moved(orbit, move_keys{-key, 0.0, 0.0}, {}, 0.5, pose)}; + CHECK(moved.azimuth < orbit.azimuth); + auto const place{cameraviews::orbit_placement(moved, pose)}; + CHECK((place.eye - place.target).x > 0.0); // the right of a vehicle facing -z is +x + + // so does the mouse moved to the right (TCamera::Angle.y goes down) + CHECK(cameraviews::orbit_moved(orbit, {}, {0.0, -0.2}, 0.0, pose).azimuth == doctest::Approx(orbit.azimuth - 0.2)); + + // all the way round, the azimuth stays within half a turn either way + auto round{orbit}; + for (int frame = 0; frame < 200; ++frame) { + round = cameraviews::orbit_moved(round, move_keys{key, 0.0, 0.0}, {}, 0.1, pose); + REQUIRE(std::abs(round.azimuth) <= std::numbers::pi + 1e-9); + } +} + +TEST_CASE("camera views: the orbit turns with the vehicle and moves with it") { + auto const north{coach({0.0, 10.0, 0.0}, {0.0, 0.0, -1.0})}; + // the same vehicle further on, turned to face east (+x) on a slope + auto const east{coach({500.0, 20.0, -300.0}, glm::normalize(glm::dvec3{1.0, 0.05, 0.0}))}; + auto const orbit{cameraviews::orbit_start(north)}; + + auto const before{cameraviews::orbit_placement(orbit, north)}; + auto const after{cameraviews::orbit_placement(orbit, east)}; + auto const a{before.eye - before.target}; + auto const b{after.eye - after.target}; + CHECK(b.y == doctest::Approx(a.y)); + // a quarter turn clockwise from above: -z becomes +x, so the offset (x, z) becomes (-z, x) + CHECK(b.x == doctest::Approx(-a.z)); + CHECK(b.z == doctest::Approx(a.x)); + CHECK(after.target == cameraviews::orbit_centre(east)); +} + +TEST_CASE("camera views: a longer vehicle picked keeps the orbit outside its body") { + auto const shortvehicle{coach()}; + auto longvehicle{coach()}; + longvehicle.length = 40.0; + cameraviews::orbit orbit; + orbit.radius = cameraviews::orbit_min_radius(shortvehicle); + orbit = cameraviews::orbit_clamped(orbit, longvehicle); + CHECK(orbit.radius == doctest::Approx(cameraviews::orbit_min_radius(longvehicle))); + CHECK(orbit.radius > 20.0); +} + +TEST_CASE("camera views: the shunting view looks straight down, the way the user drives up the screen") { + auto const pose{coach()}; + cameraviews::topdown view; + view = cameraviews::topdown_clamped(view, pose, 100.0); + CHECK(view.height >= cameraviews::topdown_min_height(pose)); + + auto const place{cameraviews::topdown_placement(view, pose, 1)}; + CHECK(place.eye.x == doctest::Approx(pose.position.x)); + CHECK(place.eye.z == doctest::Approx(pose.position.z)); + CHECK(place.eye.y == doctest::Approx(pose.position.y + view.height)); + CHECK(place.target.x == doctest::Approx(place.eye.x)); + CHECK(place.target.z == doctest::Approx(place.eye.z)); + CHECK(place.up.z == doctest::Approx(-1.0)); // the front of the vehicle up the screen + + // driven from the rear cab, its rear is up the screen + CHECK(cameraviews::topdown_placement(view, pose, -1).up.z == doctest::Approx(1.0)); + + // the vehicle turned to face east: the screen turns with it + auto const east{coach({0.0, 0.0, 0.0}, {1.0, 0.0, 0.0})}; + CHECK(cameraviews::topdown_placement(view, east, 1).up.x == doctest::Approx(1.0)); +} + +TEST_CASE("camera views: the shunting view moves along and across the train and up, within its limits") { + auto const pose{coach()}; + auto const along{60.0}; + auto view{cameraviews::topdown_clamped({}, pose, along)}; + auto const height{view.height}; + + // the up arrow moves it up the screen, the way the user drives + auto const forward{cameraviews::topdown_moved(view, move_keys{0.0, 0.0, -key}, 1.0, pose, along)}; + CHECK(forward.along > 0.0); + auto const place{cameraviews::topdown_placement(forward, pose, -1)}; + CHECK(place.eye.z > pose.position.z); // driven from the rear cab, up the screen is +z + // the right arrow to the right of the screen + auto const right{cameraviews::topdown_moved(view, move_keys{key, 0.0, 0.0}, 1.0, pose, along)}; + CHECK(cameraviews::topdown_placement(right, pose, 1).eye.x > pose.position.x); + CHECK(cameraviews::topdown_placement(right, pose, -1).eye.x < pose.position.x); + + for (int frame = 0; frame < 600; ++frame) { + view = cameraviews::topdown_moved(view, move_keys{key, -key, -key}, 0.1, pose, along); + } + CHECK(view.along == doctest::Approx(along)); + CHECK(view.across == doctest::Approx(cameraviews::topdown_max_across)); + CHECK(view.height == doctest::Approx(cameraviews::topdown_min_height(pose))); + CHECK(view.height < height); + for (int frame = 0; frame < 600; ++frame) { + view = cameraviews::topdown_moved(view, move_keys{0.0, key, 0.0}, 0.1, pose, along); + } + CHECK(view.height == doctest::Approx(cameraviews::topdown_max_height)); +} + +TEST_CASE("camera views: the way the user drives, seen from another vehicle of the train") { + glm::dvec3 const north{0.0, 0.0, -1.0}; + glm::dvec3 const south{0.0, 0.0, 1.0}; + CHECK(cameraviews::driving_facing(north, north, 1) == 1); + CHECK(cameraviews::driving_facing(north, north, -1) == -1); + CHECK(cameraviews::driving_facing(north, north, 0) == 1); // no cab occupied counts as the front one + // a vehicle turned round in the train + CHECK(cameraviews::driving_facing(south, north, 1) == -1); + CHECK(cameraviews::driving_facing(south, north, -1) == 1); +} + +TEST_CASE("camera views: [ and ] step through the vehicles of the train and stop at its ends") { + CHECK(cameraviews::step_index(2, 5, 1) == 3); + CHECK(cameraviews::step_index(2, 5, -1) == 1); + CHECK(cameraviews::step_index(0, 5, -1) == 0); + CHECK(cameraviews::step_index(4, 5, 1) == 4); + CHECK(cameraviews::step_index(1, 5, 10) == 4); + CHECK(cameraviews::step_index(3, 1, 1) == 0); // a vehicle alone + CHECK(cameraviews::step_index(3, 0, 1) == 0); // no train + // a picked vehicle beyond the end of a train which got shorter + CHECK(cameraviews::step_index(7, 3, 0) == 2); +} + +TEST_CASE("camera views: the head and the tail of a train are its ends the way it goes") { + std::vector const positions{{0.0, 0.0, 0.0}, {0.0, 0.0, 20.0}, {0.0, 0.0, 40.0}}; + CHECK(cameraviews::train_ends(positions, {0.0, 0.0, -1.0}) == std::pair{0, 2}); + CHECK(cameraviews::train_ends(positions, {0.0, 0.0, 1.0}) == std::pair{2, 0}); + CHECK(cameraviews::train_ends({}, {0.0, 0.0, 1.0}) == std::pair{-1, -1}); +} + +TEST_CASE("camera views: the coupling view starts where another vehicle comes closer") { + auto const count{5}; + CHECK(cameraviews::first_coupling(-1.0, -1.0, count) == 0); + CHECK(cameraviews::first_coupling(30.0, -1.0, count) == 0); + CHECK(cameraviews::first_coupling(-1.0, 30.0, count) == count); + CHECK(cameraviews::first_coupling(50.0, 10.0, count) == count); + CHECK(cameraviews::first_coupling(10.0, 50.0, count) == 0); + // a vehicle too far away doesn't count + CHECK(cameraviews::first_coupling(-1.0, cameraviews::coupler_watch_range + 1.0, count) == 0); +} + +TEST_CASE("camera views: the coupling view stands beside the coupler and steps back for the vehicle coming closer") { + cameraviews::coupler coupler; + coupler.position = {0.0, 10.0, -10.0}; + coupler.outward = {0.0, 0.0, -1.0}; + coupler.width = 3.0; + cameraviews::coupler_view const view; + + auto const alone{cameraviews::coupler_placement(view, coupler, nullptr)}; + CHECK(alone.eye.x == doctest::Approx(-(1.5 + view.distance))); // on the left of the outward way, -x + CHECK(alone.eye.z > coupler.position.z); // a little back towards its vehicle + CHECK(alone.eye.y == doctest::Approx(coupler.position.y + cameraviews::buffer_height + view.height)); + CHECK(alone.target.z < coupler.position.z); // looking out past the coupler + + // a vehicle 30 m away: the camera steps back from the track and looks between the two couplers + glm::dvec3 const other{0.0, 10.0, -40.0}; + auto const coming{cameraviews::coupler_placement(view, coupler, &other)}; + CHECK(coming.eye.x < alone.eye.x); + CHECK(coming.target.z == doctest::Approx(-25.0)); + CHECK(coming.target.y == doctest::Approx(10.0 + cameraviews::buffer_height)); + // closer, the camera comes back to the track with it + glm::dvec3 const closer{0.0, 10.0, -12.0}; + CHECK(cameraviews::coupler_placement(view, coupler, &closer).eye.x == doctest::Approx(alone.eye.x)); + // far away, it stops stepping back + glm::dvec3 const distant{0.0, 10.0, -500.0}; + CHECK(cameraviews::coupler_placement(view, coupler, &distant).eye.x == doctest::Approx(-(1.5 + cameraviews::coupler_max_distance))); +} + +TEST_CASE("camera views: the keys of the coupling view") { + cameraviews::coupler_view view; + view = cameraviews::coupler_moved(view, move_keys{key, 0.0, 0.0}, 0.1); + CHECK(view.side == -1.0); + view = cameraviews::coupler_moved(view, {}, 0.1); + CHECK(view.side == -1.0); // stays on its side without the key + view = cameraviews::coupler_moved(view, move_keys{-key, 0.0, 0.0}, 0.1); + CHECK(view.side == 1.0); + for (int frame = 0; frame < 600; ++frame) { + view = cameraviews::coupler_moved(view, move_keys{0.0, key, key}, 0.1); + } + CHECK(view.distance == doctest::Approx(cameraviews::coupler_max_distance)); + CHECK(view.height == doctest::Approx(cameraviews::coupler_max_height)); + for (int frame = 0; frame < 600; ++frame) { + view = cameraviews::coupler_moved(view, move_keys{0.0, -key, -key}, 0.1); + } + CHECK(view.distance == doctest::Approx(cameraviews::coupler_min_distance)); + CHECK(view.height == doctest::Approx(cameraviews::coupler_min_height)); + // the lowest still above the rails + CHECK(cameraviews::buffer_height + cameraviews::coupler_min_height > 0.0); +} + +TEST_CASE("camera views: along an arc of the line, and its curvature from two vehicles") { + glm::dvec3 const start{0.0, 5.0, 0.0}; + glm::dvec3 const north{0.0, 0.0, -1.0}; + auto const [straight, straightway]{cameraviews::along_arc(start, north, 0.0, 100.0)}; + CHECK(straight.z == doctest::Approx(-100.0)); + CHECK(straight.y == doctest::Approx(5.0)); + CHECK(straightway.z == doctest::Approx(-1.0)); + + // a quarter of a circle of 500 m to the left: from going north to going west + auto const radius{500.0}; + auto const [point, way]{cameraviews::along_arc(start, north, 1.0 / radius, 0.5 * std::numbers::pi * radius)}; + CHECK(point.x == doctest::Approx(-radius)); + CHECK(point.z == doctest::Approx(-radius)); + CHECK(way.x == doctest::Approx(-1.0)); + CHECK(way.z == doctest::Approx(0.0).epsilon(1e-9)); + + // two vehicles 25 m apart on that circle, the one ahead turned to the left of the one behind + auto const angle{25.0 / radius}; + glm::dvec3 const centre{-radius, 0.0, 0.0}; + glm::dvec3 const behind{0.0, 0.0, 0.0}; + glm::dvec3 const ahead{centre + glm::dvec3{radius * std::cos(angle), 0.0, -radius * std::sin(angle)}}; + glm::dvec3 const aheadway{-std::sin(angle), 0.0, -std::cos(angle)}; + auto const curvature{cameraviews::line_curvature(ahead, aheadway, behind, north)}; + CHECK(curvature == doctest::Approx(1.0 / radius).epsilon(0.01)); + // the other way round it turns to the right + CHECK(cameraviews::line_curvature(ahead, glm::dvec3{-aheadway.x, 0.0, aheadway.z}, behind, north) < 0.0); + // too close to tell + CHECK(cameraviews::line_curvature(behind, aheadway, behind, north) == 0.0); +} + +TEST_CASE("camera views: the railfan waits for the train ahead of it and moves on once it's gone by") { + cameraviews::train_motion train; + train.direction = {0.0, 0.0, -1.0}; + train.head = {0.0, 0.0, 0.0}; + train.tail = {0.0, 0.0, 100.0}; + train.speed = 20.0; // 72 km/h + train.width = 3.0; + + cameraviews::trackside view; + REQUIRE(cameraviews::trackside_expired(view, train)); + view = cameraviews::trackside_next(view, train); + REQUIRE(view.placed); + // ahead of the head by the 15 s it needs to get there, beside the line on the right, at the eye of a man + CHECK(view.spot.z == doctest::Approx(-20.0 * cameraviews::trackside_lead_time)); + CHECK(view.spot.x == doctest::Approx(1.5 + cameraviews::trackside_distance)); + CHECK(view.spot.y == doctest::Approx(cameraviews::trackside_eye_height)); + + // the train comes and goes by: the railfan stays until its tail is well past + auto const spot{view.spot}; + for (int step = 0; step < 50; ++step) { + auto const run{10.0 * step}; + auto passing{train}; + passing.head.z -= run; + passing.tail.z -= run; + auto const tailpast{spot.z - passing.tail.z}; + CAPTURE(run); + CHECK(cameraviews::trackside_expired(view, passing) == (tailpast > cameraviews::trackside_passed)); + } + // and then walks to the other side of the line, ahead again + auto gone{train}; + gone.head.z -= 500.0; + gone.tail.z -= 500.0; + auto const next{cameraviews::trackside_next(view, gone)}; + CHECK(next.side == -view.side); + CHECK(next.spot.x == doctest::Approx(-(1.5 + cameraviews::trackside_distance))); + CHECK(next.spot.z < gone.head.z); + CHECK(false == cameraviews::trackside_expired(next, gone)); +} + +TEST_CASE("camera views: the railfan's spot ahead keeps to the line in a curve, and nearby when the train stands") { + cameraviews::train_motion train; + train.direction = {0.0, 0.0, -1.0}; + train.speed = 40.0; + auto const radius{400.0}; + train.curvature = 1.0 / radius; + cameraviews::trackside const view; + auto const next{cameraviews::trackside_next(view, train)}; + // the centre of the curve is on the left of the head, the railfan on the right of the line: outside the circle + glm::dvec3 const centre{-radius, 0.0, 0.0}; + CHECK(flat_distance(next.spot, centre) == doctest::Approx(radius + 0.5 * train.width + cameraviews::trackside_distance)); + // no further round than a quarter of the circle + CHECK(next.spot.z >= -radius - 1e-6); + + // a train standing still gets a railfan at the shortest lead + auto standing{train}; + standing.speed = 0.0; + standing.curvature = 0.0; + auto const nearby{cameraviews::trackside_next(view, standing)}; + CHECK(nearby.spot.z == doctest::Approx(-cameraviews::trackside_min_lead)); + // and as long as it stands, the railfan stays + CHECK(false == cameraviews::trackside_expired(nearby, standing)); + // a train gone far away (moved by the user, or a long way back) gets a new railfan + auto away{standing}; + away.head = {0.0, 0.0, 2000.0}; + away.tail = {0.0, 0.0, 2100.0}; + CHECK(cameraviews::trackside_expired(nearby, away)); +} diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index a2cb6f59d..c5b62edfa 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -443,6 +443,13 @@ bool global_settings::ConfigParseInput(cParser& Parser, const std::string& token return true; } + if (token == "consistviews") + { + // no: [Shift]+[F4] cycles through the four views of the train it had before the views of its vehicles + ParseOne(Parser, ConsistViews); + return true; + } + if (token == "input.gamepad") { ParseOne(Parser, InputGamepad); @@ -1746,6 +1753,7 @@ global_settings::export_as_text( std::ostream &Output ) const { << fMouseXScale << " " << fMouseYScale << "\n"; export_as_text( Output, "mousecontrol", InputMouse ); + export_as_text( Output, "consistviews", ConsistViews ); export_as_text( Output, "enabletraction", bEnableTraction ); export_as_text( Output, "loadtraction", bLoadTraction ); export_as_text( Output, "friction", fFriction ); diff --git a/utilities/Globals.h b/utilities/Globals.h index 8d32a463c..83d6d87c1 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -232,6 +232,7 @@ struct global_settings { int iFeedbackPort{ 0 }; // dodatkowy adres dla informacji zwrotnych bool InputGamepad{ true }; // whether gamepad support is enabled bool InputMouse{ true }; // whether control pick mode can be activated + bool ConsistViews{ true }; // whether [Shift]+[F4] goes on to the orbit, shunting, coupling and trackside views of the train (eu07/maszyna#551) double fBrakeStep { 1.0 }; // krok zmiany hamulca innych niż FV4a dla klawiszy [Num3] i [Num9] double brake_speed { 3.0 }; // prędkość przesuwu hamulca dla FV4a // parametry kalibracyjne wejść z pulpitu diff --git a/vehicle/blackbox.h b/vehicle/blackbox.h index 473cf677c..58735ff60 100644 --- a/vehicle/blackbox.h +++ b/vehicle/blackbox.h @@ -301,7 +301,7 @@ struct station_event { struct camera_state { double time{0.0}; std::uint8_t mode{camera_modes::free}; - std::uint8_t view{0}; // of an outside view: 0 the front of the train, 1 its rear, 2 a bogie, 3 drive-by + std::uint8_t view{0}; // of an outside view: 0 the front of the train, 1 its rear, 2 a bogie, 3 drive-by, 4 orbit, 5 shunting, 6 coupling, 7 trackside std::uint32_t vehicle{no_vehicle}; // the vehicle the camera goes with, no_vehicle for none glm::dvec3 position{0.0}; float heading{0.0f}; // [rad] of where it looks, from +z towards +x, as the heading of a vehicle diff --git a/vehicle/cameraviews.cpp b/vehicle/cameraviews.cpp new file mode 100644 index 000000000..ef0975088 --- /dev/null +++ b/vehicle/cameraviews.cpp @@ -0,0 +1,281 @@ +/* +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/cameraviews.h" + +#include +#include +#include + +namespace cameraviews { + +namespace { + +glm::dvec3 const world_up{0.0, 1.0, 0.0}; + +// radians per second of the left and right keys, and of the page keys, for a key held +double constexpr orbit_turn_rate{1.2}; +double constexpr orbit_climb_rate{0.8}; +// the radius grows (or shrinks) e times in a second of a key held +double constexpr orbit_zoom_rate{1.0}; +// the height of the shunting view grows (or shrinks) e times in a second of a key held +double constexpr topdown_zoom_rate{0.8}; +// metres per second of the shunting view moved along and across, for each metre of its height +double constexpr topdown_pan_rate{0.6}; +// metres per second of the coupling view moved closer, further, up and down +double constexpr coupler_move_rate{3.0}; +// metres the coupling view stands back from the coupler, towards its vehicle +double constexpr coupler_step_back{2.0}; +// the share of the gap to the vehicle coming closer the coupling view keeps from the side of the train +double constexpr coupler_gap_share{0.7}; + +double flat_distance(glm::dvec3 const &A, glm::dvec3 const &B) { + return std::hypot(A.x - B.x, A.z - B.z); +} + +} // namespace + +glm::dvec3 flat_front(glm::dvec3 const &Front) { + glm::dvec3 const flat{Front.x, 0.0, Front.z}; + auto const length{glm::length(flat)}; + if (length < 1e-6) { + return {0.0, 0.0, -1.0}; + } + return flat / length; +} + +glm::dvec3 flat_left(glm::dvec3 const &Flatfront) { + return glm::cross(world_up, Flatfront); +} + +int step_index(int const Index, int const Count, int const Step) { + if (Count <= 0) { + return 0; + } + return std::clamp(Index + Step, 0, Count - 1); +} + +std::pair train_ends(std::vector const &Positions, glm::dvec3 const &Direction) { + if (Positions.empty()) { + return {-1, -1}; + } + auto const way{flat_front(Direction)}; + auto const along{[&way](glm::dvec3 const &Position) { return glm::dot(Position, way); }}; + auto const [tail, head]{std::ranges::minmax_element(Positions, {}, along)}; + return {static_cast(head - Positions.begin()), static_cast(tail - Positions.begin())}; +} + +int driving_facing(glm::dvec3 const &Front, glm::dvec3 const &Drivenfront, int const Cab) { + auto const cab{Cab < 0 ? -1 : 1}; + auto const aligned{glm::dot(flat_front(Front), flat_front(Drivenfront)) < 0.0 ? -1 : 1}; + return cab * aligned; +} + +// orbit + +glm::dvec3 orbit_centre(vehicle_pose const &Vehicle) { + return Vehicle.position + world_up * (0.4 * Vehicle.height); +} + +double orbit_min_radius(vehicle_pose const &Vehicle) { + return 0.5 * std::hypot(Vehicle.length, Vehicle.width) + 1.0; +} + +orbit orbit_start(vehicle_pose const &Vehicle) { + orbit start; + start.azimuth = 0.6; + start.elevation = 0.25; + start.radius = std::max(orbit_min_radius(Vehicle), Vehicle.length + 5.0); + return orbit_clamped(start, Vehicle); +} + +double orbit_lowest_elevation(vehicle_pose const &Vehicle, double const Radius) { + auto const centre{0.4 * Vehicle.height}; + auto const sine{std::clamp((rail_clearance - centre) / std::max(Radius, 1e-3), -1.0, 1.0)}; + return std::max(orbit_min_elevation, std::asin(sine)); +} + +orbit orbit_clamped(orbit Orbit, vehicle_pose const &Vehicle) { + if (Orbit.radius <= 0.0) { + Orbit.radius = orbit_start(Vehicle).radius; + } + Orbit.radius = std::clamp(Orbit.radius, orbit_min_radius(Vehicle), std::max(orbit_min_radius(Vehicle), orbit_max_radius)); + Orbit.elevation = std::clamp(Orbit.elevation, orbit_lowest_elevation(Vehicle, Orbit.radius), orbit_max_elevation); + Orbit.azimuth = std::remainder(Orbit.azimuth, 2.0 * std::numbers::pi); + return Orbit; +} + +orbit orbit_moved(orbit Orbit, move_keys const &Keys, glm::dvec2 const &Turn, double const Seconds, vehicle_pose const &Vehicle) { + Orbit = orbit_clamped(Orbit, Vehicle); + // the left key takes the camera to the left around the vehicle, as a step to the left would while looking at it: + // clockwise seen from above. so does the mouse moved to the right, which turns the view to the right + Orbit.azimuth += Keys.x * orbit_turn_rate * Seconds + Turn.y; + // the mouse moved down looks down at the vehicle, from higher up + Orbit.elevation += Keys.y * orbit_climb_rate * Seconds - Turn.x; + // the up arrow (a negative z) brings the camera closer + Orbit.radius *= std::exp(Keys.z * orbit_zoom_rate * Seconds); + return orbit_clamped(Orbit, Vehicle); +} + +placement orbit_placement(orbit const &Orbit, vehicle_pose const &Vehicle) { + auto const front{flat_front(Vehicle.front)}; + auto const left{flat_left(front)}; + auto const around{std::cos(Orbit.azimuth) * front + std::sin(Orbit.azimuth) * left}; + auto const way{std::cos(Orbit.elevation) * around + std::sin(Orbit.elevation) * world_up}; + placement place; + place.target = orbit_centre(Vehicle); + place.eye = place.target + Orbit.radius * way; + place.up = world_up; + return place; +} + +// shunting view + +double topdown_min_height(vehicle_pose const &Vehicle) { + return Vehicle.height + 3.0; +} + +topdown topdown_clamped(topdown View, vehicle_pose const &Vehicle, double const Alonglimit) { + auto const lowest{topdown_min_height(Vehicle)}; + if (View.height <= 0.0) { + View.height = 1.5 * Vehicle.length; + } + View.height = std::clamp(View.height, lowest, std::max(lowest, topdown_max_height)); + auto const along{std::max(0.0, Alonglimit)}; + View.along = std::clamp(View.along, -along, along); + View.across = std::clamp(View.across, -topdown_max_across, topdown_max_across); + return View; +} + +topdown topdown_moved(topdown View, move_keys const &Keys, double const Seconds, vehicle_pose const &Vehicle, double const Alonglimit) { + View = topdown_clamped(View, Vehicle, Alonglimit); + auto const pan{View.height * topdown_pan_rate * Seconds}; + // the up arrow (a negative z) moves the view up the screen, the way the user drives + View.along -= Keys.z * pan; + View.across += Keys.x * pan; + View.height *= std::exp(Keys.y * topdown_zoom_rate * Seconds); + return topdown_clamped(View, Vehicle, Alonglimit); +} + +placement topdown_placement(topdown const &View, vehicle_pose const &Vehicle, int const Facing) { + auto const up{flat_front(Vehicle.front) * (Facing < 0 ? -1.0 : 1.0)}; + // looking down with the screen up the way the user drives, the right of the screen is the right of that way + auto const right{-flat_left(up)}; + placement place; + auto const ground{Vehicle.position + up * View.along + right * View.across}; + place.target = ground; + place.eye = ground + world_up * View.height; + place.up = up; + return place; +} + +// coupling view + +coupler_view coupler_moved(coupler_view View, move_keys const &Keys, double const Seconds) { + if (Keys.x < 0.0) { + View.side = 1.0; + } + else if (Keys.x > 0.0) { + View.side = -1.0; + } + View.distance = std::clamp(View.distance + Keys.z * coupler_move_rate * Seconds, coupler_min_distance, coupler_max_distance); + View.height = std::clamp(View.height + Keys.y * coupler_move_rate * Seconds, coupler_min_height, coupler_max_height); + return View; +} + +placement coupler_placement(coupler_view const &View, coupler const &Coupler, glm::dvec3 const *Other) { + auto const outward{flat_front(Coupler.outward)}; + auto const aside{flat_left(outward) * (View.side < 0.0 ? -1.0 : 1.0)}; + auto const buffers{Coupler.position + world_up * buffer_height}; + auto distance{View.distance}; + placement place; + if (Other != nullptr) { + auto const otherbuffers{*Other + world_up * buffer_height}; + distance = std::max(distance, coupler_gap_share * flat_distance(Coupler.position, *Other)); + place.target = 0.5 * (buffers + otherbuffers); + } + else { + place.target = buffers + outward; + } + distance = std::min(distance, coupler_max_distance); + place.eye = buffers - outward * coupler_step_back + aside * (0.5 * Coupler.width + distance) + world_up * View.height; + place.up = world_up; + return place; +} + +int first_coupling(double const Frontgap, double const Reargap, int const Count) { + auto const watched{[](double const Gap) { return Gap >= 0.0 && Gap <= coupler_watch_range; }}; + auto const front{watched(Frontgap)}; + auto const rear{watched(Reargap)}; + if (rear && (false == front || Reargap < Frontgap)) { + return std::max(Count, 0); + } + return 0; +} + +// trackside view + +std::pair along_arc(glm::dvec3 const &Start, glm::dvec3 const &Direction, double const Curvature, double const Distance) { + auto const way{flat_front(Direction)}; + if (std::abs(Curvature) < 1e-6) { + return {Start + way * Distance, way}; + } + auto const left{flat_left(way)}; + auto const angle{Curvature * Distance}; + auto const point{Start + way * (std::sin(angle) / Curvature) + left * ((1.0 - std::cos(angle)) / Curvature)}; + auto const heading{way * std::cos(angle) + left * std::sin(angle)}; + return {point, heading}; +} + +double line_curvature(glm::dvec3 const &Positiona, glm::dvec3 const &Directiona, glm::dvec3 const &Positionb, glm::dvec3 const &Directionb) { + auto const distance{flat_distance(Positiona, Positionb)}; + if (distance < 1.0) { + return 0.0; + } + auto const ahead{flat_front(Directiona)}; + auto const behind{flat_front(Directionb)}; + // the vehicle ahead turned to the left of the one behind it: a turn about the up axis, anticlockwise from above + auto const angle{std::atan2(glm::cross(behind, ahead).y, glm::dot(behind, ahead))}; + return angle / distance; +} + +bool trackside_expired(trackside const &View, train_motion const &Train) { + if (false == View.placed) { + return true; + } + auto const way{flat_front(Train.direction)}; + auto const offset{View.spot - Train.tail}; + auto const passed{glm::dot(glm::dvec3{offset.x, 0.0, offset.z}, way) < -trackside_passed}; + return passed || flat_distance(View.spot, Train.head) > trackside_max_distance; +} + +trackside trackside_next(trackside const &View, train_motion const &Train) { + auto lead{std::clamp(Train.speed * trackside_lead_time, trackside_min_lead, trackside_max_lead)}; + // along a sharp curve the line comes round: the spot stays within a quarter of the circle + if (auto const quarter{0.5 * std::numbers::pi}; std::abs(Train.curvature) * lead > quarter) { + lead = quarter / std::abs(Train.curvature); + } + auto const [point, heading]{along_arc(Train.head, Train.direction, Train.curvature, lead)}; + trackside next; + next.side = View.placed ? -View.side : View.side; + next.spot = point + flat_left(heading) * (next.side * (0.5 * Train.width + trackside_distance)) + world_up * trackside_eye_height; + next.placed = true; + return next; +} + +placement trackside_placement(trackside const &View, glm::dvec3 const &Target) { + placement place; + place.eye = View.spot; + place.target = Target; + place.up = world_up; + return place; +} + +} // namespace cameraviews diff --git a/vehicle/cameraviews.h b/vehicle/cameraviews.h new file mode 100644 index 000000000..a23d09e55 --- /dev/null +++ b/vehicle/cameraviews.h @@ -0,0 +1,182 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include + +// The outside views of the user's train that go with one of its vehicles (eu07/maszyna#551): the orbit around a +// vehicle, the shunting view from above, the view beside a coupling and the trackside view of a railfan. Each one +// is worked out here from the place of the vehicle and the keys of the user alone, so it can be tested without the +// game; application/consistviews.cpp hands over the vehicles of the train and turns the results into the camera. +// The world has y up; the rails are at the height of the place of a vehicle (TDynamicObject::GetPosition). +namespace cameraviews { + +// a vehicle of the train, as the views see it +struct vehicle_pose { + glm::dvec3 position{}; // its middle, at the height of the rails + glm::dvec3 front{0.0, 0.0, -1.0}; // unit, towards its front coupler + double length{20.0}; + double width{3.0}; + double height{4.0}; +}; + +// where the camera stands, the point it looks at and its up +struct placement { + glm::dvec3 eye{}; + glm::dvec3 target{}; + glm::dvec3 up{0.0, 1.0, 0.0}; +}; + +// the movement keys of the camera as TCamera::Velocity has them outside the cab: x to the right, y up, z backwards +// (the up arrow gives a negative z), 1 for a key held, 5 with ctrl +using move_keys = glm::dvec3; + +// the Front of a vehicle flattened on the ground, unit; a vehicle standing upright (no heading) faces -z +glm::dvec3 flat_front(glm::dvec3 const &Front); +// to the left of the flat Front, unit +glm::dvec3 flat_left(glm::dvec3 const &Flatfront); + +// the index after Step vehicles (or couplings) from Index, among Count of them, held at the first and the last +int step_index(int Index, int Count, int Step); + +// the two ends of a train whose vehicles stand at Positions, going in the Direction: the index of the vehicle +// at its head (furthest along the Direction) and at its tail +std::pair train_ends(std::vector const &Positions, glm::dvec3 const &Direction); + +// +1 when the front of the vehicle the view goes with points the way the user drives, -1 when it points back: +// the Front of that vehicle, the Front of the vehicle the user drives and its occupied cab (1 the front one, +// -1 the rear one, 0 none) +int driving_facing(glm::dvec3 const &Front, glm::dvec3 const &Drivenfront, int Cab); + +// orbit: around the middle of the vehicle, the left and right keys (and the mouse) turn the camera around it, +// the up and down arrows bring it closer and further away, the page keys (and the mouse) raise and lower it +struct orbit { + double azimuth{0.0}; // radians around the vehicle from its front, towards its left + double elevation{0.0}; // radians above the horizon of the middle of the vehicle + double radius{0.0}; // metres from the middle of the vehicle, 0 for the default one of the vehicle +}; + +inline constexpr double orbit_max_radius{250.0}; +inline constexpr double orbit_max_elevation{1.4}; // radians, about 80 degrees +inline constexpr double orbit_min_elevation{-0.5}; // radians, about -30 degrees, if the rails let it +inline constexpr double rail_clearance{0.5}; // metres the camera keeps above the rails + +// the first orbit around a vehicle: ahead of it on its left, a little above it, as far as the vehicle is long +orbit orbit_start(vehicle_pose const &Vehicle); +// the point the orbit goes around: the middle of the vehicle, a little lower than half of its height +glm::dvec3 orbit_centre(vehicle_pose const &Vehicle); +// the nearest the camera comes to the middle of the Vehicle: outside its body whichever way it looks +double orbit_min_radius(vehicle_pose const &Vehicle); +// the lowest elevation at the Radius which keeps the camera above the rails +double orbit_lowest_elevation(vehicle_pose const &Vehicle, double Radius); +// the Orbit held within its limits around the Vehicle (radius 0 becomes the default one) +orbit orbit_clamped(orbit Orbit, vehicle_pose const &Vehicle); +// the Orbit after Seconds of the Keys held and the mouse moved by Turn (radians: x up and down, y to the left and +// right, as TCamera::Angle takes them), within its limits around the Vehicle +orbit orbit_moved(orbit Orbit, move_keys const &Keys, glm::dvec2 const &Turn, double Seconds, vehicle_pose const &Vehicle); +// the camera of the Orbit around the Vehicle, looking at its middle +placement orbit_placement(orbit const &Orbit, vehicle_pose const &Vehicle); + +// shunting view: straight down from above the vehicle, the way the user drives up the screen; it goes with the +// vehicle, the up and down arrows move it along the train, left and right across, the page keys up and down +struct topdown { + double height{0.0}; // metres above the rails, 0 for the default one of the vehicle + double along{0.0}; // metres from the middle of the vehicle along it, the way the user drives + double across{0.0}; // metres from the middle of the vehicle across it, to the right of the screen +}; + +inline constexpr double topdown_max_height{300.0}; +inline constexpr double topdown_max_across{60.0}; + +// the lowest the camera comes: above the roof of the Vehicle +double topdown_min_height(vehicle_pose const &Vehicle); +// the View held within its limits: Alonglimit metres along the vehicle either way +topdown topdown_clamped(topdown View, vehicle_pose const &Vehicle, double Alonglimit); +// the View after Seconds of the Keys held; the further the camera, the faster it moves +topdown topdown_moved(topdown View, move_keys const &Keys, double Seconds, vehicle_pose const &Vehicle, double Alonglimit); +// the camera of the View over the Vehicle; Facing +1 puts the front of the vehicle up the screen, -1 its rear +placement topdown_placement(topdown const &View, vehicle_pose const &Vehicle, int Facing); + +// coupling view: beside a coupler, low, looking along the train at it; when another vehicle comes closer to it +// the camera steps back from the track to keep both couplers in sight, looking between them +inline constexpr double buffer_height{1.06}; // metres above the rails + +struct coupler { + glm::dvec3 position{}; // the coupler at the height of the rails (TDynamicObject::CouplerPosition) + glm::dvec3 outward{0.0, 0.0, -1.0}; // unit, from its vehicle out through the coupler + double width{3.0}; // of its vehicle +}; + +struct coupler_view { + double side{1.0}; // 1 on the left of the outward way, -1 on the right + double height{0.4}; // metres above the buffers + double distance{2.5}; // metres from the side of the vehicle, before the vehicle coming closer moves it further +}; + +inline constexpr double coupler_min_distance{1.0}; +inline constexpr double coupler_max_distance{40.0}; +inline constexpr double coupler_min_height{-0.8}; // metres above the buffers: a little above the rails +inline constexpr double coupler_max_height{10.0}; +inline constexpr double coupler_watch_range{150.0}; // metres to a vehicle that still counts as coming closer + +// the View after Seconds of the Keys held: left and right move it to that side of the track, the arrows closer +// and further, the page keys up and down +coupler_view coupler_moved(coupler_view View, move_keys const &Keys, double Seconds); +// the camera beside the Coupler; Other is the facing coupler of the vehicle coming closer, when there is one +placement coupler_placement(coupler_view const &View, coupler const &Coupler, glm::dvec3 const *Other); +// the coupling of a train of Count vehicles the view starts at, numbered from 0 (its front end) to Count (its rear +// end): the end with another vehicle, not coupled, closer than coupler_watch_range (the closer one of the two), +// otherwise the front. Frontgap and Reargap are the distances to such vehicles, negative for none +int first_coupling(double Frontgap, double Reargap, int Count); + +// trackside view: a railfan standing beside the line ahead of the train, looking at it as it comes and goes by; +// once the whole train has gone past (or gone far away) the railfan walks to a new spot ahead of it, on the other +// side of the line +struct trackside { + glm::dvec3 spot{}; // the eye of the railfan + double side{-1.0}; // 1 on the left of the line, -1 on the right + bool placed{false}; +}; + +// the train as the trackside view sees it +struct train_motion { + glm::dvec3 head{}; // the vehicle at its head, the way it goes, at the height of the rails + glm::dvec3 tail{}; // the vehicle at its tail + glm::dvec3 direction{0.0, 0.0, -1.0}; // unit, flat, the way it goes + double speed{0.0}; // m/s + double curvature{0.0}; // 1/m of the line at the head, positive turning left + double width{3.0}; // of the vehicles +}; + +inline constexpr double trackside_eye_height{1.7}; +inline constexpr double trackside_distance{8.0}; // metres from the side of the train +inline constexpr double trackside_passed{40.0}; // metres the tail goes past the spot before the railfan moves on +inline constexpr double trackside_max_distance{1000.0}; // metres to the head before the railfan moves on anyway +inline constexpr double trackside_lead_time{15.0}; // seconds the train needs to reach the new spot +inline constexpr double trackside_min_lead{80.0}; +inline constexpr double trackside_max_lead{500.0}; + +// whether the railfan at the View has seen the Train go by and moves on +bool trackside_expired(trackside const &View, train_motion const &Train); +// the next spot of the railfan, ahead of the Train along its line, on the other side than the View had +trackside trackside_next(trackside const &View, train_motion const &Train); +// the camera of the railfan at the View, looking at the Target +placement trackside_placement(trackside const &View, glm::dvec3 const &Target); + +// the point and the way Distance metres on from Start going in the (flat, unit) Direction along a line which +// turns by Curvature (1/m, positive to the left) +std::pair along_arc(glm::dvec3 const &Start, glm::dvec3 const &Direction, double Curvature, double Distance); +// the curvature of the line under two vehicles of a train going its way: A ahead of B, each at its Position with +// its front (or rear) towards the way of the train; 0 when they stand too close to tell +double line_curvature(glm::dvec3 const &Positiona, glm::dvec3 const &Directiona, glm::dvec3 const &Positionb, glm::dvec3 const &Directionb); + +} // namespace cameraviews From 66b8a673616b84032f41b9abb8fb9d0650d8e4d4 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 08:54:50 +0100 Subject: [PATCH 053/136] fix(timetable): read the table from its start, bound the station index both ways read_timetable() went on from the StationCount it was given and checked only the upper bound, so TimeTable[StationCount] and TimeTable[StationCount - 1] could index out of the table (Sonar cpp:S3519). It now resets the count and the table first, and checks both bounds before the next station. --- tests/unit/test_timetable.cpp | 18 ++++++++++++++++++ world/timetablereader.cpp | 9 ++++++--- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/tests/unit/test_timetable.cpp b/tests/unit/test_timetable.cpp index f4387e7f8..a41aafcce 100644 --- a/tests/unit/test_timetable.cpp +++ b/tests/unit/test_timetable.cpp @@ -229,6 +229,24 @@ TEST_CASE("timetable: a timetable longer than the table is an error") { CHECK(data.StationCount == Mtable::MaxTTableSize); } +TEST_CASE("timetable: the reader starts from an empty table, whatever the data held before") { + auto const text{timetable_with("", "R2,H", "po", "R3")}; + auto const [error, fresh]{read(text)}; + REQUIRE(error == 0); + // a count past the table, a negative one, a stale one: the reader used to go on from it and index out of the table + for (auto const count : {Mtable::MaxTTableSize, Mtable::MaxTTableSize + 7, -3, 2}) { + CAPTURE(count); + std::istringstream input{text}; + Mtable::timetable_data data; + data.TrainName = "file"; + data.StationCount = count; + data.TimeTable[fresh.StationCount + 1].StationName = "stale"; + CHECK(Mtable::read_timetable(input, data) == 0); + CHECK(contents(data) == contents(fresh)); + CHECK(data.TimeTable[fresh.StationCount + 1].StationName == "nowhere"); + } +} + TEST_CASE("timetable: the entry whose flags hold at the stop and on the way") { // before the timetable is loaded, and with none CHECK(timetable::stop_flags_entry(0, 0) == 0); diff --git a/world/timetablereader.cpp b/world/timetablereader.cpp index 3d340e8bd..087c0205c 100644 --- a/world/timetablereader.cpp +++ b/world/timetablereader.cpp @@ -58,6 +58,9 @@ int read_timetable(std::istream &fin, timetable_data &Data) { int conversionerror{0}; auto &TimeTable{Data.TimeTable}; auto &StationCount{Data.StationCount}; + // the table is read from its start, whatever Data held before + StationCount = 0; + TimeTable.fill(TMTableEntry{}); // zapisywanie prędkości maksymalnej do wcześniejszych odcinków auto const UpdateVelocity{[&TimeTable, &StationCount](double const Velocity) { int i = StationCount; @@ -164,12 +167,12 @@ int read_timetable(std::istream &fin, timetable_data &Data) { TimeTable[0].flags = Data.Flags; auto activeradiochannel{-1}; while (!fin.fail() && !EndTable) { - ++StationCount; - if (StationCount > MaxTTableSize) { - --StationCount; + // both bounds, so TimeTable[StationCount] and TimeTable[StationCount - 1] below stay in the table + if (StationCount < 0 || StationCount >= MaxTTableSize) { conversionerror = timetable_too_long; break; } + ++StationCount; do { fin >> s; } while (!(s == "[" || fin.fail())); From 178f5b63fe4c651a8095eb281f2eb13bd55fb98e Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 09:10:08 +0100 Subject: [PATCH 054/136] fix(scripting): gsub with a metatable'd table, the trim idiom, the memory doc - replacement_length() popped nothing after lua_getmetatable() pushed a metatable, so gsub got it as its 4th argument ("bad argument #4 to 'gsub'"); it is popped now. - lua_pattern_cost(): a repetition followed by what always matches (as the first %s* of "^%s*(.-)%s*$") is tried once and doesn't multiply; a repetition of a character or a %class right before the final '$' counts the longest run of it in the subject, not the subject. The trim of a 10 KB line of words is allowed, a long run of spaces is still refused (it takes the square of the run). The doc names a trim that is linear on any string. - the doc says every concatenation within one hook interval is made whole before the memory check. --- script_screens_doc.md | 29 +++- scripting/luaprogram.cpp | 12 +- scripting/scriptscreenrules.cpp | 200 +++++++++++++++++++------ scripting/scriptscreenrules.h | 10 +- tests/unit/test_script_screen_host.cpp | 31 ++++ tests/unit/test_script_screens.cpp | 41 +++++ 6 files changed, 267 insertions(+), 56 deletions(-) diff --git a/script_screens_doc.md b/script_screens_doc.md index 3919cda7d..7b14cb317 100644 --- a/script_screens_doc.md +++ b/script_screens_doc.md @@ -146,8 +146,10 @@ Besides the 200 million instructions of a call, a Lua screen is held to what run exceeded`), and a screen found holding more stops with that error. Garbage doesn't count: the check collects it first. Where LuaJIT takes an allocator of the game's (2.1 in its GC64 mode), anything over twice the limit is refused as it is asked for (`not enough memory`); the game's LuaJIT 2.0 on 64-bit Windows takes none, and there the heap is - checked every thousand instructions and before the calls below, but a single concatenation (`a .. b`) of large - strings is made whole first; + checked every thousand instructions and before the calls below, and whatever a script makes between two checks is + made whole first: every concatenation (`a .. b`) within one interval of a thousand instructions, so a loop doubling a + string (`for i = 1, 11 do s = s .. s end` on a 1 MB `s`) gets to LuaJIT's own heap limit of about 2 GB before the + check sees it; - `string.rep` makes no string over 1 MB; `string.format`, `table.concat` and `string.gsub` (with a string or a table to replace with) refuse a result that may be over the memory of a screen, counted from the lengths of what they are given; @@ -155,12 +157,23 @@ Besides the 200 million instructions of a call, a Lua screen is held to what run subject (`("a"):rep(1e6):find(".-b")`). A call is refused (`the pattern may take too long`) when the steps it may take at worst are over 100 million, about a tenth of a second at worst: the length of the subject (plus one), times the length of the pattern, times the subject again for each repetition (`*`, `+`, `-`, `%b`, a back reference `%1`) but - a last one that ends the pattern, times 2 for each `?`, and taken once rather than from every position for a pattern - anchored with `^` (not in `gmatch`). A plain search (`find` with `plain`, or a pattern of no special characters) is - the subject times the pattern. So a pattern ending in its only repetition (`"[^ -]+"`, `"%d+"`) works on any subject, - one more repetition (`"(%w+)=(%w+)"`, `"%s+$"`) on some 3 000 to 5 000 bytes, and each further one divides that - a lot; + one followed by what always matches (nothing, as in a repetition that ends the pattern, or `(.-)%s*$`), times 2 for + each `?`, and taken once rather than from every position for a pattern anchored with `^` (not in `gmatch`). A + repetition of a character or a `%` class right before the final `$` (`%s*$`) counts the longest run of it in the + subject rather than the whole subject. A plain search (`find` with `plain`, or a pattern of no special characters) is + the subject times the pattern. So a pattern ending in its only repetition (`"[^\n]+"`, `"%d+"`) works on any subject, + one more repetition (`"(%w+)=(%w+)"`) on some 3 000 to 5 000 bytes, and each further one divides that a lot. The + usual trim, `s:match("^%s*(.-)%s*$")`, costs the line times its longest run of spaces: a line of words, even a + megabyte long, is fine, but a long run of spaces inside it is refused, since the trim really takes the square of that. + A trim that stays linear on any string: + + ```lua + local function trim(s) + local first = s:find("%S") + if not first then return "" end + return s:sub(first, #s - s:reverse():find("%S") + 1) + end + ``` - `xpcall` is made of `pcall`: the handler gets the error once it has left the function, and a coroutine may yield inside either. There is no `newproxy`, so no finalizer (`__gc`) of the script's own: LuaJIT runs those without the instruction count; diff --git a/scripting/luaprogram.cpp b/scripting/luaprogram.cpp index 9a5de6c9e..9b2a5c255 100644 --- a/scripting/luaprogram.cpp +++ b/scripting/luaprogram.cpp @@ -942,8 +942,14 @@ std::optional replacement_length(lua_State *L, int const Index, double c // the matches don't overlap: a capture of each takes at most the subject; a position capture is a number return Matches * static_cast(length) + captures * (Subject + 24.0 * Matches); } - if (lua_type(L, Index) == LUA_TTABLE && 0 == lua_getmetatable(L, Index)) + if (lua_type(L, Index) == LUA_TTABLE) { + if (lua_getmetatable(L, Index) != 0) + { + // pushed: off the stack again, or the library gets it as the 4th argument + lua_pop(L, 1); + return std::nullopt; + } auto longest{0.0}; lua_pushnil(L); while (lua_next(L, Index) != 0) @@ -964,11 +970,11 @@ int api_pattern(lua_State *L) auto const function{static_cast(lua_tointeger(L, lua_upvalueindex(2)))}; auto const *name{pattern_function_names[static_cast(function)]}; std::size_t subject{0}; - luaL_checklstring(L, 1, &subject); + auto const *text{luaL_checklstring(L, 1, &subject)}; std::size_t length{0}; auto const *pattern{luaL_checklstring(L, 2, &length)}; auto const plain{function == pattern_function::find && lua_toboolean(L, 4) != 0}; - if (lua_pattern_cost({pattern, length}, subject, plain, function != pattern_function::gmatch) > max_pattern_cost) + if (lua_pattern_cost(std::string_view{pattern, length}, std::string_view{text, subject}, plain, function != pattern_function::gmatch) > max_pattern_cost) { return luaL_error(L, "%s: the pattern may take too long on a subject of %d bytes", name, static_cast(subject)); } diff --git a/scripting/scriptscreenrules.cpp b/scripting/scriptscreenrules.cpp index 35f918618..e8df2692e 100644 --- a/scripting/scriptscreenrules.cpp +++ b/scripting/scriptscreenrules.cpp @@ -13,7 +13,9 @@ http://mozilla.org/MPL/2.0/. #include "utilities/parser.h" #include +#include #include +#include namespace script_screens { @@ -161,55 +163,60 @@ std::size_t set_end(std::string_view const Pattern, std::size_t Start) return idx + 1; } -} // namespace - -double lua_pattern_cost(std::string_view const Pattern, std::size_t const Subject, bool const Plain, bool const Anchorable) +// one item of a pattern, as Lua's matcher takes them +struct pattern_item { - auto const length{static_cast(std::max(Pattern.size(), 1))}; - auto const positions{static_cast(Subject) + 1.0}; - // LuaJIT searches plainly for a pattern without the special characters as well - if (Plain || Pattern.find_first_of("^$*+?.([%-") == std::string_view::npos) + enum class kind { - return positions * length; - } - auto const anchored{Anchorable && Pattern.front() == '^'}; - int repeats{0}; - int optional{0}; - // a repetition that ends the pattern doesn't multiply: past it the match is over - auto last_repeat{false}; - std::size_t idx{anchored ? 1U : 0U}; + single, // a character, '.', a %class or a [set], with its quantifier if any + paren, // '(' or ')': a capture costs nothing + scan, // %bxy or a back reference %1-%9: goes along the subject + frontier, // %f[set]: a test of one position + end_anchor // '$' that ends the pattern + }; + kind type{kind::single}; + std::size_t begin{0}; // of a single, without its quantifier + std::size_t end{0}; + char quantifier{0}; // '*', '+', '-', '?' or none +}; + +std::vector pattern_items(std::string_view const Pattern, std::size_t idx) +{ + std::vector items; while (idx < Pattern.size()) { auto const character{Pattern[idx]}; if (character == '(' || character == ')') { + items.push_back({pattern_item::kind::paren, idx, idx + 1}); ++idx; - // a ')' after the last repetition keeps it last continue; } - last_repeat = false; + if (character == '$' && idx + 1 == Pattern.size()) + { + items.push_back({pattern_item::kind::end_anchor, idx, idx + 1}); + break; + } std::size_t end{idx + 1}; if (character == '%' && idx + 1 < Pattern.size()) { auto const next{Pattern[idx + 1]}; if (next == 'b') { - // %bxy goes along the subject to the balancing character - ++repeats; - last_repeat = true; + items.push_back({pattern_item::kind::scan, idx, idx + 4}); idx += 4; continue; } if (next == 'f') { - idx = idx + 2 < Pattern.size() && Pattern[idx + 2] == '[' ? set_end(Pattern, idx + 2) : idx + 2; + auto const after{idx + 2 < Pattern.size() && Pattern[idx + 2] == '[' ? set_end(Pattern, idx + 2) : idx + 2}; + items.push_back({pattern_item::kind::frontier, idx, after}); + idx = after; continue; } if (next >= '0' && next <= '9') { - // a back reference compares the capture, as long as the subject - ++repeats; - last_repeat = true; + items.push_back({pattern_item::kind::scan, idx, idx + 2}); idx += 2; continue; } @@ -219,28 +226,135 @@ double lua_pattern_cost(std::string_view const Pattern, std::size_t const Subjec { end = set_end(Pattern, idx); } - if (end < Pattern.size() && (Pattern[end] == '*' || Pattern[end] == '+' || Pattern[end] == '-')) + pattern_item item{pattern_item::kind::single, idx, end}; + if (end < Pattern.size() && (Pattern[end] == '*' || Pattern[end] == '+' || Pattern[end] == '-' || Pattern[end] == '?')) { - ++repeats; - last_repeat = true; - idx = end + 1; - } - else if (end < Pattern.size() && Pattern[end] == '?') - { - ++optional; - idx = end + 1; - } - else - { - idx = end; + item.quantifier = Pattern[end]; + ++end; } + items.push_back(item); + idx = end; } - if (last_repeat) - { - --repeats; - } - auto const starts{anchored ? 1.0 : positions}; - return starts * std::pow(positions, repeats) * std::pow(2.0, optional) * length; + return items; } +// when the rest of a pattern matches, once the matcher gets to it +enum class rest_match +{ + always, // from any position: whatever comes before it is tried once + at_end, // at least at the end of the subject + maybe +}; + +rest_match match_with(std::string_view const Pattern, pattern_item const &Item, rest_match const Rest) +{ + switch (Item.type) + { + case pattern_item::kind::paren: + return Rest; + case pattern_item::kind::end_anchor: + return rest_match::at_end; + case pattern_item::kind::single: + if (Item.quantifier == '*' || Item.quantifier == '-' || Item.quantifier == '?') + { + // matches nothing as well; '.' repeated goes on to the end of the subject + auto const dot{Item.quantifier != '?' && Item.end - Item.begin == 1 && Pattern[Item.begin] == '.'}; + return dot && Rest == rest_match::at_end ? rest_match::always : Rest; + } + return rest_match::maybe; + default: + return rest_match::maybe; + } +} + +// whether Character is in the %class Class, as Lua's match_class +bool in_class(unsigned char const Character, unsigned char const Class) +{ + bool in{false}; + switch (std::tolower(Class)) + { + case 'a': in = std::isalpha(Character) != 0; break; + case 'c': in = std::iscntrl(Character) != 0; break; + case 'd': in = std::isdigit(Character) != 0; break; + case 'l': in = std::islower(Character) != 0; break; + case 'p': in = std::ispunct(Character) != 0; break; + case 's': in = std::isspace(Character) != 0; break; + case 'u': in = std::isupper(Character) != 0; break; + case 'w': in = std::isalnum(Character) != 0; break; + case 'x': in = std::isxdigit(Character) != 0; break; + case 'z': in = Character == 0; break; + default: return Class == Character; + } + return std::isupper(Class) != 0 ? !in : in; +} + +// the longest run of the subject that the single item (a character, '.' or a %class) matches; the whole subject for a +// set, which isn't gone through here +std::size_t longest_run(std::string_view const Pattern, pattern_item const &Item, std::string_view const Subject) +{ + auto const single{Pattern.substr(Item.begin, Item.end - Item.begin)}; + if (single == "." || single.front() == '[') + { + return Subject.size(); + } + std::size_t longest{0}; + std::size_t run{0}; + for (auto const character : Subject) + { + auto const c{static_cast(character)}; + auto const in{single.size() == 2 ? in_class(c, static_cast(single[1])) : c == static_cast(single[0])}; + run = in ? run + 1 : 0; + longest = std::max(longest, run); + } + return longest; +} + +double pattern_cost(std::string_view const Pattern, std::size_t const Size, std::string_view const *Subject, bool const Plain, bool const Anchorable) +{ + auto const length{static_cast(std::max(Pattern.size(), 1))}; + auto const positions{static_cast(Size) + 1.0}; + // LuaJIT searches plainly for a pattern without the special characters as well + if (Plain || Pattern.find_first_of("^$*+?.([%-") == std::string_view::npos) + { + return positions * length; + } + auto const anchored{Anchorable && Pattern.front() == '^'}; + auto const items{pattern_items(Pattern, anchored ? 1U : 0U)}; + auto cost{anchored ? 1.0 : positions}; + // from the end: what follows each item, and whether that's only the end of the subject + auto rest{rest_match::always}; + auto only_end{true}; + for (auto item{items.rbegin()}; item != items.rend(); ++item) + { + if (item->type == pattern_item::kind::single && item->quantifier == '?') + { + cost *= 2.0; + } + auto const repeated{item->type == pattern_item::kind::scan + || (item->type == pattern_item::kind::single && item->quantifier != 0 && item->quantifier != '?')}; + // a repetition followed by what always matches is tried once (as one that ends the pattern): past it the match + // is over. otherwise the rest is tried at each length it takes, as many as the subject has positions; before + // '$' alone, as many as its longest run in the subject, past which it stops + if (repeated && rest != rest_match::always) + { + auto const before_end{only_end && rest == rest_match::at_end && item->type == pattern_item::kind::single}; + cost *= before_end && Subject != nullptr ? static_cast(longest_run(Pattern, *item, *Subject)) + 1.0 : positions; + } + only_end = only_end && (item->type == pattern_item::kind::paren || item->type == pattern_item::kind::end_anchor); + rest = match_with(Pattern, *item, rest); + } + return cost * length; +} + +} // namespace + +double lua_pattern_cost(std::string_view const Pattern, std::size_t const Subject, bool const Plain, bool const Anchorable) +{ + return pattern_cost(Pattern, Subject, nullptr, Plain, Anchorable); +} + +double lua_pattern_cost(std::string_view const Pattern, std::string_view const Subject, bool const Plain, bool const Anchorable) +{ + return pattern_cost(Pattern, Subject.size(), &Subject, Plain, Anchorable); +} } // namespace script_screens diff --git a/scripting/scriptscreenrules.h b/scripting/scriptscreenrules.h index 8690793e6..889f7e9c3 100644 --- a/scripting/scriptscreenrules.h +++ b/scripting/scriptscreenrules.h @@ -88,9 +88,15 @@ constexpr double max_pattern_cost{1e8}; // - a plain search (string.find with plain set, or a pattern without special characters): Subject x m; // - a pattern: tried from every position of the subject (Subject + 1), or from the first only when Anchored (it starts // with '^', and the function anchors: find, match, gsub, not gmatch), times (Subject + 1) for each repetition ('*', -// '+', '-', %b, a back reference %1-%9) but a last one (followed by nothing but ')', which ends the match where it -// stops), times 2 for each '?', times m for the work of each step (a set is gone through item by item) +// '+', '-', %b, a back reference %1-%9) but one followed by what always matches (nothing, ')', a repetition with '*' +// or '-' or a '?' of what always matches, '.*' / '.-' before '$'), where the match is over: so neither the last +// repetition nor the first %s* of "^%s*(.-)%s*$" multiplies. times 2 for each '?', times m for the work of each step +// (a set is gone through item by item) // a malformed pattern costs nothing here: the function raises its error itself double lua_pattern_cost(std::string_view Pattern, std::size_t Subject, bool Plain, bool Anchorable); +// as above, on the subject itself: a repetition of a character or a %class right before the final '$' ("%s*$") counts +// as many times as the longest run of it in the subject (plus one), not the whole subject: past that run it fails or +// gets to the end, so the trim "^%s*(.-)%s*$" costs about the subject times its longest run of spaces +double lua_pattern_cost(std::string_view Pattern, std::string_view Subject, bool Plain, bool Anchorable); } // namespace script_screens diff --git a/tests/unit/test_script_screen_host.cpp b/tests/unit/test_script_screen_host.cpp index 8fd4de2f4..7c7130f85 100644 --- a/tests/unit/test_script_screen_host.cpp +++ b/tests/unit/test_script_screen_host.cpp @@ -1209,6 +1209,30 @@ return { } )"}; +// white when gsub takes a table with a metatable as Lua does (the metatable doesn't get to the library as an argument), +// and a line is trimmed: with the usual idiom on a long line of words, without a pattern on a long run of spaces +constexpr std::string_view gsub_metatable_trim_script{R"( +local upper = setmetatable({}, { __index = function(_, k) return k:upper() end }) +local replaced, count = ("one two"):gsub("%w+", upper) +local line = ("word next\tone "):rep(700) +local trimmed = (" " .. line .. " "):match("^%s*(.-)%s*$") +local ok, message = pcall(string.match, "x" .. (" "):rep(1000000) .. "x", "^%s*(.-)%s*$") +local refused = not ok and message:find("may take too long", 1, true) ~= nil +local function trim(s) + local first = s:find("%S") + if not first then return "" end + return s:sub(first, #s - s:reverse():find("%S") + 1) +end +local spaced = trim(" x" .. (" "):rep(1000000) .. "x ") +local good = replaced == "ONE TWO" and count == 2 and trimmed == line:sub(1, -2) and refused + and #spaced == 1000002 and trim(" ") == "" and trim(" a b ") == "a b" +return { + render = function(state) + return eu07.image(1, 1, good and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + // white when the images a screen holds are held to its memory, and the images it dropped don't count constexpr std::string_view image_memory_script{R"( local kept = {} @@ -1338,6 +1362,13 @@ TEST_CASE("lua screens: what makes a large string in one call is held to the mem CHECK(first_pixel(folder.write("large.lua", large_result_script), "large") == 255); } +TEST_CASE("lua screens: gsub with a table that has a metatable, and the trim of a long line") { + script_folder const folder{"lua_gsub_metatable_trim"}; + auto const started{std::chrono::steady_clock::now()}; + CHECK(first_pixel(folder.write("trim.lua", gsub_metatable_trim_script), "trim") == 255); + CHECK(std::chrono::steady_clock::now() - started < std::chrono::seconds(10)); +} + TEST_CASE("lua screens: the images a screen holds are held to its memory") { script_folder const folder{"lua_image_memory"}; CHECK(first_pixel(folder.write("images.lua", image_memory_script), "images") == 255); diff --git a/tests/unit/test_script_screens.cpp b/tests/unit/test_script_screens.cpp index 0b92e7505..59aa19560 100644 --- a/tests/unit/test_script_screens.cpp +++ b/tests/unit/test_script_screens.cpp @@ -159,3 +159,44 @@ TEST_CASE("script screens: the steps a Lua pattern function may take at worst") } CHECK(lua_pattern_cost(optional + std::string(30, 'a'), 100, false, true) > max_pattern_cost); } + +TEST_CASE("script screens: a repetition followed by what always matches doesn't multiply") { + using script_screens::lua_pattern_cost; + // the first %s* of the trim: past it, (.-)%s*$ matches from wherever it stopped, so it's tried once + CHECK(lua_pattern_cost("^%s*(.-)%s*$", 999, false, true) == doctest::Approx(1000.0 * 1000 * 12)); + CHECK(lua_pattern_cost("^%s*(.*)", 999, false, true) == doctest::Approx(8.0)); + CHECK(lua_pattern_cost("a*.-$", 999, false, true) == doctest::Approx(1000.0 * 1000 * 5)); + // what may not match still multiplies + CHECK(lua_pattern_cost("^%s*(.*%S)", 999, false, true) == doctest::Approx(1000.0 * 1000 * 10)); + CHECK(lua_pattern_cost("^%s*x%s*$", 999, false, true) == doctest::Approx(1000.0 * 1000 * 9)); + // '$' is the end only at the end of the pattern + CHECK(lua_pattern_cost("a*$b", 999, false, true) == doctest::Approx(1000.0 * 1000 * 4)); +} + +TEST_CASE("script screens: a repetition right before the final $ counts its longest run in the subject") { + using script_screens::lua_pattern_cost; + using script_screens::max_pattern_cost; + std::string words; + while (words.size() < 10'000) { + words += "word next\tone "; + } + // a line of 10 KB trimmed: the subject times the longest run of spaces (2), where the length alone gives the + // subject squared + CHECK(lua_pattern_cost("^%s*(.-)%s*$", std::string_view{words}, false, true) == doctest::Approx((words.size() + 1.0) * 3 * 12)); + CHECK(lua_pattern_cost("^%s*(.-)%s*$", std::string_view{words}, false, true) < max_pattern_cost); + CHECK(lua_pattern_cost("^%s*(.-)%s*$", words.size(), false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%s+$", std::string_view{words}, false, true) < max_pattern_cost); + CHECK(lua_pattern_cost("%d*$", std::string_view{words}, false, true) == doctest::Approx((words.size() + 1.0) * 1 * 4)); + CHECK(lua_pattern_cost("x*$", std::string_view{"axxxa"}, false, true) == doctest::Approx(6.0 * 4 * 3)); + CHECK(lua_pattern_cost("%%*$", std::string_view{"a%%%a"}, false, true) == doctest::Approx(6.0 * 4 * 4)); + // a long run is still the subject squared: "x", 10 000 spaces, "x" takes the trim about 10^8 steps, and a + // megabyte of them hours + auto const spaces{"x" + std::string(10'000, ' ') + "x"}; + CHECK(lua_pattern_cost("^%s*(.-)%s*$", std::string_view{spaces}, false, true) > max_pattern_cost); + auto const megabyte{"x" + std::string(1'000'000, ' ') + "x"}; + CHECK(lua_pattern_cost("^%s*(.-)%s*$", std::string_view{megabyte}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%s*$", std::string_view{megabyte}, false, true) > max_pattern_cost); + // a set or '.' isn't gone through: the whole subject + CHECK(lua_pattern_cost("[ ]*$", std::string_view{words}, false, true) == doctest::Approx((words.size() + 1.0) * (words.size() + 1.0) * 5)); + CHECK(lua_pattern_cost(".-b", std::string(1'000'000, 'a'), false, true) > max_pattern_cost); +} From ebe0a42be7891edc797e262c49ac42286d404f3e Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 09:17:19 +0100 Subject: [PATCH 055/136] fix(camera): the trackside view sets the train's way again when the vehicle picked changes pick() kept m_lastposition of the vehicle before, so the next motion_of() took the step between the two vehicles for a move: the direction could point back along the train, the ends swapped and the railfan went to a spot 80+ m behind the tail. Now a change of the vehicle sets m_moved to false, and the way is set again from the way the user drives. --- application/consistviews.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/application/consistviews.cpp b/application/consistviews.cpp index 15762d437..49815f6e8 100644 --- a/application/consistviews.cpp +++ b/application/consistviews.cpp @@ -132,6 +132,11 @@ TDynamicObject *consist_views::pick(std::vector const &Train, index = cameraviews::step_index(index, static_cast(Train.size()), m_step); m_step = 0; } + if (Train[index] != m_vehicle) { + // m_lastposition is of the vehicle before: the way the train goes is set again from the way the user drives, + // or the step between the two vehicles would be taken for a move + m_moved = false; + } m_vehicle = Train[index]; return m_vehicle; } From 0645096e13180a5943c00aa306c68e247c883ff6 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 09:33:02 +0100 Subject: [PATCH 056/136] feat(physics): ship with physics.derailment monitor as the default 144 tracks in 12 of the bundled scenarios have a speed limit above the overturning speed of the reference vehicles, so the criteria as the default would change how they play. Until those limits are corrected in the pctga data, the default (and a name not known) is monitor: the legacy draw decides, and the log tells where new would derail a vehicle. new stays opt-in. --- tests/unit/test_derailment_vehicle.cpp | 8 +++++--- utilities/Globals.h | 14 ++++++++------ 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index d6c94b9b0..99b6c0417 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -314,9 +314,11 @@ TEST_CASE("derailment: the names of the models in eu07.ini") { CHECK(derailment_model_of("off") == model::off); CHECK(derailment_model_of("no") == model::off); CHECK(derailment_model_of("monitor") == model::monitor); - // a name it doesn't know is the default - CHECK(derailment_model_of("physical") == model::physical); - CHECK(global_settings{}.derailment == model::physical); + // a name it doesn't know is the default: monitor, the legacy draw decides and the criteria go to the log, until the + // speed limits of the bundled sceneries are checked against them + CHECK(derailment_model_of("physical") == model::monitor); + CHECK(derailment_model_of("") == model::monitor); + CHECK(global_settings{}.derailment == model::monitor); CHECK_FALSE(global_settings{}.track_check); // written back the way it's read for (auto const value : {model::off, model::old, model::physical, model::monitor}) { diff --git a/utilities/Globals.h b/utilities/Globals.h index bc206913c..efbd7c5ca 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -298,9 +298,11 @@ struct global_settings { // by the criteria of McZapkie/derailment.h held over 2 m, and slides on with the friction of the ballast; old, the // legacy draw of the lateral acceleration against the gauge to the height of the vehicle in every step, which stops // it; off, it stays on the rails at any speed; monitor, the legacy draw decides and the log tells where the criteria - // would derail a vehicle (derailment monitor:, once for a vehicle on a track), for the run of a scenery as it was + // would derail a vehicle (derailment monitor:, once for a vehicle on a track), for the run of a scenery as it was. + // monitor is the default until the speed limits of the bundled sceneries are checked against the criteria (some + // tracks allow more than the reference vehicle survives there): new is opt-in until then enum class derailment_model { off, old, physical, monitor }; - derailment_model derailment = derailment_model::physical; + derailment_model derailment = derailment_model::monitor; // the collisions of rail vehicles past their buffers (physics.collisions in eu07.ini): new, the ends crush, a vehicle // may ride up onto the other one or be pushed off the track (McZapkie/collision.h); old, the legacy rule of the safe // closing speed weighed by the masses; monitor, the legacy rule decides and the log tells what the crush would be @@ -473,13 +475,13 @@ inline std::string_view name_of( global_settings::collision_model const Model ) default: { return "new"; } } } -// the models of physics.derailment by their names in eu07.ini: new (the default, also for a name it doesn't know), old, off -// or no, monitor +// the models of physics.derailment by their names in eu07.ini: new, old, off or no, monitor (the default, also for a +// name it doesn't know) inline global_settings::derailment_model derailment_model_of(std::string_view const Name) { + if( Name == "new" ) { return global_settings::derailment_model::physical; } if( Name == "old" ) { return global_settings::derailment_model::old; } if( Name == "off" || Name == "no" ) { return global_settings::derailment_model::off; } - if( Name == "monitor" ) { return global_settings::derailment_model::monitor; } - return global_settings::derailment_model::physical; + return global_settings::derailment_model::monitor; } inline std::string_view name_of( global_settings::derailment_model const Model ) { switch( Model ) { From edc961486fd845f5c4b8aa7e30366a5548a4a17a Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 09:52:07 +0100 Subject: [PATCH 057/136] fix(physics): the diesel-electric dynamic brake lets the vehicle come to rest without a fade With EDBrakeV0 = EDBrakeV1 = 0 the whole force acted down to the stop and turned round each time the speed crossed zero; in FTrain it never let the stop of ComputeMovement() catch it, so the speed swung round zero. Near the stop the force is now no more than what stops the vehicle within the step. --- McZapkie/MOVER.h | 2 +- McZapkie/Mover.cpp | 11 +++++---- tests/unit/test_dynamic_brake_diesel.cpp | 30 ++++++++++++++++++++++++ 3 files changed, 38 insertions(+), 5 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 1411ff4bd..4a3b2dba5 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2591,7 +2591,7 @@ class TMoverParameters void update_dieselelectric_dynamic_brake(double dt); double dieselelectric_dynamic_brake_demand() const; // 0..1, the effort the driver asks for double dieselelectric_dynamic_brake_limit() const; // [N] the force at full effort at the speed - void apply_dieselelectric_dynamic_brake(); // the force in place of the drive's one + void apply_dieselelectric_dynamic_brake(double dt); // the force in place of the drive's one, over the step dt double dieselelectric_motor_current(double Moment) const; // the current of the motors giving the moment double FrictionForce() const; double BrakeForceR(double ratio, double velocity) const; diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 9c0b6b881..7f0ed3361 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -6615,7 +6615,7 @@ double TMoverParameters::TractionForce(double dt) if (DEDynamicBrake.level > 0.0) { // braking: no power asked for, so the drive above gave no force - apply_dieselelectric_dynamic_brake(); + apply_dieselelectric_dynamic_brake(dt); } break; } // DieselElectric @@ -7019,10 +7019,13 @@ void TMoverParameters::update_dieselelectric_dynamic_brake(double const dt) } // the force of a diesel-electric vehicle's dynamic brake, against the motion, in place of the drive's one: the motors -// work as generators into the resistors, the ammeter shows their current, the main generator gives nothing -void TMoverParameters::apply_dieselelectric_dynamic_brake() +// work as generators into the resistors, the ammeter shows their current, the main generator gives nothing. near the +// stop no more than what stops the vehicle within the step dt: with no fade (EDBrakeV0 = EDBrakeV1 = 0) the whole force +// would turn round each time the speed crosses zero, and in FTrain it never lets the stop of ComputeMovement() catch it +void TMoverParameters::apply_dieselelectric_dynamic_brake(double const dt) { - Ft = V > 0.0 ? -DEDynamicBrake.force : V < 0.0 ? DEDynamicBrake.force : 0.0; + auto const force{dt > 0.0 ? std::min(DEDynamicBrake.force, TotalMass * std::abs(V) / dt) : DEDynamicBrake.force}; + Ft = V > 0.0 ? -force : V < 0.0 ? force : 0.0; Fw = Ft / NPoweredAxles; Mw = Fw * WheelDiameter / 2.0; Mm = Mw / Transmision.Ratio; diff --git a/tests/unit/test_dynamic_brake_diesel.cpp b/tests/unit/test_dynamic_brake_diesel.cpp index f0851d061..fc3f30f27 100644 --- a/tests/unit/test_dynamic_brake_diesel.cpp +++ b/tests/unit/test_dynamic_brake_diesel.cpp @@ -232,3 +232,33 @@ TEST_CASE("diesel-electric dynamic brake: blended with the locomotive's air brak scenario.check(); } } + +TEST_CASE("diesel-electric dynamic brake: without a fade it brings the vehicle to rest") { + // EDBrakeV0 = EDBrakeV1 = 0 (the defaults): the whole force down to the stop. near it no more than what stops the + // vehicle within the step, or the force turned round each time the speed crossed zero and the vehicle never + // came to rest, the air brake being off + scenario scenario{"dynamic brake/diesel electric/br285 no fade", motion() + traction() + brakes() + dynamic_brake()}; + scenario.train().add(definition::fiz("br285_v1/br285").set("Engine", "EDBrake", "Controller").set("Engine", "EDBrakeFmax", 150), 1); + auto &locomotive{scenario.cab()}; + REQUIRE(locomotive.DEDynamicBrake.fade_low == doctest::Approx(0.0)); + REQUIRE(locomotive.DEDynamicBrake.fade_high == doctest::Approx(0.0)); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(30.0); + REQUIRE(locomotive.Vel > 10.0); + + scenario.act("EB+ to the stop"); + controller_to(locomotive, 0); + for (int i = 0; i < 120 && locomotive.V != 0.0; ++i) { + scenario.wait(1.0); + } + CHECK(locomotive.BrakePress < 0.1); + // at rest, and staying there: no speed either way, no force + for (int i = 0; i < 5; ++i) { + scenario.wait(1.0); + CHECK(locomotive.V == 0.0); + CHECK(locomotive.Ft == doctest::Approx(0.0)); + } + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); + scenario.check(); +} From 68c704e51338d361915d1850011602fc0159d72b Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 10:00:49 +0100 Subject: [PATCH 058/136] fix(config): a scenery switches a script runtime off as before, only switching it on is refused keep() put python.enabled, luascreens.enabled, wasm.enabled and lua.fulllibraries back in either direction, so a scenery with config python.enabled no endconfig, which the release honoured, was overridden and got an error in the log. They are put back now only when the scenery turned them on; switched off they stay so, silently. --- script_screens_doc.md | 5 +-- tests/unit/test_ini_only_settings.cpp | 49 +++++++++++++++++++++------ utilities/inionlysettings.cpp | 20 ++++++++--- utilities/inionlysettings.h | 3 +- 4 files changed, 59 insertions(+), 18 deletions(-) diff --git a/script_screens_doc.md b/script_screens_doc.md index 7ebf14caf..0be028952 100644 --- a/script_screens_doc.md +++ b/script_screens_doc.md @@ -264,7 +264,8 @@ again: |---------------------|---------|------------------------------------------------------------------------------------------| | `lua.fulllibraries` | no | yes: the scenery scripts get all of LuaJIT's libraries (`io`, `os`, `ffi`, `require`...), and with them the files and programs of the computer. The Lua screens stay sandboxed | -Only `eu07.ini` sets it: a `config` block of a scenery doesn't (the log says the key was ignored). Nor does it set +Only `eu07.ini` turns it on: a `config` block of a scenery doesn't (the log says the key was ignored). Nor does it set the other keys that would take a scenery out of its sandbox or reach the computer: `execonexit`, `extcam.cmd`, `extcam.rec`, `screenshotsdir`, `network.server`, `network.client`, `zmq.address`, `motiontelemetry`, `uart`, -`feedbackmode`, `feedbackport`, `python.enabled`, `luascreens.enabled` and `wasm.enabled`. +`feedbackmode`, `feedbackport`, nor does it switch on `python.enabled`, `luascreens.enabled` or `wasm.enabled` when +`eu07.ini` has them off. A scenery may still switch those three off, or `lua.fulllibraries` off, as it always could. diff --git a/tests/unit/test_ini_only_settings.cpp b/tests/unit/test_ini_only_settings.cpp index 8ae73fe43..f90e9b2f9 100644 --- a/tests/unit/test_ini_only_settings.cpp +++ b/tests/unit/test_ini_only_settings.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include namespace { @@ -32,17 +33,43 @@ TEST_CASE("ini only settings: a scenery's config block doesn't give its scripts CHECK(changed == std::vector{"lua.fulllibraries"}); } -TEST_CASE("ini only settings: what eu07.ini turned on stays on") { - auto const settings{std::make_unique()}; - settings->lua_fulllibraries = true; - settings->python_enabled = false; - ini_only_settings const ini{*settings}; - settings->lua_fulllibraries = false; - settings->python_enabled = true; - auto const changed{ini.restore(*settings)}; - CHECK(settings->lua_fulllibraries); - CHECK_FALSE(settings->python_enabled); - CHECK(changed.size() == 2); +TEST_CASE("ini only settings: a scenery switches a runtime off, but not on") { + auto const python{[](global_settings &Settings) -> bool & { return Settings.python_enabled; }}; + auto const luascreens{[](global_settings &Settings) -> bool & { return Settings.luascreens_enabled; }}; + auto const wasm{[](global_settings &Settings) -> bool & { return Settings.wasm_enabled; }}; + auto const fulllibraries{[](global_settings &Settings) -> bool & { return Settings.lua_fulllibraries; }}; + using setting = bool &(*)(global_settings &); + for (auto const &[key, switched] : {std::pair{"python.enabled", python}, {"luascreens.enabled", luascreens}, + {"wasm.enabled", wasm}, {"lua.fulllibraries", fulllibraries}}) { + CAPTURE(key); + { + // on in eu07.ini, off in the scenery: off, and nothing in the log + auto const settings{std::make_unique()}; + switched(*settings) = true; + ini_only_settings const ini{*settings}; + // "config python.enabled no endconfig" in the .scn, as the release honoured it + switched(*settings) = false; + CHECK(ini.restore(*settings).empty()); + CHECK_FALSE(switched(*settings)); + } + { + // off in eu07.ini, on in the scenery: back off, and told + auto const settings{std::make_unique()}; + switched(*settings) = false; + ini_only_settings const ini{*settings}; + switched(*settings) = true; + CHECK(ini.restore(*settings) == std::vector{key}); + CHECK_FALSE(switched(*settings)); + } + // as eu07.ini set it: kept, nothing told + for (auto const value : {false, true}) { + auto const settings{std::make_unique()}; + switched(*settings) = value; + ini_only_settings const ini{*settings}; + CHECK(ini.restore(*settings).empty()); + CHECK(switched(*settings) == value); + } + } } TEST_CASE("ini only settings: a scenery runs no program, opens no connection and switches no runtime back on") { diff --git a/utilities/inionlysettings.cpp b/utilities/inionlysettings.cpp index 836954bf1..9d6c587c2 100644 --- a/utilities/inionlysettings.cpp +++ b/utilities/inionlysettings.cpp @@ -23,6 +23,17 @@ template void keep(Type_ &Current, Type_ const &Kept, std::stri } } +// a switch a scenery may turn off but not on: puts Kept back into Current, and adds Key to Changed, only when the +// scenery turned it on. turned off it stays so, as before these keys were kept +void keep_off(bool &Current, bool const Kept, std::string_view const Key, std::vector &Changed) +{ + if (Current && false == Kept) + { + Current = false; + Changed.push_back(Key); + } +} + } // namespace ini_only_settings::ini_only_settings(global_settings const &Settings) @@ -74,9 +85,10 @@ std::vector ini_only_settings::restore(global_settings &Settin #endif keep(Settings.iFeedbackMode, m_feedback_mode, "feedbackmode", changed); keep(Settings.iFeedbackPort, m_feedback_port, "feedbackport", changed); - keep(Settings.python_enabled, m_python_enabled, "python.enabled", changed); - keep(Settings.luascreens_enabled, m_luascreens_enabled, "luascreens.enabled", changed); - keep(Settings.lua_fulllibraries, m_lua_fulllibraries, "lua.fulllibraries", changed); - keep(Settings.wasm_enabled, m_wasm_enabled, "wasm.enabled", changed); + // a scenery may switch a runtime off, and keep its scripts in the sandbox + keep_off(Settings.python_enabled, m_python_enabled, "python.enabled", changed); + keep_off(Settings.luascreens_enabled, m_luascreens_enabled, "luascreens.enabled", changed); + keep_off(Settings.lua_fulllibraries, m_lua_fulllibraries, "lua.fulllibraries", changed); + keep_off(Settings.wasm_enabled, m_wasm_enabled, "wasm.enabled", changed); return changed; } diff --git a/utilities/inionlysettings.h b/utilities/inionlysettings.h index eff5c067f..667703b94 100644 --- a/utilities/inionlysettings.h +++ b/utilities/inionlysettings.h @@ -22,7 +22,8 @@ http://mozilla.org/MPL/2.0/. // (execonexit, extcam.cmd, extcam.rec), write the screenshots elsewhere (screenshotsdir), open connections and ports // (network.server, network.client, zmq.address, motiontelemetry, uart, feedbackmode, feedbackport), switch back on a // script runtime the player switched off (python.enabled, luascreens.enabled, wasm.enabled) or take its own scripts -// out of the sandbox (lua.fulllibraries). they keep what eu07.ini set +// out of the sandbox (lua.fulllibraries). they keep what eu07.ini set; a scenery may still switch a runtime off, or +// keep its scripts in the sandbox when eu07.ini didn't, as it always could class ini_only_settings { public: From aa2200418a2f5f8b33c33db99e167e4ca374a9ca Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 10:06:41 +0100 Subject: [PATCH 059/136] fix(doors): an animdoor entry without its } leaves the rest of the .mmd to be read read_spec() took every token up to the end of the file into the block when the closing brace was missing, so endmodels, sounds:, the lights and the rest were lost. The block now ends at the first token that is neither a key nor the value right after one (or at endmodels), and that token is put back for the caller. --- tests/unit/test_door_wings.cpp | 38 +++++++++++++++++++++++++++++++++- vehicle/doorwings.h | 17 ++++++++++++++- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/tests/unit/test_door_wings.cpp b/tests/unit/test_door_wings.cpp index e049d6c61..9eff62441 100644 --- a/tests/unit/test_door_wings.cpp +++ b/tests/unit/test_door_wings.cpp @@ -125,11 +125,47 @@ TEST_CASE("door wings: a faulty animdoor entry says what is wrong with it") { CHECK(read("3 { type: Roll range: 0.65 }", spec) == "unknown door type \"Roll\""); CHECK(read("3 { type: Shift range: 0,65 }", spec) == "bad number \"0,65\" for \"range:\""); CHECK(read("3 { type: Shift range: wide }", spec) == "bad number \"wide\" for \"range:\""); - CHECK(read("3 { kind: Shift }", spec) == "unknown key \"kind:\""); + CHECK(read("3 { kind: Shift }", spec) == "no } after the keys, \"kind:\" is none of them"); CHECK(read("3 { type: Shift range: }", spec) == "no value for \"range:\""); CHECK(read("3 { type: Shift range: 0.65", spec) == "no } after the keys"); } +TEST_CASE("door wings: an animdoor entry without its } leaves the entries after it to the .mmd") { + // the first token that is neither a key nor the value of one ends the entry, and is read next by the caller + auto const next{[](std::string const &Text) { + door_wings::wing_spec spec{fizdoors}; + cParser parser(Text, cParser::buffer_TEXT); + auto const error{door_wings::read_spec(parser, spec)}; + std::vector rest; + std::string token; + do { + token.clear(); + parser.getTokens(1, false); + parser >> token; + if (false == token.empty()) { + rest.emplace_back(token); + } + } while (false == token.empty()); + return std::pair{error, rest}; + }}; + { + auto const [error, rest]{next("3 { type: Plug range: 0.9\nsounds: horn.wav\nlights: 1\nendmodels")}; + CHECK(error == "no } after the keys, \"sounds:\" is none of them"); + CHECK(rest == std::vector{"sounds:", "horn.wav", "lights:", "1", "endmodels"}); + } + { + auto const [error, rest]{next("3 { type: Plug range: endmodels")}; + CHECK(error == "no } after the keys, \"endmodels\" is none of them"); + CHECK(rest == std::vector{"endmodels"}); + } + { + // a whole entry leaves the rest as it is + auto const [error, rest]{next("3 { type: Plug range: 0.9 } sounds: horn.wav endmodels")}; + CHECK(error.empty()); + CHECK(rest == std::vector{"sounds:", "horn.wav", "endmodels"}); + } +} + TEST_CASE("door wings: the parsed keys go into the spec, pairs of a key and its value") { door_wings::wing_spec spec{fizdoors}; CHECK(door_wings::parse_spec({"type:", "Shift", "range:", "0.65"}, spec).empty()); diff --git a/vehicle/doorwings.h b/vehicle/doorwings.h index 1266dafec..db05b03fc 100644 --- a/vehicle/doorwings.h +++ b/vehicle/doorwings.h @@ -137,8 +137,17 @@ inline std::string parse_spec(std::vector const &Tokens, wing_spec return {}; } +// whether the token is one of the keys of an animdoor block, in any letter case +inline bool is_spec_key(std::string const &Token) { + std::string key{Token}; + std::transform(key.begin(), key.end(), key.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + return key == "type:" || key == "range:" || key == "rangeout:"; +} + // reads an animdoor entry after its key: the wing number and the block in braces, into the spec filled with the values -// of the .fiz. returns what is wrong with the entry, or an empty text when nothing is. the parser is a cParser +// of the .fiz. returns what is wrong with the entry, or an empty text when nothing is. the parser is a cParser. a block +// without its } ends at the first token that is neither a key nor the value right after one (or at endmodels): that +// token is left for the caller, so the entries after a faulty one are read as ever template std::string read_spec(Parser_ &Parser, wing_spec &Spec) { Parser.getTokens(1, false); @@ -150,6 +159,7 @@ std::string read_spec(Parser_ &Parser, wing_spec &Spec) { return "no { after the wing number"; } std::vector block; + auto value{false}; // the token is the value of the key before it while (true) { token.clear(); Parser.getTokens(1, false); @@ -160,6 +170,11 @@ std::string read_spec(Parser_ &Parser, wing_spec &Spec) { if (token == "}") { break; } + if (token == "endmodels" || (false == value && false == is_spec_key(token))) { + Parser.injectString(token); + return "no } after the keys, \"" + token + "\" is none of them"; + } + value = false == value; block.emplace_back(token); } return parse_spec(block, Spec); From 0bd805fb19722e6e98574a9e4791b3b56140ef3e Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 13:01:32 +0100 Subject: [PATCH 060/136] docs: scenario README, a Connect first order releases the hand brake now --- tests/scenarios/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index b6eab8326..7ab7646e7 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -290,9 +290,9 @@ into the game dir. What they add to the scenery: A train whose trainset has velocity 0 has a driver that sleeps in `Wait_for_orders` when nobody is in the cab: the player would drive it, so the fragment has to give the orders the player's hands stand for, with `PutValues` from an event the vehicle itself sets off (`event0` of the -track it stands on). The first of them must not be the one to couple (`Shunt -2 -3`): a driver -whose first order is `Connect` never releases the hand brake a cold locomotive starts with. The -mission trains of velocity 0.1 wait for their signal and need nothing. +track it stands on). The first of them may be the one to couple (`Shunt -2 -3`): a driver whose +first order is `Connect` releases the hand brake a cold locomotive starts with +(`eu07_td_cold_connect`). The mission trains of velocity 0.1 wait for their signal and need nothing. The cases and what they showed on master of 2026-11-11: From f90005e649ab4c44c07e1f8c7ca8ef07e16b3c86 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 17 Nov 2026 17:36:15 +0100 Subject: [PATCH 061/136] fix(physics): a legacy derailment makes no crash inside its own train With physics.collisions new and the legacy derailment (the default physics.derailment monitor), a vehicle derailed the old way manufactured collisions with the vehicles coupled to it: - Derail() cuts its speed by 35 % in one step; the coupled vehicles kept theirs and ran into it at a third of the speed of the train (moczniki_eu06_eu07, tomaszewo_raj49843). The vehicles coupled to it now get the same change of velocity. - crush_hit() took it as an immovable wall and its motion ignored every force (decelerating at g, then stuck by resistances x1e20), so the train behind it stopped against it at once and crushed by the energy of the whole train (l053-sluzba-2-night: 0.3 m on both ends at 8 km/h). It is now a wall only to vehicles not coupled to it; it keeps the legacy deceleration of g as a friction of its weight, and the forces of its train act on it, so the train pushes it on and it holds the train back. Alone it stops as before. - Vehicles of the pile-up found inside each other kept what their springs took in pressed past the stop as buffer energy, which let a later small closing velocity crush them; a pair parting at the start of the step and knocked back in during it was crushed with the springs added to its closing velocity (l053_calkowo-sluzba-tlk-1, linia61_osobowy3: crush at -7.1 km/h). The contact found inside each other takes in nothing until the buffers part, and a pair parting at the start of the step is left to the legacy collision. The monitor test of a locomotive into a wagon at 60 km/h now counts one hit: the second one was the locomotive resting on the legacy wall, parting at the start of the step, at 0.3 km/h. --- McZapkie/MOVER.h | 6 +- McZapkie/Mover.cpp | 93 +++++++++++++-- McZapkie/collision.cpp | 10 +- McZapkie/collision.h | 8 +- tests/unit/test_collisions.cpp | 202 ++++++++++++++++++++++++++++++++- tests/unit/vehicle.cpp | 4 +- tests/unit/vehicle.h | 4 + 7 files changed, 307 insertions(+), 20 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index ba0a76951..ab1ae9dba 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2463,6 +2463,9 @@ class TMoverParameters // was a broken coupler to repair bool repair_coupler(int const End); void Derail(DerailReason Reason); + // the velocity of the vehicles coupled to this one changes by the Change along the axis of this one [m/s], as the + // legacy derailment changes the velocity of this one (physics.collisions new) + void change_train_velocity(double Change); // physics.derailment new: the criteria of derailment.h over the step, which travelled the Distance [m]; monitor: what // they would do, to the log void check_derailment(TTrackShape const &Shape, TTrackParam const &Track, double Distance); @@ -2476,7 +2479,8 @@ class TMoverParameters // what resetconsist does to a vehicle: no damage of any kind, the alarm chain released, back on the rails void repair_damage(); // how the vehicle left the rails by the criteria of derailment.h: upright, or on its side. none for any other - // derailment, which stops it as the legacy model does + // derailment, which stops it as the legacy model does (with physics.collisions new by a friction of its weight, the + // forces of the vehicles coupled to it acting on it) derailment::outcome Derailed{derailment::outcome::none}; // physics.collisions new: what the vehicle is for the defaults of its crush and its buffers, the crush curve and the // height of the buffers of an end, and how long the push of its ends held its wheels over the climbing limit diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 3ce03219d..48543c7f4 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -69,6 +69,21 @@ int DirPatch(int Coupler1, int Coupler2) return Coupler1 != Coupler2 ? 1 : -1; } +namespace +{ + +// physics.collisions new: a rail vehicle derailed the legacy way keeps the deceleration of the legacy model, g, as the +// friction of its weight, and the forces of the vehicles coupled to it act on it as on any other: the train behind it +// pushes it on, and it holds the train back. alone it stops as the legacy model has it. the legacy model stops it +// whatever pushes it, and the train behind it stopped at once against it, in a hit no train had +bool legacy_derailed_slides(TMoverParameters const &Vehicle) +{ + return Global.collisions == global_settings::collision_model::physical && TestFlag(Vehicle.CategoryFlag, 1) && TestFlag(Vehicle.DamageFlag, dtrain_out) && + Vehicle.Derailed == derailment::outcome::none; +} + +} // namespace + int DirF(int CouplerN) { switch (CouplerN) @@ -1423,8 +1438,12 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) // integration of the next step (ComputeMovement()) would carry a quarter of an acceleration spike over into the // velocity once more, and the vehicles would bounce off the stop faster than they hit it auto const accelerationspike{physical ? 0.0 : 1.0}; - // derailed the legacy way a vehicle is a wall, off the rails by the new criteria it slides on and takes the hit - auto const wall = [crushing](TMoverParameters const &Vehicle) { return TestFlag(Vehicle.DamageFlag, dtrain_out) && (false == crushing || Vehicle.Derailed == derailment::outcome::none); }; + // derailed the legacy way a vehicle is a wall, off the rails by the new criteria it slides on and takes the hit. with + // the crush, the vehicles coupled to the wall push it on (crush_hit()) + auto const coupled{thiscoupler.CouplingFlag != coupling::faux}; + auto const wall = [crushing, coupled](TMoverParameters const &Vehicle) { + return TestFlag(Vehicle.DamageFlag, dtrain_out) && (false == crushing || (Vehicle.Derailed == derailment::outcome::none && false == coupled)); + }; if (false == wall(*this)) { auto const accelerationchange{(velocity - V) / dt}; @@ -1604,6 +1623,9 @@ bool TMoverParameters::crush_hit(int const End, double const dt) auto const overlap{-static_cast(Neighbours[End].distance)}; if (overlap > stop + collision::inside_margin + closing * dt) { + // nor is what their springs took in pressed past the stop and back a hit, for as long as the buffers touch + thiscoupler.contact.inside(); + othercoupler.contact.inside(); if (false == thiscoupler.inside_reported) { thiscoupler.inside_reported = true; @@ -1612,9 +1634,19 @@ bool TMoverParameters::crush_hit(int const End, double const dt) } return false; } - // a vehicle derailed the legacy way (the end of the track, say) stays where it is, whatever hits it - auto const wall{TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none}; - auto const otherwall{TestFlag(othervehicle->DamageFlag, dtrain_out) && othervehicle->Derailed == derailment::outcome::none}; + // parting at the start of the step: what closes the pair in now is the knock of a hit of either vehicle in the step, + // or of the vehicles inside each other next to it, not a hit of this pair. the legacy collision takes it; a pair + // still closing in at the start of the next step is a hit + if (thiscoupler.closing < 0.0) + { + return false; + } + // a vehicle derailed the legacy way (the end of the track, say) stays where it is, whatever hits it from outside its + // train. the vehicles coupled to it push it on, as the train behind a derailed vehicle does: a wall to them, it + // stopped the whole train at once, and the vehicles behind it crushed by the energy of the train + auto const coupled{thiscoupler.CouplingFlag != coupling::faux}; + auto const wall{false == coupled && TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none}; + auto const otherwall{false == coupled && TestFlag(othervehicle->DamageFlag, dtrain_out) && othervehicle->Derailed == derailment::outcome::none}; if (wall && otherwall) { return false; @@ -2031,8 +2063,16 @@ void TMoverParameters::Derail(DerailReason const Reason) EventFlag = true; MainSwitch(false, range_t::local); + auto const velocity{V}; AccS *= 0.65; V *= 0.65; + // physics.collisions new: the vehicles coupled to it lose the speed with it. the cut in a step stands for the + // train coming to a stop with the vehicle; the coupled ones keeping their speed would run into it at a third of + // the speed of the train, and crush their ends and ride up onto it for a hit no train had + if (Global.collisions == global_settings::collision_model::physical && TestFlag(CategoryFlag, 1)) + { + change_train_velocity(V - velocity); + } RunningShape.R = 0; if (Vel < 5.0) { @@ -2057,6 +2097,28 @@ void TMoverParameters::Derail(DerailReason const Reason) } } +void TMoverParameters::change_train_velocity(double const Change) +{ + // the vehicles coupled to this one in a line, each with the direction of its axis to the axis of this one + std::vector> train{{this, 1}}; + for (std::size_t i = 0; i < train.size(); ++i) + { + auto const [vehicle, direction] = train[i]; + for (int end = end::front; end <= end::rear; ++end) + { + auto const &coupler{vehicle->Couplers[end]}; + auto *other{coupler.Connected}; + if (other == nullptr || coupler.CouplingFlag == coupling::faux || std::any_of(train.begin(), train.end(), [other](auto const &Entry) { return Entry.first == other; })) + { + continue; + } + auto const otherdirection{direction * DirPatch(end, coupler.ConnectedNr)}; + other->V += Change * otherdirection; + train.emplace_back(other, otherdirection); + } + } +} + // ************************************************************************************************* // Oblicza przemieszczenie taboru // ************************************************************************************************* @@ -2099,11 +2161,12 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap AccS = std::lerp(AccSprev, FTotal / TotalMass, 0.5); // std::clamp( dt * 3.0, 0.0, 1.0 ) ); // prawo Newtona ale z wygladzaniem (średnia z poprzednim) - // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce() - if (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none) + // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce(), and so does one + // derailed the legacy way with physics.collisions new + if (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this)) AccS = -Sign(V) * g * 1; // random(0.0, 0.1) // stuck in the ballast: the friction holds a derailed vehicle once it stopped, until the forces on it are larger - auto const stuck{Derailed != derailment::outcome::none && V == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; + auto const stuck{(Derailed != derailment::outcome::none || legacy_derailed_slides(*this)) && V == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; if (stuck) AccS = 0.0; @@ -2212,9 +2275,9 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh AccS = std::lerp(AccSprev, FTotal / TotalMass, 0.5); // std::clamp( dt * 3.0, 0.0, 1.0 ) ); // prawo Newtona ale z wygladzaniem (średnia z poprzednim) - if (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none) + if (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this)) AccS = -Sign(V) * g * 1; // * random(0.0, 0.1) - auto const stuck{Derailed != derailment::outcome::none && V == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; + auto const stuck{(Derailed != derailment::outcome::none || legacy_derailed_slides(*this)) && V == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; if (stuck) AccS = 0.0; @@ -2237,8 +2300,9 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh // simple mode skips calculation of vertical acceleration AccVert = 0.0; - // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce() - if (true == TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none && Vel < 1.0) + // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce(), and so does one + // derailed the legacy way with physics.collisions new + if (true == TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this) && Vel < 1.0) { V = 0.0; AccS = 0.0; @@ -5803,6 +5867,11 @@ void TMoverParameters::ComputeTotalForce(double dt) // off the rails by the physical criteria: the vehicle slides on the sleepers and the ballast, or on its side FStand = derailment::sliding_friction(Derailed) * (TotalMass - Mred) * g; } + else if (legacy_derailed_slides(*this)) + { + // derailed the legacy way with physics.collisions new: the deceleration of g of the legacy model, as a friction + FStand = TotalMass * g; + } else { // HACK: crude way to reduce speed after derailment diff --git a/McZapkie/collision.cpp b/McZapkie/collision.cpp index ef3874b93..2fb085e69 100644 --- a/McZapkie/collision.cpp +++ b/McZapkie/collision.cpp @@ -171,8 +171,8 @@ void contact_energy::update(bool const Pressed, bool const Solid, double const C reset(); return; } - if (Solid) { - // pressed all the way, the buffers take in nothing more + if (Solid || m_inside) { + // pressed all the way, the buffers take in nothing more; nor do those of vehicles inside each other return; } auto const force{std::max(Force, 0.0)}; @@ -185,6 +185,11 @@ void contact_energy::update(bool const Pressed, bool const Solid, double const C } } +void contact_energy::inside() { + m_absorbed = 0.0; + m_inside = true; +} + void contact_energy::crushed(double const Work) { m_crushed += std::max(Work, 0.0); } @@ -199,6 +204,7 @@ double contact_energy::budget(double const Mass, double const Closing, double co void contact_energy::reset() { m_absorbed = 0.0; m_crushed = 0.0; + m_inside = false; } hit_result hit(end_state const &First, end_state const &Second, hit_input const &Input) { diff --git a/McZapkie/collision.h b/McZapkie/collision.h index fb719315d..01239a3cd 100644 --- a/McZapkie/collision.h +++ b/McZapkie/collision.h @@ -136,12 +136,17 @@ inline constexpr double inside_margin{0.5}; // buffers pressed and the pair closing in. springing back they keep what they still hold, so a train pushing at a // stand never builds up what it feeds into their damping. the buffers pressed all the way from the start of the // contact took in nothing: vehicles put down inside each other, or knocked onto each other by a hit elsewhere, bring -// in only the kinetic energy they close in with +// in only the kinetic energy they close in with. nor do the buffers of vehicles found inside each other in the +// contact (inside_margin) take in anything until they part: their springs pressed past the stop and back throw the +// pair about, which is no hit class contact_energy { public: // the step of the pair: whether its buffers press, and all the way; the closing velocity [m/s] and the force // pressing the buffers [N] at the start of the step; how far they're pressed in [m]; the length of the step [s] void update(bool Pressed, bool Solid, double Closing, double Force, double Compression, double Dt); + // the vehicles of the pair are inside each other: what the buffers took in is gone, and they take in nothing more + // until the contact is over + void inside(); // the crush of the hit took the energy [J] void crushed(double Work); // the energy the crush may take now, closing in at the velocity [m/s] with the reduced mass [kg], the buffers of @@ -155,6 +160,7 @@ public: private: double m_absorbed{0.0}; double m_crushed{0.0}; + bool m_inside{false}; }; // ---- the hit past the buffers diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index 3dead8771..6aee28e98 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -748,10 +748,11 @@ TEST_CASE("collisions: the legacy rule with physics.collisions old, the crush wi }; // the legacy rule: over 15 km/h weighed by the ratio of the masses. the crush: the light wagon is crushed deep and // climbs onto the locomotive at 60 km/h; two locomotives at 25 km/h crush their ends 0.1-0.3 m and stay on the rails - // the monitor tells of each hit once: the wagon derailed by the legacy rule is a wall, which the locomotive behind - // it hits once more; the locomotives derailed both stay where they are + // the monitor tells of each hit once: the wagon derailed by the legacy rule is a wall the locomotive presses on into + // until it springs back, the same hit (the wall slowing down took the pair from parting at the start of a step to + // closing in at 0.3 km/h, which was told of as a second hit); the locomotives derailed both stay where they are for (auto const &[name, front, back, speed, frontout_old, backout_old, frontout_new, backout_new, monitored] : { - collision{"locomotive into a wagon at 60", "3wl_v2/3wl", "4e_v1/4e", 60.0, true, false, true, false, 2}, + collision{"locomotive into a wagon at 60", "3wl_v2/3wl", "4e_v1/4e", 60.0, true, false, true, false, 1}, collision{"locomotive into a locomotive at 25", "4e_v1/4e", "4e_v1/4e", 25.0, true, true, false, false, 1}, collision{"locomotive into a locomotive at 50", "4e_v1/4e", "4e_v1/4e", 50.0, true, true, true, true, 1}, }) { @@ -1308,3 +1309,198 @@ TEST_CASE("collisions: the monitor goes by the energy of the hit as well") { train.run(10.0); CHECK(train[0]->crush_reports + train[1]->crush_reports == 1); } + +// ---- the legacy derailment (physics.derailment old or monitor) in a train, with physics.collisions new + +namespace { + +// what the vehicles of the train did to each other +struct train_damage { + double crush{0.0}; // the deepest crush of an end [m] + double energy{0.0}; // the crush of all the ends took [J] + int derailed{0}; // in a collision + int broken{0}; // couplings torn off + std::string list; // which vehicle, for the messages +}; + +train_damage damage_of(consist &Train) { + train_damage result; + for (std::size_t i = 0; i < Train.size(); ++i) { + auto const &vehicle{Train[i].mover()}; + result.crush = std::max(result.crush, crush_of(vehicle)); + for (auto const end : {end::front, end::rear}) { + result.energy += vehicle.crush_curve_at(end).energy(0.0, vehicle.Couplers[end].crush); + } + result.derailed += vehicle.CollisionDerail != NONE; + if (i + 1 < Train.size()) { + result.broken += vehicle.Couplers[end::rear].broken; + } + if (crush_of(vehicle) > 0.0 || vehicle.CollisionDerail != NONE) { + result.list += std::format("{} crushed {:.2f} m{}; ", i, crush_of(vehicle), vehicle.CollisionDerail != NONE ? ", derailed" : ""); + } + } + return result; +} + +// the kinetic energy of the vehicles of the train [J] +double kinetic_of(consist &Train) { + auto energy{0.0}; + for (std::size_t i = 0; i < Train.size(); ++i) { + energy += 0.5 * Train[i]->TotalMass * Train[i]->V * Train[i]->V; + } + return energy; +} + +} // namespace + +TEST_CASE("collisions: the cut of the speed of the legacy derailment is no hit inside the train (moczniki_eu06_eu07, tomaszewo_raj49843)") { + // the legacy derailment takes 35 % of the speed of the vehicle off in a step: the coaches coupled behind it, at the + // speed they had, ran into it at a third of the speed of the train, crushed their ends and rode up onto it + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const physics : {false, true}) { + CAPTURE(physics); + flag_setting const couplerphysics{Global.coupler_physics, physics}; + flag_setting const everywhere{Global.coupler_physics_all, physics}; + // an SU46 with its coaches at 95 km/h, as in moczniki_eu06_eu07; an electric locomotive at 48 km/h, as in + // tomaszewo_raj49843 + for (auto const &[path, speed] : {std::pair{"su46_v2/303d", 95.0}, std::pair{"4e_v1/4e", 48.0}}) { + CAPTURE(path); + // too fast in a curve, the draw in the movement of the vehicle; off the end of the track, in its next step + for (auto const reason : {TOO_HIGH_SPEED, END_OF_TRACK}) { + CAPTURE(reason); + consist train; + auto &locomotive{train.add(definition::fiz(path), 0, coupling::faux, speed)}; + for (int i = 0; i < 3; ++i) { + train.add(coach(41.0e3), 0, consist::full_coupling, speed); + } + train.run(2.0); + if (reason == END_OF_TRACK) { + locomotive.damage_track(dtrack_norail); + } + else { + locomotive->Derail(reason); + } + train.step(); + REQUIRE(derailed(locomotive.mover())); + // the train loses the speed with it + for (std::size_t i = 1; i < train.size(); ++i) { + CAPTURE(i); + CHECK(train[i].speed() == doctest::Approx(locomotive.speed()).epsilon(0.03)); + } + train.run(15.0); + auto const damage{damage_of(train)}; + INFO(damage.list); + CHECK(damage.crush < cl::crush_mark); + CHECK(damage.derailed == 0); + CHECK(damage.broken == 0); + } + } + } +} + +TEST_CASE("collisions: the train behind a vehicle that ran off the end of the track doesn't crush into it (l053-sluzba-2-night, l053_calkowo-sluzba-tlk-1, linia61_osobowy3)") { + // the vehicle derailed the legacy way at the end of the track stopped as a wall the train behind it ran into: the + // vehicles behind it pressed into each other past their stops, and crushed by more than the energy of the train + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const physics : {false, true}) { + CAPTURE(physics); + flag_setting const couplerphysics{Global.coupler_physics, physics}; + flag_setting const everywhere{Global.coupler_physics_all, physics}; + // pulled: an M62 leading wagons of 22 t at 30 km/h (l053_calkowo-sluzba-tlk-1, linia61_osobowy3); pushed: an SM42 + // at the back of wagons of 35 t at 33 km/h, the leading wagon goes off (l053-sluzba-2-night) + for (auto const pushed : {false, true}) { + CAPTURE(pushed); + auto const speed{pushed ? 33.0 : 30.0}; + consist train; + if (false == pushed) { + train.add(definition::fiz("st44_v2/m62-1151"), 0, coupling::faux, speed); + } + constexpr int wagons{6}; + for (int i = 0; i < wagons; ++i) { + auto &wagon{train.add(definition::fiz("430w_v2/430w"), 0, consist::full_coupling, speed)}; + if (pushed) { + wagon->AssignLoad("coal", 12.0f); + wagon->ComputeMass(); + } + } + if (pushed) { + train.add(definition::fiz("sm42_v1/6d1"), 0, consist::full_coupling, speed); + } + train.run(2.0); + auto const kinetic{kinetic_of(train)}; + train[0].damage_track(dtrack_norail); + train.run(20.0); + REQUIRE(derailed(train[0].mover())); + auto const damage{damage_of(train)}; + INFO(damage.list); + MESSAGE(std::format("{}: crush {:.3f} m, {:.0f} kJ of the {:.0f} kJ of the train", pushed ? "pushed" : "pulled", damage.crush, damage.energy / 1000.0, kinetic / 1000.0)); + CHECK(damage.crush < cl::crush_mark); + CHECK(damage.energy <= kinetic); + CHECK(damage.derailed == 0); + CHECK(damage.broken == 0); + for (std::size_t i = 1; i < train.size(); ++i) { + CAPTURE(i); + CHECK_FALSE(derailed(train[i].mover())); + } + } + } +} + +TEST_CASE("collisions: the buffers of vehicles found inside each other take in nothing for the budget of the crush") { + cl::contact_energy contact; + // pressed in at 2 m/s under 1 MN for 0.1 s: 200 kJ, past the 120 kJ the buffers of both ends take + contact.update(true, false, 2.0, 1.0e6, 0.1, 0.1); + REQUIRE(contact.absorbed() == doctest::Approx(200.0e3)); + CHECK(contact.budget(11.0e3, 1.7, 120.0e3) > 0.0); + // found inside each other: what their springs made of it is no hit (l053_calkowo-sluzba-tlk-1: 163 kJ "in the + // buffers" let a pair crush with 15 kJ of motion) + contact.inside(); + CHECK(contact.absorbed() == 0.0); + contact.update(true, false, 2.0, 1.0e6, 0.1, 0.1); + CHECK(contact.absorbed() == 0.0); + CHECK(contact.budget(11.0e3, 1.7, 120.0e3) < 0.0); + // the buffers apart, the next contact is a hit again + contact.update(false, false, 0.0, 0.0, 0.0, 0.01); + contact.update(true, false, 2.0, 1.0e6, 0.1, 0.1); + CHECK(contact.absorbed() == doctest::Approx(200.0e3)); +} + +TEST_CASE("collisions: a pair parting at the start of the step isn't crushed (l053_calkowo-sluzba-tlk-1, linia61_osobowy3)") { + // the log had "closing at -7.1 km/h at the start of the step" on a crush of a pair knocked back onto each other in + // the step: the legacy collision takes such a knock, a pair still closing in at the start of a step is a hit + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const parting : {true, false}) { + CAPTURE(parting); + consist train; + auto &front{train.add(definition::fiz("430w_v2/430w"))}; + // behind it with the buffers pressed to their stop, moving back away from it, or standing + auto &back{train.add(definition::fiz("430w_v2/430w"), 0, coupling::faux, parting ? -3.0 : 0.0, -0.3)}; + // one step, the way the consist steps it, with the vehicle behind knocked forwards onto the front one between + // the forces and the movement, as a hit of another vehicle in the step does + constexpr double dt{0.01}; + for (auto *vehicle : {&front, &back}) { + vehicle->begin_step(); + } + for (auto *vehicle : {&front, &back}) { + vehicle->forces(dt); + } + REQUIRE((front->Couplers[end::rear].closing < 0.0) == parting); + back->V = 25.0 * kmh; + for (auto *vehicle : {&front, &back}) { + vehicle->move({}, dt, (*vehicle)->Loc, 5.0); + } + auto const crush{front->Couplers[end::rear].crush + back->Couplers[end::front].crush}; + if (parting) { + CHECK(crush == 0.0); + // the legacy collision pushed them apart + CHECK(back->V < 25.0 * kmh); + } + else { + // closing in from a stand, the knock is a hit past the energy of the buffers + CHECK(crush > 0.0); + } + } +} diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp index 61609d3ba..8872c6a6e 100644 --- a/tests/unit/vehicle.cpp +++ b/tests/unit/vehicle.cpp @@ -195,6 +195,7 @@ TTrackParam parameters_of(track const &Track, TMoverParameters const &Mover) { double vehicle::fast_move(track const &Track, double Dt, TLocation const &Location) { // TDynamicObject::FastUpdate(), the iterations of a frame before the last one auto param{parameters_of(Track, *m_mover)}; + param.DamageFlag = m_trackdamage; return m_mover->FastComputeMovement(Dt, shape_of(Track), param, Location, TRotation{0.0, 0.0, 0.0}); } @@ -217,7 +218,8 @@ void vehicle::forces(double Dt) { double vehicle::move(track const &Track, double Dt, TLocation const &Location, double Trainpipe) { auto const shape{shape_of(Track)}; - auto const param{parameters_of(Track, *m_mover)}; + auto param{parameters_of(Track, *m_mover)}; + param.DamageFlag = m_trackdamage; TRotation const rotation{0.0, 0.0, 0.0}; // what TDynamicObject::Update() does before the movement. a raised pantograph touches the wire at once, diff --git a/tests/unit/vehicle.h b/tests/unit/vehicle.h index 1e7db3599..05c03dbf6 100644 --- a/tests/unit/vehicle.h +++ b/tests/unit/vehicle.h @@ -92,6 +92,9 @@ public: // keeps the main reservoir at the given pressure [bar], as a running compressor or a coupled vehicle // feeding it would; a negative value leaves it alone void hold_main_reservoir(double Pressure) { m_reservoirpressure = Pressure; } + // the track under this vehicle alone has the damage flags (dtrack_*) from now on: dtrack_norail runs it off the + // end of the track in its next step, as the legacy derailment has it + void damage_track(int Flags) { m_trackdamage = Flags; } // advances the physics by one frame of Track.iterations steps of Dt, the way the simulation loop does void step(track const &Track = {}, double Dt = 0.01); @@ -116,6 +119,7 @@ private: int m_cab{0}; double m_pipepressure{-1.0}; double m_reservoirpressure{-1.0}; + int m_trackdamage{0}; trace *m_trace{nullptr}; double m_time{0.0}; // of the simulation, since the vehicle got created }; From f6e9075a73a780803386246d18f8482b09405f34 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 18 Nov 2026 19:29:25 +0100 Subject: [PATCH 062/136] fix(scripting): a %b counts the way it walks along the subject A %bxy at the end of a pattern (or before what always matches) was costed as one pass over the subject, but matchbalance walks to the end of the subject from every opening character nothing closes: ("("):rep(1e6):find("%b()") was let through and ran for hours in C, past the instruction hook. A %b now multiplies wherever it stands. With the subject at hand it counts the longest way from an opening character to its closing one, or, when it is tried once from each position, the ways from all of them over the positions: a long text of short balanced pairs stays cheap, one that doesn't balance is refused. --- scripting/scriptscreenrules.cpp | 87 ++++++++++++++++++++++++++ scripting/scriptscreenrules.h | 6 ++ tests/unit/test_script_screen_host.cpp | 8 ++- tests/unit/test_script_screens.cpp | 44 +++++++++++++ 4 files changed, 144 insertions(+), 1 deletion(-) diff --git a/scripting/scriptscreenrules.cpp b/scripting/scriptscreenrules.cpp index e8df2692e..5aa71cdd4 100644 --- a/scripting/scriptscreenrules.cpp +++ b/scripting/scriptscreenrules.cpp @@ -309,6 +309,84 @@ std::size_t longest_run(std::string_view const Pattern, pattern_item const &Item return longest; } +// the characters Lua's matchbalance goes along for a %bxy tried in the subject: from each opening character to the one +// that closes it, or to the end of the subject when nothing does +struct balance_walks +{ + double longest{0.0}; // of one try + double total{0.0}; // of a try at every opening character +}; + +// the openings held while their closing characters are looked for; a subject nested deeper counts as never closed +constexpr std::size_t max_balance_depth{65536}; + +balance_walks balance_walks_of(char const Open, char const Close, std::string_view const Subject) +{ + balance_walks walks; + auto const size{Subject.size()}; + auto const add{[&walks](std::size_t const Walk) { + walks.longest = std::max(walks.longest, static_cast(Walk)); + walks.total += static_cast(Walk); + }}; + if (Open == Close) + { + // the next one closes it, and opens the try that starts there + auto previous{Subject.find(Open)}; + while (previous != std::string_view::npos) + { + auto const next{Subject.find(Open, previous + 1)}; + add((next != std::string_view::npos ? next : size) - previous); + previous = next; + } + return walks; + } + std::vector open; + for (std::size_t idx{0}; idx < size; ++idx) + { + if (Subject[idx] == Close) + { + if (false == open.empty()) + { + add(idx - open.back()); + open.pop_back(); + } + } + else if (Subject[idx] == Open) + { + if (open.size() >= max_balance_depth) + { + auto const openings{static_cast(std::count(Subject.begin(), Subject.end(), Open))}; + return {static_cast(size), openings * static_cast(size)}; + } + open.push_back(idx); + } + } + for (auto const idx : open) + { + add(size - idx); + } + return walks; +} + +// how many times over a %bxy counts: it goes along the subject on its own, whatever follows it, so it counts where it +// ends the pattern as well. without the subject, as many times as the subject has positions. with it: the longest walk +// of one try (plus one); or, when nothing but captures is before it in a pattern tried from every position, each +// opening character is tried once, and it's the walks of all of them over the positions (plus one) +double balance_cost(std::string_view const Pattern, pattern_item const &Item, std::string_view const *Subject, double const Positions, bool const Once) +{ + if (Subject == nullptr) + { + return Positions; + } + if (Item.begin + 3 >= Pattern.size()) + { + // malformed: the function raises its error + return 1.0; + } + auto const walks{balance_walks_of(Pattern[Item.begin + 2], Pattern[Item.begin + 3], *Subject)}; + return Once ? 1.0 + walks.total / Positions : 1.0 + walks.longest; +} + double pattern_cost(std::string_view const Pattern, std::size_t const Size, std::string_view const *Subject, bool const Plain, bool const Anchorable) { auto const length{static_cast(std::max(Pattern.size(), 1))}; @@ -324,12 +402,21 @@ double pattern_cost(std::string_view const Pattern, std::size_t const Size, std: // from the end: what follows each item, and whether that's only the end of the subject auto rest{rest_match::always}; auto only_end{true}; + // the first item that isn't a capture: a %bxy there is tried once from each position + auto const first{std::find_if(items.begin(), items.end(), [](pattern_item const &Item) { return Item.type != pattern_item::kind::paren; })}; for (auto item{items.rbegin()}; item != items.rend(); ++item) { if (item->type == pattern_item::kind::single && item->quantifier == '?') { cost *= 2.0; } + if (item->type == pattern_item::kind::scan && Pattern[item->begin + 1] == 'b') + { + cost *= balance_cost(Pattern, *item, Subject, positions, false == anchored && first != items.end() && &*item == &*first); + only_end = false; + rest = rest_match::maybe; + continue; + } auto const repeated{item->type == pattern_item::kind::scan || (item->type == pattern_item::kind::single && item->quantifier != 0 && item->quantifier != '?')}; // a repetition followed by what always matches is tried once (as one that ends the pattern): past it the match diff --git a/scripting/scriptscreenrules.h b/scripting/scriptscreenrules.h index 889f7e9c3..bd751e50b 100644 --- a/scripting/scriptscreenrules.h +++ b/scripting/scriptscreenrules.h @@ -92,11 +92,17 @@ constexpr double max_pattern_cost{1e8}; // or '-' or a '?' of what always matches, '.*' / '.-' before '$'), where the match is over: so neither the last // repetition nor the first %s* of "^%s*(.-)%s*$" multiplies. times 2 for each '?', times m for the work of each step // (a set is gone through item by item) +// - a %bxy goes along the subject on its own, whatever follows it, so it counts where it ends the pattern as well: +// ("("):rep(1e6):find("%b()") walks to the end of the subject from each of its characters // a malformed pattern costs nothing here: the function raises its error itself double lua_pattern_cost(std::string_view Pattern, std::size_t Subject, bool Plain, bool Anchorable); // as above, on the subject itself: a repetition of a character or a %class right before the final '$' ("%s*$") counts // as many times as the longest run of it in the subject (plus one), not the whole subject: past that run it fails or // gets to the end, so the trim "^%s*(.-)%s*$" costs about the subject times its longest run of spaces +// a %bxy counts as many times as the longest way from an opening character to the one that closes it (to the end of +// the subject when nothing does), plus one; when only captures are before it in a pattern tried from every position, +// each opening character is tried once, and it's the ways from all of them over the positions of the subject. so +// "%b()" on a long text of short balanced pairs is cheap, and on one that doesn't balance it's the subject squared double lua_pattern_cost(std::string_view Pattern, std::string_view Subject, bool Plain, bool Anchorable); } // namespace script_screens diff --git a/tests/unit/test_script_screen_host.cpp b/tests/unit/test_script_screen_host.cpp index 7c7130f85..c4226da40 100644 --- a/tests/unit/test_script_screen_host.cpp +++ b/tests/unit/test_script_screen_host.cpp @@ -1171,6 +1171,11 @@ local slow = refused(string.find, long, ".-b") and refused(function() for x in long:gmatch("a-b") do end end) and refused(string.find, ("a"):rep(1000), "a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?aaaaaaaaaaaaaaaaaaaaaaaaaaaaaab") and refused(string.find, long, ("a"):rep(1000) .. "b", 1, true) +-- %b walks to the end of the subject from each opening character that nothing closes +local open = ("("):rep(1000000) +slow = slow and refused(string.find, open, '%b()') + and refused(string.gsub, open, '%b()', "") + and refused(function() for x in open:gmatch('%b()') do end end) -- what a screen does: lines of a file, fields of a line, a plain search, short subjects local text = ("key=value\n"):rep(10000) local lines = 0 @@ -1178,7 +1183,8 @@ for line in text:gmatch("[^\n]+") do lines = lines + 1 end local key, value = ("speed=120"):match("^(%w+)=(%d+)$") local spaced = select(2, (("a b c "):rep(100)):gsub("%s+", " ")) local found = long:find("aaab", 1, true) == nil and (long .. "b"):find("ab", 1, true) == 1000000 -local fast = lines == 10000 and key == "speed" and value == "120" and spaced == 300 and found +local calls = select(2, (("call(a, b) "):rep(10000)):gsub('%b()', "")) +local fast = lines == 10000 and key == "speed" and value == "120" and spaced == 300 and found and calls == 10000 and ("x = 1"):find("=") == 3 and ("abc"):gsub("b", "%0%0") == "abbc" return { render = function(state) diff --git a/tests/unit/test_script_screens.cpp b/tests/unit/test_script_screens.cpp index 59aa19560..af8678f2e 100644 --- a/tests/unit/test_script_screens.cpp +++ b/tests/unit/test_script_screens.cpp @@ -136,6 +136,10 @@ TEST_CASE("script screens: the steps a Lua pattern function may take at worst") CHECK(lua_pattern_cost("[^\n]+", 999, false, false) == doctest::Approx(1000.0 * 5)); CHECK(lua_pattern_cost("[%]x]*y", 999, false, true) == doctest::Approx(1000.0 * 1000 * 7)); CHECK(lua_pattern_cost("%bxyz", 999, false, true) == doctest::Approx(1000.0 * 1000 * 5)); + // %b goes along the subject on its own: it counts where it ends the pattern too + CHECK(lua_pattern_cost("%b()", 999, false, true) == doctest::Approx(1000.0 * 1000 * 4)); + CHECK(lua_pattern_cost("(%b())", 999, false, true) == doctest::Approx(1000.0 * 1000 * 6)); + CHECK(lua_pattern_cost("%b().*", 999, false, true) == doctest::Approx(1000.0 * 1000 * 6)); CHECK(lua_pattern_cost("(a)%1x", 999, false, true) == doctest::Approx(1000.0 * 1000 * 6)); CHECK(lua_pattern_cost("%f[%w]%w+", 999, false, true) == doctest::Approx(1000.0 * 9)); // '?' doubles @@ -173,6 +177,46 @@ TEST_CASE("script screens: a repetition followed by what always matches doesn't CHECK(lua_pattern_cost("a*$b", 999, false, true) == doctest::Approx(1000.0 * 1000 * 4)); } +TEST_CASE("script screens: %b counts the way from an opening character to the one that closes it") { + using script_screens::lua_pattern_cost; + using script_screens::max_pattern_cost; + // nothing closes: from each character to the end of the subject, the subject squared; whatever follows the %b + auto const open{std::string(1'000'000, '(')}; + CHECK(lua_pattern_cost("%b()", std::string_view{open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b()", std::string_view{open}, false, false) > max_pattern_cost); + CHECK(lua_pattern_cost("(%b())", std::string_view{open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b().*", std::string_view{open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b()x*", std::string_view{open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b()", std::string_view{open + open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b()", std::string_view{open}.substr(0, 10'000), false, true) > max_pattern_cost); + // the same with a hundred thousand of them, more than the openings held at a time + CHECK(lua_pattern_cost("%b()", std::string_view{open}.substr(0, 100'000), false, true) > max_pattern_cost); + // tried once from each position: the positions and the ways from the three openings, 2 + 5 + 2 + std::string_view const calls{"a(b)c(d(e))"}; + CHECK(lua_pattern_cost("%b()", calls, false, true) == doctest::Approx((12.0 + 9.0) * 4)); + CHECK(lua_pattern_cost("(%b())", calls, false, true) == doctest::Approx((12.0 + 9.0) * 6)); + // tried from the first position only, or after a repetition: the longest way of one try, and one + CHECK(lua_pattern_cost("^%b()", calls, false, true) == doctest::Approx(6.0 * 5)); + CHECK(lua_pattern_cost(".-%b()", calls, false, true) == doctest::Approx(12.0 * 12 * 6 * 6)); + // the same character opens and closes: to the next one + CHECK(lua_pattern_cost("%b\"\"", std::string_view{"a\"b\"c\""}, false, true) == doctest::Approx((7.0 + 5.0) * 4)); + // none in the subject: nothing to go along + CHECK(lua_pattern_cost("%b()", std::string_view{"abc"}, false, true) == doctest::Approx(4.0 * 4)); + // a long text of short calls is cheap, and so is one opening left unclosed in it + std::string text; + while (text.size() < 100'000) { + text += "call(a, b) "; + } + CHECK(lua_pattern_cost("%b()", std::string_view{text}, false, true) < max_pattern_cost); + text[9] = ' '; + CHECK(lua_pattern_cost("%b()", std::string_view{text}, false, true) < max_pattern_cost); + // nested deep, the ways add up to the subject squared again + auto const nested{std::string(20'000, '(') + std::string(20'000, ')')}; + CHECK(lua_pattern_cost("%b()x", std::string_view{nested}, false, true) > max_pattern_cost); + // malformed: the function raises its error + CHECK(lua_pattern_cost("%b(", std::string_view{open}, false, true) > 0.0); +} + TEST_CASE("script screens: a repetition right before the final $ counts its longest run in the subject") { using script_screens::lua_pattern_cost; using script_screens::max_pattern_cost; From 9f77bd688b0e4dbe353b41b0cb375eb33586ff4b Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 18 Nov 2026 23:50:06 +0100 Subject: [PATCH 063/136] fix(utilities): Bezogonkow() takes the marks off the same letters in every build The table of Bezogonkow() had the plus-minus sign of 0xB1 written as the character, in a source kept in utf-8. GCC and Clang (and MSVC with /utf-8) made two bytes of it, so every entry from 0xB2 on was off by one: the polish letters came out as "ALELDNSZZ,le,dnszl", and with them the file names of the destination boards and the names of the stations the python screens get. The entry is the byte now. Nothing changes for a build which made one byte of the sign (MSVC on a machine with a central or western european code page). The test checks the one table in place of whichever the build had. --- tests/unit/COVERAGE.md | 3 +-- tests/unit/test_utilities.cpp | 24 ++++++++++++------------ utilities/utilities.cpp | 5 ++++- 3 files changed, 17 insertions(+), 15 deletions(-) diff --git a/tests/unit/COVERAGE.md b/tests/unit/COVERAGE.md index 5e2c55696..ffb849ffd 100644 --- a/tests/unit/COVERAGE.md +++ b/tests/unit/COVERAGE.md @@ -139,7 +139,6 @@ The tests are written for the first two columns, and for what the game doesn't c - **`utilities.cpp`:** - `Now()`, `user_config_path()`, `user_cache_path()` and `true_random_seed()` depend on the clock, the environment and the entropy source of the system. The tests call them and check the shape of the result. The branches for a system without the variables or without an entropy source aren't run, and those of the other systems aren't compiled. - `FileCased()` looks through the working folder for a name given without a folder, and through the folder of the file elsewhere; on Windows it only asks whether the file is there. The search is run on Linux only. - - `Bezogonkow()` gives other letters with MSVC than with GCC and Clang, see the findings. The test takes either, told by the entry of the table the difference starts at, so each build checks the half it is. - **`ladderlogic.cpp`:** the two `return`s marked "not reachable" after the switches over the kind of an element. **Code nothing in the game runs** (checked against the whole source tree): @@ -201,7 +200,7 @@ The tests record the behaviour as it is. The following points may deserve a look - `deserialize_map()` (`utilities.h`, the sound overrides) therefore reads an empty key from an empty file, and one from a file ending with a line break; in a file with Windows line ends its values keep the carriage return. The game's `sound_overrides.txt` is a single line without a line break. - The separators given as a null pointer are taken as none by the tokenizer, but passed on to `strcmp` for a token of 7 characters or more starting with `i`, which crashes (tried by hand, not kept as a test). No caller gives a null pointer. - **The helpers (`utilities.cpp`, `utilities.h`):** - - `Bezogonkow()`, which takes the marks off the letters for the timetable and the on-screen texts: its table has a `±` in the source, a UTF-8 file. MSVC makes one byte of it, GCC and Clang two, which moves every entry from 0xB2 on by one. With MSVC the 18 polish letters come out as `ACELNOSZZacelnoszz`; with GCC as `ALELDNSZZ,le,dnszl`: `Ć` as L, `Ń` as D, `Ó` as N, `ą` and `ł` as a comma, `ć` as l, `ń` as d, `ó` as n, `ż` as l, only `Ę` and `ę` by luck as themselves. The Linux and macOS builds of the game show the names of the stations that way. The test checks whichever table the build has (the GCC one was tried with the table alone, compiled by GCC 6.3). + - `Bezogonkow()`, which takes the marks off the letters for the file names, the scripts and the multiplayer texts: its table had a `±` written as the character in the source, a UTF-8 file. MSVC made one byte of it, GCC and Clang two, which moved every entry from 0xB2 on by one: with GCC the 18 polish letters came out as `ALELDNSZZ,le,dnszl`. Fixed with MaSzyna-EU07/maszyna#94: the entry is written as the byte `±`, and the test checks the one table in every build. - `to_minutes_str()` reads past its table of raised digits for minutes with a fraction of 0.99 or more, and before it for negative minutes, which `CompareTime()` can give it for a timetable whose times go back. Tried by hand, both ended in `std::bad_alloc`, the text read from outside of the table being no text; not kept as a test. A width under 2 throws `std::length_error`. - `stol_def()` gives its default only for an empty text. A text which isn't a number gives 0 (the flags of an event, the log setting). - `split_string_and_number()` throws for a name with a hyphen which no digit follows (`a-b`), and for a number too big. The gamepad bindings and the PLC use it on names from files. diff --git a/tests/unit/test_utilities.cpp b/tests/unit/test_utilities.cpp index f04d9e34a..11acb9b8f 100644 --- a/tests/unit/test_utilities.cpp +++ b/tests/unit/test_utilities.cpp @@ -364,18 +364,18 @@ TEST_CASE("utilities: a text for the timetable loses its marks, control characte CHECK(Bezogonkow("Bia\xA3" "a_Podlaska", true) == "BiaLa Podlaska"); } -TEST_CASE("utilities: the polish letters from 0xB2 on lose their marks only in a build which makes one byte of the table's mark") { - // the table of Bezogonkow() has a plus-minus sign for 0xB1, written as the character in the source, a utf-8 file. - // MSVC puts it into the table as the one byte of the system's code page, and the table is as it was meant. - // GCC and Clang put the two bytes of utf-8 there, which moves the entries after it by one (see COVERAGE.md) - if (Bezogonkow("\xB1") == "\xB1") { - CHECK(Bezogonkow(kWin1250) == "ACELNOSZZacelnoszz"); - } - else { - // the first byte of the sign for 0xB1, the second for 0xB2, and each letter after them as the entry before its own - CHECK(Bezogonkow("\xB1\xB2") == "\xC2\xB1"); - CHECK(Bezogonkow(kWin1250) == "ALELDNSZZ,le,dnszl"); - } +TEST_CASE("utilities: the polish letters from 0xB2 on lose their marks in every build") { + // the table of Bezogonkow() has the plus-minus sign for 0xB1. it used to be written as the character in the source, + // a utf-8 file: GCC and Clang put the two bytes of utf-8 into the table, which moved the entries after it by one + // (the polish letters came out as "ALELDNSZZ,le,dnszl"). now it's the byte, and the table is the same everywhere + CHECK(Bezogonkow("\xB1") == "\xB1"); + CHECK(Bezogonkow("\xB1\xB2") == "\xB1,"); + CHECK(Bezogonkow(kWin1250) == "ACELNOSZZacelnoszz"); + // the last entry of the table, and the first: none is left out and none added + CHECK(Bezogonkow("\xFF") == "?"); + CHECK(Bezogonkow("\x80") == "E"); + // the letters of other languages the table knows (c-caron, e-caron, s-caron, u-ring, a-acute) + CHECK(Bezogonkow("\xE8\xEC\x9A\xF9\xE1") == "cesua"); } TEST_CASE("utilities: utf-8 is decoded into code points of one to four bytes") { diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index 550ad016a..04feded2e 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -458,8 +458,11 @@ void win1250_to_utf32(std::string const &Text, std::u32string &Output) } // Ra: tymczasowe rozwiązanie kwestii zagranicznych (czeskich) napisów +// NOTE: the entry of 0xB1 (the plus-minus sign of windows-1250, left as it is) is written as its byte. written as the +// character it took two bytes in the builds which keep the texts of the sources in utf-8 (GCC, Clang, MSVC with /utf-8), +// and every entry after it was off by one char const charsetconversiontable[] = "E?,?\"_++?%Sstzz" - " ^^L$A|S^CS<--RZo±,l'uP.,as>L\"lz" + " ^^L$A|S^CS<--RZo\xB1,l'uP.,as>L\"lz" "RAAAALCCCEEEEIIDDNNOOOOxRUUUUYTB" "raaaalccceeeeiiddnnoooo-ruuuuyt?"; From c0a0a4204ebff15cec29df80862b4022d2d2a9ca Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 18 Nov 2026 23:50:07 +0100 Subject: [PATCH 064/136] feat(utilities): a text of the data files as utf-8 for the user interface data_text_to_utf8() turns a text read from a data file into utf-8: one which already is valid utf-8 stays, any other is read as windows-1250, the whole code page (win1250_to_utf8() knows the polish letters only, and utf8_to_win1250() counts on that, so the two stay as they are). A windows-1250 text which is valid utf-8 by chance (two capital letters with marks in a row) is told by what it would decode to. data_name_to_utf8() is the same for a name shown in one line: control characters and, when asked, underscores become spaces, as Bezogonkow() has them, but the letters keep their marks. utf8_length() and utf8_fit() count, cut and fill by characters, for the columns of a fixed width. Nothing uses them yet (MaSzyna-EU07/maszyna#94). --- tests/unit/test_win1250.cpp | 81 +++++++++++++++++++++++++ utilities/utilities.cpp | 114 ++++++++++++++++++++++++++++++++++++ utilities/utilities.h | 11 ++++ 3 files changed, 206 insertions(+) diff --git a/tests/unit/test_win1250.cpp b/tests/unit/test_win1250.cpp index f1d861e94..77fe35a5f 100644 --- a/tests/unit/test_win1250.cpp +++ b/tests/unit/test_win1250.cpp @@ -8,6 +8,8 @@ namespace std::string const kWin1250{"\xA5\xC6\xCA\xA3\xD1\xD3\x8C\x8F\xAF\xB9\xE6\xEA\xB3\xF1\xF3\x9C\x9F\xBF"}; std::string const kUtf8{"\xC4\x84\xC4\x86\xC4\x98\xC5\x81\xC5\x83\xC3\x93\xC5\x9A\xC5\xB9\xC5\xBB" "\xC4\x85\xC4\x87\xC4\x99\xC5\x82\xC5\x84\xC3\xB3\xC5\x9B\xC5\xBA\xC5\xBC"}; +// the name of a station the way a timetable has it: Biala_Podlaska with its l-stroke, in windows-1250 +std::string const kBiala{"Bia\xB3" "a_Podlaska"}; } // namespace TEST_CASE("win1250: the polish letters of a scenery file read as utf-8") { @@ -32,3 +34,82 @@ TEST_CASE("win1250: utf-8 written back the way a scenery file has it") { // the letters other than the polish ones turn into question marks CHECK(utf8_to_win1250("\xC3\xA9t\xC3\xA9") == "?t?"); } + +TEST_CASE("win1250: a text of a data file is turned into utf-8 for the user interface") { + // plain ascii stays + CHECK(data_text_to_utf8("tor 1, km 0.178") == "tor 1, km 0.178"); + CHECK(data_text_to_utf8("").empty()); + // windows-1250: the polish letters + CHECK(data_text_to_utf8(kWin1250) == kUtf8); + CHECK(data_text_to_utf8(kBiala) == "Bia\xC5\x82" "a_Podlaska"); + // and the letters of the other languages of the code page: a-acute, z-caron, i-acute, u-diaeresis, o-double-acute + CHECK(data_text_to_utf8("n\xE1" "dra\x9E\xED") == "n\xC3\xA1" "dra\xC5\xBE\xC3\xAD"); + CHECK(data_text_to_utf8("\xFC\xF5") == "\xC3\xBC\xC5\x91"); + // a character outside of the two-byte range (the euro sign), and a byte the code page has nothing for + CHECK(data_text_to_utf8("5 \x80") == "5 \xE2\x82\xAC"); + CHECK(data_text_to_utf8("a\x81" "b") == "a?b"); + // a text already in utf-8 stays as it is + CHECK(data_text_to_utf8(kUtf8) == kUtf8); + CHECK(data_text_to_utf8("Bia\xC5\x82" "a Podlaska") == "Bia\xC5\x82" "a Podlaska"); + CHECK(data_text_to_utf8("\xE2\x94\x82 60 \xE2\x94\x82") == "\xE2\x94\x82 60 \xE2\x94\x82"); + // capital letters with marks in a row make valid utf-8 by chance (O-acute and L-stroke: D3 A3), but of a + // cyrillic letter; they are read as the windows-1250 they are + CHECK(data_text_to_utf8("W\xD3\xA3KA") == "W\xC3\x93\xC5\x81KA"); + CHECK(data_text_to_utf8("R\xD3\xAF" "A") == "R\xC3\x93\xC5\xBB" "A"); + // line ends and tabs of a longer text stay + CHECK(data_text_to_utf8("jedna\n\tdruga \xB3") == "jedna\n\tdruga \xC5\x82"); + // what comes out is valid utf-8 + std::u32string decoded; + std::string all; + for (auto value{0x20}; value < 0x100; ++value) { + all += static_cast(value); + } + REQUIRE(utf8_to_utf32(data_text_to_utf8(all), decoded)); + CHECK(decoded.size() == all.size()); +} + +TEST_CASE("win1250: a name of a data file is shown in one line, with its letters") { + // what Bezogonkow() did for the user interface, but for the marks: control characters and, when asked, + // underscores turn into spaces + CHECK(data_name_to_utf8("a\tb\nc") == "a b c"); + CHECK(data_name_to_utf8(kBiala) == "Bia\xC5\x82" "a_Podlaska"); + CHECK(data_name_to_utf8(kBiala, true) == "Bia\xC5\x82" "a Podlaska"); + CHECK(data_name_to_utf8("Warszawa_Zachodnia", true) == "Warszawa Zachodnia"); + CHECK(data_name_to_utf8("Warszawa_Zachodnia") == "Warszawa_Zachodnia"); + CHECK(data_name_to_utf8("Bia\xC5\x82" "a_Podlaska\r", true) == "Bia\xC5\x82" "a Podlaska "); + // for a name without letters outside of ascii it gives what Bezogonkow() gave + for (auto const *name : {"Warszawa_Zachodnia", "Gorna", "tor 1\t2", "", "Os1234"}) { + CAPTURE(name); + CHECK(data_name_to_utf8(name) == Bezogonkow(name)); + CHECK(data_name_to_utf8(name, true) == Bezogonkow(name, true)); + } +} + +TEST_CASE("win1250: a column of the timetable panel is as wide in letters as it was in bytes") { + CHECK(utf8_length("") == 0); + CHECK(utf8_length("Gorna") == 5); + CHECK(utf8_length("Bia\xC5\x82" "a Podlaska") == 14); + CHECK(utf8_length(kUtf8) == 18); + CHECK(utf8_length("\xE2\x94\x82 60 \xE2\x94\x82") == 6); + // a byte which is no part of a valid sequence counts as a character + CHECK(utf8_length("a\xB3" "b") == 3); + CHECK(utf8_length("a\xC5") == 2); + + // filled with spaces + CHECK(utf8_fit("Gorna", 8) == "Gorna "); + CHECK(utf8_fit("", 3) == " "); + auto const caption{data_name_to_utf8(kBiala, true)}; + auto const fitted{utf8_fit(caption, 34)}; + CHECK(utf8_length(fitted) == 34); + CHECK(fitted.size() == 35); // one letter of two bytes + CHECK(fitted.starts_with(caption)); + // cut between the letters, never inside of one + CHECK(utf8_fit("Bia\xC5\x82" "a Podlaska", 4) == "Bia\xC5\x82"); + CHECK(utf8_fit("Bia\xC5\x82" "a Podlaska", 3) == "Bia"); + CHECK(utf8_fit(kUtf8, 2) == "\xC4\x84\xC4\x86"); + CHECK(utf8_fit("Gorna", 0).empty()); + // a name of ascii fits the way the panel cut it before + std::string const longname{"Bardzo_Dluga_Nazwa_Stacji_Wezlowej_Osobowej"}; + CHECK(utf8_fit(longname, 34) == (longname + " ").substr(0, 34)); + CHECK(utf8_fit("Gorna", 34) == (std::string{"Gorna"} + " ").substr(0, 34)); +} diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index 04feded2e..898e833d5 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -457,6 +457,120 @@ void win1250_to_utf32(std::string const &Text, std::u32string &Output) } } +namespace +{ +void append_utf8(std::string &Output, char32_t const Codepoint) +{ + if (Codepoint < 0x80) + { + Output += static_cast(Codepoint); + } + else if (Codepoint < 0x800) + { + Output += static_cast(0xC0 | (Codepoint >> 6)); + Output += static_cast(0x80 | (Codepoint & 0x3F)); + } + else if (Codepoint < 0x10000) + { + Output += static_cast(0xE0 | (Codepoint >> 12)); + Output += static_cast(0x80 | ((Codepoint >> 6) & 0x3F)); + Output += static_cast(0x80 | (Codepoint & 0x3F)); + } + else + { + Output += static_cast(0xF0 | (Codepoint >> 18)); + Output += static_cast(0x80 | ((Codepoint >> 12) & 0x3F)); + Output += static_cast(0x80 | ((Codepoint >> 6) & 0x3F)); + Output += static_cast(0x80 | (Codepoint & 0x3F)); + } +} +} // namespace + +std::string data_text_to_utf8(std::string const &Text) +{ + if (std::ranges::all_of(Text, [](char const Character) { return static_cast(Character) < 0x80; })) + { + return Text; + } + std::u32string codepoints; + // a text in windows-1250 can happen to be valid utf-8 as well: two capital letters with marks in a row, as the bytes + // D3 A3 of "WOLKA" with its marks, make a sequence of two bytes. such a pair decodes to a letter between U+0180 and + // U+07FF (cyrillic, greek and the like), which the texts of the data files, when they are in utf-8, don't have + if (utf8_to_utf32(Text, codepoints) && std::ranges::none_of(codepoints, [](char32_t const Codepoint) { return Codepoint >= 0x180 && Codepoint < 0x800; })) + { + return Text; + } + // the code page the data files are written in + win1250_to_utf32(Text, codepoints); + std::string output; + output.reserve(Text.size() + 8); + for (auto const codepoint : codepoints) + { + // the bytes the code page has no character for come as 0 + append_utf8(output, codepoint != 0 ? codepoint : U'?'); + } + return output; +} + +std::string data_name_to_utf8(std::string const &Name, bool const Underscorestospaces) +{ + auto name{data_text_to_utf8(Name)}; + // in utf-8 the bytes below 0x80 are characters of their own, never a part of another one + for (auto &character : name) + { + if (static_cast(character) < 0x20 || (Underscorestospaces && character == '_')) + { + character = ' '; + } + } + return name; +} + +namespace +{ +// number of bytes of the character of a text in utf-8 which starts at given position; 1 for a byte which starts no valid sequence +std::size_t utf8_character_size(std::string_view const Text, std::size_t const Position) +{ + auto const length{utf8_sequence_length(static_cast(Text[Position]))}; + if (length < 2 || Position + length > Text.size()) + { + return 1; + } + for (std::size_t offset = 1; offset < length; ++offset) + { + if ((static_cast(Text[Position + offset]) & std::byte{0xC0}) != std::byte{0x80}) + { + return 1; + } + } + return length; +} +} // namespace + +std::size_t utf8_length(std::string_view const Text) +{ + std::size_t length{0}; + for (std::size_t position = 0; position < Text.size(); position += utf8_character_size(Text, position)) + { + ++length; + } + return length; +} + +std::string utf8_fit(std::string_view const Text, std::size_t const Width) +{ + std::size_t length{0}; + std::size_t position{0}; + while (position < Text.size() && length < Width) + { + position += utf8_character_size(Text, position); + ++length; + } + std::string output{Text.substr(0, position)}; + output.append(Width - length, ' '); + return output; +} + // Ra: tymczasowe rozwiązanie kwestii zagranicznych (czeskich) napisów // NOTE: the entry of 0xB1 (the plus-minus sign of windows-1250, left as it is) is written as its byte. written as the // character it took two bytes in the builds which keep the texts of the sources in utf-8 (GCC, Clang, MSVC with /utf-8), diff --git a/utilities/utilities.h b/utilities/utilities.h index 748c4c8d9..7e3a227f1 100644 --- a/utilities/utilities.h +++ b/utilities/utilities.h @@ -175,6 +175,17 @@ std::string utf8_to_win1250(std::string const &Text); bool utf8_to_utf32(std::string const &Text, std::u32string &Output); // decodes windows-1250 (ansi) encoded text into unicode code points void win1250_to_utf32(std::string const &Text, std::u32string &Output); +// a text of the data files as utf-8, for the user interface. the files are in windows-1250, some of the newer ones in +// utf-8: a text which is valid utf-8 stays as it is, any other is read as windows-1250, every letter of the code page +// (not only the polish ones win1250_to_utf8() knows) turned into utf-8 +std::string data_text_to_utf8(std::string const &Text); +// the same for a name (of a station, a train, an event, a node, a file) shown in a line of the user interface: what +// Bezogonkow() is for, but the letters keep their marks. control characters become spaces and, when asked, underscores too +std::string data_name_to_utf8(std::string const &Name, bool Underscorestospaces = false); +// number of characters (code points) of a text in utf-8; a byte which isn't a part of a valid sequence counts as one +std::size_t utf8_length(std::string_view Text); +// a text in utf-8 cut or filled with spaces to given number of characters, for the columns of the fixed width +std::string utf8_fit(std::string_view Text, std::size_t Width); inline std::string extract_value(std::string const &Key, std::string const &Input) { From 022e59fde314355c4a97331fb0ab95a8d02a7614 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 18 Nov 2026 23:50:07 +0100 Subject: [PATCH 065/136] feat(timetable): station names keep their polish letters, a W4 finds its station by one key MaSzyna-EU07/maszyna#94. The timetable reader and the W4 event (putvalues PassengerStopPoint:) threw the polish letters of a name away as they read it. Now: - the reader keeps the name as the file spells it in TMTableEntry::StationLabel and timetable_data::RelationLabel1/2 (TTrainParameters::RelationLabel1/2), for showing; StationName and Relation1/2 hold the ascii form as before, byte for byte, so the announcement files, the destination boards, the memory cells written by WhoIs events, the python dictionary, the log and the black box get what they always got - the W4 event keeps its text as the scenery spells it (a scenery saved by the editor no longer loses the letters of its W4 events); the black box map still gets the ascii form - world/stationnames.h has the one place which tells whether a W4 is for a station: timetable::stop_point_is_for(), used by TController::TableUpdateStopPoint() and TTrainParameters::RewindTimeTable(). It compares keys (ascii form, lower case, spaces as underscores), so the timetable and the W4 may each spell the station with or without the letters - TTrainParameters::relation_caption() / station_caption() and TController::NextStop() give the names for the player: with the letters, in utf-8 The folding stays in the matching because the game data needs it: in 36 scenario x station pairs of the Steam install (6 of the SVN) the timetable and the W4 spell the station differently (BALTYK_GLOWNY in capitals against Baltyk_Glowny, Rzepedz with one of its two marks, Lupkow without them), and no announcement file has a letter outside of ascii in its name. Every W4 which matched a station still does. New matches, none of them in the game data: a memory cell text spelled with polish letters, a space where the timetable has an underscore, a name longer than the 32 characters (sizeof(std::string)) the old comparison took. A memory cell text with a # part is still compared whole. win1250_to_ascii() builds its map once: the comparison runs it for every stop point a driver scans. --- CMakeLists.txt | 1 + application/editormodeminimap.cpp | 13 +- simulation/blackboxrecorder.cpp | 4 +- tests/unit/test_station_names.cpp | 295 ++++++++++++++++++++++++++++++ utilities/utilities.cpp | 2 +- vehicle/Driver.cpp | 9 +- world/Event.cpp | 3 +- world/mtable.cpp | 38 +++- world/mtable.h | 6 + world/stationnames.cpp | 43 +++++ world/stationnames.h | 40 ++++ world/timetablereader.cpp | 19 +- world/timetablereader.h | 9 +- 13 files changed, 459 insertions(+), 23 deletions(-) create mode 100644 tests/unit/test_station_names.cpp create mode 100644 world/stationnames.cpp create mode 100644 world/stationnames.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 7f189096b..4b98ae937 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -565,6 +565,7 @@ set(CORE_SOURCES "vehicle/timetableservice.cpp" "world/timetableflags.cpp" "world/timetablereader.cpp" +"world/stationnames.cpp" ) add_library(eu07_core STATIC ${CORE_SOURCES}) target_link_libraries(eu07_core PUBLIC eu07_settings) diff --git a/application/editormodeminimap.cpp b/application/editormodeminimap.cpp index 2717cd447..e11fe57d4 100644 --- a/application/editormodeminimap.cpp +++ b/application/editormodeminimap.cpp @@ -122,16 +122,19 @@ void minimap_tool::gather_stations() if (false == stale(m_stations_seen)) return; std::map found; - // the texts are in windows-1250; the ones of the events lost their polish letters as they were read - auto const add = [&](std::string const &Text, bool const Letters, glm::dvec3 const &Point, TTrack *Track) { + // the texts are in windows-1250; the stop points of a station can spell it with or without its polish letters + std::unordered_set lettered; + auto const add = [&](std::string const &Text, glm::dvec3 const &Point, TTrack *Track) { auto const name{stop_name(Text)}; if (name.empty()) return; auto const key{folded(name)}; auto &entry{found[key]}; entry.key = key; + // the station is shown by a spelling with the letters, when any of its stop points has one + auto const letters{std::ranges::any_of(name, [](char const Character) { return static_cast(Character) >= 0x80; })}; // the timetables join the words with underscores - if (entry.name.empty() || Letters) + if (entry.name.empty() || (letters && lettered.insert(key).second)) { entry.name = win1250_to_utf8(name); std::replace(entry.name.begin(), entry.name.end(), '_', ' '); @@ -145,10 +148,10 @@ void minimap_tool::gather_stations() }; for (auto *cell : simulation::Memory.sequence()) if (cell != nullptr && cell->Text().starts_with(stop_prefix)) - add(cell->Text(), true, cell->location(), cell->Track); + add(cell->Text(), cell->location(), cell->Track); for (auto *event : simulation::Events.sequence()) if (auto const *values{dynamic_cast(event)}; values != nullptr && values->input_command() == TCommandType::cm_PassengerStopPoint) - add(values->input_text(), false, values->input_location(), nullptr); + add(values->input_text(), values->input_location(), nullptr); std::vector stations; for (auto &entry : found) stations.push_back(std::move(entry.second)); diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index d886bddf0..608b07586 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -24,6 +24,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Globals.h" #include "utilities/Logs.h" #include "utilities/utilities.h" +#include "world/stationnames.h" #include #include @@ -380,8 +381,9 @@ void blackbox_recorder::write_map() { if (values == nullptr) continue; auto const &text{values->input_text()}; + // the name in the form the station records and the rows of the timetable have theirs, as it always was if (text.starts_with(stoppoint)) - m_writer->stop_point(stoppoints++, text_of(std::string_view{text}.substr(stoppoint.size())), values->input_location(), + m_writer->stop_point(stoppoints++, text_of(timetable::station_ascii(text.substr(stoppoint.size()))), values->input_location(), static_cast(values->input_value(1)), static_cast(values->input_value(2)), heading_of(values->input_location())); else if (text == "Warning_signal") m_writer->horn_point(hornpoints++, text_of(values->name()), values->input_location(), static_cast(values->input_value(1)), diff --git a/tests/unit/test_station_names.cpp b/tests/unit/test_station_names.cpp new file mode 100644 index 000000000..0bcc7953a --- /dev/null +++ b/tests/unit/test_station_names.cpp @@ -0,0 +1,295 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "utilities/utilities.h" +#include "world/stationnames.h" +#include "world/timetablereader.h" + +#include +#include +#include + +// the names of the stations (MaSzyna-EU07/maszyna#94): the timetable keeps a name as its file spells it, with its polish +// letters, for showing; the W4 stop points of the scenery, spelled in their own files, still find their station whatever +// the spelling; the form the announcement files, the scenery events and the scripts get stays the ascii one. +// the texts are windows-1250, written as bytes: the build reads the sources in any code page + +using timetable::same_station; +using timetable::station_ascii; +using timetable::station_caption; +using timetable::station_key; +using timetable::stop_point_is_for; + +namespace { + +// Biała_Podlaska, Łódź_Żabieniec, Częstochowa_Osobowa in windows-1250 +std::string const biala{"Bia\xB3" "a_Podlaska"}; +std::string const lodz{"\xA3\xF3" "d\x9F_\xAF" "abieniec"}; +std::string const czestochowa{"Cz\xEAstochowa_Osobowa"}; +// the 18 polish letters in windows-1250, as in test_win1250.cpp +std::string const letters1250{"\xA5\xC6\xCA\xA3\xD1\xD3\x8C\x8F\xAF\xB9\xE6\xEA\xB3\xF1\xF3\x9C\x9F\xBF"}; + +// a timetable with polish letters in the relation and in the names of the stations +std::string const timetable_text{ + " ___________________________________________________________________\n" + "[ Rodzaj i numer pociagu | Os1234 ]\n" + "[ Kategoria | Os ]\n" + "[________________________________________________|__________________]\n" + "[ | Bia\xB3" "a_Podlaska ]\n" + "[ Relacja pociagu | \xA3\xF3" "d\x9F_\xAF" "abieniec ]\n" + "[________________________________________________|__________________]\n" + "[ Wymagany % ciezaru hamujacego | 60% ]\n" + "[________________________________________________|__________________]\n" + "[ Seria i obciazenie lokomotywy | EN57 120 ]\n" + "[________________________________________________|__________________]\n" + "[ 1.13 | 60 | Bia\xB3" "a_Podlaska 1 | | ]\n" + "[ | | R2,H 1 12.47 | ]\n" + "[ | |----------------------------------1---------|--------]\n" + "[ 5.06 |_____| Cz\xEAstochowa_Osobowa 1 12.54 | 7 ]\n" + "[ | 40 | po 1 12.55 | ]\n" + "[ | |----------------------------------1---------|--------]\n" + "[ 9.16 | | \xA3\xF3" "d\x9F_\xAF" "abieniec 2 13.01 | 6 ]\n" + "[ | | R3 2 | | ]\n" + "[_______|_____|__________________________________2_________|________]\n"}; + +Mtable::timetable_data read(std::string const &Text) { + std::istringstream input{Text}; + Mtable::timetable_data data; + data.TrainName = "file"; + REQUIRE(Mtable::read_timetable(input, data) == 0); + return data; +} + +// the text of a W4 as the driver gets it: a putvalues event cuts what follows # when the scenery is read +// (putvalues_event::deserialize_), a memory cell keeps the whole of its text +std::string text_seen(std::string Text, bool const Event) { + if (auto const hash{Text.find('#')}; Event && hash != std::string::npos) { + Text.erase(hash); + } + return Text; +} + +// the comparison of a W4 text with the next stop of the timetable as TController::TableUpdateStopPoint() made it before +// the names kept their letters: the text of a putvalues event lost its polish letters too when the scenery was read; +// 32 is the sizeof( std::string ) the code had for the length +bool matched_before(std::string const &Text, bool const Event, std::string const &Nextstop) { + auto text{text_seen(Text, Event)}; + if (Event) { + win1250_to_ascii(text); + } + return ToLower(text).compare(19, 32, ToLower(Nextstop)) == 0; +} + +bool matched_now(std::string const &Text, bool const Event, std::string const &Nextstop) { + return stop_point_is_for(text_seen(Text, Event), Nextstop); +} + +} // namespace + +TEST_CASE("station names: the ascii form takes the marks off the polish letters and nothing else") { + CHECK(station_ascii(biala) == "Biala_Podlaska"); + CHECK(station_ascii(lodz) == "Lodz_Zabieniec"); + CHECK(station_ascii(czestochowa) == "Czestochowa_Osobowa"); + CHECK(station_ascii(letters1250) == "ACELNOSZZacelnoszz"); + // a name without them stays, the case, the underscores and the spaces included + CHECK(station_ascii("Warszawa_Zachodnia") == "Warszawa_Zachodnia"); + CHECK(station_ascii("Nowy Targ") == "Nowy Targ"); + // what win1250_to_ascii() always made of a name: letters of other languages stay as they are + auto ostrava{std::string{"Ostrava_hl.n\xE1" "dra\x9E\xED"}}; + auto const expected{ostrava}; + CHECK(station_ascii(ostrava) == expected); + win1250_to_ascii(ostrava); + CHECK(ostrava == expected); +} + +TEST_CASE("station names: the file names of a station come from the ascii form, as before") { + // the announcement of a stop is /.ogg or sounds/sip/.ogg, of the name the timetable entry has + // as StationName; the files have no polish letters in their names + auto const data{read(timetable_text)}; + CHECK(data.TimeTable[2].StationName + ".ogg" == "Czestochowa_Osobowa.ogg"); + CHECK(data.TimeTable[3].StationName + ".ogg" == "Lodz_Zabieniec.ogg"); + // the destination board is looked up by the last station of the relation, through Bezogonkow() + CHECK(Bezogonkow(data.Relation2) == "Lodz_Zabieniec"); +} + +TEST_CASE("station names: a timetable with polish letters keeps them for showing") { + auto const data{read(timetable_text)}; + REQUIRE(data.StationCount == 3); + // as written + CHECK(data.RelationLabel1 == biala); + CHECK(data.RelationLabel2 == lodz); + CHECK(data.TimeTable[1].StationLabel == biala); + CHECK(data.TimeTable[2].StationLabel == czestochowa); + CHECK(data.TimeTable[3].StationLabel == lodz); + // what the player sees: utf-8, spaces for the underscores + CHECK(station_caption(data.TimeTable[1].StationLabel) == "Bia\xC5\x82" "a Podlaska"); + CHECK(station_caption(data.TimeTable[2].StationLabel) == "Cz\xC4\x99stochowa Osobowa"); + CHECK(station_caption(data.TimeTable[3].StationLabel) == "\xC5\x81\xC3\xB3" "d\xC5\xBA \xC5\xBB" "abieniec"); + CHECK(station_caption(data.RelationLabel2) == "\xC5\x81\xC3\xB3" "d\xC5\xBA \xC5\xBB" "abieniec"); + // the rest of the row reads as it did + CHECK(data.TimeTable[2].StationWare == "po"); + CHECK(data.TimeTable[2].Ah == 12); + CHECK(data.TimeTable[3].TrackNo == 2); +} + +TEST_CASE("station names: the name a timetable is matched and handed over by stays the ascii one") { + auto const data{read(timetable_text)}; + // TMTableEntry::StationName and the relation: what the W4 comparison, the announcement files, the scenery events + // (WhoIs) and the python screens get + CHECK(data.Relation1 == "Biala_Podlaska"); + CHECK(data.Relation2 == "Lodz_Zabieniec"); + CHECK(data.TimeTable[1].StationName == "Biala_Podlaska"); + CHECK(data.TimeTable[2].StationName == "Czestochowa_Osobowa"); + CHECK(data.TimeTable[3].StationName == "Lodz_Zabieniec"); + // the first station is still told to be the start of the relation by the two names being the same + CHECK(data.TimeTable[1].StationName == data.Relation1); +} + +TEST_CASE("station names: a timetable without polish letters has the same name in both forms") { + auto const plain{station_ascii(timetable_text)}; + auto const data{read(plain)}; + REQUIRE(data.StationCount == 3); + CHECK(data.RelationLabel1 == data.Relation1); + CHECK(data.RelationLabel2 == data.Relation2); + for (auto i{1}; i <= data.StationCount; ++i) { + CAPTURE(i); + CHECK(data.TimeTable[i].StationLabel == data.TimeTable[i].StationName); + } + // and reads the same as the one with the letters, but for the labels + auto const lettered{read(timetable_text)}; + for (auto i{0}; i <= data.StationCount; ++i) { + CAPTURE(i); + CHECK(data.TimeTable[i].StationName == lettered.TimeTable[i].StationName); + CHECK(data.TimeTable[i].Dh == lettered.TimeTable[i].Dh); + CHECK(data.TimeTable[i].Dm == lettered.TimeTable[i].Dm); + } + // the entry before the first station is the technical one in both forms + CHECK(data.TimeTable[0].StationName == "nowhere"); + CHECK(data.TimeTable[0].StationLabel == "nowhere"); +} + +TEST_CASE("station names: two spellings of a station have one key") { + // with and without the letters + CHECK(same_station(biala, "Biala_Podlaska")); + CHECK(same_station("Biala_Podlaska", biala)); + CHECK(same_station(lodz, "Lodz_Zabieniec")); + // some of the letters only (linia 107 has the W4 of Rzepedz spelled so) + CHECK(same_station("Rzep\xEA" "d\x9F", "Rzeped\x9F")); + // in any case, the letters with marks included (baltyk has BALTYK_GLOWNY in capitals in a timetable) + CHECK(same_station("BA\xA3TYK_G\xA3\xD3WNY", "Ba\xB3tyk_G\xB3\xF3wny")); + CHECK(same_station("BA\xA3TYK_G\xA3\xD3WNY", "baltyk_glowny")); + CHECK(same_station("ZAG\xD3RZ", "Zag\xF3rz")); + // with spaces or underscores + CHECK(same_station("Bia\xB3" "a Podlaska", biala)); + CHECK(same_station("Biala Podlaska", biala)); + CHECK(same_station("Biala Podlaska", "biala_podlaska")); + // the key itself + CHECK(station_key(biala) == "biala_podlaska"); + CHECK(station_key("Bia\xB3" "a Podlaska") == "biala_podlaska"); + CHECK(station_key(letters1250) == "acelnoszzacelnoszz"); + CHECK(station_key("").empty()); +} + +TEST_CASE("station names: different stations have different keys") { + CHECK_FALSE(same_station(biala, "Biala")); + CHECK_FALSE(same_station("Biala_Podlaska", "Biala_Podlaska_po")); + CHECK_FALSE(same_station("Lodz_Zabieniec", "Lodz_Kaliska")); + CHECK_FALSE(same_station("Gorna", "Dolna")); + CHECK_FALSE(same_station("Gorna", "")); + // no other separator stands for a space + CHECK_FALSE(same_station("Biala-Podlaska", "Biala_Podlaska")); + CHECK_FALSE(same_station("BialaPodlaska", "Biala_Podlaska")); + // letters of other languages aren't folded, as they never were + CHECK_FALSE(same_station("Ostrava_hl.n\xE1" "dra\x9E\xED", "Ostrava_hl.nadrazi")); + CHECK(same_station("Ostrava_hl.n\xE1" "dra\x9E\xED", "ostrava_hl.n\xE1" "dra\x9E\xED")); +} + +TEST_CASE("station names: a W4 finds the station of the timetable whatever the two spellings") { + auto const data{read(timetable_text)}; + // the next stop of the driver is the StationName of the entry + auto const &nextstop{data.TimeTable[1].StationName}; + // the W4 spelled with the letters, without them, in another case, with a space + CHECK(stop_point_is_for("PassengerStopPoint:" + biala, nextstop)); + CHECK(stop_point_is_for("PassengerStopPoint:Biala_Podlaska", nextstop)); + CHECK(stop_point_is_for("PassengerStopPoint:BIA\xA3" "A_PODLASKA", nextstop)); + CHECK(stop_point_is_for("PassengerStopPoint:biala_podlaska", nextstop)); + CHECK(stop_point_is_for("PassengerStopPoint:Bia\xB3" "a Podlaska", nextstop)); + CHECK(stop_point_is_for("PassengerStopPoint:Biala Podlaska", nextstop)); + // the usual W4 of a scenery, with the part which makes its event unique: the event cuts it as it's read + CHECK(matched_now("PassengerStopPoint:" + biala + "#W4-P1-T2-1", true, nextstop)); + CHECK(matched_now("PassengerStopPoint:Biala_Podlaska#W4-1", true, nextstop)); + // and the other way round: the timetable name as written against a W4 without the letters + CHECK(stop_point_is_for("PassengerStopPoint:Biala_Podlaska", data.TimeTable[1].StationLabel)); + CHECK(stop_point_is_for("PassengerStopPoint:Lodz_Zabieniec", data.TimeTable[3].StationLabel)); + // another station, a text which isn't a W4 one + CHECK_FALSE(stop_point_is_for("PassengerStopPoint:Biala", nextstop)); + CHECK_FALSE(stop_point_is_for("PassengerStopPoint:Biala_Podlaska_po", nextstop)); + CHECK_FALSE(stop_point_is_for("PassengerStopPoint:" + lodz, nextstop)); + CHECK_FALSE(stop_point_is_for("Biala_Podlaska", nextstop)); + CHECK_FALSE(stop_point_is_for("passengerstoppoint:Biala_Podlaska", nextstop)); + CHECK_FALSE(stop_point_is_for("SetVelocity", nextstop)); + CHECK_FALSE(stop_point_is_for("", nextstop)); + // a memory cell keeps what follows the #: as before, it is a W4 only of a station which has that in its name + CHECK_FALSE(matched_now("PassengerStopPoint:Biala_Podlaska#W4-1", false, nextstop)); + CHECK(matched_now("PassengerStopPoint:Gorna#1", false, "Gorna#1")); + CHECK_FALSE(matched_now("PassengerStopPoint:Gorna", false, "Gorna#1")); + // a W4 without a name is for the end of the timetable, where the next stop has none either + CHECK(stop_point_is_for("PassengerStopPoint:", "")); + CHECK_FALSE(stop_point_is_for("PassengerStopPoint:", nextstop)); + CHECK_FALSE(stop_point_is_for("PassengerStopPoint:Biala_Podlaska", "")); +} + +TEST_CASE("station names: every W4 the driver matched before is matched now") { + // the next stops as the timetable gives them (ascii), and the special ones the driver has when there's no station + std::vector const nextstops{"Biala_Podlaska", "Lodz_Zabieniec", "Czestochowa_Osobowa", "BALTYK_GLOWNY", "Gorna", "Gorna#1", "Rzepedz", "", "nowhere", "[End of route]", + "Ostrava_hl.n\xE1" "dra\x9E\xED"}; + std::vector const names{biala, "Biala_Podlaska", "biala_podlaska", "BIA\xA3" "A_PODLASKA", "Bia\xB3" "a Podlaska", lodz, "Lodz_Zabieniec", czestochowa, + "Ba\xB3tyk_G\xB3\xF3wny", "Rzeped\x9F", "Rzep\xEA" "d\x9F", "Gorna", "Gorna#1", "Dolna", "", "nowhere", "Ostrava_hl.n\xE1" "dra\x9E\xED", + "Ostrava_hl.nadrazi", "Biala", "Biala_Podlaska_po"}; + auto matches{0}; + auto gained{0}; + for (auto const &nextstop : nextstops) { + for (auto const &name : names) { + for (auto const *suffix : {"", "#W4-1"}) { + auto const text{"PassengerStopPoint:" + name + suffix}; + for (auto const event : {true, false}) { + CAPTURE(nextstop); + CAPTURE(text); + CAPTURE(event); + auto const before{matched_before(text, event, nextstop)}; + auto const now{matched_now(text, event, nextstop)}; + // nothing is lost + CHECK((false == before || now)); + // and nothing changes for the spellings the comparison never told apart: a name without polish letters + // and without spaces + if (name == station_ascii(name) && name.find(' ') == std::string::npos) { + CHECK(before == now); + } + matches += (now ? 1 : 0); + gained += (now && false == before ? 1 : 0); + } + } + } + } + CHECK(matches > 0); + // what is new: a memory cell spelled with the polish letters, a space for an underscore + CHECK(gained > 0); + CHECK(matched_now("PassengerStopPoint:" + biala, false, "Biala_Podlaska")); + CHECK_FALSE(matched_before("PassengerStopPoint:" + biala, false, "Biala_Podlaska")); + CHECK(matched_now("PassengerStopPoint:Biala Podlaska", true, "Biala_Podlaska")); + CHECK_FALSE(matched_before("PassengerStopPoint:Biala Podlaska", true, "Biala_Podlaska")); + // and a name longer than the 32 characters the old comparison took of it + std::string const longname{"Bardzo_Dluga_Nazwa_Stacji_Wezlowej_Osobowej"}; + CHECK(matched_now("PassengerStopPoint:" + longname, true, longname)); + CHECK_FALSE(matched_before("PassengerStopPoint:" + longname, true, longname)); +} + +TEST_CASE("station names: the caption of a station is its name as written, in utf-8, with spaces") { + CHECK(station_caption(biala) == "Bia\xC5\x82" "a Podlaska"); + CHECK(station_caption(lodz) == "\xC5\x81\xC3\xB3" "d\xC5\xBA \xC5\xBB" "abieniec"); + CHECK(station_caption("Warszawa_Zachodnia") == "Warszawa Zachodnia"); + CHECK(station_caption("[End of route]") == "[End of route]"); + CHECK(station_caption("").empty()); + // a name already in utf-8 stays + CHECK(station_caption("Bia\xC5\x82" "a_Podlaska") == "Bia\xC5\x82" "a Podlaska"); +} diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index 898e833d5..238e276f5 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -323,7 +323,7 @@ std::string ToUpper(std::string const &text) void win1250_to_ascii(std::string &Input) { - std::unordered_map const charmap{{165, 'A'}, {198, 'C'}, {202, 'E'}, {163, 'L'}, {209, 'N'}, {211, 'O'}, {140, 'S'}, {143, 'Z'}, {175, 'Z'}, + static std::unordered_map const charmap{{165, 'A'}, {198, 'C'}, {202, 'E'}, {163, 'L'}, {209, 'N'}, {211, 'O'}, {140, 'S'}, {143, 'Z'}, {175, 'Z'}, {185, 'a'}, {230, 'c'}, {234, 'e'}, {179, 'l'}, {241, 'n'}, {243, 'o'}, {156, 's'}, {159, 'z'}, {191, 'z'}}; std::unordered_map::const_iterator lookup; for (auto &input : Input) diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 13b13f58d..bfa0e70c7 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -23,6 +23,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/handover.h" #include "vehicle/timetableservice.h" #include "world/mtable.h" +#include "world/stationnames.h" #include "vehicle/DynObj.h" #include "world/Event.h" #include "world/MemCell.h" @@ -1201,8 +1202,9 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub if( ( OrderCurrentGet() & ( Shunt | Loose_shunt | Obey_train | Bank ) ) == 0 ) { return true; } // jeśli przystanek, trzeba obsłużyć wg rozkładu iDrivigFlags |= moveStopPointFound; - // first 19 chars of the command is expected to be "PassengerStopPoint:" so we skip them - if( ToLower( Point.evEvent->input_text() ).compare( 19, sizeof( asNextStop ), ToLower( asNextStop ) ) != 0 ) + // the W4 and the timetable name the station each in its own file, so the two spellings are compared by their key: + // with or without the polish letters, in any case, with spaces or underscores + if( false == timetable::stop_point_is_for( Point.evEvent->input_text(), asNextStop ) ) { // jeśli nazwa nie jest zgodna if( false == IsScheduledPassengerStopVisible // check if our next scheduled stop didn't show up earlier in the scan && Point.fDist < 1.15 * fBrakeDist + 300 @@ -6139,7 +6141,8 @@ std::string TController::NextStop() const if (asNextStop == "[End of route]") return ""; // nie zawiera nazwy stacji, gdy dojechał do końca // dodać godzinę odjazdu - auto nextstop{ Bezogonkow( asNextStop, true ) }; + // the name the way the timetable spells it, in utf-8 as the user interface takes it + auto nextstop{ TrainParams.station_caption( asNextStop ) }; auto const *t{ TrainParams.TimeTable + TrainParams.StationIndex }; if( t->Ah >= 0 ) { // przyjazd diff --git a/world/Event.cpp b/world/Event.cpp index 2452b7881..94f528589 100644 --- a/world/Event.cpp +++ b/world/Event.cpp @@ -716,7 +716,8 @@ putvalues_event::deserialize_( cParser &Input, scene::scratch_data &Scratchpad ) if( contains( token, '#' ) ) { token.erase( token.find( '#' ) ); // obcięcie unikatowości } - win1250_to_ascii( token ); // get rid of non-ascii chars + // NOTE: the name stays as the scenery spells it, with its polish letters; whoever matches it with the name + // a timetable has goes by timetable::stop_point_is_for(), which takes any spelling of the station m_input.command_type = TCommandType::cm_PassengerStopPoint; // nie do kolejki (dla SetVelocity też, ale jak jest do toru dowiązany) m_passive = true; diff --git a/world/mtable.cpp b/world/mtable.cpp index daf7b6637..ce10eaafd 100644 --- a/world/mtable.cpp +++ b/world/mtable.cpp @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationtime.h" #include "utilities/dictionary.h" #include "utilities/utilities.h" +#include "world/stationnames.h" double TTrainParameters::CheckTrainLatency() const { @@ -160,12 +161,14 @@ bool TTrainParameters::UpdateMTable(double hh, double mm, std::string_view NewNa bool Mtable::TTrainParameters::RewindTimeTable(std::string actualStationName) { - if( actualStationName.compare( 0, 19, "PassengerStopPoint:" ) == 0 ) { - actualStationName = ToLower( actualStationName.substr( 19 ) ); - } + // the text of a W4 or a plain name, spelled the way its file has it: with or without the polish letters, in any case + auto const isstoppoint { actualStationName.starts_with( timetable::stop_point_prefix ) }; for( auto i = 1; i <= StationCount; ++i ) { // przechodzimy po całej tabelce i sprawdzamy nazwy stacji (bez pierwszej) - if (ToLower(TimeTable[i].StationName) == actualStationName) { + auto const &stationname { TimeTable[i].StationName }; + if( isstoppoint ? + timetable::stop_point_is_for( actualStationName, stationname ) : + timetable::same_station( actualStationName, stationname ) ) { // nazwa stacji zgodna więc ustawiamy na poprzednią, żeby w następnym kroku poprawnie obsłużyć StationIndex = i; NextStationName = TimeTable[ i ].StationName; @@ -218,6 +221,29 @@ std::string TTrainParameters::ShowRelation() const return ""; } +std::string TTrainParameters::relation_caption() const +{ + if (Relation1 != "" && Relation2 != "") + return timetable::station_caption( RelationLabel1 ) + " - " + timetable::station_caption( RelationLabel2 ); + else + return ""; +} + +std::string TTrainParameters::station_caption( std::string const &Name ) const +{ + // the station the train makes for first, then the rest of the table + if( StationIndex >= 0 && StationIndex <= StationCount && TimeTable[ StationIndex ].StationName == Name ) { + return timetable::station_caption( TimeTable[ StationIndex ].StationLabel ); + } + for( auto i = 1; i <= StationCount; ++i ) { + if( TimeTable[ i ].StationName == Name ) { + return timetable::station_caption( TimeTable[ i ].StationLabel ); + } + } + // not a station of the timetable + return timetable::station_caption( Name ); +} + TTrainParameters::TTrainParameters(std::string const &NewTrainName) /*wstępne ustawienie parametrów rozkładu jazdy*/ { @@ -236,6 +262,8 @@ void TTrainParameters::NewName(std::string_view NewTrainName) Direction = 1; Relation1 = ""; Relation2 = ""; + RelationLabel1 = ""; + RelationLabel2 = ""; for (auto &tableline : TimeTable) { tableline = TMTableLine(); @@ -307,6 +335,8 @@ bool TTrainParameters::LoadTTfile(std::string const &scnpath, int iPlus, double TrainLabel = data.TrainLabel; Relation1 = data.Relation1; Relation2 = data.Relation2; + RelationLabel1 = data.RelationLabel1; + RelationLabel2 = data.RelationLabel2; BrakeRatio = data.BrakeRatio; LocSeries = data.LocSeries; LocLoad = data.LocLoad; diff --git a/world/mtable.h b/world/mtable.h index 31fdd8810..be8b2c90d 100644 --- a/world/mtable.h +++ b/world/mtable.h @@ -42,6 +42,9 @@ class TTrainParameters double TTVmax; std::string Relation1; std::string Relation2; // nazwy stacji danego odcinka + // the two as the timetable spells them, with their letters (see TMTableEntry::StationLabel) + std::string RelationLabel1; + std::string RelationLabel2; double BrakeRatio; std::string LocSeries; // seria (typ) pojazdu double LocLoad; @@ -55,6 +58,9 @@ class TTrainParameters double CheckTrainLatency() const; /*todo: str hh:mm to int i z powrotem*/ std::string ShowRelation() const; + // the relation and the name of given station for the player: utf-8, with the letters the timetable has + std::string relation_caption() const; + std::string station_caption( std::string const &Name ) const; double WatchMTable(double DistCounter) const; std::string NextStop() const; // wpis rozkladu Offset pozycji za StationIndex (Offset>=1); poza zakresem 1..StationCount diff --git a/world/stationnames.cpp b/world/stationnames.cpp new file mode 100644 index 000000000..62948d7c8 --- /dev/null +++ b/world/stationnames.cpp @@ -0,0 +1,43 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "world/stationnames.h" + +#include "utilities/utilities.h" + +#include + +namespace timetable { + +std::string station_ascii(std::string Name) { + win1250_to_ascii(Name); + return Name; +} + +std::string station_key(std::string_view const Name) { + // the same steps the comparison of a W4 with the timetable always took: the marks off, then the case + auto key{ToLower(station_ascii(std::string{Name}))}; + std::ranges::replace(key, ' ', '_'); + return key; +} + +bool same_station(std::string_view const Left, std::string_view const Right) { + return station_key(Left) == station_key(Right); +} + +bool stop_point_is_for(std::string_view const Text, std::string_view const Station) { + return Text.starts_with(stop_point_prefix) && same_station(Text.substr(stop_point_prefix.size()), Station); +} + +std::string station_caption(std::string const &Name) { + return data_name_to_utf8(Name, true); +} + +} // namespace timetable diff --git a/world/stationnames.h b/world/stationnames.h new file mode 100644 index 000000000..0d171363f --- /dev/null +++ b/world/stationnames.h @@ -0,0 +1,40 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include + +// the names of the stations (MaSzyna-EU07/maszyna#94): a timetable and the W4 stop points of a scenery name a station +// each in its own file, in windows-1250, and they don't have to spell it the same way (with or without the polish +// letters, in another case). a name has three forms here: +// - as written, with its letters: what the files hold and what the player is shown (station_caption()) +// - the ascii one, the polish letters without their marks: what the timetable always kept as the name of a station, +// what the scenery events, the scripts and the file names of the announcements and destination boards go by +// (station_ascii()) +// - the key two spellings are the same station by (station_key(), same_station()) +namespace timetable { + +// what a W4 text starts with: "PassengerStopPoint:". in the scenery a "#" follows; the event cuts it as it's read, a memory cell keeps the whole of its text +inline constexpr std::string_view stop_point_prefix{"PassengerStopPoint:"}; + +// the name without the marks of the polish letters of windows-1250, the rest as written +std::string station_ascii(std::string Name); +// the key of a name: the ascii form in lower case, spaces as underscores +std::string station_key(std::string_view Name); +// whether the two names are spellings of the same station +bool same_station(std::string_view Left, std::string_view Right); +// whether the W4 text, as an event or a memory cell holds it, is for the station of given name, in any spelling of the two +bool stop_point_is_for(std::string_view Text, std::string_view Station); +// the name for the player: utf-8, with its letters, underscores as spaces +std::string station_caption(std::string const &Name); + +} // namespace timetable diff --git a/world/timetablereader.cpp b/world/timetablereader.cpp index 087c0205c..331680f54 100644 --- a/world/timetablereader.cpp +++ b/world/timetablereader.cpp @@ -12,6 +12,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/utilities.h" +#include "world/stationnames.h" namespace Mtable { @@ -125,8 +126,9 @@ int read_timetable(std::istream &fin, timetable_data &Data) { break; } if (s != "|") { - Data.Relation1 = s; - win1250_to_ascii(Data.Relation1); + // the name is kept as written, for showing; the ascii form is what the rest of the simulator goes by + Data.RelationLabel1 = s; + Data.Relation1 = timetable::station_ascii(s); } else conversionerror = -5; @@ -138,8 +140,9 @@ int read_timetable(std::istream &fin, timetable_data &Data) { if (s == "|") break; } - fin >> Data.Relation2; - win1250_to_ascii(Data.Relation2); + if (fin >> Data.RelationLabel2) { + Data.Relation2 = timetable::station_ascii(Data.RelationLabel2); + } while (fin >> s) { if (s == "Wymagany") break; @@ -195,9 +198,11 @@ int read_timetable(std::istream &fin, timetable_data &Data) { } while (false == contains(s, "|") && false == fin.fail()) fin >> s; - fin >> record->StationName; - // get rid of non-ascii chars. TODO: run correct version based on locale - win1250_to_ascii(record->StationName); + // the name is kept as written, for showing; the W4 stop points, the announcement files, the scenery + // events and the scripts go by its ascii form, as they always did + if (fin >> record->StationLabel) { + record->StationName = timetable::station_ascii(record->StationLabel); + } do { fin >> s; } while (!(s == "1" || s == "2" || fin.fail())); diff --git a/world/timetablereader.h b/world/timetablereader.h index aaf43e34c..8c60d3361 100644 --- a/world/timetablereader.h +++ b/world/timetablereader.h @@ -25,7 +25,11 @@ static int const MaxTTableSize = 100; // można by to robić dynamicznie struct TMTableEntry { float km{0.f}; // kilometraz linii float vmax{-1.f}; // predkosc rozkladowa przed przystankiem - std::string StationName{"nowhere"}; // nazwa stacji ('_' zamiast spacji) + // nazwa stacji ('_' zamiast spacji), bez ogonków: the form the station is matched, looked up and handed over by + // (the W4 stop points, the announcement files, the scenery events, the scripts) + std::string StationName{"nowhere"}; + // the name as the timetable spells it, in windows-1250 with its letters: for showing (timetable::station_caption()) + std::string StationLabel{"nowhere"}; std::string StationWare; // typ i wyposazenie stacji, oddz. przecinkami, bez flag obsługi int TrackNo{1}; // ilosc torow szlakowych int Ah{-1}; @@ -45,8 +49,11 @@ struct timetable_data { std::string TrainName; // the name the file is looked up by, then the one the file gives std::string TrainCategory; std::string TrainLabel; + // the first and the last station, in the two forms a station name has (see TMTableEntry) std::string Relation1; std::string Relation2; + std::string RelationLabel1; + std::string RelationLabel2; double BrakeRatio{0.0}; std::string LocSeries; double LocLoad{0.0}; From 4e0c2f71bbfa2e0e337014066158e5e5827dd7e7 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 18 Nov 2026 23:50:07 +0100 Subject: [PATCH 066/136] feat(ui): names and texts of the data shown with their letters MaSzyna-EU07/maszyna#94. What the panels took the marks off, they show as written, in utf-8: - timetable panel: the relation, the train, the station rows (the column cut and filled by characters, a letter being more than one byte now) - transcripts of the sounds and the assignment of a trainset, which lost their polish letters when read - debug panel (event of the current signal, scan table) and the editor panels (names of nodes, layers, events, tracks and include files), which went through Bezogonkow() Bezogonkow() and win1250_to_ascii() are left where the ascii form is what is wanted: file names, the python dictionary, the multiplayer packets, the search key of the editor's station list. --- application/driveruipanels.cpp | 17 +++++++++-------- application/editoruipanels.cpp | 20 ++++++++++---------- application/uitranscripts.cpp | 8 ++++---- simulation/simulationstateserializer.cpp | 4 ++-- 4 files changed, 25 insertions(+), 24 deletions(-) diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index c598842d7..015b574e6 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -21,6 +21,7 @@ http://mozilla.org/MPL/2.0/. #include "world/TractionPower.h" #include "vehicle/Camera.h" #include "world/mtable.h" +#include "world/stationnames.h" #include "vehicle/Train.h" #include "vehicle/Driver.h" #include "vehicle/drivingaid.h" @@ -350,9 +351,10 @@ timetable_panel::update() { // destination { - auto textline = Bezogonkow( owner->Relation(), true ); + // the names with the letters their files have, in utf-8 as the user interface takes it + auto textline = table.relation_caption(); if( false == textline.empty() ) { - textline += " (" + Bezogonkow( owner->TrainName(), true ) + ")"; + textline += " (" + data_name_to_utf8( owner->TrainName(), true ) + ")"; } text_lines.emplace_back( textline, Global.UITextColor ); } @@ -419,10 +421,9 @@ timetable_panel::update() { vmax += to_string( tableline->vmax, 0 ); vmax = vmax.substr( vmax.size() - 3, 3 ); // z wyrównaniem do prawej } - auto const station { ( - Bezogonkow( tableline->StationName, true ) - + " " ) - .substr( 0, 34 ) }; + // the name as the timetable spells it; in utf-8 a letter can take more than one byte, the column is + // 34 characters wide + auto const station { utf8_fit( timetable::station_caption( tableline->StationLabel ), 34 ) }; auto const location { ( ( tableline->km > 0.0 ? to_string( tableline->km, 2 ) : @@ -1164,7 +1165,7 @@ debug_panel::update_section_ai( std::vector &Output ) const { if( mechanik.VelNext == 0.0 && mechanik.eSignNext ) { // jeśli ma zapamiętany event semafora, nazwa eventu semafora - Output.emplace_back( "Current signal: " + Bezogonkow( mechanik.eSignNext->m_name ), Global.UITextColor ); + Output.emplace_back( "Current signal: " + data_name_to_utf8( mechanik.eSignNext->m_name ), Global.UITextColor ); } // distances @@ -1275,7 +1276,7 @@ debug_panel::update_section_scantable( std::vector &Output ) const { do { auto const scanline = mechanik.TableText( i ); if( scanline.empty() ) { break; } - Output.emplace_back( Bezogonkow( scanline ), Global.UITextColor ); + Output.emplace_back( data_name_to_utf8( scanline ), Global.UITextColor ); ++i; } while( i < speedtablesize ); if( Output.size() == 1 ) { diff --git a/application/editoruipanels.cpp b/application/editoruipanels.cpp index da3b56741..5b6a5a3ee 100644 --- a/application/editoruipanels.cpp +++ b/application/editoruipanels.cpp @@ -166,14 +166,14 @@ void itemproperties_panel::update(scene::basic_node *Node) } } */ - textline = format(STR_C("Name: %s"), (node->name().empty() ? std::string{STR_C("(no name)")} : Bezogonkow(node->name())).c_str()) + "\n" + format(STR_C("Type: %s"), node->node_type.c_str()); + textline = format(STR_C("Name: %s"), (node->name().empty() ? std::string{STR_C("(no name)")} : data_name_to_utf8(node->name())).c_str()) + "\n" + format(STR_C("Type: %s"), node->node_type.c_str()); text_lines.emplace_back(textline, Global.UITextColor); textline = format(STR_C("Location: %.2f, %.2f, %.2f (distance %.1f m)"), node->location().x, node->location().y, node->location().z, glm::length(glm::dvec3{node->location().x, 0.0, node->location().z} - glm::dvec3{camera.Pos.x, 0.0, camera.Pos.z})) + "\nUUID: " + node->uuid.to_string(); if (scene::Layers.valid(node->layer())) { - textline += "\n" + format(STR_C("Layer: %s"), Bezogonkow(scene::Layers.layer(node->layer()).name).c_str()); + textline += "\n" + format(STR_C("Layer: %s"), data_name_to_utf8(scene::Layers.layer(node->layer()).name).c_str()); } text_lines.emplace_back(textline, Global.UITextColor); @@ -286,7 +286,7 @@ void itemproperties_panel::update(scene::basic_node *Node) { textline += ", "; } - textline += event.second != nullptr ? Bezogonkow(event.second->m_name) : event.first + STR_C(" (missing)"); + textline += event.second != nullptr ? data_name_to_utf8(event.second->m_name) : event.first + STR_C(" (missing)"); } textline += "] "; } @@ -299,7 +299,7 @@ void itemproperties_panel::update(scene::basic_node *Node) textline = format(STR_C("Data: [%s] [%.2f] [%.2f]"), subnode->Text().c_str(), subnode->Value1(), subnode->Value2()); text_lines.emplace_back(textline, Global.UITextColor); - textline = format(STR_C("Track: %s"), (subnode->asTrackName.empty() ? std::string{STR_C("(none)")} : Bezogonkow(subnode->asTrackName)).c_str()); + textline = format(STR_C("Track: %s"), (subnode->asTrackName.empty() ? std::string{STR_C("(none)")} : data_name_to_utf8(subnode->asTrackName)).c_str()); text_lines.emplace_back(textline, Global.UITextColor); } @@ -888,7 +888,7 @@ void nodebank_panel::render_templates_list(std::string const &Filter) ImGui::TextDisabled(" %s", entry.category.c_str()); } category = &entry.category; - auto const label{(entry.category.empty() ? " " : " ") + entry.name + " (" + Bezogonkow(entry.file) + ")##inc" + std::to_string(entryidx)}; + auto const label{(entry.category.empty() ? " " : " ") + entry.name + " (" + data_name_to_utf8(entry.file) + ")##inc" + std::to_string(entryidx)}; if (list_item(label.c_str(), entry.statement == m_selectedtemplate)) m_selectedtemplate = entry.statement; ++listed; @@ -1704,7 +1704,7 @@ std::string layer_content(scene::basic_layer const &Layer) std::string layer_name(scene::layer_handle const Layer) { - return scene::Layers.valid(Layer) ? Bezogonkow(scene::Layers.layer(Layer).name) : std::string{STR_C("(none)")}; + return scene::Layers.valid(Layer) ? data_name_to_utf8(scene::Layers.layer(Layer).name) : std::string{STR_C("(none)")}; } // button which can be greyed out, with an explanation shown when it's hovered @@ -1748,7 +1748,7 @@ void itemproperties_panel::render_include() auto &include{*m_include}; include.active = false; - ImGui::Text(STR_C("include: %s"), Bezogonkow(include.target).c_str()); + ImGui::Text(STR_C("include: %s"), data_name_to_utf8(include.target).c_str()); if (false == include.info.name.empty()) { ImGui::TextDisabled("%s", include.info.name.c_str()); @@ -2280,7 +2280,7 @@ void includes_panel::render_list() { auto const &entry{entries[m_listed[row]]}; auto const marker{entry.complete ? std::string{STR_C("[ready]")} + " " : entry.described ? std::string{STR_C("[incomplete]")} + " " : std::string{}}; - auto const label{marker + Bezogonkow(entry.file) + (entry.name.empty() ? "" : " - " + entry.name) + "##" + std::to_string(m_listed[row])}; + auto const label{marker + data_name_to_utf8(entry.file) + (entry.name.empty() ? "" : " - " + entry.name) + "##" + std::to_string(m_listed[row])}; if (false == entry.described) { ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled)); @@ -2310,7 +2310,7 @@ void includes_panel::render_list() void includes_panel::render_description() { ImGui::Separator(); - ImGui::Text("%s", Bezogonkow(m_file).c_str()); + ImGui::Text("%s", data_name_to_utf8(m_file).c_str()); input_text(STR_C("Name"), m_info.name); input_text(STR_C("Category"), m_info.category); input_text(STR_C("Description"), m_info.description); @@ -2388,7 +2388,7 @@ void includes_panel::render_description() { std::string error; m_statuserror = false == editor_includes::save(m_file, m_info, error); - m_status = m_statuserror ? error : format(STR_C("Description saved in \"%s\""), Bezogonkow(m_file).c_str()); + m_status = m_statuserror ? error : format(STR_C("Description saved in \"%s\""), data_name_to_utf8(m_file).c_str()); if (false == m_statuserror) { EditorIncludes.update(m_file); diff --git a/application/uitranscripts.cpp b/application/uitranscripts.cpp index 7ce360530..dc0aec0eb 100644 --- a/application/uitranscripts.cpp +++ b/application/uitranscripts.cpp @@ -38,8 +38,8 @@ TTranscripts::Add( std::string const &txt, bool /*backgorund*/ ) { if( true == txt.empty() ) { return; } - std::string asciitext{ txt }; win1250_to_ascii( asciitext ); // TODO: launch relevant conversion table based on language - cParser parser( asciitext ); + // the captions are read as their files have them (windows-1250, the newer ones utf-8) and shown with their letters + cParser parser( txt ); while( true == parser.getTokens( 3, false, "[]\n" ) ) { float begin{ 0.f }; @@ -49,14 +49,14 @@ TTranscripts::Add( std::string const &txt, bool /*backgorund*/ ) { >> begin >> end >> transcript; - AddLine( transcript, static_cast(0.10 * begin), static_cast(0.12 * end), false ); + AddLine( data_text_to_utf8( transcript ), static_cast(0.10 * begin), static_cast(0.12 * end), false ); } // try to handle malformed(?) cases with no show/hide times std::string transcript; parser >> transcript; while( false == transcript.empty() ) { // WriteLog( "Transcript text with no display/hide times: \"" + transcript + "\"" ); - AddLine( transcript, 0.0, static_cast(0.12 * static_cast(transcript.size())), false ); + AddLine( data_text_to_utf8( transcript ), 0.0, static_cast(0.12 * static_cast(transcript.size())), false ); transcript = ""; parser >> transcript; } } diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index 5dbc6efbf..41f67398c 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -250,8 +250,8 @@ state_serializer::deserialize_assignment( cParser &Input, scene::scratch_data &S while( false == token.empty() && token != "endassignment" ) { // assignment is expected to come as string pairs: language id and the actual assignment enclosed in quotes to form a single token - auto assignment{ Input.getToken() }; - win1250_to_ascii( assignment ); + // the assignment is only shown to the player, so it's kept with its letters, in utf-8 as the user interface takes it + auto const assignment{ data_text_to_utf8( Input.getToken() ) }; Scratchpad.trainset.assignment.emplace( token, assignment ); token = Input.getToken(); } From 3633c254fcce939a97d3aa3e4bcb1efbd28d6b6d Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 19 Nov 2026 01:58:29 +0100 Subject: [PATCH 067/136] feat(physics): pullee mode, a vehicle prepared for being hauled dead in a train A dead locomotive or unit in somebody else's train (hook and brake hose, coupling 3) brakes the train today (MaSzyna-EU07/maszyna#64): - one with the emergency brake of an inactive cab (InactiveCabFlag bit 1: of the test vehicles the Vectron, Dragon, Elf, Impuls and EN57AKL) vents the brake pipe for as long as it is in the train, since its cab is never activated. Behind an EU07 the pipe is empty in two seconds and stays so, - the spring brake applies once the feed pipe of the vehicle, which is its own main reservoir, falls below MinFP: at once without air, and within 20 minutes of a cold start as the reservoir leaks down (EU47: 0.077 bar a minute, from 4.4 bar). TMoverParameters::PulleeMode, set with PulleeModeSwitch(), is the vehicle prepared for hauling. In the mode it: - vents the brake pipe for nothing of its own (inactive cab, vigilance and cab signalling, radio-stop, the spring brake of SpringBrakeDriveEmergencyVel); the alarm chain, which a train parting sets, still does, - gets no force from its spring brake, whatever air its cylinder has, - has its driver's valve cut out and its local brake released, whatever the handles show. The distributor stays on the brake pipe: it brakes and releases with the train, - keeps its battery off and takes no cab: BatterySwitch(true) and CabActivisation() are refused, and the BatterySwitch and CabActivisation commands of a train's driver pass through it. Entering the mode lets go of the hand brake and of the spring brake switch and switches the battery off; a vehicle with an active cab can't enter it. Leaving it gives the controls back and the spring brake as its cylinder has it. Nothing sets the mode yet, and a vehicle not in it does what it did. Refs MaSzyna-EU07/maszyna#64 --- McZapkie/MOVER.h | 4 + McZapkie/Mover.cpp | 73 ++++++- tests/unit/test_pullee.cpp | 432 +++++++++++++++++++++++++++++++++++++ 3 files changed, 500 insertions(+), 9 deletions(-) create mode 100644 tests/unit/test_pullee.cpp diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 2ca88ff39..06c0e6ec0 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2258,6 +2258,9 @@ class TMoverParameters int CabActive = 0; // numer kabiny, z której jest sterowanie: 1 lub -1; w przeciwnym razie brak sterowania - rozrzad int CabOccupied = 0; // numer kabiny, w ktorej jest obsada (zwykle jedna na skład) // TODO: move to TController bool CabMaster = false; // czy pojazd jest nadrzędny w składzie + // pullee mode ("jazda ciągniona", MaSzyna-EU07/maszyna#64): the vehicle is prepared for being hauled dead in a + // train, see PulleeModeSwitch() + bool PulleeMode{false}; inline bool IsCabMaster() const { return CabActive == CabOccupied && CabMaster; @@ -2622,6 +2625,7 @@ class TMoverParameters bool SpringBrakeActivate(bool State); bool SpringBrakeShutOff(bool State); bool SpringBrakeRelease(); + bool PulleeModeSwitch(bool const State); /*! stopnie hamowania - hamulec zasadniczy*/ bool IncBrakeLevelOld(void); diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 2284f7b41..3ae2a9242 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -3701,6 +3701,11 @@ bool TMoverParameters::CabActivisation(bool const Enforce) bool OK = false; OK = Enforce || CabActive == 0; // numer kabiny, z której jest sterowanie + if (PulleeMode) + { + // nobody drives from a vehicle prepared for hauling + OK = false; + } if (OK) { CabActive = CabOccupied; // sterowanie jest z kabiny z obsadą @@ -3961,6 +3966,11 @@ void TMoverParameters::SecuritySystemCheck(double dt) bool TMoverParameters::BatterySwitch(bool State, range_t const Notify) { using enum range_t; + if (PulleeMode && State) + { + // the battery of a vehicle prepared for hauling stays off + return false; + } auto const initialstate{Battery}; // Ra: ukrotnienie załączania baterii jest jakąś fikcją... @@ -4045,6 +4055,35 @@ bool TMoverParameters::SpringBrakeRelease() return false; } +// ************************************************************************************************* +// pullee mode ("jazda ciągniona", MaSzyna-EU07/maszyna#64): prepares the vehicle for being hauled dead in a +// train, or puts it back in service. while in the mode the vehicle: +// - vents the brake pipe for nothing of its own (inactive cab, vigilance, radio-stop, spring brake), only when +// the train parts (UpdatePipePressure()), +// - gets no force from its spring brake, whatever air its cylinder has (BrakeForce()), +// - has its driver's valve cut out and its local brake released, whatever the handles show; the distributor +// stays on the brake pipe, so it brakes and releases with the train, +// - keeps its battery off and takes no cab (BatterySwitch(), CabActivisation() and their commands). +// entering it also lets go of the hand brake and of the spring brake switch. +// returns whether the mode changed; a vehicle driven from can't enter it +// ************************************************************************************************* +bool TMoverParameters::PulleeModeSwitch(bool const State) +{ + if (PulleeMode == State || (State && CabActive != 0)) + { + return false; + } + PulleeMode = State; + if (PulleeMode) + { + DecManualBrakeLevel(ManualBrakePosNo); + SpringBrake.Activate = false; + SecuritySystem.set_enabled(false); + Battery = false; + } + return true; +} + // ************************************************************************************************* // Q: 20160710 // kierunek do tyłu @@ -5313,6 +5352,7 @@ void TMoverParameters::UpdatePipePressure(double dt) if (BrakeCtrlPosNo > 1) { + // the local brake of a vehicle prepared for hauling (PulleeMode) is held released, whatever asks for it if (EngineType != TEngineType::ElectricInductionMotor) { double lbpa = LocHandleTimeTraxx ? eim_localbrake : LocalBrakePosA; @@ -5324,7 +5364,7 @@ void TMoverParameters::UpdatePipePressure(double dt) { lbpa = std::max(lbpa, StopBrakeDecc); } - dpLocalValve = LocHandle->GetPF(std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); + dpLocalValve = LocHandle->GetPF(PulleeMode ? 0.0 : std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); } else { @@ -5345,7 +5385,7 @@ void TMoverParameters::UpdatePipePressure(double dt) { lbpa = 0.0; } - dpLocalValve = LocHandle->GetPF(std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); + dpLocalValve = LocHandle->GetPF(PulleeMode ? 0.0 : std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); } LockPipe = PipePress < (LockPipe ? LockPipeOff : LockPipeOn); @@ -5363,7 +5403,12 @@ void TMoverParameters::UpdatePipePressure(double dt) } Handle->SetReductor(BrakeCtrlPos2); - if ((BrakeOpModes & bom_PS) == 0 || (CabOccupied != 0 && BrakeOpModeFlag != bom_PS)) + if (PulleeMode) + { + // the driver's valve of a vehicle prepared for hauling is cut out, whatever its handle shows + dpMainValve = 0; + } + else if ((BrakeOpModes & bom_PS) == 0 || (CabOccupied != 0 && BrakeOpModeFlag != bom_PS)) { if (BrakeOpModeFlag < bom_EP || Handle->GetPos(bh_EB) - 0.5 < BrakeCtrlPosR || (BrakeHandle != TBrakeHandle::MHZ_EN57 && BrakeHandle != TBrakeHandle::MHZ_K8P)) @@ -5407,10 +5452,13 @@ void TMoverParameters::UpdatePipePressure(double dt) // EngDmgFlag 32 (load destroyed) used to trigger this too; dropped, it has nothing to do with // the emergency brake (a broken coupler sets AlarmChainFlag instead). the Elf's emergency brake position - // vents the pipe only from the vehicle driven from, whatever the controllers of the others show - if (RadioStopFlag || AlarmChainFlag || (EIMCtrlEmergency && LocalBrakePosA >= 1.0) || (IsMainCtrlEmergencyPos() && IsCabMaster()) || SecuritySystem.is_braking() || - (SpringBrakeDriveEmergencyVel >= 0 && Vel > SpringBrakeDriveEmergencyVel && SpringBrake.IsActive) || - (0 == CabActive && (InactiveCabFlag & activation::emergencybrake) != 0)) + // vents the pipe only from the vehicle driven from, whatever the controllers of the others show. + // a vehicle prepared for hauling (PulleeMode) vents it for nothing of its own, only for the alarm chain, + // which a train parting sets too + auto const ownemergency{RadioStopFlag || (EIMCtrlEmergency && LocalBrakePosA >= 1.0) || (IsMainCtrlEmergencyPos() && IsCabMaster()) || SecuritySystem.is_braking() || + (SpringBrakeDriveEmergencyVel >= 0 && Vel > SpringBrakeDriveEmergencyVel && SpringBrake.IsActive) || + (0 == CabActive && (InactiveCabFlag & activation::emergencybrake) != 0)}; + if (AlarmChainFlag || (ownemergency && false == PulleeMode)) { EmergencyValveFlow = PF(0, PipePress, 0.15) * dt; } @@ -6210,7 +6258,8 @@ double TMoverParameters::BrakeForce(TTrackParam const & /*Track*/) K = MaxBrakeForce * ManualBrakeRatio(); } - if (SpringBrake.IsReady) + // the spring brake of a vehicle prepared for hauling (PulleeMode) is released by hand: no force, whatever its cylinder has + if (SpringBrake.IsReady && false == PulleeMode) K += std::max(0.0, SpringBrake.MinForcePressure - SpringBrake.Cylinder->P()) * SpringBrake.MaxBrakeForce; u = (BrakePress * P2FTrans - BrakeCylSpring) * BrakeCylMult[0] - BrakeSlckAdj; @@ -14205,6 +14254,11 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do break; } } + if (PulleeMode) + { + // a vehicle prepared for hauling takes no cab, the command only passes through it + CabActive = 0; + } DirAbsolute = DirActive * CabActive; CabMaster = false; OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); @@ -14232,7 +14286,8 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do } else if (Command == "BatterySwitch") /*NBMX*/ { - if (BatteryStart == start_t::manual) + // the battery of a vehicle prepared for hauling (PulleeMode) stays off + if (BatteryStart == start_t::manual && (false == PulleeMode || CValue1 <= 0.0)) { Battery = CValue1 > 0.0; } diff --git a/tests/unit/test_pullee.cpp b/tests/unit/test_pullee.cpp new file mode 100644 index 000000000..9800532c7 --- /dev/null +++ b/tests/unit/test_pullee.cpp @@ -0,0 +1,432 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "consist.h" +#include "drive.h" +#include "real_vehicles.h" + +using test::definition; +using test::vehicle; + +// the pullee mode ("jazda ciągniona", MaSzyna-EU07/maszyna#64): a vehicle prepared for being hauled dead in a +// train, TMoverParameters::PulleeModeSwitch(). the trains here are an EU07 and the vehicle behind it, coupled with +// the hook and the brake hose alone, as with coupling 3 of a scenery. every test has both sides: what the vehicle +// does as it is (unchanged by the mode being there), and what it does prepared for hauling. +// pressures in bar, the brake pipe runs at 5.0 + +namespace { + +constexpr int hook_and_brake_hose{coupling::coupler | coupling::brakehose}; + +// an EU07 with nobody in it, its brake pipe held by the test the way a driver's valve would hold it, and the +// vehicle it hauls. Velocity as of a trainset of a scenery [km/h]: not 0, the vehicles are ready to depart, +// 0, they stand braked (brake pipe at 3.5, hand and spring brakes on, batteries off) +struct hauled_train { + test::consist train; + vehicle &locomotive; + vehicle &hauled; + + hauled_train(definition const &Hauled, double const Velocity, bool const Pullee) + : locomotive{train.add(definition::fiz("4e_v1/4e"), 0, test::consist::full_coupling, Velocity)}, hauled{train.add(Hauled, 0, hook_and_brake_hose, Velocity)} { + if (Pullee) { + REQUIRE(hauled->PulleeModeSwitch(true)); + } + locomotive.hold_brake_pipe(5.0); + } + + void run(double const Seconds) { train.run(Seconds); } +}; + +// no air in the main reservoir and the feed pipe, as after standing dead for some hours +void drain_feed_air(TMoverParameters &Vehicle) { + Vehicle.Pipe2->CreatePress(0.0); + Vehicle.Pipe2->Act(); + Vehicle.CompressedVolume = 0.0; +} + +// whether the real vehicle can go in a train at all: the road vehicles can't, nor can the draisine, which has no coupler +bool can_be_hauled(std::string const &Path) { + vehicle probe{definition::fiz(Path)}; + return (probe->CategoryFlag & 1) != 0 && probe->Couplers[end::front].CouplerType != TCouplerType::NoCoupler; +} + +} // namespace + +TEST_CASE("pullee: a dead Vectron vents the brake pipe of the train hauling it, prepared for hauling it doesn't") { + // the Vectron applies the emergency brake while none of its cabs is active (InactiveCabFlag bit 1), which a + // vehicle hauled with the hook and the brake hose never has + auto const vectron{definition::fiz("vectron_v1/wariant_7w")}; + SUBCASE("as it is") { + hauled_train train{vectron, 60.0, false}; + REQUIRE((train.hauled->InactiveCabFlag & activation::emergencybrake) != 0); + REQUIRE_FALSE(train.hauled->PulleeMode); + train.run(120.0); + CHECK(train.hauled->EmergencyValveFlow > 0.0); + CHECK(train.locomotive->PipePress < 4.95); // the pipe sags although the locomotive keeps feeding it + CHECK(train.hauled->BrakePress > 0.4); + CHECK(train.hauled.speed() < 30.0); + } + SUBCASE("prepared for hauling") { + hauled_train train{vectron, 60.0, true}; + train.run(120.0); + CHECK(train.hauled->EmergencyValveFlow == 0.0); + CHECK(train.locomotive->PipePress > 4.99); + CHECK(train.hauled->BrakePress < 0.1); + CHECK(train.hauled->Fb < 1.0); + CHECK(train.hauled.speed() > 40.0); // running resistance alone + } +} + +TEST_CASE("pullee: an EU07 with a driver can't release the brakes of a dead Vectron, and hauls one prepared for hauling") { + for (auto const pullee : {false, true}) { + CAPTURE(pullee); + test::reseed_random(); + test::consist train; + // a trainset ready to depart, as with velocity 0.1 in a scenery + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 1, test::consist::full_coupling, 0.1)}; + auto &hauled{train.add(definition::fiz("vectron_v1/wariant_7w"), 0, hook_and_brake_hose, 0.1)}; + if (pullee) { + REQUIRE(hauled->PulleeModeSwitch(true)); + } + test::track const track{0.15, 0.0, test::catenary_3kv}; + auto driven{test::driving(train)}; + REQUIRE(test::start_up(driven, track, 600.0)); + test::release_brakes(driven.cab); + // the driver of a train switches on the batteries of the vehicles not controlled from the cab, TController::CheckVehicles() + hauled->BatterySwitch(true); + test::drive(driven, track, 60.0); + if (false == pullee) { + // the Vectron has emptied the brake pipe, and both locomotives stand on an emergency application + CHECK(hauled->Battery); + CHECK(locomotive->PipePress < 1.0); + CHECK(locomotive->BrakePress > 3.0); + CHECK(hauled->BrakePress > 3.0); + continue; + } + CHECK_FALSE(hauled->Battery); + CHECK(locomotive->PipePress > 4.9); + CHECK(locomotive->BrakePress < 0.1); + CHECK(hauled->BrakePress < 0.1); + // the driver notches up watching the ammeter + for (int i = 0; i < 3 && driven.cab.DirActive <= 0; ++i) { + driven.cab.DirectionForward(); + } + for (int second = 0; second < 60; second += 5) { + if (std::abs(driven.controlling.Im) < 350.0 && false == driven.controlling.IsMainCtrlMaxPowerPos()) { + driven.controlling.IncMainCtrl(1); + } + test::drive(driven, track, 5.0); + } + CHECK(hauled.speed() > 20.0); + } +} + +TEST_CASE("pullee: the spring brake of a dead locomotive without air stops the train, prepared for hauling it gives no force") { + // the spring brake is held off by the air of the feed pipe, which on a dead locomotive is what its main + // reservoir has left. the EU47 and the EP09 have the spring brake alone, the Vectron the emergency brake too + for (auto const *path : {"e186_v2/eu47", "ep09_v2/104e", "vectron_v1/wariant_7w"}) { + for (auto const pullee : {false, true}) { + CAPTURE(path); + CAPTURE(pullee); + test::reseed_random(); + hauled_train train{definition::fiz(path), 60.0, pullee}; + auto const &hauled{train.hauled.mover()}; + REQUIRE(hauled.SpringBrake.MaxBrakeForce > 0.0); + drain_feed_air(train.hauled.mover()); + train.run(60.0); + // no air came from anywhere: the cylinder of the spring brake is empty either way + REQUIRE(hauled.SpringBrake.SBP < 0.1); + if (pullee) { + CHECK(hauled.Fb < 1.0); + CHECK(train.hauled.speed() > 45.0); + } + else { + CHECK(hauled.Fb > 30000.0); + CHECK(std::abs(train.hauled.speed()) < 1.0); + } + } + } +} + +TEST_CASE("pullee: a dead EU47 starts to drag once its main reservoir has leaked down, prepared for hauling it never does") { + // from a standing start the reservoir has 4.4 bar, and the spring brake comes on below 3.5 (MinFP) + for (auto const pullee : {false, true}) { + CAPTURE(pullee); + test::reseed_random(); + hauled_train train{definition::fiz("e186_v2/eu47"), 0.0, pullee}; + auto &hauled{train.hauled.mover()}; + // what the driver of the train does on its inspection, TController::AutoRewident() + hauled.DecManualBrakeLevel(ManualBrakePosNo); + hauled.SpringBrake.Activate = false; + train.run(180.0); + // charged and released: nothing holds it yet + CHECK(hauled.BrakePress < 0.1); + CHECK(hauled.Fb < 1.0); + train.run(1020.0); // 20 minutes since the start + CHECK(hauled.ScndPipePress < hauled.SpringBrake.MinForcePressure); + if (pullee) { + CHECK(hauled.Fb < 1.0); + } + else { + CHECK(hauled.Fb > 5000.0); + } + } +} + +TEST_CASE("pullee: a vehicle prepared for hauling brakes and releases with the train, and its spring brake stays off after") { + // the distributor stays on the brake pipe. with air in the feed pipe and without: the cylinders fill from the + // auxiliary reservoir, and the spring brake, with no air to hold it off, still gives nothing after the release + for (auto const *path : {"vectron_v1/wariant_7w", "e6act_v2/e6acta", "ep09_v2/104e", "e186_v2/eu47"}) { + for (auto const feedair : {true, false}) { + CAPTURE(path); + CAPTURE(feedair); + test::reseed_random(); + hauled_train train{definition::fiz(path), 60.0, true}; + auto const &hauled{train.hauled.mover()}; + if (false == feedair) { + drain_feed_air(train.hauled.mover()); + } + train.run(30.0); + CHECK(hauled.BrakePress < 0.1); + // a full service application + train.locomotive.hold_brake_pipe(3.5); + train.run(20.0); + CHECK(hauled.BrakePress > 2.0); + CHECK(hauled.Fb > 30000.0); + train.locomotive.hold_brake_pipe(5.0); + train.run(90.0); + CHECK(hauled.BrakePress < 0.1); + CHECK(hauled.Fb < 1.0); + CHECK(hauled.EmergencyValveFlow == 0.0); + } + } +} + +TEST_CASE("pullee: the spring brake of an Impuls prepared for hauling doesn't call the emergency brake") { + // SpringBrakeDriveEmergencyVel=2: above 2 km/h an applied spring brake vents the brake pipe. the emergency + // brake of the inactive cab (InactiveCabFlag) is taken out of the definition, so that it's the spring brake's + auto const impuls{definition::fiz("impuls_v1/31we-a_pr").set("Cntrl", "InactiveCabFlag", 0)}; + for (auto const pullee : {false, true}) { + CAPTURE(pullee); + test::reseed_random(); + hauled_train train{impuls, 60.0, pullee}; + auto const &hauled{train.hauled.mover()}; + REQUIRE(hauled.InactiveCabFlag == 0); + REQUIRE(hauled.SpringBrakeDriveEmergencyVel == doctest::Approx(2.0)); + drain_feed_air(train.hauled.mover()); + train.run(10.0); + REQUIRE(hauled.Vel > 2.0); + REQUIRE(hauled.SpringBrake.IsActive); + if (pullee) { + CHECK(hauled.EmergencyValveFlow == 0.0); + CHECK(hauled.BrakePress < 0.1); + } + else { + CHECK(hauled.EmergencyValveFlow > 0.0); + } + } +} + +TEST_CASE("pullee: the brake valves in the cab of a vehicle prepared for hauling move no air") { + // with somebody in the cab: nobody is put there by a scenery, but the valves are cut out whoever sits down. + // the Elf has the MHZ_K5P driver's valve, the EU47 the MHZ_6P, the Vectron the MHZ_K8P, the EP09 and the EU07 the FV4a + for (auto const *path : {"elf_v1/21we-a", "e186_v2/eu47", "vectron_v1/wariant_7w", "ep09_v2/104e", "4e_v1/4e"}) { + for (auto const pullee : {false, true}) { + CAPTURE(path); + CAPTURE(pullee); + test::reseed_random(); + vehicle driven{definition::fiz(path), 0.1, "test", 1}; + // the emergency brake of the inactive cab is another matter, see above + driven->InactiveCabFlag = 0; + if (pullee) { + REQUIRE(driven->PulleeModeSwitch(true)); + } + // the local brake a driver keeps a standing vehicle on is let go + driven->DecLocalBrakeLevel(LocalBrakePosNo); + driven.run(20.0); + REQUIRE(driven->BrakePress < 0.1); + auto const charged{driven->PipePress}; + // full service braking with the driver's valve + driven->BrakeLevelSet(driven->Handle->GetPos(bh_FB)); + driven.run(10.0); + if (pullee) { + CHECK(driven->dpMainValve == 0.0); + CHECK(driven->PipePress > charged - 0.1); + CHECK(driven->BrakePress < 0.1); + } + else { + CHECK(driven->PipePress < charged - 0.5); + CHECK(driven->BrakePress > 1.0); + } + // and the emergency position + driven->BrakeLevelSet(driven->Handle->GetPos(bh_EB)); + driven.run(10.0); + if (pullee) { + CHECK(driven->dpMainValve == 0.0); + CHECK(driven->PipePress > charged - 0.1); + } + else { + CHECK(driven->PipePress < 1.0); + } + } + } +} + +TEST_CASE("pullee: the local brake of a vehicle prepared for hauling stays released") { + for (auto const *path : {"vectron_v1/wariant_7w", "4e_v1/4e", "ep09_v2/104e"}) { + for (auto const pullee : {false, true}) { + CAPTURE(path); + CAPTURE(pullee); + test::reseed_random(); + vehicle driven{definition::fiz(path), 0.1, "test", 1}; + driven->InactiveCabFlag = 0; + driven.hold_brake_pipe(5.0); + if (pullee) { + REQUIRE(driven->PulleeModeSwitch(true)); + } + // applied with the lever, as on a vehicle left on standby, and asked for by the brake computer of a unit + // (what the MED of TDynamicObject writes; the lever of a Vectron does nothing without it) + driven->IncLocalBrakeLevel(LocalBrakePosNo); + driven->LocalBrakePosAEIM = 1.0; + driven.run(20.0); + if (pullee) { + CHECK(driven->BrakePress < 0.1); + } + else { + CHECK(driven->BrakePress > 1.0); + } + } + } +} + +TEST_CASE("pullee: entering the mode lets go of the hand brake and the spring brake switch, and switches the battery off") { + SUBCASE("a locomotive standing braked, its spring brake switched on") { + vehicle vectron{definition::fiz("vectron_v1/wariant_7w")}; + REQUIRE(vectron->SpringBrake.Activate); + REQUIRE_FALSE(vectron->PulleeMode); + CHECK(vectron->PulleeModeSwitch(true)); + CHECK(vectron->PulleeMode); + CHECK_FALSE(vectron->SpringBrake.Activate); + // already in it + CHECK_FALSE(vectron->PulleeModeSwitch(true)); + } + SUBCASE("a unit standing with its hand brake on") { + vehicle en57{definition::fiz("en57_v1/5bgb")}; + REQUIRE(en57->ManualBrakePos > 0); + CHECK(en57->PulleeModeSwitch(true)); + CHECK(en57->ManualBrakePos == 0); + } + SUBCASE("a locomotive ready to depart, its battery on") { + vehicle vectron{definition::fiz("vectron_v1/wariant_7w"), 0.1}; + REQUIRE(vectron->Battery); + CHECK(vectron->PulleeModeSwitch(true)); + CHECK_FALSE(vectron->Battery); + } +} + +TEST_CASE("pullee: the battery and the cabs of a vehicle prepared for hauling stay off, until it leaves the mode") { + vehicle vectron{definition::fiz("vectron_v1/wariant_7w"), 0.0, "test", 1}; + REQUIRE(vectron->PulleeModeSwitch(true)); + CHECK_FALSE(vectron->BatterySwitch(true)); + CHECK_FALSE(vectron->Battery); + CHECK_FALSE(vectron->CabActivisation()); + CHECK_FALSE(vectron->CabActivisation(true)); + CHECK(vectron->CabActive == 0); + vectron.run(5.0); + // the vigilance device and the cab signalling of a cab never activated stay out of it + CHECK_FALSE(vectron->SecuritySystem.is_braking()); + CHECK(vectron->EmergencyValveFlow == 0.0); + + REQUIRE(vectron->PulleeModeSwitch(false)); + CHECK_FALSE(vectron->PulleeMode); + CHECK(vectron->BatterySwitch(true)); + CHECK(vectron->Battery); + CHECK(vectron->CabActivisation()); + CHECK(vectron->CabActive == 1); + // a vehicle driven from isn't one to haul + CHECK_FALSE(vectron->PulleeModeSwitch(true)); + CHECK_FALSE(vectron->PulleeMode); +} + +TEST_CASE("pullee: a cab activated on a dead battery calls the emergency brake, which the mode keeps from happening") { + // the vigilance device of an activated cab brakes when it has no power + for (auto const pullee : {false, true}) { + CAPTURE(pullee); + test::reseed_random(); + vehicle vectron{definition::fiz("vectron_v1/wariant_7w"), 0.0, "test", 1}; + vectron->InactiveCabFlag = 0; + if (pullee) { + REQUIRE(vectron->PulleeModeSwitch(true)); + } + CHECK(vectron->CabActivisation() == (false == pullee)); + vectron.run(0.5); + CHECK(vectron->SecuritySystem.is_braking() == (false == pullee)); + CHECK((vectron->EmergencyValveFlow > 0.0) == (false == pullee)); + } +} + +TEST_CASE("pullee: the battery and cab commands of the train's driver pass a vehicle prepared for hauling by") { + // coupled with the control cable too, which a hauled vehicle normally isn't + for (auto const pullee : {false, true}) { + CAPTURE(pullee); + test::reseed_random(); + test::consist train; + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 1)}; + auto &hauled{train.add(definition::fiz("4e_v1/4e"))}; + auto &last{train.add(definition::fiz("4e_v1/4e"))}; + if (pullee) { + REQUIRE(hauled->PulleeModeSwitch(true)); + } + REQUIRE_FALSE(hauled->Battery); + locomotive->BatterySwitch(true); + locomotive->CabActivisation(); + train.run(2.0); + CHECK(hauled->Battery == (false == pullee)); + CHECK(hauled->CabActive == (pullee ? 0 : 1)); + // the vehicle behind it gets them either way + CHECK(last->Battery); + CHECK(last->CabActive == 1); + } +} + +TEST_CASE("pullee: every real vehicle prepared for hauling runs free behind a locomotive, with no air of its own") { + for (auto const &path : test::real_vehicles()) { + CAPTURE(path); + test::reseed_random(); + if (false == can_be_hauled(path)) { + continue; + } + test::reseed_random(); + hauled_train train{definition::fiz(path), 60.0, true}; + auto const &hauled{train.hauled.mover()}; + drain_feed_air(train.hauled.mover()); + train.run(60.0); + CHECK(hauled.EmergencyValveFlow == 0.0); + CHECK(hauled.BrakePress < 0.1); + CHECK(hauled.Fb < 1.0); + CHECK(train.locomotive->PipePress > 4.99); + CHECK(train.hauled.speed() > 40.0); + } +} + +TEST_CASE("pullee: every real vehicle standing braked releases once prepared for hauling and charged") { + for (auto const &path : test::real_vehicles()) { + CAPTURE(path); + test::reseed_random(); + if (false == can_be_hauled(path)) { + continue; + } + test::reseed_random(); + // hand brakes on, spring brakes switched on, cylinders half full, the pipe at 3.5 + hauled_train train{definition::fiz(path), 0.0, true}; + auto const &hauled{train.hauled.mover()}; + CHECK(hauled.ManualBrakePos == 0); + CHECK_FALSE(hauled.SpringBrake.Activate); + CHECK_FALSE(hauled.Battery); + train.run(180.0); + CHECK(hauled.EmergencyValveFlow == 0.0); + CHECK(hauled.BrakePress < 0.1); + // the cylinders of a few are still letting out the last of their air (6Dg, SM42, 810: 15-72 N) + CHECK(hauled.Fb < 500.0); + } +} From 79616ba5a420232c32f914d3046a6ef278318673 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 19 Nov 2026 01:58:56 +0100 Subject: [PATCH 068/136] feat(scenery): the parameter H after the coupling of a vehicle prepares it for hauling A vehicle of a trainset spawns in the pullee mode (MaSzyna-EU07/maszyna#64) with the parameter H among the ones written after its coupling, on its own or with the others: node -1 0 EU160-001 dynamic pkp/vectron_v1 1293-107 wariant_7w 0 nobody 3.H 0 enddynamic ... 3.BG.H ... The parameters are told by their first letter (B brakes, W wheels, T temperatures, L load); H was free, and one a build doesn't know is skipped, so a scenery with it loads in the releases too, where the vehicle is as before. The letters after the H are left for later. The mode is entered once the vehicle has its starting state, so a standing one lets go of its hand brake and its spring brake switch. A vehicle with the H has nobody driving it, whatever its crew entry says (its cab can't be activated); a driver left out is written to the log. Refs MaSzyna-EU07/maszyna#64 --- tests/unit/test_pullee.cpp | 17 +++++++++++++++++ vehicle/DynObj.cpp | 14 ++++++++++++++ vehicle/pulleemode.h | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+) create mode 100644 vehicle/pulleemode.h diff --git a/tests/unit/test_pullee.cpp b/tests/unit/test_pullee.cpp index 9800532c7..7e2742f7a 100644 --- a/tests/unit/test_pullee.cpp +++ b/tests/unit/test_pullee.cpp @@ -5,6 +5,8 @@ #include "drive.h" #include "real_vehicles.h" +#include "vehicle/pulleemode.h" + using test::definition; using test::vehicle; @@ -52,6 +54,21 @@ bool can_be_hauled(std::string const &Path) { } // namespace +TEST_CASE("pullee: the parameter H among the ones after the coupling of a vehicle asks for the mode") { + CHECK(pullee_mode::requested("H")); + CHECK(pullee_mode::requested("h")); + CHECK(pullee_mode::requested("BG.H")); + CHECK(pullee_mode::requested("H.BG")); + CHECK(pullee_mode::requested("BP.WF10.h.TA")); + CHECK(pullee_mode::requested("HX")); // letters after it are for later + // the parameters the sceneries have: brakes, wheels (their H is the hunting of a bogie), temperatures, load + CHECK_FALSE(pullee_mode::requested("")); + CHECK_FALSE(pullee_mode::requested("BG")); + CHECK_FALSE(pullee_mode::requested("WH25")); + CHECK_FALSE(pullee_mode::requested("BR.WF5R10P50H25.TA.L50")); + CHECK_FALSE(pullee_mode::requested("0")); +} + TEST_CASE("pullee: a dead Vectron vents the brake pipe of the train hauling it, prepared for hauling it doesn't") { // the Vectron applies the emergency brake while none of its cabs is active (InactiveCabFlag bit 1), which a // vehicle hauled with the hook and the brake hose never has diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index d4b7ea7f4..6a2d390e7 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -23,6 +23,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Camera.h" #include "vehicle/Train.h" #include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" #include "vehicle/Driver.h" #include @@ -2076,6 +2077,14 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" // another run of the same scenario, with another seed, dresses it differently m_variantseed = hash_string( asName, Global.random_seed ); std::string asAnimName; // zmienna robocza do wyszukiwania osi i wózków + // a vehicle prepared for being hauled dead (parameter H after its coupling, MaSzyna-EU07/maszyna#64) has nobody + // driving it, whatever its crew entry says: its cab can't be activated, and a driver in it would either take + // the train or be one more for the train's driver to put to sleep + auto const hauled { pullee_mode::requested( MoreParams ) }; + if( hauled && ( DriverType == "headdriver" || DriverType == "reardriver" ) ) { + WriteLog( "Vehicle " + asName + " is prepared for hauling (parameter H), the driver it was given is left out" ); + DriverType = "nobody"; + } // Ra: zmieniamy znaczenie obsady na jednoliterowe, żeby dosadzić kierownika if (DriverType == "headdriver") DriverType = "1"; // sterujący kabiną +1 @@ -2395,6 +2404,11 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" */ } // koniec while kropka + if( hauled ) { + // once the vehicle has its starting state: the hand brake and the spring brake of a standing one let go, battery off + MoverParameters->PulleeModeSwitch( true ); + } + if (MoverParameters->CategoryFlag & 2) // jeśli samochód { // ustawianie samochodow na poboczu albo na środku drogi if( Track->fTrackWidth < 3.5 // jeśli droga wąska diff --git a/vehicle/pulleemode.h b/vehicle/pulleemode.h new file mode 100644 index 000000000..f01ed5768 --- /dev/null +++ b/vehicle/pulleemode.h @@ -0,0 +1,35 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include + +// the pullee mode ("jazda ciągniona", MaSzyna-EU07/maszyna#64): a vehicle prepared for being hauled dead in a train, +// TMoverParameters::PulleeModeSwitch(). a scenery asks for it with the parameter H among the ones written after the +// coupling of the vehicle, split by dots: "3.H", or with others, "3.BG.H" +// node -1 0 EU160-001 dynamic pkp/vectron_v1 1293-107 wariant_7w 0 nobody 3.H 0 enddynamic +namespace pullee_mode { + +// whether the parameters of a vehicle, the text after the first dot of its coupling entry, ask for the mode. a +// parameter is told by its first letter, as the others are (B brakes, W wheels, T temperatures, L load), in either +// case; the letters after the H are left for later +inline bool requested(std::string_view const Parameters) { + auto first{true}; // of a parameter + for (auto const character : Parameters) { + if (first && std::toupper(static_cast(character)) == 'H') { + return true; + } + first = character == '.'; + } + return false; +} + +} // namespace pullee_mode From ecaa6872b9ac77db2425198e5109f99ed626bdcd Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 19 Nov 2026 01:58:56 +0100 Subject: [PATCH 069/136] test: scenario cases of an EU07 hauling a dead Vectron prepared for hauling eu07_td_hauls_dead_vectron: the timetable run on td.scn with a Vectron behind the EU07, hook and brake hose only, nobody in it, parameter H (MaSzyna-EU07/maszyna#64). eu07_td_hauls_dead_vectron_cold: the same from a cold start (trainset velocity 0, fragment td_cold_timetable.scn, the driver woken with Obey_train). Both reach Przystanek and stop there. Without the H neither train moves: the Vectron vents the brake pipe (run before the feature, on the code of staging: the pipe empty in 2 s, the Vectron's cylinders at 3.7 bar for the whole 300 s; cold, the pipe below 1 bar and a standstill). Refs MaSzyna-EU07/maszyna#64 --- tests/scenarios/README.md | 13 +++++++++++ .../cases/eu07_td_hauls_dead_vectron.json | 20 ++++++++++++++++ .../eu07_td_hauls_dead_vectron_cold.json | 23 +++++++++++++++++++ tests/scenarios/cases/td_cold_timetable.scn | 19 +++++++++++++++ 4 files changed, 75 insertions(+) create mode 100644 tests/scenarios/cases/eu07_td_hauls_dead_vectron.json create mode 100644 tests/scenarios/cases/eu07_td_hauls_dead_vectron_cold.json create mode 100644 tests/scenarios/cases/td_cold_timetable.scn diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index 7ab7646e7..6156828de 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -265,6 +265,19 @@ 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. +`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 +MaSzyna-EU07/maszyna#64). The checks are those of the timetable cases; the train takes 300 s to +Przystanek and on (20 km/h after 79 s, the stop after 220 s and 1405 m). Without the `H` the Vectron, +which applies the emergency brake while none of its cabs is active, empties the brake pipe of the train +in two seconds, both locomotives stand with their brake cylinders full and the train never moves. +`eu07_td_hauls_dead_vectron_cold` (fragment `td_cold_timetable.scn`) is the same train from a cold start: +trainset velocity 0, so both locomotives stand braked (brake pipe at 3.5 bar, batteries off, the spring +brake of the Vectron switched on), and `event0` of the track gives the driver `Obey_train`, once. The EU07 +starts up, charges the brake pipe and leaves on time (the stop after 209 s and 1393 m); without the `H` +the pipe stays below 1 bar and the case ends as a standstill after 300 s. + ### Cases on a mission of a scenery The cases made from players' reports (eu07/maszyna#421, #506, #524, #525) run a whole mission diff --git a/tests/scenarios/cases/eu07_td_hauls_dead_vectron.json b/tests/scenarios/cases/eu07_td_hauls_dead_vectron.json new file mode 100644 index 000000000..8c06596c8 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_hauls_dead_vectron.json @@ -0,0 +1,20 @@ +{ + "description": "EU07 on td.scn hauls a dead Vectron prepared for hauling (coupling 3, parameter H: the pullee mode of MaSzyna-EU07/maszyna#64), AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek. Without the H the Vectron vents the brake pipe and the train never moves.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp/4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 dead_{{vehicle}} dynamic pkp/vectron_v1 1293-107 wariant_7w 0 nobody 0.H 0 enddynamic" + ] + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "brakes", "min_pressure": 0.5 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/scenarios/cases/eu07_td_hauls_dead_vectron_cold.json b/tests/scenarios/cases/eu07_td_hauls_dead_vectron_cold.json new file mode 100644 index 000000000..ed43f3c98 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_hauls_dead_vectron_cold.json @@ -0,0 +1,23 @@ +{ + "description": "As eu07_td_hauls_dead_vectron, from a cold start: the trainset stands with velocity 0, so both locomotives start braked (brake pipe at 3.5 bar, batteries off, the Vectron's spring brake on). The EU07's driver gets the order to run as a train, starts the engine, charges the brake pipe and hauls the Vectron, prepared for hauling (parameter H), to Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_cold_timetable.scn", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp/4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 dead_{{vehicle}} dynamic pkp/vectron_v1 1293-107 wariant_7w 0 nobody 0.H 0 enddynamic" + ] + }, + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "brakes", "min_pressure": 0.5 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/scenarios/cases/td_cold_timetable.scn b/tests/scenarios/cases/td_cold_timetable.scn new file mode 100644 index 000000000..b11c4825a --- /dev/null +++ b/tests/scenarios/cases/td_cold_timetable.scn @@ -0,0 +1,19 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed: +// the trainset goes after FirstInit, the launcher and the events before it. +// the case's consist stands cold where td.scn keeps its timetable train (track 1 of Stacja1): trainset +// velocity 0, so every vehicle starts "Braked": brake pipe at 3.5 bar, battery off, hand and spring brakes on. +// it has the same timetable: Stacja1 10:35 -> Przystanek -> Stacja2. +trainset td/rozklad tdo_n1734 0.0 0.0 +{{consist}} +endtrainset + +// the way out of track 1, as in td_timetable.scn +node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end + +// a driver of a standing trainset sleeps on Wait_for_orders until something wakes it. event0 of the train's +// track (the case's track_events) runs while it stands there and gives it, once (the memory cell), the order +// to run as a train: Obey_train. the engine is cold, so the AI starts it first (Prepare_engine). +node -1 0 autotest_ordered memcell 0 0 0 ordered 0 0 none endmemcell +event autotest_wake multiple 0 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event autotest_order PutValues 0 none 0 0 0 Obey_train 0 0 endevent +event autotest_order_given UpdateValues 0 autotest_ordered * 1 * endevent From c2a48d7450618ca1a200eae245e272c9b0ddfbe8 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 19 Nov 2026 17:44:03 +0100 Subject: [PATCH 070/136] feat(mover): pressure switch without the brake cylinders, line breaker opened by an emergency application Two optional .fiz keys, for the EP05 (git.eu07.pl eu07/maszyna#48). Without them nothing changes. Engine: PressureSwitchBrakeCylinder=No leaves the pressure switch with the brake pipe alone (below 3.6 bar), so the vehicle takes current whatever the pressure in its brake cylinders. PressureSwitch=Yes/No means what it meant. Cntrl. EmergencyBrakeMainOff= is the brake pipe pressure taken for an emergency brake application. Below it, with the master controller on a power position, the line breaker opens and doesn't close again. Where the pantographs stay up only through the closed line breaker (PantRequiresMain) they drop with it. Data, not in this repository: dynamic/pkp/ep05_v2/ep05.fiz and ep05v1.fiz are to get PressureSwitchBrakeCylinder=No in the Engine: line and EmergencyBrakeMainOff=2.5 in the Cntrl. line. Until then the EP05 behaves as before. --- McZapkie/MOVER.h | 15 +++++++++++++++ McZapkie/Mover.cpp | 16 ++++++++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 2ca88ff39..d7820eeb0 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -2247,6 +2247,15 @@ class TMoverParameters bool LineBreakerClosesOnlyAtNoPowerPos{false}; bool ControlPressureSwitch{false}; // activates if the main pipe and/or brake cylinder pressure aren't within operational levels bool HasControlPressureSwitch{true}; + // config, .fiz Engine:PressureSwitchBrakeCylinder. whether the pressure switch watches the brake cylinders (it cuts the + // start off above 2 bar there) as well as the brake pipe (below 3.6 bar). off, it's left with the brake pipe alone, + // and the vehicle takes current whatever the pressure in its brake cylinders (EP05) + bool PressureSwitchBrakeCylinder{true}; + // config, .fiz Cntrl.EmergencyBrakeMainOff. the brake pipe pressure [bar] taken for an emergency brake application: + // below it, with the master controller on a power position, the line breaker opens and doesn't close again. where + // the pantographs stay up only through the closed line breaker (PantographsRequireMains) they drop with it (EP05). + // 0: an emergency application leaves the line breaker alone + double EmergencyBrakeMainOffPressure{0.0}; bool ReleaserEnabledOnlyAtNoPowerPos{false}; int MainCtrlPos = 0; /*polozenie glownego nastawnika*/ int ScndCtrlPos = 0; /*polozenie dodatkowego nastawnika*/ @@ -2724,6 +2733,12 @@ class TMoverParameters { return false == ControlPressureSwitch && (HasControlPressureSwitch || BrakePress < 1.0); } + // whether an emergency brake application holds the line breaker open: the brake pipe below the pressure taken for one + // (EmergencyBrakeMainOffPressure) while the master controller is on a power position + bool EmergencyBrakeHoldsMainOff() const + { + return EmergencyBrakeMainOffPressure > 0.0 && PipePress < EmergencyBrakeMainOffPressure && false == IsMainCtrlNoPowerPos(); + } // whether the lamp of the open line contactors is lit. on the electric locomotives it tells the start can be made, so // it goes out with the start cut off; on the diesel-electric ones (the SU45 and SU46 family) it just tells the // contactors are open, whatever opened them: the master controller at 0, or the pressure switch (eu07/maszyna#263) diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 2284f7b41..15906e44c 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -2510,6 +2510,12 @@ void TMoverParameters::MainsCheck(double const Deltatime) // no power supply MainsInitTimeCountdown = MainsInitTime; } + + // an emergency brake application made under power opens the line breaker, where the vehicle has such an interlock + if (Mains && EmergencyBrakeHoldsMainOff()) + { + MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); + } } void TMoverParameters::LowVoltagePowerCheck(double const /*Deltatime*/) @@ -4502,7 +4508,7 @@ bool TMoverParameters::MainSwitchCheck() const (HasCamshaft ? IsMainCtrlActualNoPowerPos() : LineBreakerClosesOnlyAtNoPowerPos ? IsMainCtrlNoPowerPos() : true) && - false == TestFlag(DamageFlag, dtrain_out) && false == TestFlag(EngDmgFlag, 1); + false == TestFlag(DamageFlag, dtrain_out) && false == TestFlag(EngDmgFlag, 1) && false == EmergencyBrakeHoldsMainOff(); } // ************************************************************************************************* @@ -8398,7 +8404,8 @@ bool TMoverParameters::MotorConnectorsCheck() { // hunter-111211: wylacznik cisnieniowy - ControlPressureSwitch = HasControlPressureSwitch && (BrakePress > 2.0 || PipePress < 3.6); + // (on some vehicles it watches the brake pipe alone) + ControlPressureSwitch = HasControlPressureSwitch && ((PressureSwitchBrakeCylinder && BrakePress > 2.0) || PipePress < 3.6); if (true == ControlPressureSwitch) { @@ -12608,6 +12615,9 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) MainsStart = lookup != starts.end() ? lookup->second : start_t::manual; } extract_value(PantographsRequireMains, "PantRequiresMain", line, ""); + // the brake pipe pressure of an emergency brake application, which opens the line breaker under power + extract_value(EmergencyBrakeMainOffPressure, "EmergencyBrakeMainOff", line, ""); + EmergencyBrakeMainOffPressure = std::max(0.0, EmergencyBrakeMainOffPressure); // battery { auto lookup = starts.find(extract_value("BatteryStart", line)); @@ -13089,6 +13099,8 @@ void TMoverParameters::LoadFIZ_Engine(std::string const &Input) MotorBlowers[end::rear] = MotorBlowers[end::front]; // pressure switch extract_value(HasControlPressureSwitch, "PressureSwitch", Input, TrainType != dt_EZT ? "yes" : "no"); + // its brake cylinder half; the brake pipe one stays + extract_value(PressureSwitchBrakeCylinder, "PressureSwitchBrakeCylinder", Input, ""); } void TMoverParameters::LoadFIZ_Switches(std::string const &Input) From e04d6af93ecd9f28cd4db664b60332aca2944318 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 19 Nov 2026 17:44:03 +0100 Subject: [PATCH 071/136] test: the pressure switch keys on the EP05 The EP05 takes current with 3.8 bar in its brake cylinders once the brake cylinder half of the pressure switch is off, and loses it when the brake pipe goes down. An emergency application with the master controller on a power position opens the line breaker and drops the pantographs; with the controller at zero, or on a service application, it doesn't. The driver's start-up gets the locomotive going again. Without the keys all of it is as before. --- tests/unit/test_pressure_switch.cpp | 295 ++++++++++++++++++++++++++++ 1 file changed, 295 insertions(+) create mode 100644 tests/unit/test_pressure_switch.cpp diff --git a/tests/unit/test_pressure_switch.cpp b/tests/unit/test_pressure_switch.cpp new file mode 100644 index 000000000..65672b252 --- /dev/null +++ b/tests/unit/test_pressure_switch.cpp @@ -0,0 +1,295 @@ +#include "stdafx.h" +#include "doctest.h" +#include "drive.h" + +#include "McZapkie/hamulce.h" + +// the pressure switch of the EP05 (git.eu07.pl eu07/maszyna#48). the pressure switch of the simulator is two +// conditions in one: it cuts the traction motors off above 2 bar in the brake cylinders and below 3.6 bar in the +// brake pipe. the EP05 takes current whatever the pressure in its brake cylinders (Engine: PressureSwitchBrakeCylinder=No +// leaves the brake pipe half alone), and an emergency brake application made with the master controller on a power +// position opens its line breaker (Cntrl. EmergencyBrakeMainOff=), which on this locomotive +// drops the pantographs too, as they stay up only through the closed line breaker (Cntrl. PantRequiresMain) + +namespace { + +constexpr test::track line{0.15, 0.0, test::catenary_3kv}; + +// the brake pipe pressure taken for an emergency application in these tests [bar]: below the 2.8 bar the FV4a +// gives on its last service position, above what is left in the pipe once it's vented +constexpr double emergency_pressure{2.5}; + +struct keys { + bool brakecylinder{true}; // Engine: PressureSwitchBrakeCylinder + bool mainoff{false}; // Cntrl. EmergencyBrakeMainOff + bool mainsfirst{true}; // Cntrl. PantRequiresMain, which the game's EP05 has +}; + +test::definition ep05(keys const &Keys) { + auto definition{test::definition::fiz("ep05_v2/ep05")}; + if (Keys.mainsfirst) { + // the game's definition got it after the one of the tests was converted + definition.set("Cntrl", "PantRequiresMain", "Yes"); + } + if (false == Keys.brakecylinder) { + definition.set("Engine", "PressureSwitchBrakeCylinder", "No"); + } + if (Keys.mainoff) { + definition.set("Cntrl", "EmergencyBrakeMainOff", emergency_pressure); + } + return definition; +} + +// the locomotive started up the way the driver does it and its brakes released, until the pressure switch lets go +void get_ready(test::vehicle &Loco, test::driven const &Driven) { + REQUIRE(test::start_up(Driven, line)); + test::release_brakes(Driven.cab); + test::drive(Driven, line, 20.0); + for (int i = 0; i < 120 && Loco->ControlPressureSwitch; ++i) { + test::drive(Driven, line, 1.0); + } + REQUIRE_FALSE(Loco->ControlPressureSwitch); + REQUIRE(Loco->Mains); + REQUIRE(Loco->Pantographs[end::rear].is_active); +} + +// the master controller taken to the given position a notch a second +void notch_up(test::vehicle &Loco, test::driven const &Driven, int const Position) { + while (Loco->MainCtrlPos < Position && Loco->IncMainCtrl(1)) { + test::drive(Driven, line, 1.0); + } + test::drive(Driven, line, 2.0); + REQUIRE(Loco->MainCtrlPos == Position); +} + +void get_under_power(test::vehicle &Loco, test::driven const &Driven, int const Position) { + get_ready(Loco, Driven); + notch_up(Loco, Driven, Position); + REQUIRE(Loco->StLinFlag); + REQUIRE(std::abs(Loco->Im) > 10.0); +} + +// the independent brake applied in full: 3.8 bar in the brake cylinders of the locomotive (Brake: MaxBP) +void apply_independent_brake(test::vehicle &Loco, test::driven const &Driven) { + Loco->IncLocalBrakeLevel(LocalBrakePosNo); + test::drive(Driven, line, 20.0); + REQUIRE(Loco->BrakePress == doctest::Approx(3.8).epsilon(0.03)); + REQUIRE(Loco->PipePress > 4.8); +} + +void emergency_application(test::vehicle &Loco, test::driven const &Driven) { + Loco->BrakeLevelSet(Loco->Handle->GetPos(bh_EB)); + test::drive(Driven, line, 10.0); + REQUIRE(Loco->PipePress < 1.0); +} + +} // namespace + +TEST_CASE("pressure switch: the keys are off by default") { + test::vehicle loco{ep05({}), 0.0, "test", 1}; + CHECK(loco->HasControlPressureSwitch); + CHECK(loco->PressureSwitchBrakeCylinder); + CHECK(loco->EmergencyBrakeMainOffPressure == 0.0); + + test::vehicle changed{ep05({.brakecylinder = false, .mainoff = true}), 0.0, "test", 1}; + CHECK(changed->HasControlPressureSwitch); + CHECK_FALSE(changed->PressureSwitchBrakeCylinder); + CHECK(changed->EmergencyBrakeMainOffPressure == doctest::Approx(emergency_pressure)); +} + +TEST_CASE("pressure switch: with the brake cylinders at 3.8 bar the EP05 takes no current, as before") { + test::vehicle loco{ep05({}), 0.0, "test", 1}; + auto driven{test::driving(loco)}; + get_ready(loco, driven); + apply_independent_brake(loco, driven); + CHECK(loco->ControlPressureSwitch); + CHECK_FALSE(loco->MainCircuitLampsEnabled()); + + notch_up(loco, driven, 3); + CHECK_FALSE(loco->StLinFlag); + CHECK(loco->Im == 0.0); + CHECK(loco->Mains); + CHECK(loco->Pantographs[end::rear].is_active); +} + +TEST_CASE("pressure switch: without its brake cylinder half the EP05 takes current with the brake cylinders at 3.8 bar") { + test::vehicle loco{ep05({.brakecylinder = false}), 0.0, "test", 1}; + auto driven{test::driving(loco)}; + get_ready(loco, driven); + apply_independent_brake(loco, driven); + CHECK_FALSE(loco->ControlPressureSwitch); + // the lamps of the main circuit tell the start can be made + CHECK(loco->MainCircuitLampsEnabled()); + CHECK(loco->LineContactorsLampLit()); + + notch_up(loco, driven, 3); + CHECK(loco->StLinFlag); + CHECK(loco->MainCtrlActualPos == 3); + CHECK(std::abs(loco->Im) > 100.0); + CHECK(loco->BrakePress == doctest::Approx(3.8).epsilon(0.03)); + MESSAGE("current with 3.8 bar in the brake cylinders, position 3: " << std::abs(loco->Im) << " A"); +} + +TEST_CASE("pressure switch: without its brake cylinder half the brake pipe still cuts the traction motors off") { + test::vehicle loco{ep05({.brakecylinder = false}), 0.0, "test", 1}; + auto driven{test::driving(loco)}; + get_under_power(loco, driven, 5); + + SUBCASE("a service application") { + loco->BrakeLevelSet(loco->Handle->GetPos(bh_FB)); + test::drive(driven, line, 15.0); + REQUIRE(loco->PipePress < 3.6); + REQUIRE(loco->PipePress > 3.0); + } + SUBCASE("an emergency application") { + emergency_application(loco, driven); + } + CHECK(loco->ControlPressureSwitch); + CHECK_FALSE(loco->StLinFlag); + CHECK(loco->Im == 0.0); + // nothing else lets go without the other key + CHECK(loco->Mains); + CHECK(loco->Pantographs[end::rear].is_active); +} + +TEST_CASE("pressure switch: an emergency application with the master controller on a power position opens the line breaker and drops the pantographs") { + test::vehicle loco{ep05({.brakecylinder = false, .mainoff = true}), 0.0, "test", 1}; + auto driven{test::driving(loco)}; + get_under_power(loco, driven, 5); + + SUBCASE("made with the brake handle") { + loco->BrakeLevelSet(loco->Handle->GetPos(bh_EB)); + } + SUBCASE("made with the emergency brake of the train") { + loco->AlarmChainSwitch(true); + } + test::drive(driven, line, 10.0); + REQUIRE(loco->PipePress < emergency_pressure); + REQUIRE(loco->MainCtrlPos == 5); + CHECK_FALSE(loco->Mains); + CHECK_FALSE(loco->Pantographs[end::front].is_active); + CHECK_FALSE(loco->Pantographs[end::rear].is_active); + CHECK(loco->PantographVoltage == 0.0); + CHECK_FALSE(loco->StLinFlag); + CHECK(loco->Im == 0.0); + + // the line breaker doesn't close again while the master controller is where it was + loco->MainSwitch(true); + test::drive(driven, line, 2.0); + CHECK_FALSE(loco->Mains); + CHECK_FALSE(loco->Pantographs[end::rear].is_active); +} + +TEST_CASE("pressure switch: an emergency application with the master controller at zero leaves the line breaker and the pantographs alone") { + test::vehicle loco{ep05({.brakecylinder = false, .mainoff = true}), 0.0, "test", 1}; + auto driven{test::driving(loco)}; + get_under_power(loco, driven, 5); + while (loco->DecMainCtrl(1)) { + // down to zero + } + test::drive(driven, line, 2.0); + REQUIRE(loco->MainCtrlPos == 0); + + emergency_application(loco, driven); + CHECK(loco->Mains); + CHECK(loco->Pantographs[end::rear].is_active); + CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); + CHECK(loco->Im == 0.0); + + // and the master controller moved with the pipe empty is the same as the application made with it moved + loco->IncMainCtrl(1); + test::drive(driven, line, 2.0); + CHECK_FALSE(loco->Mains); + CHECK_FALSE(loco->Pantographs[end::rear].is_active); +} + +TEST_CASE("pressure switch: a service application with the master controller on a power position doesn't open the line breaker") { + test::vehicle loco{ep05({.brakecylinder = false, .mainoff = true}), 0.0, "test", 1}; + auto driven{test::driving(loco)}; + get_under_power(loco, driven, 5); + + // the last service position of the FV4a, 2.8 bar in the pipe + loco->BrakeLevelSet(5.0); + auto lowest{loco->PipePress}; + for (int second = 0; second < 60; ++second) { + test::drive(driven, line, 1.0); + lowest = std::min(lowest, loco->PipePress); + } + MESSAGE("the lowest brake pipe pressure of the service application: " << lowest << " bar"); + REQUIRE(lowest < 3.0); + CHECK(lowest > emergency_pressure); + CHECK(loco->Mains); + CHECK(loco->Pantographs[end::rear].is_active); + // the pressure switch has cut the motors off + CHECK_FALSE(loco->StLinFlag); + CHECK(loco->Im == 0.0); +} + +TEST_CASE("pressure switch: without the key an emergency application leaves the line breaker closed and the pantographs up, as before") { + test::vehicle loco{ep05({}), 0.0, "test", 1}; + auto driven{test::driving(loco)}; + get_under_power(loco, driven, 5); + + emergency_application(loco, driven); + REQUIRE(loco->MainCtrlPos == 5); + CHECK(loco->Mains); + CHECK(loco->Pantographs[end::rear].is_active); + CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); + // the pressure switch cuts the motors off + CHECK(loco->ControlPressureSwitch); + CHECK_FALSE(loco->StLinFlag); + CHECK(loco->Im == 0.0); +} + +TEST_CASE("pressure switch: where the pantographs don't hang on the line breaker the emergency application opens only the line breaker") { + test::vehicle loco{ep05({.brakecylinder = false, .mainoff = true, .mainsfirst = false}), 0.0, "test", 1}; + REQUIRE_FALSE(loco->PantographsRequireMains); + auto driven{test::driving(loco)}; + get_under_power(loco, driven, 5); + + emergency_application(loco, driven); + CHECK_FALSE(loco->Mains); + CHECK(loco->Pantographs[end::rear].is_active); + CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); + CHECK_FALSE(loco->StLinFlag); + CHECK(loco->Im == 0.0); +} + +TEST_CASE("pressure switch: after the emergency application the driver's start-up gets the locomotive going again") { + // test::start_up() takes the AI's steps of TController::PrepareEngine(): the master controller to zero, the relays + // reset, the line breaker closed. the pantograph switches stay as they were, so the pantograph rises with the line + // breaker + test::vehicle loco{ep05({.brakecylinder = false, .mainoff = true}), 0.0, "test", 1}; + auto driven{test::driving(loco)}; + get_under_power(loco, driven, 5); + emergency_application(loco, driven); + REQUIRE_FALSE(loco->Mains); + REQUIRE_FALSE(loco->Pantographs[end::rear].is_active); + REQUIRE(loco->Pantographs[end::rear].valve.is_enabled); + + // with the brake pipe still empty + REQUIRE(test::start_up(driven, line, 60.0)); + CHECK(loco->MainCtrlPos == 0); + CHECK(loco->Mains); + CHECK(loco->Pantographs[end::rear].is_active); + CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); + REQUIRE(loco->PipePress < emergency_pressure); + // and it stays so + test::drive(driven, line, 30.0); + CHECK(loco->Mains); + CHECK(loco->Pantographs[end::rear].is_active); + + // the brakes released (the AI fills an emptied pipe with the releaser held, TController::control_releaser()), + // the pressure switch lets the start be made + test::release_brakes(driven.cab); + for (int i = 0; i < 180 && loco->ControlPressureSwitch; ++i) { + loco->BrakeReleaser(loco->PipePress < 3.0 ? 1 : 0); + test::drive(driven, line, 1.0); + } + loco->BrakeReleaser(0); + REQUIRE_FALSE(loco->ControlPressureSwitch); + notch_up(loco, driven, 3); + CHECK(loco->Mains); + CHECK(loco->StLinFlag); + CHECK(std::abs(loco->Im) > 10.0); +} From 24266d6e5cc927740a9488cd6fea1e5e1c66eeb6 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 19 Nov 2026 19:06:45 +0100 Subject: [PATCH 072/136] feat(med): let the holding brake go only after a set time of power demand A new Cntrl key, SBDReleaseDelay (seconds, default 0), makes the holding brake of a unit with the MED (SBD) wait until power has been demanded for that long before it lets go. Without the key the brake lets go at the first demand, as before. The count starts again whenever the demand drops to zero. The Elf data would get SBDReleaseDelay=1.0 (its IniCDelay) in the files with SBD; that data change is for the SVN later, nothing needs it now. --- McZapkie/MOVER.h | 7 +++++++ McZapkie/Mover.cpp | 14 ++++++++++++++ vehicle/DynObj.cpp | 4 +++- 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 2ca88ff39..1d3e57fa7 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -1806,6 +1806,10 @@ class TMoverParameters bool MBrake = false; /*Czy jest hamulec reczny*/ double maxTachoSpeed = {0.0}; // maksymalna predkosc na tarczce predkosciomierza analogowego double StopBrakeDecc = 0.0; + // the holding brake (StopBrakeDecc) of a unit with the MED lets go only once power has been demanded for this long (SBDReleaseDelay, s); + // 0 lets it go at the first demand + double StopBrakeReleaseDelay = 0.0; + double StopBrakeReleaseTimer = 0.0; // how long power has been demanded without a break, s bool ReleaseParkingBySpringBrake{false}; bool ReleaseParkingBySpringBrakeWhenDoorIsOpen{false}; bool SpringBrakeCutsOffDrive{true}; @@ -2858,6 +2862,9 @@ class TMoverParameters bool DropAllPantographs(bool const State, range_t const Notify = range_t::consist); void CheckEIMIC(double dt); // sprawdzenie i zmiana nastawy zintegrowanego nastawnika jazdy/hamowania + // whether the holding brake (StopBrakeDecc) lets go at the power demand (eimic, above 0 when power is demanded) of this step of + // Dt seconds: once the demand has stayed above 0 for StopBrakeReleaseDelay. a demand of 0 or less starts the count again + bool UpdateStopBrakeRelease(double Demand, double Dt); void CheckSpeedCtrl(double dt); // whether the cruise control has a switch of its own: the secondary controller doubles as its switch unless it // shunts the field of the traction motors already, or there's none (the 6Dg, the ST45; eu07/maszyna#69) diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 2284f7b41..9fa603abb 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -8831,6 +8831,19 @@ void TMoverParameters::CheckEIMIC(double dt) eimic = std::clamp(eimic, -1.0, eimicpowerenabled ? eimic_max : 0.0); } +bool TMoverParameters::UpdateStopBrakeRelease(double const Demand, double const Dt) +{ + if (Demand <= 0.0) + { + StopBrakeReleaseTimer = 0.0; + return false; + } + // the step the demand rises above 0 is time 0 of it, so without the delay the brake lets go at once, as it always did + auto const released{StopBrakeReleaseTimer >= StopBrakeReleaseDelay}; + StopBrakeReleaseTimer += Dt; + return released; +} + void TMoverParameters::CheckSpeedCtrl(double dt) { if (EIMCtrlType == 0) @@ -12584,6 +12597,7 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) extract_value(InactiveCabFlag, "InactiveCabFlag", line, ""); extract_value(StopBrakeDecc, "SBD", line, ""); + extract_value(StopBrakeReleaseDelay, "SBDReleaseDelay", line, ""); // the holding brake waits for the power demand this long, s extract_value(ReleaseParkingBySpringBrake, "ReleaseParkingBySpringBrake", line, ""); extract_value(ReleaseParkingBySpringBrakeWhenDoorIsOpen, "ReleaseParkingBySpringBrakeWhenDoorIsOpen", line, ""); extract_value(SpringBrakeCutsOffDrive, "SpringBrakeCutsOffDrive", line, ""); diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index d4b7ea7f4..65045bb27 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -3491,7 +3491,9 @@ bool TDynamicObject::Update(double dt, double dt1) { Fzad = std::min(LBR * FmaxED, FfulED); } - if (MoverParameters->ShuntMode && eimic <= 0 || doorisopen /*|| + // the holding brake lets go once power has been demanded for its delay (SBDReleaseDelay, none by default) + auto const holdingbrakereleased { MoverParameters->UpdateStopBrakeRelease( eimic, dt1 ) }; + if (MoverParameters->ShuntMode && false == holdingbrakereleased || doorisopen /*|| (MoverParameters->V * MoverParameters->DirAbsolute < -0.2)*/) { auto const sbd { ( MoverParameters->SpringBrake.IsActive && MoverParameters->ReleaseParkingBySpringBrake ? 0.0 : MoverParameters->StopBrakeDecc ) }; From 7a4a9532d1df3ff9c47e6d239f40d65c22216191 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 19 Nov 2026 19:30:44 +0100 Subject: [PATCH 073/136] test: cover the release delay of the Elf's holding brake Without SBDReleaseDelay the holding brake lets go at the first demand, as before. With SBDReleaseDelay=1.0 it lets go about 1 s after the handle, both with the controller held at power and flicked there once and back to holding the power; it holds again at no demand, a demand dropped before the delay starts the count again, and two coupled Elfs do the same as one. A start with the holding brake shared out as the MED does at standstill shows the train held at the 1% of the first step until the release. --- tests/unit/test_elf_controller.cpp | 282 ++++++++++++++++++++++++++++- 1 file changed, 281 insertions(+), 1 deletion(-) diff --git a/tests/unit/test_elf_controller.cpp b/tests/unit/test_elf_controller.cpp index 212ed51d0..bb7d34b74 100644 --- a/tests/unit/test_elf_controller.cpp +++ b/tests/unit/test_elf_controller.cpp @@ -5,7 +5,9 @@ #include "McZapkie/hamulce.h" +#include #include +#include #include // the master controller of the Elf (EIMCtrlType 2): its positions, and the emergency brake position below @@ -26,10 +28,14 @@ enum class data { plain, emergency, emergency_old_layout }; // controller's eimic is worked out there) struct elf { explicit elf(bool Emergency) : elf({Emergency ? data::emergency : data::plain}) {} - explicit elf(std::initializer_list Units) { + // HoldingBrakeDelay, when given, goes to every car as SBDReleaseDelay + explicit elf(std::initializer_list Units, std::optional HoldingBrakeDelay = std::nullopt) { 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 (HoldingBrakeDelay) { + cardefinition.set("Cntrl", "SBDReleaseDelay", *HoldingBrakeDelay); + } if (units != data::plain) { cardefinition.set("Cntrl", "EIMCtrlMainEmergency", "Yes"); } @@ -254,3 +260,277 @@ TEST_CASE("elf controller: EIMCtrlMainEmergency leaves the other controllers alo impuls->MainCtrlPos = 0; CHECK_FALSE(impuls->IsMainCtrlEmergencyPos()); } + +// the holding brake of the Elf (SBD) lets go only once power has been demanded for SBDReleaseDelay (eu07/maszyna#556): +// the release waits the initial delay of the controller (IniCDelay) instead of going at the first percent of the +// demand. TDynamicObject::Update() works the holding brake out, its MED isn't in the tests, so they do here what it +// does with it: TMoverParameters::UpdateStopBrakeRelease() of the cab with its demand after every step and, where the +// brake matters, the brake's share of every car on its cylinders (LocalBrakePosAEIM) + +namespace { + +constexpr double step_time{0.01}; // of a step of the tests, see test::consist::step() +constexpr double elf_delay{1.0}; // IniCDelay of the Elf with a cab + +// the time from the start to the first step with the holding brake let go, the brake worked out after every step; +// Act runs before every step with the time so far. negative when it holds all the time +template double release_time(elf &Unit, double Seconds, Action Act) { + auto &cab{Unit.cab()}; + auto const steps{std::lround(Seconds / step_time)}; + for (long i = 0; i < steps; ++i) { + auto const time{i * step_time}; + Act(time); + Unit.unit.step(Unit.line); + if (cab.UpdateStopBrakeRelease(cab.eimic_real, step_time)) { + return time; + } + } + return -1.0; +} + +// the holding brake of TDynamicObject::Update() at standstill: StopBrakeDecc times the mass of the train, shared out +// by the axles, each car's share made a position of its brake valve (LocalBrakePosAEIM) as there. at standstill the +// electric brake makes no part of it +void hold(elf &Unit, bool Hold) { + auto mass{0.0}; + auto axles{0}; + for (std::size_t i = 0; i < Unit.unit.size(); ++i) { + mass += Unit.car(i).TotalMass; + axles += Unit.car(i).NAxles; + } + auto const force{Unit.cab().StopBrakeDecc * mass}; + for (std::size_t i = 0; i < Unit.unit.size(); ++i) { + auto &car{Unit.car(i)}; + auto const nmax{((car.P2FTrans * car.MaxBrakePress[0] - car.BrakeCylSpring) * car.BrakeCylMult[0] - car.BrakeSlckAdj) * car.BrakeCylNo * car.BrakeRigEff}; + auto const fmax{nmax * car.Hamulec->GetFC(nmax / (car.NAxles * car.NBpA), car.MED_Vref) * 1000}; + auto position{Hold ? force * car.NAxles / axles / fmax : 0.0}; + if (position > 0.009) { + auto const slack{(car.BrakeSlckAdj / car.BrakeCylMult[0] + car.BrakeCylSpring) / (car.P2FTrans * car.MaxBrakePress[0])}; + position = slack + (1 - slack) * position; + } + else { + position = 0.0; + } + car.LocalBrakePosAEIM = position; + } +} + +// how a start of the Elf goes with its holding brake +struct start { + double release{-1.0}; // the time the holding brake let go + double moving{-1.0}; // the time the train got above 0.5 km/h + double running{-1.0}; // the time it got above 10 km/h + double demand{0.0}; // of the controller when the brake let go + double pressure{0.0}; // in the brake cylinders of the cab car then +}; + +// the brake applied at standstill, then Act before every step with the time from the start; the brake let go as +// TDynamicObject::Update() lets it go (in ShuntMode, until above 1 km/h) +template start start_off(elf &Unit, double Seconds, Action Act) { + auto &cab{Unit.cab()}; + // the train stands held, its cylinders filled + hold(Unit, true); + Unit.wait(10.0); + start result; + result.pressure = cab.BrakePress; + auto shuntmode{true}; + auto const steps{std::lround(Seconds / step_time)}; + for (long i = 0; i < steps && result.running < 0.0; ++i) { + auto const time{i * step_time}; + Act(time); + Unit.unit.step(Unit.line); + auto const released{cab.UpdateStopBrakeRelease(cab.eimic_real, step_time)}; + if (cab.Vel > 1.0) { + shuntmode = false; + } + hold(Unit, shuntmode && false == released); + if (released && result.release < 0.0) { + result.release = time; + result.demand = cab.eimic_real; + } + if (cab.Vel > 0.5 && result.moving < 0.0) { + result.moving = time; + } + if (cab.Vel > 10.0) { + result.running = time; + } + } + return result; +} + +void flick(elf &Unit, double Time) { + Unit.set_controller(Time < 0.5 * step_time ? 4 : 3); +} + +} // namespace + +TEST_CASE("elf holding brake: without SBDReleaseDelay it lets go at the first demand, as it always did") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + CHECK(car->StopBrakeDecc == doctest::Approx(0.6)); + CHECK(car->StopBrakeReleaseDelay == 0.0); + CHECK_FALSE(car->UpdateStopBrakeRelease(0.0, step_time)); + CHECK_FALSE(car->UpdateStopBrakeRelease(-0.5, step_time)); + CHECK(car->UpdateStopBrakeRelease(0.001, step_time)); + CHECK(car->UpdateStopBrakeRelease(0.01, step_time)); + // and holds again at no demand + CHECK_FALSE(car->UpdateStopBrakeRelease(0.0, step_time)); +} + +TEST_CASE("elf holding brake: SBDReleaseDelay holds it for that long of a demand") { + vehicle car{definition::fiz("elf_v1/21we-a").set("Cntrl", "SBDReleaseDelay", 1.0)}; + REQUIRE(car->StopBrakeReleaseDelay == doctest::Approx(1.0)); + // the demand rises above 0 in the step of time 0 + long held{0}; + while (held < 500 && false == car->UpdateStopBrakeRelease(0.01, step_time)) { + ++held; + } + CHECK(held * step_time == doctest::Approx(1.0).epsilon(0.015)); + // it holds again once there's no demand, and waits the whole delay again for the next one + CHECK_FALSE(car->UpdateStopBrakeRelease(0.0, step_time)); + CHECK(car->StopBrakeReleaseTimer == 0.0); + CHECK_FALSE(car->UpdateStopBrakeRelease(0.01, step_time)); +} + +TEST_CASE("elf holding brake: the controller held at power") { + SUBCASE("without SBDReleaseDelay the brake lets go at the first step of the power position, at 1%") { + elf unit{{data::plain}}; + REQUIRE(unit.ready); + auto const release{release_time(unit, 5.0, [&unit](double) { unit.set_controller(4); })}; + CHECK(release == doctest::Approx(0.0)); + CHECK(unit.cab().eimic_real == doctest::Approx(0.01)); + } + SUBCASE("with SBDReleaseDelay=1.0 it lets go as the demand starts to ramp up, about 1 s on") { + elf unit{{data::plain}, elf_delay}; + REQUIRE(unit.ready); + auto &cab{unit.cab()}; + auto const release{release_time(unit, 5.0, [&unit](double) { unit.set_controller(4); })}; + // the 1% of the first step is all there is until then + auto const demand{cab.eimic_real}; + // the step the ramp of the demand starts at + auto rampstart{release}; + while (cab.eimic_real < 0.0101 && rampstart < 5.0) { + rampstart += step_time; + unit.unit.step(unit.line); + } + MESSAGE("held: release " << release << " s at " << demand << ", ramp from " << rampstart << " s"); + CHECK(release == doctest::Approx(1.0).epsilon(0.015)); + CHECK(demand == doctest::Approx(0.01).epsilon(0.02)); + // it lets go within a step of the ramp's start + CHECK(std::abs(release - rampstart) <= 1.5 * step_time); + } +} + +TEST_CASE("elf holding brake: the controller flicked to power once and back to holding the power") { + elf unit{{data::plain}, elf_delay}; + REQUIRE(unit.ready); + auto &cab{unit.cab()}; + auto const release{release_time(unit, 5.0, [&unit](double Time) { flick(unit, Time); })}; + MESSAGE("flick: release " << release << " s, demand " << cab.eimic_real); + CHECK(release == doctest::Approx(1.0).epsilon(0.015)); + // the demand stays at the 1% of the flick + CHECK(cab.eimic_real == doctest::Approx(0.01).epsilon(0.02)); +} + +TEST_CASE("elf holding brake: a demand dropped to zero before the delay starts the count again") { + elf unit{{data::plain}, elf_delay}; + REQUIRE(unit.ready); + auto &cab{unit.cab()}; + // power for 0.5 s, the braking position for 0.2 s (no demand), then power again + auto const release{release_time(unit, 5.0, [&unit](double Time) { unit.set_controller(Time > 0.495 && Time < 0.695 ? 2 : 4); })}; + MESSAGE("restart: release " << release << " s"); + CHECK(release == doctest::Approx(1.7).epsilon(0.01)); + CHECK(cab.eimic_real > 0.0); +} + +TEST_CASE("elf holding brake: it comes back when the demand drops to zero at standstill") { + elf unit{{data::plain}, elf_delay}; + REQUIRE(unit.ready); + auto &cab{unit.cab()}; + auto const release{release_time(unit, 5.0, [&unit](double) { unit.set_controller(4); })}; + REQUIRE(release > 0.0); + // the braking position takes the demand off: the brake holds from the next step + unit.set_controller(2); + unit.unit.step(unit.line); + CHECK(cab.eimic_real <= 0.0); + CHECK_FALSE(cab.UpdateStopBrakeRelease(cab.eimic_real, step_time)); + // and power demanded again waits the delay again + auto const again{release_time(unit, 5.0, [&unit](double) { unit.set_controller(4); })}; + CHECK(again == doctest::Approx(1.0).epsilon(0.015)); +} + +TEST_CASE("elf holding brake: two Elfs coupled let it go as one does") { + elf one{{data::plain}, elf_delay}; + elf two{{data::plain, data::plain}, elf_delay}; + REQUIRE(one.ready); + REQUIRE(two.ready); + REQUIRE(two.unit.size() == 6); + auto const oneheld{release_time(one, 5.0, [&one](double) { one.set_controller(4); })}; + auto const twoheld{release_time(two, 5.0, [&two](double) { two.set_controller(4); })}; + CHECK(oneheld == doctest::Approx(1.0).epsilon(0.015)); + CHECK(twoheld == doctest::Approx(oneheld)); + // no demand for a while, which holds the brake, then the flick + CHECK(release_time(one, 5.0, [&one](double) { one.set_controller(2); }) < 0.0); + CHECK(release_time(two, 5.0, [&two](double) { two.set_controller(2); }) < 0.0); + auto const oneflicked{release_time(one, 5.0, [&one](double Time) { flick(one, Time); })}; + auto const twoflicked{release_time(two, 5.0, [&two](double Time) { flick(two, Time); })}; + CHECK(oneflicked == doctest::Approx(1.0).epsilon(0.015)); + CHECK(twoflicked == doctest::Approx(oneflicked)); +} + +TEST_CASE("elf holding brake: the train doesn't move before the brake lets go, and starts off after it") { + // the driver and the AI both put the controller to power and keep it there: TController::CheckTimeControllers() + // drops it to holding the power once there's a demand, but IncSpeedEIM() puts it back to power in the same update + // of the AI, so the physics sees it held + elf now{{data::plain}}; + elf delayed{{data::plain}, elf_delay}; + REQUIRE(now.ready); + REQUIRE(delayed.ready); + auto const before{start_off(now, 60.0, [&now](double) { now.set_controller(4); })}; + auto const after{start_off(delayed, 60.0, [&delayed](double) { delayed.set_controller(4); })}; + MESSAGE("held brake " << before.pressure << " bar in the cab car"); + MESSAGE("without the delay: release " << before.release << " s at " << before.demand << ", moving " << before.moving << " s, 10 km/h " << before.running << " s"); + MESSAGE("with the delay: release " << after.release << " s at " << after.demand << ", moving " << after.moving << " s, 10 km/h " << after.running << " s"); + CHECK(before.pressure > 1.0); + CHECK(before.release == doctest::Approx(0.0)); + CHECK(after.release == doctest::Approx(1.0).epsilon(0.015)); + // held until then, at the 1% of the first step + CHECK(after.demand == doctest::Approx(0.01).epsilon(0.05)); + CHECK(after.moving > after.release); + // both start off, the delayed one at most the delay later + REQUIRE(before.running > 0.0); + REQUIRE(after.running > 0.0); + CHECK(after.running >= before.running); + CHECK(after.running <= before.running + elf_delay + 0.05); +} + +TEST_CASE("elf holding brake: the flick to power doesn't move the train before the brake lets go") { + elf unit{{data::plain}, elf_delay}; + REQUIRE(unit.ready); + auto const flicked{start_off(unit, 10.0, [&unit](double Time) { flick(unit, Time); })}; + MESSAGE("flick: release " << flicked.release << " s, moving " << flicked.moving << " s, speed " << unit.cab().Vel << " km/h after 10 s"); + CHECK(flicked.release == doctest::Approx(1.0).epsilon(0.015)); + CHECK((flicked.moving < 0.0 || flicked.moving > flicked.release)); +} + +TEST_CASE("elf holding brake: the force of the motors at 1% against the holding brake") { + // the numbers for the report: the holding force of the train (SBD times its mass), and what the motors of the cab + // car make at the 1% of the first step of the controller with no brake holding them back + elf unit{{data::plain}}; + REQUIRE(unit.ready); + auto &cab{unit.cab()}; + auto mass{0.0}; + auto powered{0}; + for (std::size_t i = 0; i < unit.unit.size(); ++i) { + mass += unit.car(i).TotalMass; + powered += unit.car(i).NPoweredAxles > 0 ? 1 : 0; + } + unit.set_controller(4); + unit.unit.step(unit.line); + unit.set_controller(3); + unit.wait(5.0); + auto const holding{cab.StopBrakeDecc * mass}; + MESSAGE("mass " << mass << " kg, holding " << holding << " N, cars with motors " << powered << ", demand " << cab.eimic_real << ", cab car Ft " << cab.Ft + << " N, Fful " << cab.eimv[eimv_Fful] << " kN, speed " << cab.Vel << " km/h after 5 s"); + CHECK(cab.eimic_real == doctest::Approx(0.01).epsilon(0.02)); + CHECK(cab.Ft * powered < 0.1 * holding); +} From 32356fe31b473260930398c8d1d50ec5524ed8a0 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:37:29 +0100 Subject: [PATCH 074/136] feat(audio): the OpenAL Soft options in eu07.ini and in the settings panel (#404) * feat(audio): the OpenAL Soft options in eu07.ini and in the settings panel New optional eu07.ini keys, each defaulting to what the simulator did before: - sound.outputmode auto|mono|stereo|stereo-basic|uhj|headphones|quad|5.1|6.1|7.1 (ALC_SOFT_output_mode) - sound.hrtf auto|on|off and sound.hrtf.profile "" (ALC_SOFT_HRTF) - sound.limiter auto|on|off (ALC_SOFT_output_limiter) - sound.frequency , 0 for the device's own rate (ALC_FREQUENCY) - sound.resampler "" (AL_SOFT_source_resampler), empty for the library default - sound.doppler , 0.25 as before - sound.efx.lowpass yes|no: the soundproofing of the cab also takes the high tones away, through an EFX low-pass filter (off by default) - sound.efx.airabsorption : distant sounds lose their high tones (0 by default) With a library lacking an extension the key is ignored. sound.openal.renderer is now also tried as CP1250 converted to UTF-8 (the starter writes eu07.ini in CP1250, OpenAL names devices in UTF-8), and a device that isn't there falls back to the default one with a line in the log instead of no sound at all. The device's connection is polled even with system events, as a safety net; a failed reopen is retried each second but logged once. The log gets one "sound: device ..." line with what the device ended up with, and export_as_text writes the new keys and sound.maxsources. The debug panel's settings section lists the devices, output modes, HRTF data sets and resamplers the library offers; device options reopen the device (ALC_SOFT_reopen_device, or alcResetDeviceSOFT), source options apply to the playing sounds at once. sound.maxsources gets no control there: OpenAL Soft gives at least 256 sources whatever is asked; the key works as before. Sound files are also looked for as .opus and .mp3 after .ogg, .flac and .wav, which libsndfile 1.1 and later reads; an existing file is found as before. No asset changes are needed. * fix(audio): the low-pass filter muffles by the soundproofing, not by the volume trim of the ambient sounds With sound.efx.lowpass yes the filter took the 0.4 volume trim of the sounds placed on top of the listener (range below -1) for soundproofing: the ambient sounds of the scenery were muffled everywhere, outdoors too, and in a cab more than its soundproofing says. The filter takes the soundproofing before the trim now. The gain and the reference distance keep the trim as before, so nothing changes with the filter off. * fix(audio): no low-pass filter for a soundproofing the data leaves undefined The soundproofing: table of a sound, and the one of a vehicle's PA system, keep their -1 entries as -1, and a gauge's keeps any value as it is; update_soundproofing passes them on as they are. OpenAL refuses the negative gain, so such a sound keeps the gain it had, as it did before the filter; the low-pass filter clamped the -1 to 0 and took away all the high frequencies of it. A negative soundproofing sets no filter now. Without sound.efx.lowpass nothing changes. --------- Co-authored-by: maj00r --- application/driveruipanels.cpp | 83 ++++++++ audio/audio.cpp | 2 +- audio/audiorenderer.cpp | 360 ++++++++++++++++++++++++++++++++- audio/audiorenderer.h | 38 +++- audio/sound.cpp | 2 + utilities/Globals.cpp | 69 +++++++ utilities/Globals.h | 11 + 7 files changed, 554 insertions(+), 11 deletions(-) diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 015b574e6..124e3fef8 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -41,6 +41,10 @@ http://mozilla.org/MPL/2.0/. #endif #include +#include +#include + +#include "audio/audiorenderer.h" namespace { @@ -1720,6 +1724,81 @@ bool debug_panel::render_section_developer() const return true; } +namespace { + +// a combo choosing one of the names, the first entry standing for the library's own choice. the names are asked for +// each time the list opens, as devices come and go. returns: true if the choice changed +template +bool name_combo( char const *Label, std::string &Value, Names_ const &Names, char const *Defaultlabel, std::string_view const Defaultvalue ) { + + auto const preview { Value == Defaultvalue ? std::string{ Defaultlabel } : Value }; + if( false == ImGui::BeginCombo( Label, preview.c_str() ) ) { return false; } + + static std::vector names; // one list per call site, as each passes its own lambda + if( ImGui::IsWindowAppearing() ) { + names = Names(); + } + auto changed { false }; + if( ImGui::Selectable( Defaultlabel, Value == Defaultvalue ) ) { + Value = Defaultvalue; + changed = true; + } + for( auto const &name : names ) { + if( ImGui::Selectable( name.c_str(), name == Value ) ) { + Value = name; + changed = true; + } + } + ImGui::EndCombo(); + return changed; +} + +// options of the audio device, applied by reopening it: output device, output mode, HRTF, limiter, mixing rate, sources +void render_audio_device_settings() { + + auto changed { false }; + changed |= name_combo( "Output device###audiodevice", Global.AudioRenderer, + [] { return audio::renderer.output_devices(); }, "System default", "" ); + changed |= name_combo( "Output mode###audiooutputmode", Global.AudioOutputMode, + [] { return std::vector{ "mono", "stereo", "stereo-basic", "uhj", "headphones", "quad", "5.1", "6.1", "7.1" }; }, + "Automatic", "auto" ); + changed |= name_combo( "HRTF###audiohrtf", Global.AudioHrtf, + [] { return std::vector{ "on", "off" }; }, "Automatic", "auto" ); + changed |= name_combo( "HRTF data set###audiohrtfprofile", Global.AudioHrtfProfile, + [] { return audio::renderer.hrtf_profiles(); }, "Library's choice", "" ); + changed |= name_combo( "Limiter###audiolimiter", Global.AudioLimiter, + [] { return std::vector{ "on", "off" }; }, "Automatic", "auto" ); + + auto frequency { Global.AudioFrequency > 0 ? std::to_string( Global.AudioFrequency ) : std::string{} }; + if( name_combo( "Mixing rate###audiofrequency", frequency, + [] { return std::vector{ "22050", "32000", "44100", "48000", "96000" }; }, "Device's", "" ) ) { + Global.AudioFrequency = ( frequency.empty() ? 0 : std::stoi( frequency ) ); + changed = true; + } + + if( changed ) { + audio::renderer.apply_device_settings(); + } +} + +// options of the sources, applied to the playing ones right away: resampler, Doppler effect, EFX +void render_audio_source_settings() { + + auto changed { false }; + changed |= name_combo( "Resampler###audioresampler", Global.AudioResampler, + [] { return audio::renderer.resamplers(); }, "Library's default", "" ); + changed |= ImGui::SliderFloat( ( to_string( Global.AudioDoppler, 2 ) + "###audiodoppler" ).c_str(), &Global.AudioDoppler, 0.0f, 1.0f, "Doppler effect" ); + changed |= ImGui::Checkbox( "Soundproofing muffles high frequencies###audiolowpass", &Global.AudioLowpass ); + changed |= ImGui::SliderFloat( ( to_string( Global.AudioAirAbsorption, 1 ) + "###audioairabsorption" ).c_str(), &Global.AudioAirAbsorption, 0.0f, 10.0f, "Air absorption" ); + + if( changed ) { + audio::renderer.apply_source_settings(); + } + ImGui::TextWrapped( "%s", audio::renderer.device_status().c_str() ); +} + +} // namespace + bool debug_panel::render_section_settings() const { @@ -1767,6 +1846,10 @@ debug_panel::render_section_settings() const { commandrelay.post(user_command::radiovolumeset, val, 0.0, GLFW_PRESS, 0); } } + if( Global.bSoundEnabled ) { + render_audio_device_settings(); + render_audio_source_settings(); + } return true; } diff --git a/audio/audio.cpp b/audio/audio.cpp index 3be2810d1..845fba9e7 100644 --- a/audio/audio.cpp +++ b/audio/audio.cpp @@ -391,7 +391,7 @@ buffer_manager::find_file( std::string const &Filename ) const { auto const lookup { FileExists( { Filename }, - { ".ogg", ".flac", ".wav" } ) }; + { ".ogg", ".flac", ".wav", ".opus", ".mp3" } ) }; return lookup.first + lookup.second; } diff --git a/audio/audiorenderer.cpp b/audio/audiorenderer.cpp index 080ab66f3..7950fca56 100644 --- a/audio/audiorenderer.cpp +++ b/audio/audiorenderer.cpp @@ -14,14 +14,102 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Globals.h" #include "vehicle/Camera.h" #include "utilities/Logs.h" +#include "utilities/utilities.h" #include "simulation/simulation.h" #include "vehicle/Train.h" +#include +#include +#include +#include + namespace audio { openal_renderer renderer; bool event_volume_change { false }; +namespace { + +struct named_value { + std::string_view name; + ALCint value; +}; + +// values of sound.outputmode, as ALC_OUTPUT_MODE_SOFT takes them +constexpr std::array output_modes { + named_value{ "mono", ALC_MONO_SOFT }, + named_value{ "stereo", ALC_STEREO_SOFT }, + named_value{ "stereo-basic", ALC_STEREO_BASIC_SOFT }, + named_value{ "uhj", ALC_STEREO_UHJ_SOFT }, + named_value{ "headphones", ALC_STEREO_HRTF_SOFT }, + named_value{ "quad", ALC_QUAD_SOFT }, + named_value{ "5.1", ALC_SURROUND_5_1_SOFT }, + named_value{ "6.1", ALC_SURROUND_6_1_SOFT }, + named_value{ "7.1", ALC_SURROUND_7_1_SOFT } }; + +// returns: ALC_OUTPUT_MODE_SOFT value for given sound.outputmode, or nothing for auto +std::optional output_mode_value( std::string_view const Name ) { + + if( Name == "auto" ) { return std::nullopt; } + if( auto const lookup { std::ranges::find( output_modes, Name, &named_value::name ) }; lookup != std::end( output_modes ) ) { + return lookup->value; + } + WriteLog( std::format( "sound: unknown output mode \"{}\", left to the library", Name ) ); + return std::nullopt; +} + +// returns: name of given ALC_OUTPUT_MODE_SOFT value +std::string_view output_mode_name( ALCint const Value ) { + + if( auto const lookup { std::ranges::find( output_modes, Value, &named_value::value ) }; lookup != std::end( output_modes ) ) { + return lookup->name; + } + return "other"; +} + +// returns: ALC_TRUE or ALC_FALSE for given on/off option, or nothing for auto +std::optional switch_value( std::string_view const Name ) { + + if( Name == "on" ) { return ALC_TRUE; } + if( Name == "off" ) { return ALC_FALSE; } + return std::nullopt; +} + +// opens the output device of sound.openal.renderer. the library names devices in UTF-8, but the starter writes eu07.ini +// in code page 1250, so a name that fails as written is tried as 1250 text too. a device found neither way, unplugged +// say, leaves the default one rather than no sound at all. the name is set to what got opened, for a later reopen +ALCdevice *open_output_device() { + + if( Global.AudioRenderer.empty() ) { + return ::alcOpenDevice( nullptr ); + } + if( auto *device { ::alcOpenDevice( Global.AudioRenderer.c_str() ) } ) { + return device; + } + if( auto const utf8name { win1250_to_utf8( Global.AudioRenderer ) }; utf8name != Global.AudioRenderer ) { + if( auto *device { ::alcOpenDevice( utf8name.c_str() ) } ) { + Global.AudioRenderer = utf8name; + return device; + } + } + ErrorLog( std::format( "sound: audio device \"{}\" not found, the default one used", Global.AudioRenderer ) ); + Global.AudioRenderer.clear(); + return ::alcOpenDevice( nullptr ); +} + +// splits a list of null-terminated names ending with an empty name, as alcGetString gives device lists +std::vector split_name_list( ALCchar const *List ) { + + std::vector names; + while( List != nullptr && *List != '\0' ) { + auto const &name { names.emplace_back( List ) }; + List += name.size() + 1; + } + return names; +} + +} // namespace + float const EU07_SOUND_CUTOFFRANGE { 3000.f }; // 2750 m = max expected emitter spawn range, plus safety margin float const EU07_SOUND_VELOCITYLIMIT { 250 / 3.6f }; // 343 m/sec ~= speed of sound; arbitrary limit of 250 km/h @@ -178,6 +266,7 @@ openal_source::sync_with( sound_properties const &State ) { sound_range : 5 ) }; // range of -1 means sound of unlimited range, positioned at the listener ::alSourcef( id, AL_REFERENCE_DISTANCE, range * ( 1.f / 16.f ) * State.soundproofing ); + renderer.soundproofing_filter( id, State.soundproofing_hf ); } if( sound_range != -1 ) { auto const rangesquared { sound_range * sound_range }; @@ -274,6 +363,8 @@ openal_renderer::~openal_renderer() { if( m_alcEventCallbackSOFT != nullptr ) { m_alcEventCallbackSOFT( nullptr, nullptr ); } // stop callbacks before teardown + if( m_lowpassfilter != 0 ) { m_alDeleteFilters( 1, &m_lowpassfilter ); } + ::alcMakeContextCurrent( nullptr ); if( m_context != nullptr ) { ::alcDestroyContext( m_context ); } @@ -325,7 +416,9 @@ openal_renderer::init() { return false; } ::alDistanceModel( AL_INVERSE_DISTANCE_CLAMPED ); - ::alDopplerFactor( 0.25f ); + ::alDopplerFactor( Global.AudioDoppler ); + m_resampler = resampler_index(); + WriteLog( "sound: " + device_status() ); // all done m_ready = true; return true; @@ -400,8 +493,9 @@ openal_renderer::update( double const Deltatime ) { // event-driven: the callback (any thread) flags default-output / device-removal changes needsreopen = m_outputchanged.exchange( false ); } - else if( m_candetectdisconnect ) { - // fallback without ALC_SOFT_system_events: poll for a hard disconnect at ~1 Hz + if( false == needsreopen && m_candetectdisconnect ) { + // poll for a hard disconnect at ~1 Hz: the fallback without ALC_SOFT_system_events, and a safety net + // with it, as not every backend reports the removal of a device m_devicechecktime += Deltatime; if( m_devicechecktime >= 1.0 ) { m_devicechecktime = 0.0; @@ -411,12 +505,15 @@ openal_renderer::update( double const Deltatime ) { } } if( needsreopen ) { - if( m_alcReopenDeviceSOFT( m_device, nullptr, m_contextattributes ) == ALC_TRUE ) { + if( m_alcReopenDeviceSOFT( m_device, nullptr, m_contextattributes.data() ) == ALC_TRUE ) { auto const *nowon { (char const *)::alcGetString( nullptr, ALC_DEFAULT_ALL_DEVICES_SPECIFIER ) }; WriteLog( "sound: audio output changed, reopened playback on \"" + std::string{ nowon ? nowon : "?" } + "\"" ); + m_reopenfailed = false; } - else { + else if( false == m_reopenfailed ) { + // with no output left the poll retries each second; the log gets it once ErrorLog( "sound: audio output changed but reopening on the default device failed (will retry)" ); + m_reopenfailed = true; } } } @@ -562,6 +659,7 @@ openal_renderer::fetch_source() { glm::vec3 zero_pos{ 0.f, 0.f, 0.f }; ::alSourcefv( newsource.id, AL_POSITION, glm::value_ptr( zero_pos ) ); ::alSourcefv( newsource.id, AL_VELOCITY, glm::value_ptr( zero_pos ) ); + configure_source( newsource.id ); } return newsource; @@ -583,7 +681,7 @@ openal_renderer::init_caps() { } // NOTE: default value of audio renderer variable is empty string, meaning argument of NULL i.e. 'preferred' device - m_device = ::alcOpenDevice( Global.AudioRenderer.empty() ? nullptr : Global.AudioRenderer.c_str() ); + m_device = open_output_device(); if( m_device == nullptr ) { ErrorLog( "Failed to obtain audio device" ); return false; @@ -604,10 +702,16 @@ openal_renderer::init_caps() { WriteLog( "Supported extensions: " + std::string{ (char *)::alcGetString( m_device, ALC_EXTENSIONS ) } ); - ALCint attr[3] = { ALC_MONO_SOURCES, Global.audio_max_sources, 0 }; // request more sounds - std::copy( std::begin( attr ), std::end( attr ), std::begin( m_contextattributes ) ); // cached for device reopen + // the device options (output mode, HRTF and the like) are known once the device is open + m_hasoutputmode = ( alcIsExtensionPresent( m_device, "ALC_SOFT_output_mode" ) == ALC_TRUE ); + m_haslimiter = ( alcIsExtensionPresent( m_device, "ALC_SOFT_output_limiter" ) == ALC_TRUE ); + if( alcIsExtensionPresent( m_device, "ALC_SOFT_HRTF" ) == ALC_TRUE ) { + m_alcGetStringiSOFT = (LPALCGETSTRINGISOFT)alcGetProcAddress( m_device, "alcGetStringiSOFT" ); + m_alcResetDeviceSOFT = (LPALCRESETDEVICESOFT)alcGetProcAddress( m_device, "alcResetDeviceSOFT" ); + } + m_contextattributes = device_attributes(); // cached for device reopen - m_context = ::alcCreateContext( m_device, attr ); + m_context = ::alcCreateContext( m_device, m_contextattributes.data() ); if( m_context == nullptr ) { ErrorLog( "Failed to create audio context" ); return false; @@ -664,7 +768,245 @@ openal_renderer::init_caps() { } } + init_extensions(); + return true; } +// resolves the entry points of the context extensions the settings use: source resampler, EFX filters +void +openal_renderer::init_extensions() { + + if( alIsExtensionPresent( "AL_SOFT_source_resampler" ) == AL_TRUE ) { + m_alGetStringiSOFT = (LPALGETSTRINGISOFT)alGetProcAddress( "alGetStringiSOFT" ); + } + if( alcIsExtensionPresent( m_device, "ALC_EXT_EFX" ) == ALC_TRUE ) { + m_alGenFilters = (LPALGENFILTERS)alGetProcAddress( "alGenFilters" ); + m_alDeleteFilters = (LPALDELETEFILTERS)alGetProcAddress( "alDeleteFilters" ); + m_alFilteri = (LPALFILTERI)alGetProcAddress( "alFilteri" ); + m_alFilterf = (LPALFILTERF)alGetProcAddress( "alFilterf" ); + m_hasefx = ( m_alGenFilters != nullptr && m_alDeleteFilters != nullptr && m_alFilteri != nullptr && m_alFilterf != nullptr ); + } + if( false == m_hasefx ) { + return; + } + ::alGetError(); + m_alGenFilters( 1, &m_lowpassfilter ); + m_alFilteri( m_lowpassfilter, AL_FILTER_TYPE, AL_FILTER_LOWPASS ); + if( ::alGetError() != AL_NO_ERROR ) { + WriteLog( "sound: warning: EFX low-pass filter not available" ); + m_lowpassfilter = 0; + } +} + +// returns: attributes of the device and the context made from the settings. with the defaults they are as before the +// settings existed, which leaves output mode, HRTF, limiter and mixing rate to the library +std::vector +openal_renderer::device_attributes() const { + + // sound.maxsources, kept for an OpenAL other than OpenAL Soft: that one gives at least 256 sources whatever is asked + std::vector attributes { ALC_MONO_SOURCES, Global.audio_max_sources }; + auto const add { [ &attributes ]( ALCint const Key, ALCint const Value ) { + attributes.push_back( Key ); + attributes.push_back( Value ); } }; + + if( auto const mode { output_mode_value( Global.AudioOutputMode ) }; mode && m_hasoutputmode ) { + add( ALC_OUTPUT_MODE_SOFT, *mode ); + } + if( m_alcGetStringiSOFT != nullptr ) { + if( auto const hrtf { switch_value( Global.AudioHrtf ) } ) { + add( ALC_HRTF_SOFT, *hrtf ); + } + if( auto const index { hrtf_index( Global.AudioHrtfProfile ) }; index >= 0 ) { + add( ALC_HRTF_ID_SOFT, index ); + } + } + if( auto const limiter { switch_value( Global.AudioLimiter ) }; limiter && m_haslimiter ) { + add( ALC_OUTPUT_LIMITER_SOFT, *limiter ); + } + if( Global.AudioFrequency > 0 ) { + add( ALC_FREQUENCY, Global.AudioFrequency ); + } + attributes.push_back( 0 ); + return attributes; +} + +// returns: index of the named HRTF data set, or -1 if the name is empty or unknown +int +openal_renderer::hrtf_index( std::string const &Name ) const { + + if( Name.empty() ) { return -1; } + auto const profiles { hrtf_profiles() }; + if( auto const lookup { std::ranges::find( profiles, Name ) }; lookup != std::end( profiles ) ) { + return static_cast( std::distance( std::begin( profiles ), lookup ) ); + } + WriteLog( std::format( "sound: unknown HRTF data set \"{}\", left to the library", Name ) ); + return -1; +} + +// returns: index of the resampler of the settings, the library's default with none set, or -1 without the extension +ALint +openal_renderer::resampler_index() const { + + if( m_alGetStringiSOFT == nullptr ) { return -1; } + if( false == Global.AudioResampler.empty() ) { + auto const names { resamplers() }; + if( auto const lookup { std::ranges::find( names, Global.AudioResampler ) }; lookup != std::end( names ) ) { + return static_cast( std::distance( std::begin( names ), lookup ) ); + } + WriteLog( std::format( "sound: unknown resampler \"{}\", the library's default used", Global.AudioResampler ) ); + } + return ::alGetInteger( AL_DEFAULT_RESAMPLER_SOFT ); +} + +// sets the options of the settings on a source +void +openal_renderer::configure_source( ALuint const Source ) const { + + if( m_resampler >= 0 ) { + ::alSourcei( Source, AL_SOURCE_RESAMPLER_SOFT, m_resampler ); + } + if( m_hasefx ) { + ::alSourcef( Source, AL_AIR_ABSORPTION_FACTOR, Global.AudioAirAbsorption ); + } +} + +// sets the EFX low-pass filter of a source for given soundproofing: the stronger the soundproofing, the more muffled +void +openal_renderer::soundproofing_filter( ALuint const Source, float const Soundproofing ) const { + + if( m_lowpassfilter == 0 ) { return; } + // a soundproofing left undefined by the data (-1, which OpenAL doesn't take as the gain either) isn't muffled + if( false == Global.AudioLowpass || Soundproofing < 0.f || Soundproofing >= 1.f ) { + ::alSourcei( Source, AL_DIRECT_FILTER, AL_FILTER_NULL ); + return; + } + // the level is set by the gain already, the filter takes away only the high frequencies + m_alFilterf( m_lowpassfilter, AL_LOWPASS_GAIN, 1.f ); + m_alFilterf( m_lowpassfilter, AL_LOWPASS_GAINHF, std::clamp( Soundproofing, 0.f, 1.f ) ); + ::alSourcei( Source, AL_DIRECT_FILTER, static_cast( m_lowpassfilter ) ); +} + +// returns: names of the output devices +std::vector +openal_renderer::output_devices() const { + + if( ::alcIsExtensionPresent( nullptr, "ALC_ENUMERATE_ALL_EXT" ) == ALC_TRUE ) { + return split_name_list( ::alcGetString( nullptr, ALC_ALL_DEVICES_SPECIFIER ) ); + } + return split_name_list( ::alcGetString( nullptr, ALC_DEVICE_SPECIFIER ) ); +} + +// returns: names of the HRTF data sets of the device +std::vector +openal_renderer::hrtf_profiles() const { + + std::vector names; + if( m_device == nullptr || m_alcGetStringiSOFT == nullptr ) { return names; } + ALCint count { 0 }; + ::alcGetIntegerv( m_device, ALC_NUM_HRTF_SPECIFIERS_SOFT, 1, &count ); + for( ALCint index = 0; index < count; ++index ) { + auto const *name { m_alcGetStringiSOFT( m_device, ALC_HRTF_SPECIFIER_SOFT, index ) }; + names.emplace_back( name != nullptr ? name : "" ); + } + return names; +} + +// returns: names of the resamplers +std::vector +openal_renderer::resamplers() const { + + std::vector names; + if( m_alGetStringiSOFT == nullptr ) { return names; } + auto const count { ::alGetInteger( AL_NUM_RESAMPLERS_SOFT ) }; + for( ALint index = 0; index < count; ++index ) { + auto const *name { m_alGetStringiSOFT( AL_RESAMPLER_NAME_SOFT, index ) }; + names.emplace_back( name != nullptr ? name : "" ); + } + return names; +} + +// returns: what the device ended up with +std::string +openal_renderer::device_status() const { + + if( m_device == nullptr ) { return "no audio device"; } + + auto const namequery { ::alcIsExtensionPresent( nullptr, "ALC_ENUMERATE_ALL_EXT" ) == ALC_TRUE ? ALC_ALL_DEVICES_SPECIFIER : ALC_DEVICE_SPECIFIER }; + auto const *devicename { ::alcGetString( m_device, namequery ) }; + ALCint frequency { 0 }; + ::alcGetIntegerv( m_device, ALC_FREQUENCY, 1, &frequency ); + auto status { std::format( "device \"{}\", {} Hz", devicename != nullptr ? devicename : "?", frequency ) }; + + if( m_hasoutputmode ) { + ALCint mode { 0 }; + ::alcGetIntegerv( m_device, ALC_OUTPUT_MODE_SOFT, 1, &mode ); + status += std::format( ", output {}", output_mode_name( mode ) ); + } + if( m_alcGetStringiSOFT != nullptr ) { + ALCint hrtf { ALC_FALSE }; + ::alcGetIntegerv( m_device, ALC_HRTF_SOFT, 1, &hrtf ); + if( hrtf == ALC_TRUE ) { + auto const *hrtfname { ::alcGetString( m_device, ALC_HRTF_SPECIFIER_SOFT ) }; + status += std::format( ", HRTF \"{}\"", hrtfname != nullptr ? hrtfname : "?" ); + } + else { + status += ", HRTF off"; + } + } + if( m_resampler >= 0 ) { + auto const *resamplername { m_alGetStringiSOFT( AL_RESAMPLER_NAME_SOFT, m_resampler ) }; + status += std::format( ", resampler {}", resamplername != nullptr ? resamplername : "?" ); + } + if( m_lowpassfilter != 0 ) { + status += ", EFX"; + } + return status; +} + +// applies changed device options without a restart: reopens the device, or resets it with an older library +bool +openal_renderer::apply_device_settings() { + + if( false == m_ready ) { return false; } + + m_contextattributes = device_attributes(); + auto applied { false }; + if( m_alcReopenDeviceSOFT != nullptr ) { + auto const *devicename { Global.AudioRenderer.empty() ? nullptr : Global.AudioRenderer.c_str() }; + applied = ( m_alcReopenDeviceSOFT( m_device, devicename, m_contextattributes.data() ) == ALC_TRUE ); + } + else if( m_alcResetDeviceSOFT != nullptr ) { + // without ALC_SOFT_reopen_device another output device takes a restart + applied = ( m_alcResetDeviceSOFT( m_device, m_contextattributes.data() ) == ALC_TRUE ); + if( applied ) { + WriteLog( "sound: this audio library can't switch the output device while running, a changed device takes a restart" ); + } + } + if( applied ) { + WriteLog( "sound: audio settings applied, " + device_status() ); + } + else { + ErrorLog( "sound: the audio device settings take a restart to apply" ); + } + return applied; +} + +// applies changed source options to every source; spare sources get them when taken +void +openal_renderer::apply_source_settings() { + + if( false == m_ready ) { return; } + + ::alDopplerFactor( Global.AudioDoppler ); + m_resampler = resampler_index(); + for( auto const &source : m_sources ) { + if( source.id != audio::null_resource ) { + configure_source( source.id ); + } + } + // the filters follow with the gain, which this flag makes every source set anew + audio::event_volume_change = true; +} + } // audio \ No newline at end of file diff --git a/audio/audiorenderer.h b/audio/audiorenderer.h index 3f462eb49..86ea89cd8 100644 --- a/audio/audiorenderer.h +++ b/audio/audiorenderer.h @@ -48,6 +48,9 @@ struct sound_properties { sound_category category { sound_category::unknown }; float gain { 1.f }; float soundproofing { 1.f }; + // the soundproofing of what stands between the sound and the listener, without the volume trim of the sounds placed + // on top of the listener: what the low-pass filter muffles the sound by (sound.efx.lowpass) + float soundproofing_hf { 1.f }; std::uintptr_t soundproofing_stamp { ~std::uintptr_t{0} }; }; @@ -122,6 +125,20 @@ public: void erase( sound_source const *Controller ); void update( double const Deltatime ); + // choices the library offers, for the settings + std::vector output_devices() const; + std::vector hrtf_profiles() const; + std::vector resamplers() const; + // what the device ended up with: device, mixing rate, output mode, HRTF, resampler + std::string device_status() const; + // applies changed device options (sound.openal.renderer, outputmode, hrtf, limiter, frequency) + // without a restart. returns: false if the library can't do it + bool apply_device_settings(); + // applies changed source options (sound.resampler, doppler, efx.*) to every source + void apply_source_settings(); + // sets the EFX low-pass filter of a source for given soundproofing (sound.efx.lowpass) + void soundproofing_filter( ALuint const Source, float const Soundproofing ) const; + glm::dvec3 cached_camerapos; private: @@ -129,6 +146,11 @@ private: using source_sequence = std::stack; bool init_caps(); + void init_extensions(); + std::vector device_attributes() const; + int hrtf_index( std::string const &Name ) const; + ALint resampler_index() const; + void configure_source( ALuint const Source ) const; audio::openal_source fetch_source(); ALCdevice *m_device { nullptr }; @@ -149,10 +171,24 @@ private: LPALCDEVICEPAUSESOFT m_alcDevicePauseSOFT { nullptr }; LPALCDEVICERESUMESOFT m_alcDeviceResumeSOFT { nullptr }; LPALCREOPENDEVICESOFT m_alcReopenDeviceSOFT { nullptr }; + LPALCRESETDEVICESOFT m_alcResetDeviceSOFT { nullptr }; + LPALCGETSTRINGISOFT m_alcGetStringiSOFT { nullptr }; + LPALGETSTRINGISOFT m_alGetStringiSOFT { nullptr }; + LPALGENFILTERS m_alGenFilters { nullptr }; + LPALDELETEFILTERS m_alDeleteFilters { nullptr }; + LPALFILTERI m_alFilteri { nullptr }; + LPALFILTERF m_alFilterf { nullptr }; + + bool m_hasoutputmode { false }; // ALC_SOFT_output_mode + bool m_haslimiter { false }; // ALC_SOFT_output_limiter + bool m_hasefx { false }; // ALC_EXT_EFX, with its filter entry points + ALuint m_lowpassfilter { 0 }; // shared low-pass filter, its parameters are copied to a source when attached + ALint m_resampler { -1 }; // index of the resampler set on the sources, or -1 to leave the library's default bool m_candetectdisconnect { false }; - ALCint m_contextattributes[3] { 0, 0, 0 }; + std::vector m_contextattributes; // cached for device reopen double m_devicechecktime { 0.0 }; + bool m_reopenfailed { false }; // a failed reopen is retried each second, but logged once // ALC_SOFT_system_events: event-driven following of output-device / default-output changes. // Preferred over polling because it reliably catches both device removal and default changes diff --git a/audio/sound.cpp b/audio/sound.cpp index 785b976f5..b981479cc 100644 --- a/audio/sound.cpp +++ b/audio/sound.cpp @@ -998,6 +998,8 @@ sound_source::update_soundproofing() { occupiedcab ); } } + // the walls muffle the sound, the trim below only lowers its volume + m_properties.soundproofing_hf = m_properties.soundproofing; // for ambient sounds reduce their volume to account for their placement right on top of the listener if( m_range < -1 ) { m_properties.soundproofing *= 0.4f; diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 957f9fc50..c6816f850 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -220,6 +220,65 @@ bool global_settings::ConfigParseAudio(cParser& Parser, const std::string& token return true; } + return ConfigParseAudioDevice(Parser, token); +} + +bool global_settings::ConfigParseAudioDevice(cParser& Parser, const std::string& token) +{ + if (token == "sound.outputmode") + { + AudioOutputMode = Parser.getToken(true); + return true; + } + + if (token == "sound.hrtf") + { + AudioHrtf = Parser.getToken(true); + return true; + } + + if (token == "sound.hrtf.profile") + { + AudioHrtfProfile = Parser.getToken(false); + return true; + } + + if (token == "sound.resampler") + { + AudioResampler = Parser.getToken(false); + return true; + } + + if (token == "sound.limiter") + { + AudioLimiter = Parser.getToken(true); + return true; + } + + if (token == "sound.frequency") + { + ParseOneClamped(Parser, AudioFrequency, 0, 192000); + return true; + } + + if (token == "sound.doppler") + { + ParseOneClamped(Parser, AudioDoppler, 0.f, 10.f); + return true; + } + + if (token == "sound.efx.lowpass") + { + ParseOne(Parser, AudioLowpass); + return true; + } + + if (token == "sound.efx.airabsorption") + { + ParseOneClamped(Parser, AudioAirAbsorption, 0.f, 10.f); + return true; + } + return false; } @@ -1802,6 +1861,16 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "sound.volume.positional", EnvironmentPositionalVolume ); export_as_text( Output, "sound.volume.ambient", EnvironmentAmbientVolume ); export_as_text( Output, "sound.asyncload", AudioAsyncLoad ); + export_as_text( Output, "sound.maxsources", audio_max_sources ); + export_as_text( Output, "sound.outputmode", AudioOutputMode ); + export_as_text( Output, "sound.hrtf", AudioHrtf ); + export_as_text( Output, "sound.hrtf.profile", AudioHrtfProfile ); + export_as_text( Output, "sound.resampler", AudioResampler ); + export_as_text( Output, "sound.limiter", AudioLimiter ); + export_as_text( Output, "sound.frequency", AudioFrequency ); + export_as_text( Output, "sound.doppler", AudioDoppler ); + export_as_text( Output, "sound.efx.lowpass", AudioLowpass ); + export_as_text( Output, "sound.efx.airabsorption", AudioAirAbsorption ); export_as_text( Output, "physicslog", WriteLogFlag ); export_as_text( Output, "blackbox", BlackBox ); export_as_text( Output, "fullphysics", FullPhysics ); diff --git a/utilities/Globals.h b/utilities/Globals.h index efd532c6a..7bb2833bc 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -231,6 +231,16 @@ struct global_settings { int audio_max_sources = 30; std::string AudioRenderer; bool AudioAsyncLoad{ false }; // sound files are decoded by worker threads + // OpenAL Soft device and mixing options; the defaults leave the choice to the library, as before they existed + std::string AudioOutputMode{ "auto" }; // sound.outputmode: auto, mono, stereo, stereo-basic, uhj, headphones, quad, 5.1, 6.1, 7.1 + std::string AudioHrtf{ "auto" }; // sound.hrtf: auto, on, off + std::string AudioHrtfProfile; // sound.hrtf.profile: name of the HRTF data set, empty for the library's choice + std::string AudioResampler; // sound.resampler: name of the resampler, empty for the library's default + std::string AudioLimiter{ "auto" }; // sound.limiter: auto, on, off + int AudioFrequency{ 0 }; // sound.frequency: mixing rate in Hz, 0 for the device's + float AudioDoppler{ 0.25f }; // sound.doppler: strength of the Doppler effect + bool AudioLowpass{ false }; // sound.efx.lowpass: soundproofing also muffles the high frequencies + float AudioAirAbsorption{ 0.f }; // sound.efx.airabsorption: 0-10, high frequencies fade with distance // input float fMouseXScale{ 1.5f }; float fMouseYScale{ 0.2f }; @@ -437,6 +447,7 @@ struct global_settings { void ConfigParse(cParser &parser, config_source Source = config_source::ini); bool ConfigParseGeneral(cParser& Parser, const std::string& token); bool ConfigParseAudio(cParser& Parser, const std::string& token); + bool ConfigParseAudioDevice(cParser& Parser, const std::string& token); bool ConfigParseGraphics(cParser& Parser, const std::string& token); bool ConfigParseInput(cParser& Parser, const std::string& token); bool ConfigParseSimulation(cParser& Parser, const std::string& token); From 9ce2d6b7819c307e7f172f2780ccb97e5192010d Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:37:59 +0100 Subject: [PATCH 075/136] build(windows): ship OpenAL Soft 1.25.2 and libsndfile 1.2.2, downloaded by CI (#405) * build(windows): ship OpenAL Soft 1.25.2 and libsndfile 1.2.2 with the build The Windows game loads OpenAL32.dll and libsndfile-1.dll from its own folder, and the depot still had OpenAL Soft 1.18.1 and libsndfile 1.0.28 from 2017. OpenAL Soft 1.18 has neither ALC_SOFT_reopen_device nor ALC_SOFT_system_events, so the code that follows a change of the output device (headphones plugged in or out, a new default device) never ran on Windows; the log said "extension ALC_SOFT_reopen_device not found". libsndfile 1.0.28 reads no Opus and no MP3, which the Linux build (libsndfile 1.2.2) does, so such a file played on Linux only. The Windows job now takes the official release binaries, pinned by SHA-256, and puts them next to the exe in both packages: soft_oal.dll (Win64) of openal-soft-1.25.2-bin.zip as OpenAL32.dll, as its readme says for use without the router, and sndfile.dll of libsndfile-1.2.2-win64.zip as libsndfile-1.dll. The exe imports both by name with an unchanged C ABI, so it needs no rebuild. soft_oal.dll needs only system DLLs and msvcrt.dll (like the old one), sndfile.dll only KERNEL32.dll, its codecs built in. Checked with the master exe of the depot and the Steam data, editor on td.scn: the log shows "ALSOFT 1.25.2" and "following audio output device changes via ALC_SOFT_system_events", the same 160-odd sound files load as with the old DLLs, no "Bad file" and no AL error. No change to the game data. * build(windows): the license texts of the audio libraries shipped with them, AVX note corrected Review of the previous commit: - sndfile.dll is not free of AVX2 code: its static opus and mpg123 pick AVX/AVX2 paths at run time (cpuid). The comment now says so instead of "built without AVX2"; soft_oal.dll has no AVX code. - Both libraries are LGPL and now go into the public release zips, so their license texts go with them in licenses/: COPYING of the OpenAL Soft zip, and COPYING of libsndfile from the source tree of tag 1.2.2 (the libsndfile zip has none), pinned by SHA-256. licenses/ audio-libraries.txt names the versions, that they are unmodified, and where their source is. Checked by running the step's script locally (Windows PowerShell 5.1, without the retry parameters it lacks): both DLLs and the three texts land in build/bin/RelWithDebInfo as intended. * build(windows): the audio library downloads kept between the runs A release or raw.githubusercontent.com out of reach failed the Windows build after the whole MSVC build, and nothing was published for that push. The downloads are cached now (actions/cache v6.1.0, keyed on the workflow file, which pins them; a cache of an older one is restored too). They are named by their SHA-256 and checked by it before use, so only what the cache doesn't hold is downloaded, and the files no pin names any more aren't kept for the next run. * build(windows): the license texts of what the audio DLLs have built in sndfile.dll of the libsndfile 1.2.2 release has its vcpkg build's libraries linked in statically, and soft_oal.dll of OpenAL Soft 1.25.2 has third-party code built in and the MinGW-w64 runtime linked in. Their license texts go to licenses/ with the others, each pinned by SHA-256 and taken from the source tree of the version built in, and audio-libraries.txt lists them with their sources: - libsndfile's own ALAC code (Apache 2.0) and GSM 06.10 code (its COPYRIGHT); its G.721/G.723 code is public domain, named only; - libogg 1.3.5, libvorbis 1.3.7, libFLAC 1.4.2, libopus 1.4 (BSD), mpg123 1.31.3 (LGPL 2.1) and LAME 3.100 (LGPL), with the vcpkg ports they were built by (vcpkg 2023.08.09, whose ports have these versions) for their patches. The DLL names the versions of libopus, libFLAC and libVorbis; mpg123's is told by the SHA-512 of its source archive in the vcpkg build paths the DLL keeps; libogg's and LAME's are those of the vcpkg ports of mid 2023; - OpenAL Soft's PFFFT (BSD-style), GSL (MIT), its BSD 3-Clause parts (the ambisonic rotator, the vocal morpher, the compressor; its BSD-3Clause file) and bs2b (MIT, which has its notice only in its source, so the step writes it out). Its {fmt} needs no text, by the exception of its license for the object form. Its default HRTF data, from MIT's KEMAR measurements, is credited to its authors, as they ask; - the MinGW-w64 runtime and winpthreads, linked into soft_oal.dll by its MinGW GCC 15 build (the DLL has winpthreads' source paths), from mingw-w64 13.0.0: the texts are the same in 12.0.0. libstdc++ and libgcc are under the GCC Runtime Library Exception, which asks for no text. LAME's text is taken from Debian's copy of the 3.100 source, the same file as in LAME's SourceForge repository, which may answer a script with a challenge page. The downloads go with a user agent other than a browser's, as Debian's server answers those with one. A cached file is named by the last part of its URL's path, without the query, which mpg123's URL has. --------- Co-authored-by: maj00r --- .github/workflows/build_bin.yml | 173 ++++++++++++++++++++++++++++++++ 1 file changed, 173 insertions(+) diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index 041eea4f0..ad2d471ec 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -164,6 +164,179 @@ jobs: -Recurse ` -Force + # The downloads of the next step, kept between the runs: a release or raw.githubusercontent.com out of reach then + # doesn't fail the build. The key is this file, which pins them; a cache of an older one is taken too, as the next + # step checks every file by its SHA-256 and downloads only those it doesn't have. + - name: Restore the audio library downloads + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ runner.temp }}/audio-dlls-downloads + key: audio-dlls-${{ hashFiles('.github/workflows/build_bin.yml') }} + restore-keys: audio-dlls- + + # The game loads OpenAL32.dll and libsndfile-1.dll from its own folder, and the depot had OpenAL Soft 1.18.1 and + # libsndfile 1.0.28 (2017) there. OpenAL Soft 1.18 lacks ALC_SOFT_reopen_device and ALC_SOFT_system_events, so on + # Windows the sound didn't follow a change of the output device; libsndfile 1.0.28 reads no Opus and no MP3, which + # the Linux build (libsndfile 1.2) does. The official release binaries of both are taken, pinned by SHA-256. They + # need nothing beyond the system DLLs and msvcrt.dll (soft_oal.dll) or KERNEL32.dll (sndfile.dll). soft_oal.dll + # has no AVX code; sndfile.dll (its static opus and mpg123) picks its AVX/AVX2 paths at run time, so the same files + # go with both variants. The exe links them by name: soft_oal.dll is shipped as OpenAL32.dll (as its readme says, + # without the router), sndfile.dll as libsndfile-1.dll. Both are LGPL, so their license texts go with them, in + # licenses/, with those of what the DLLs have built in (below); the libsndfile zip has none, its COPYING is taken + # from the source tree of the same tag. + - name: Add the OpenAL Soft and libsndfile DLLs + shell: pwsh + timeout-minutes: 10 + run: | + $ErrorActionPreference = 'Stop' + $ProgressPreference = 'SilentlyContinue' + $output = "build/bin/$env:CONFIG_WIN" + $licenses = Join-Path $output 'licenses' + $work = Join-Path $env:RUNNER_TEMP 'audio-dlls' + $downloads = Join-Path $env:RUNNER_TEMP 'audio-dlls-downloads' + New-Item -ItemType Directory -Force -Path $work, $licenses, $downloads | Out-Null + $pinned = [System.Collections.Generic.List[string]]::new() + + # the file of the URL with the given SHA-256: the one kept by a run before, else downloaded. named by its + # SHA-256 and the last part of its path, without the query: several license texts are named the same + function Get-Pinned([string] $Url, [string] $Sha256) { + $name = "$Sha256-$([uri]::new($Url).Segments[-1])" + $pinned.Add($name) + $file = Join-Path $downloads $name + if ((Test-Path -Path $file) -and (Get-FileHash -Algorithm SHA256 -Path $file).Hash.ToLowerInvariant() -eq $Sha256) { + Write-Host "$Url kept by a run before" + return $file + } + # not a browser's user agent, which Debian's server answers with a challenge page + Invoke-WebRequest -Uri $Url -OutFile $file -UserAgent 'ci-download' -MaximumRetryCount 3 -RetryIntervalSec 10 -TimeoutSec 120 + $hash = (Get-FileHash -Algorithm SHA256 -Path $file).Hash.ToLowerInvariant() + if ($hash -ne $Sha256) { + Remove-Item -Path $file -Force + throw "${Url}: SHA-256 $hash, expected $Sha256" + } + return $file + } + + # each package: the zip and, for each file wanted from it, where it goes in the build + $packages = @( + @{ Url = 'https://github.com/kcat/openal-soft/releases/download/1.25.2/openal-soft-1.25.2-bin.zip' + Sha256 = '67a0c4b800bd860c93c04f38caf8cbe4875f9c84700ac430efc451f70e265434' + Files = [ordered]@{ + 'openal-soft-1.25.2-bin/bin/Win64/soft_oal.dll' = 'OpenAL32.dll' + 'openal-soft-1.25.2-bin/COPYING' = 'licenses/openal-soft-COPYING.txt' } }, + @{ Url = 'https://github.com/libsndfile/libsndfile/releases/download/1.2.2/libsndfile-1.2.2-win64.zip' + Sha256 = '2173935c0c1ed13cf627951d34483f9d405ead2eb473190461c42ba220643a3f' + Files = [ordered]@{ + 'libsndfile-1.2.2-win64/bin/sndfile.dll' = 'libsndfile-1.dll' } } + ) + foreach ($package in $packages) { + $zip = Get-Pinned $package.Url $package.Sha256 + $unpacked = Join-Path $work ([IO.Path]::GetFileNameWithoutExtension($zip)) + Expand-Archive -Path $zip -DestinationPath $unpacked -Force + foreach ($entry in $package.Files.GetEnumerator()) { + Copy-Item -Path (Join-Path $unpacked $entry.Key) -Destination (Join-Path $output $entry.Value) -Force + Write-Host "$($entry.Value) <- $($package.Url) $($entry.Key)" + } + } + + # the license texts, each from the source tree of the version built in: of libsndfile, its ALAC and GSM 06.10 + # code, and the libraries its vcpkg build linked into sndfile.dll; of OpenAL Soft's PFFFT, Microsoft GSL and + # its BSD 3-Clause parts, and of the MinGW-w64 runtime and winpthreads, linked into soft_oal.dll (a MinGW GCC + # 15 build: the texts are the same in mingw-w64 12 and 13). + # The versions in sndfile.dll: those it names (libopus 1.4, libFLAC 1.4.2, libVorbis 1.3.7), mpg123 1.31.3 by + # the SHA-512 of its source archive in the build paths it keeps, and libogg 1.3.5 and LAME 3.100 of the vcpkg + # ports of the time (mid 2023). LAME's from Debian's copy of the 3.100 source, the same file as in LAME's own + # repository on SourceForge, which may answer a script with a challenge page + $texts = [ordered]@{ + 'libsndfile-COPYING.txt' = @('https://raw.githubusercontent.com/libsndfile/libsndfile/1.2.2/COPYING' + 'ad01ea5cd2755f6048383c8d54c88459cd6fcb17757c5c8892f8c5ea060f6140') + 'libsndfile-ALAC-LICENSE.txt' = @('https://raw.githubusercontent.com/libsndfile/libsndfile/1.2.2/src/ALAC/LICENSE' + '232efbd83786e157286b0b96c68ebb673541b69b33036287bf1e5ec5067a49d9') + 'libsndfile-GSM610-COPYRIGHT.txt' = @('https://raw.githubusercontent.com/libsndfile/libsndfile/1.2.2/src/GSM610/COPYRIGHT' + '1bbe7119b1bcd1489e0f36cb95b8902f7f0ceec9a2f3a67394bc9f4709a4e0a7') + 'libogg-COPYING.txt' = @('https://raw.githubusercontent.com/xiph/ogg/v1.3.5/COPYING' + 'd2ab5758336489da61c12cc5bb757da5339c4ae9001f9bb0562b4370249af814') + 'libvorbis-COPYING.txt' = @('https://raw.githubusercontent.com/xiph/vorbis/v1.3.7/COPYING' + 'ec1815db59fcd302846df949d7424876cb2e2dc5ed1606c5fb0b36787b1cf43a') + 'flac-COPYING.Xiph.txt' = @('https://raw.githubusercontent.com/xiph/flac/1.4.2/COPYING.Xiph' + '6e58d3036f05e2a0d58af854c12a505ddbe75011d71a598a2170987f3b15408d') + 'opus-COPYING.txt' = @('https://raw.githubusercontent.com/xiph/opus/v1.4/COPYING' + '8338ce8d922bb4416ce3dd1e5680173332435e3f0755007ac7801ccd674fe682') + 'mpg123-COPYING.txt' = @('https://scm.orgis.org/view/mpg123/tags/1.31.3/COPYING?view=co' + 'c22482728a634a8dfdb4ff72a96d4c1ed64cd8f3e79335c401751ac591609366') + 'lame-COPYING.txt' = @('https://sources.debian.org/data/main/l/lame/3.100-6/COPYING' + 'bfe4a52dc4645385f356a8e83cc54216a293e3b6f1cb4f79f5fc0277abf937fd') + 'openal-soft-pffft-LICENSE.txt' = @('https://raw.githubusercontent.com/kcat/openal-soft/1.25.2/LICENSE-pffft' + '64056328b3e7bc104e24ef96accc1a7abead156f0c02d1b87c97e3f3a28030de') + 'openal-soft-gsl-LICENSE.txt' = @('https://raw.githubusercontent.com/kcat/openal-soft/1.25.2/gsl/LICENSE' + '4c21dc82a1c7186ea754fd59d504c00947953a3401fe8e24eaa44109ef8e2555') + 'openal-soft-BSD-3Clause.txt' = @('https://raw.githubusercontent.com/kcat/openal-soft/1.25.2/BSD-3Clause' + 'b5a08cf98996dd83aa906a72c163600f6cb17a65ce546a553815a1267abd43ff') + 'openal-soft-winpthreads-COPYING.txt' = @('https://raw.githubusercontent.com/mingw-w64/mingw-w64/v13.0.0/mingw-w64-libraries/winpthreads/COPYING' + '63263614cdd29f2f93cba85e992f041b31f9fc7b4033692f31269489a8a1b177') + 'openal-soft-mingw-w64-runtime.txt' = @('https://raw.githubusercontent.com/mingw-w64/mingw-w64/v13.0.0/COPYING.MinGW-w64-runtime/COPYING.MinGW-w64-runtime.txt' + 'e9b2dc02451ea29092a1f25fa0f3c07207ed421f1807dffb0c4e6dce69dee7bd') + } + foreach ($text in $texts.GetEnumerator()) { + $file = Get-Pinned $text.Value[0] $text.Value[1] + Copy-Item -Path $file -Destination (Join-Path $licenses $text.Key) -Force + } + + # OpenAL Soft's bs2b has its license only in its source files: the notice as core/bs2b.cpp of 1.25.2 has it + @' + Copyright (c) 2005 Boris Mikhaylov + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + '@ | Set-Content -Path (Join-Path $licenses 'openal-soft-bs2b-LICENSE.txt') -Encoding utf8 + + # what the DLLs are and have built in, where their source is (the LGPL ones); the DLLs can be replaced by the user + @( + 'OpenAL32.dll: OpenAL Soft 1.25.2, unmodified soft_oal.dll of the official binaries, GNU LGPL 2 or later' + ' (openal-soft-COPYING.txt). Source: https://github.com/kcat/openal-soft/releases/tag/1.25.2' + ' Built in: a modified PFFFT, BSD-style (openal-soft-pffft-LICENSE.txt); Microsoft GSL, MIT' + ' (openal-soft-gsl-LICENSE.txt); the ambisonic rotator, the vocal morpher and the compressor, BSD 3-Clause' + ' (openal-soft-BSD-3Clause.txt); bs2b, MIT (openal-soft-bs2b-LICENSE.txt); {fmt} 11.2.0, MIT, whose' + ' exception for the object form asks for no text. Linked into it by its MinGW-w64 build: the MinGW-w64' + ' runtime (openal-soft-mingw-w64-runtime.txt) and winpthreads, MIT and BSD-style' + ' (openal-soft-winpthreads-COPYING.txt);' + ' libstdc++ and libgcc under the GCC Runtime Library Exception, which asks for no text.' + ' Its default HRTF data set is based on the KEMAR HRTF measurements by Bill Gardner and Keith Martin,' + ' MIT Media Laboratory, 1994: http://sound.media.mit.edu/resources/KEMAR.html' + 'libsndfile-1.dll: libsndfile 1.2.2, unmodified sndfile.dll of the official binaries, GNU LGPL 2.1 or later' + ' (libsndfile-COPYING.txt). Source: https://github.com/libsndfile/libsndfile/releases/tag/1.2.2' + ' Its ALAC code: Apache License 2.0 (libsndfile-ALAC-LICENSE.txt). Its GSM 06.10 code: Jutta Degener and' + ' Carsten Bormann, TU Berlin (libsndfile-GSM610-COPYRIGHT.txt). Its G.721/G.723 code: Sun Microsystems, public' + ' domain.' + ' Linked into it by its build, made with the vcpkg ports of the time and their patches' + ' (https://github.com/microsoft/vcpkg/tree/2023.08.09/ports, the ports named below):' + ' libogg 1.3.5, BSD (libogg-COPYING.txt), port libogg. Source: https://github.com/xiph/ogg/releases/tag/v1.3.5' + ' libvorbis 1.3.7, BSD (libvorbis-COPYING.txt), port libvorbis. Source: https://github.com/xiph/vorbis/releases/tag/v1.3.7' + ' libFLAC 1.4.2, BSD (flac-COPYING.Xiph.txt), port libflac. Source: https://github.com/xiph/flac/releases/tag/1.4.2' + ' libopus 1.4, BSD (opus-COPYING.txt), port opus. Source: https://github.com/xiph/opus/releases/tag/v1.4' + ' mpg123 1.31.3, GNU LGPL 2.1 (mpg123-COPYING.txt), port mpg123. Source: https://www.mpg123.de/download/mpg123-1.31.3.tar.bz2' + ' LAME 3.100, GNU LGPL 2 or later (lame-COPYING.txt), port mp3lame. Source: https://sourceforge.net/projects/lame/files/lame/3.100/' + ) | Set-Content -Path (Join-Path $licenses 'audio-libraries.txt') -Encoding utf8 + + # the files no pin names any more aren't kept for the next run + Get-ChildItem -Path $downloads -File | Where-Object { $pinned -notcontains $_.Name } | Remove-Item -Force + - name: Upload Windows build uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: From d6c35935209a7e5b67c5a5030f660704ee91ca6f Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:38:14 +0100 Subject: [PATCH 076/136] fix(physicslog): no road-vehicle logs, formatting on the writer, a slow disk and the closing kept short (#408) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Enhance Windows build matrix with AVX2 variants * fix(lang): the two Polish lines of the download area written with \n, so they match the tooltip and the hint * fix(files): data named in another case is found on Linux, folders included The parser and the loaders lowercase every name they read, while the data made on Windows has files and folders named in any case (scenery/Braniewo, textures/siec_trakcyjna_ph/.../STS_*.tga, sounds/sip/Gorki.wav). FileCased matched the file name only, so a folder in another case wasn't found. - FileCased walks every part of the path on Linux, the folder listings kept by their lowercase and read again once the folder changed; Windows as it was - FileExists finds the file in any case on Linux, and the variant with names and extensions gives back the name as it's on the disk, so textures, materials, sounds, station announcements and scripts open that name - models, sound captions, timetables and nodebank previews open the file as it's named on the disk; the texture format is told by the extension in any case * fix(files): the banks keep the names asked for, only the opening takes the case of the disk The textures, materials and sounds are kept by the names they're asked for. Given back as named on the disk, a file in another case missed the bank and was loaded again on every request. - FileExists with names and extensions finds the file in any case but gives back the name asked for; FileOnDisk gives the file to open, used where textures, sounds and scripts are opened - FileExists of a single name is a plain check again, the places checking it and opening the same name stay as they were - the texture format is told by the extension asked for again - a folder changed shortly before it was read is read again for a name missing from it, the time of a change being as coarse as the clock of the file system; a listing cut short isn't kept * fix(files): a folder changed in the future isn't read again on every name missing from it * perf(files): a file missing costs a single check, as before Measured in a case sensitive folder (3000 textures, every 20th in mixed case, looked up the way Texture.cpp does), the walk over every part of the path made a texture lookup 4-5 times slower than master: each name tried and missing checked every folder of its path. - the folders found are kept by the name they're given with, the missing ones for a second, so a missing file checks its folder alone - a folder named as it is on the disk is taken without its listing - the time a folder was changed is looked at once a second at most The lookup is now as fast as master's (about 180 us per texture on NTFS in both) while finding the files named in another case too. * fix(files): terrain files named in another case are found on Linux The terrain directive names .txtf/.btf files in lowercase, as the parser gives every token. The name is now taken as it is on disk, from the text file first, so the binary file is made next to the text and the editor's references and layers keep one name. * fix(files): models named in another case are found on Linux The manager of the models looked for the file with FileExists of a single name, a plain check again since the banks keep the names asked for, so a model named in another case (models/przejazdy/plyty3_L, dynamic/pkp/st44_v2/main/2M62-0685-A) was reported missing before TModel3d::LoadFromFile() could open it as it's named on the disk. find_on_disk() finds the file in any case and gives back the name asked for, the key of the bank. * refactor(files): named functions instead of the lambdas of the folder cache (Sonar S2259, S3608, S6004) Sonar took the folder captured by the lambda reading it for a reference to null, failing the quality gate on reliability. The folder is read and the path kept by functions in the anonymous namespace, the age of the listing declared in its if. * fix: the simulator opens more than 512 files at once, and a shader it can't open says why With "physicslog yes" every driver keeps its .dat open, and a large scenery (Tomaszewo: some 500 vehicles, cars of the roads included) took all 512 streams the MSVC runtime gives: the next fopen failed and the simulator stopped at "cannot read shader: shaders/map.vert" on opening the map. The limit is raised to 8192 at the start (the soft limit of open files up to the hard one on Linux), and a shader file that doesn't open is told as such, with the system's reason, rather than as one that can't be read. * feat(blackbox): the black box on its own, writing the tapes of the user's vehicles at the end "blackbox yes" in eu07.ini records the black box with the physics logs on or off, "blackbox no" never; with no entry it goes with "physicslog yes" as before. With the physics logs off, the recorder keeps the line of the physics log of the driver the user is with, every 0.05 s, and writes it to physicslog/.dat when the recording closes: the speed recorder's tape of the vehicles the user was in, without every vehicle keeping a log open and written twenty times a second. The line and the header of the log are made by one function of the driver, which its own log writes too, and the file is opened the same way, so the two are the same to the byte: the readers of these logs (the old Hasler tape viewer, the starter) read them as before. * feat(physicslog): the logs written every two seconds by a thread of their own, no file kept open; the black box's tapes as it goes "physicslog yes" kept the .dat of every vehicle with a driver open for the whole run and flushed it twenty times a second from the simulation's thread: some 580 open files on Tomaszewo. The lines are kept now and a thread of their own writes them every two seconds, each file opened only for the moment it is written to. The files, their lines and their text mode stay as they were. - The black box, with the physics logs off, writes the tapes of the user's vehicles through the same writer as it goes, not at the end. A log begins when the user is first in the vehicle and goes on while the user looks around outside, until another vehicle is taken; back in it, the log goes on after the gap. The vehicle's own driver keeps the log only if it is the primary one, as a passive one's clock stands still; otherwise the driver of its train does. - What is kept is written when the simulator closes, after the black box, at the end of a test run, and when the test watchdog ends a run. A crash loses the last two seconds. - On Tomaszewo with the black box alone, the one tape grows every two seconds. With "physicslog yes", the 581 logs grow and the simulator holds as many handles as without them; writing them takes the thread about 1.9 s, which the closing waits for once. * feat(blackbox): the cab record holds the speed of the wheels, apart from the vehicle's when they slip The speed of the cab record is the vehicle's. The speedometer, and a speed recorder's tape with it, shows the speed of the wheels as they turn, which runs away from it while they slip and drops to 0 while they are locked in a skid. It is added at the end of the record (194 bytes), where the readers skip what they don't know; the .dat tapes have it already, in their second column. * fix(ci): build OpenAL Soft with the PipeWire, PulseAudio and ALSA backends, so the Linux game has sound The Linux job builds OpenAL Soft 1.24.2 from source, but the runner had none of the headers of its audio backends, and OpenAL Soft's CMake leaves out every backend it can't find. The bundled libopenal.so.1 had only OSS, Null, Wave and Loopback. Modern distributions and the Steam Linux Runtime have no /dev/dsp, so the game logged "Failed to obtain audio device" and played nothing, with any Steam Linux Runtime and without one. - install libasound2-dev, libpulse-dev and libpipewire-0.3-dev before building OpenAL Soft - configure it with ALSOFT_REQUIRE_PIPEWIRE/PULSEAUDIO/ALSA, so a missing header fails the build instead of shipping a library without sound The backends are loaded with dlopen at run time (ALSOFT_DLOPEN is on by default), so the bundled library gains no new dependency. Tested by putting an OpenAL Soft 1.24.2 with these backends next to the game from the Steam depot: under Steam Linux Runtime 4.0 the sound works. Co-Authored-By: Claude Opus 5.5 * fix(editor): the certificates of https looked for where the distribution keeps them The Linux game bundles the libcurl of Ubuntu, which knows only Ubuntu's /etc/ssl/certs/ca-certificates.crt. Fedora, RHEL and openSUSE keep the certificates elsewhere, so every download of the editor (orthophoto, terrain model, topo map) failed there with a certificate error. The file is taken from SSL_CERT_FILE or CURL_CA_BUNDLE when set, else the first of the files the distributions keep, and passed as CURLOPT_CAINFO. With none found libcurl keeps its own. * fix(editor): an https proxy checked with the same certificates CURLOPT_PROXY_CAINFO gets the file found for CURLOPT_CAINFO, so a download through an https:// proxy on Fedora or RHEL doesn't fail on the proxy's certificate. * fix(ci): the no-AVX2 Windows build has its own concurrency group and its own public download After master was merged the two Windows variants shared one concurrency group with cancel-in-progress, so one cancelled the other, and the publish job looked for an artifact name the matrix no longer produces. Each variant now has its own group, the publish job downloads both, and the release carries maszyna-windows-x64.zip (AVX2, the old name, so the links already handed out still work) and maszyna-windows-x64-noavx2.zip. The AVX2 variant passes -DENABLE_AVX2=ON explicitly instead of an empty flag. * build: a build without AVX2 has _noavx2 at the end of its executable name With ENABLE_AVX2=OFF the executable is eu07-x64___noavx2.exe (eu07-x64_noavx2.exe without ADD_VERSION_SUFFIX), so a starter can tell the two builds apart by the name alone and pick this one on a CPU without AVX2. The AVX2 build keeps its name. * ci: Linux is built without AVX2 too, published as maszyna-linux-x64-noavx2.tar.gz The Linux job becomes the same two-variant matrix as Windows (ENABLE_AVX2=ON/OFF), each variant with a concurrency group of its own. The publish job downloads both Linux artifacts, restores the executable bits in both and releases maszyna-linux-x64.tar.gz (AVX2, the old name) next to maszyna-linux-x64-noavx2.tar.gz. The no-AVX2 executable is eu07___noavx2. * fix(renderer): the legacy renderer clears the arrays the scene left before it draws the ui The legacy renderer drew the ui with the client arrays of the last scene draw still enabled: the texture coordinates of the normal map unit and the normals, pointing into the vertex buffer of whatever was drawn last, 48 bytes a vertex. The ImGui backend sets up the vertex, colour and texture coordinates of the active unit only, so the driver read the stale arrays with the indices of the ui. Once the ui had more vertices than that buffer, the NVIDIA driver read past its end and the game crashed; a crash dump of the editor (an area selected, a track being laid) shows the read of vertex 15113 at a 48-byte stride in ImGui_ImplOpenGL2_RenderDrawData. The arrays are now disabled on every texture unit the geometry uses, with the normal and colour arrays, inside the glPushClientAttrib already there, so the scene gets its state back after the ui. The default and the experimental renderers don't go through this code. * fix(app): a renderer this build doesn't have starts the full one, not the legacy one The starter writes "gfxrenderer vulkan" for the Vulkan renderer of the builds that have it. This exe doesn't know the word, and every word other than default/experimental fell to the legacy renderer: a player who picked Vulkan got the slowest renderer, the one whose ui crashes on NVIDIA (the arrays left by the scene). "experimental" in a build without the NVRHI renderer ended with "no renderer found!" and no game at all. After the settings are read, a gfxrenderer word this build has no renderer for becomes "default", with a line in the log saying so. The words it knows stay as they were: full/default, legacy, simple, null, the older starters' simpleshader and off (legacy as before), and experimental where it is built. * fix(settings): the gfxrenderer word read in any case, as the starter reads it A hand-written "gfxrenderer Legacy" started the legacy renderer only because every unknown word did; with unknown words going to the full renderer it would have changed. The word is lowercased when read, as StarterNG's RenderEngineOf does, so Legacy, Simple or Full mean what they say. * fix(physicslog): a log whose file can't be written keeps its lines and header, and the writer is stopped once on every way out A failed write put its lines back, ahead of those since, so a file held by another program for a while gets its header and every line once it can be written; up to 4 MB kept per log. Stopping is joined once, and not from the writer's own thread. main stops the logs after an error it caught too, and the test watchdog flushes with a time limit, so a disk that doesn't answer doesn't keep the run from ending. * fix(blackbox): the wheels of the powered vehicle, as the speedometer has them, and the logs described as the drivers' they are In a unit driven from an unpowered car, the speed of the wheels was of the car the user is in, whose wheels never slip; now of the motor car, signed as the occupied vehicle's speed. The doc tells of a log per driver, and of the two seconds of real time a crash loses. * fix(physicslog): failed logs kept within 64 MB in all, cut outside the lock, never written twice; the writer knows itself when stopped The lines kept while files can't be written are cut to their share of 64 MB before the lock the simulation waits on. A log written in part is cut back to its length, so the next try doesn't write its start twice. A stop from the writer itself is told by its id even after another thread took it to join, and the watchdog's flush waits at most its time, the writing on a thread of its own. * feat(physicslog): the logs of the trains only, physicslog.trains "physicslog.trains yes" in eu07.ini writes the .dat log of each driver who drives rail vehicles, not of the passengers nor of the road vehicles that make "physicslog yes" hundreds of files on a big scenery: the tape of every train. A driver made primary later begins its log then, and isn't counted while it doesn't log. The black box goes with it when the ini says nothing of its own, and doesn't write a second log of a driver writing its own. The doc tells the doors' sides are the vehicle's, the driver's swapped in the rear cab. * fix(physicslog): a train's log begun at its first line, so passive crews get no file Every crew is primary in the constructor and the drivers but one of a train with crews in more vehicles are made passive only before it starts, so a log begun there left files with only the header. With physicslog on all logs begin at once as before; one of a train waits for update_logs. * fix(editor): the texture pickers let go of the images scrolled past, the memory no longer runs out The picker of the textures of a track offers every texture of the textures folder, and each tile that came into sight read its texture full size, into the graphics card and the memory, and kept it there for good. Scrolling through the list for a trackbed texture took about 2.5 MB a tile: some 900 tiles made 3.5 GB, the whole folder 28 GB, and the game went down once the memory ran out. An image out of sight for 3 seconds is now taken out of both again (texture_manager::unload, Unload_Texture of the renderers) and read anew when it's shown once more, a few a frame as before. Only a texture the scene has never drawn is let go; those of the scene stay to the resource sweep. The texture browser lets go of its images on Refresh too. The picker no longer lists textures/previews: the 4100 previews of the node bank are images of models, not textures of anything. Checked on td.scn by a scripted run: 8000 images of the picker read one batch a few frames after another held the game at 2-3 GB, where it went to 28 GB and fell before; images shown again after they were let go come back; a trackbed texture picked from the folder is drawn on the track after its image was let go. * fix(physicslog): the writer's destructor throws nothing, its wait a plain condition variable woken to stop; a driver of no vehicle controls nothing * fix(editor): the images of the materials let go of with all their textures, the browser's Refresh a frame later An image of a material read the material with all its textures, the normal and specular maps and the variants, and only the first one was let go of: those stayed in the memory for every material scrolled past. They are let go of together now (Unload_Material). texture_manager::unload also takes the textures read and not made yet, waiting for a worker still reading one, and deletes the gl texture itself: release() would read it back from the card with gfx.resource.move only for it to be dropped. The Refresh of the texture browser let go of the images in the middle of the frame, while panels drawn before it could still refer to them; it now marks them, and they go at the start of the next frame. Checked on td.scn by a scripted run: 8040 images of the picker read a batch every few frames end at 2.0 GB, against 2.3-2.6 GB before this and 1.1 GB at the start; a trackbed material picked from the folder is drawn on the track after its image was let go. * fix(physicslog): every stop asked wakes the writer, the one from itself too; no psyche for a driver of no vehicle * fix(editor): the image of a material with no texture in its first slot is let go of too Its normal and specular maps were read with it and stayed in the memory: the trim passed over every image with no texture of its own, the material along with it. * fix(physicslog): nothing that goes wrong in the writing ends the simulator; a name in 1250 makes a path on a Windows set to UTF-8 The writer's thread called flush() with nothing around it, so an exception leaving write() ended the process with std::terminate, with no message. One that happens: the file of a log was made a std::filesystem::path of the vehicle's name, which MSVC converts in the code page of the system and throws for bytes not of it; on a Windows with "Use Unicode UTF-8 for worldwide language support" a vehicle named in 1250, as the sceneries have them (0xB3 for ł), isn't UTF-8. - the file of a log is made of the name with MultiByteToWideChar without MB_ERR_INVALID_CHARS: the same file as before for every name of the code page, U+FFFD for the bytes not of it instead of a throw. Elsewhere the bytes are the name of the file as they were - a log whose writing throws for any other reason (memory) is kept for the next try as one whose file can't be written, and the other logs are written still - the thread, flush_for() and stop() write through flush_safely(), which lets nothing out: what was taken for a writing failing as a whole is lost and told in the log, the next writing goes on - the messages name the file by the bytes of the name, not by path::string(), which converts back Tests: a log which can't be written doesn't keep the others from theirs; a vehicle named in 1250 has its log, read back by physicslog_writer::file(). Reported in the review of #385. Co-Authored-By: Claude Opus 5.5 * fix(blackbox): the tapes go on after the editor, with the physics logs off The tapes of the user's vehicles were written by update() after the check for the writer of the recording, which close() drops on entering the editor (F11). With "physicslog no", the speed recorder's tape ended at F11 while the drivers' own logs of "physicslog yes" went on. The tapes are files of their own: they are kept from the moment the recording was to be made, the file made or not, closed or not, until the simulator closes, after the gap of the time in the editor. Only the recording itself stops at F11, as before. Reported in the review of #385. Co-Authored-By: Claude Opus 5.5 * fix(physicslog): what no file name may have on Windows is replaced in the name of a log, on every system A spawned vehicle is named :, and its log went to physicslog/:.dat. On NTFS that isn't even an error: it is the stream .dat of the file , which nothing lists, so the log was written and no one could find it. On Linux the file was there, under a name Windows can't open. The name of the file of a log has < > : " / \ | ? * and the control characters replaced by _, on every system, so the logs are named alike everywhere (spawn_ezt:12 is spawn_ezt_12.dat), and a _ before a name Windows keeps for a device (con, nul, com1..., with an extension too). The bytes of 1250 stay. The black box tells the log it begins by the same name. Co-Authored-By: Claude Opus 5.5 * refactor(renderer): a material's textures let go of in one place, for every backend Unload_Material walked the textures of a material and of its variants the same way in both opengl renderers, and Sonar counted its declarations, set into the long run of overrides the two headers share, as duplicated: 5.2% of the new code, 3% allowed. The walk is gfx_renderer's now, over IMaterial::GetAllTextures and the backend's Unload_Texture. Materials that don't tell their textures, the Vulkan renderer's, give none, and are left alone as before. Co-Authored-By: Claude Opus 5.5 * fix(physicslog): road vehicles keep no log, the lines are made into text by the writer, and a slow disk gets them less often On a big scenery "physicslog yes" wrote a log for every driver, the hundreds of cars of the roads too: Tomaszewo gives over a thousand. A player with an i7-3770 and a hard disk had 1 fps there and 90 fps paused; with the physics log off the frame rate came back. The disk was busy with the logs all the time, and the simulation formatted 26 values a line, twenty lines a second, for each of them. - "physicslog yes" writes the logs of all drivers but those of road vehicles. Nobody reads those, and the starter's tapes are of rail vehicles. The black box writes the tape of a car the user drives, as it does with the physics logs off. On Tomaszewo a 120 s test run gives 20 logs instead of 579. - The simulation hands the writer the values of a line; the writer's thread makes them into text, with the same stream as before. The logs of a fixed-seed run of Tomaszewo come out byte for byte the same as before. - The writer's thread does its disk work at background priority (Windows THREAD_MODE_BACKGROUND_BEGIN, Linux the lowest best-effort I/O priority), so the simulation's own reading doesn't wait behind the logs. - A writing that takes over a third of the 2 s interval makes the next wait three times as long as it took: the disk is busy with the logs a quarter of the time at most. The log of the simulator says so once. - A log is written with one write, the header of a log begun with its lines, and a log added to is opened at its end rather than asked for its length first. What changes for the data: with "physicslog yes" no .dat files of road vehicles appear in physicslog/. Nothing in the SVN needs to change; the comment of physicslog in the shipped eu07.ini ("for all vehicles manned by AI or a human") is now a little wide of it. * fix(physicslog): the wait after a slow writing is ten seconds at most, a log whose lines can't be made into text is kept - The wait after a slow writing grew with what it left to the next one, with no end once the formatting and the bytes took a quarter of the time: it is five intervals at most now, so a crash loses ten seconds at most. - The lines given as values are made into text within the try of each log, aside and added at once: out of memory there keeps that log for the next try and the others are written, as the comment said. - The Windows background mode is described as it is: very low I/O priority, the memory pages let go of first. - The black box doc says a car the user drives has no log with the black box off. * fix(physicslog): the closing waits for the logs a second at most, the rest is dropped stop() gives the writing one second (a constructor parameter, ClosingWait). The writer thread's batch under way and the final writing check the time before each log and drop the logs past it, telling how many in the log. The final writing runs on a thread of its own, left behind when it isn't done in time, so a disk that doesn't answer in the middle of a file doesn't hold the closing either; the simulator ends with _Exit, and a writer object that goes waits for those writings in its destructor. At the closing the writer thread's disk priority is put back to normal, so that second goes to the logs. A flush() after the stop is not cut short. * fix(physicslog): a second stop keeps the time of a closing under way, and a stop lets out no exception The simulator stops the logs twice on a normal exit (Application.exit() and main). A stop while an earlier closing is still writing now keeps that closing's time instead of giving it another second, and doesn't tell it again. The thread of the closing is begun in a noexcept helper: with no memory or no thread to be had the rest is written on the calling thread, the logs past the time dropped still, so stop() doesn't throw on the way out of an out-of-memory error. * fix(physicslog): a closing whose thread is begun isn't written again by the stop when its log line fails std::format of the timeout line can throw (out of memory) after the closing's thread was started; close_aside returned false then, and stop() wrote on the calling thread too, waiting on the files the closing holds with no time limit. A thread begun counts now. * fix(physicslog): a failed log keeps its values in order, and the user's log goes first at the closing A log whose file couldn't be written kept the values the writing failed to make into text (out of memory) only until the next line came: keeping it put the values given since in their place. They're made into text again now, and the values given since go after them, added at once. Values which still can't be made into text are dropped when text was given after them, as the order can't be kept otherwise. What a writing needs before it takes the lines (the names put first, the order) is had before it takes them, so without the memory for it the lines are left for the next writing. The closing, which waits a second for the writing, dropped the logs past it by the order of their names: the user's train could lose its last seconds while a log nobody reads was written. Now: - the logs put first (put_first) are written before the others at each writing: the one of the driver the black box follows, of the vehicle the user is in (the black box goes with the physics logs unless "blackbox no"), and those of the drivers of the tested trains (test.vehicle); - a stop ends a writing of the thread under way at the log at hand, and the thread begins none after it. The logs it hasn't come to are left to the closing's writing, which has them with the lines given since, those put first first. Before, the thread went on through them and the closing's writing, coming after, had no time left for the newest lines. They go back as they were taken: their values are made into text by the closing's writing, not on the way to it unless text was given since, and they don't count toward the 64 MB kept of the logs whose file can't be written. The closing drops the logs past its time as before, the user's too: none is begun once the time is over, only the one at hand may still be written while the process ends. The thread no longer raises its disk priority at a closing, as it no longer writes there. --------- Co-authored-by: maj00r Co-authored-by: Claude Opus 5.5 Co-authored-by: Hirek193 --- .github/workflows/build_bin.yml | 98 ++++- CMakeLists.txt | 6 + EU07.cpp | 30 ++ application/application.cpp | 19 + application/editormode.cpp | 1 + application/editormode.h | 12 +- application/editormodetextures.cpp | 47 ++- application/editormodetrackprops.cpp | 6 +- audio/audio.cpp | 7 +- blackbox_doc.md | 47 ++- editor/editorHttp.cpp | 42 ++ editor/editorPreviews.cpp | 4 +- gl/shader.cpp | 8 + global_include/interfaces/IMaterial.h | 6 + lang/editor_pl.po | 12 +- model/MdlMngr.cpp | 10 +- model/Model3d.cpp | 17 +- model/Texture.cpp | 58 ++- model/Texture.h | 4 + model/material.h | 7 + rendering/opengl33renderer.cpp | 5 + rendering/opengl33renderer.h | 2 + rendering/openglrenderer.cpp | 15 + rendering/openglrenderer.h | 2 + rendering/renderer.cpp | 15 + rendering/renderer.h | 6 + scripting/PyInt.cpp | 2 +- simulation/blackboxrecorder.cpp | 48 ++- simulation/blackboxrecorder.h | 15 +- simulation/simulationstateserializer.cpp | 2 + simulation/simulationtest.cpp | 19 +- tests/unit/test_blackbox.cpp | 3 + tests/unit/test_physicslog.cpp | 385 ++++++++++++++++++ tests/unit/test_utilities.cpp | 50 +++ utilities/Globals.cpp | 18 +- utilities/Globals.h | 4 +- utilities/physicslog.cpp | 491 +++++++++++++++++++++++ utilities/physicslog.h | 189 +++++++++ utilities/utilities.cpp | 194 ++++++++- utilities/utilities.h | 11 +- vehicle/Driver.cpp | 170 ++++---- vehicle/Driver.h | 26 +- vehicle/blackbox.cpp | 1 + vehicle/blackbox.h | 5 +- world/mtable.cpp | 9 + 45 files changed, 1964 insertions(+), 164 deletions(-) create mode 100644 tests/unit/test_physicslog.cpp create mode 100644 utilities/physicslog.cpp create mode 100644 utilities/physicslog.h diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index ad2d471ec..12c5c5866 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -32,13 +32,27 @@ jobs: # running is left to finish; with a build cancelled the publish job of that run is skipped. A push # to master gets a group of its own, its commit, so the builds of master are never cancelled. + # Windows is built twice: with AVX2 (the default of ENABLE_AVX2) and without it, for CPUs older + # than Haswell (2013). Each variant has its own concurrency group, or one would cancel the other. + windows: - name: Windows x64 / MSVC + name: Windows x64 / MSVC / ${{ matrix.variant.name }} runs-on: windows-2022 concurrency: - group: ${{ github.workflow }}-windows-${{ github.event_name }}-${{ github.ref == 'refs/heads/master' && github.sha || github.ref }} + group: ${{ github.workflow }}-windows-${{ matrix.variant.suffix }}-${{ github.event_name }}-${{ github.ref == 'refs/heads/master' && github.sha || github.ref }} cancel-in-progress: true + strategy: + fail-fast: false + matrix: + variant: + - name: "AVX2" + suffix: "avx2" + cmake_flags: "-DENABLE_AVX2=ON" + - name: "No AVX2" + suffix: "noavx2" + cmake_flags: "-DENABLE_AVX2=OFF" + steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 @@ -112,11 +126,13 @@ jobs: $pythonRoot = Split-Path $pythonExe Write-Host "Python root: $pythonRoot" + Write-Host "Extra CMake flags: ${{ matrix.variant.cmake_flags }}" cmake -S . -B build ` -G "Visual Studio 17 2022" ` -A x64 ` - "-DPython3_ROOT_DIR=$pythonRoot" + "-DPython3_ROOT_DIR=$pythonRoot" ` + ${{ matrix.variant.cmake_flags }} - name: Build shell: pwsh @@ -340,7 +356,7 @@ jobs: - name: Upload Windows build uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: - name: maszyna-windows-x64-${{ env.CONFIG_WIN }} + name: maszyna-windows-x64-${{ matrix.variant.suffix }}-${{ env.CONFIG_WIN }} path: | build/bin/${{ env.CONFIG_WIN }}/ if-no-files-found: error @@ -349,7 +365,7 @@ jobs: - name: Upload Windows debug symbols uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: - name: maszyna-windows-x64-symbols-${{ env.CONFIG_WIN }} + name: maszyna-windows-x64-symbols-${{ matrix.variant.suffix }}-${{ env.CONFIG_WIN }} path: | build/pdb/${{ env.CONFIG_WIN }}/*.pdb build/bin/${{ env.CONFIG_WIN }}/*.map @@ -362,13 +378,24 @@ jobs: # ============================================================ linux: - name: Linux x64 / GCC + name: Linux x64 / GCC / ${{ matrix.variant.name }} runs-on: ubuntu-24.04 - # see the note above the windows job + # see the notes above the windows job: two variants, each with a concurrency group of its own concurrency: - group: ${{ github.workflow }}-linux-${{ github.event_name }}-${{ github.ref == 'refs/heads/master' && github.sha || github.ref }} + group: ${{ github.workflow }}-linux-${{ matrix.variant.suffix }}-${{ github.event_name }}-${{ github.ref == 'refs/heads/master' && github.sha || github.ref }} cancel-in-progress: true + strategy: + fail-fast: false + matrix: + variant: + - name: "AVX2" + suffix: "avx2" + cmake_flags: "-DENABLE_AVX2=ON" + - name: "No AVX2" + suffix: "noavx2" + cmake_flags: "-DENABLE_AVX2=OFF" + steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 @@ -394,8 +421,13 @@ jobs: | sudo tee /etc/apt/apt.conf.d/80-ci-retries > /dev/null sudo apt-get update + # libasound2-dev, libpulse-dev and libpipewire-0.3-dev: the headers of OpenAL Soft's audio backends (built below). + # Without them it builds with OSS only, which modern distributions and the Steam Linux Runtime don't have: no sound. sudo apt-get install -y \ build-essential \ + libasound2-dev \ + libpulse-dev \ + libpipewire-0.3-dev \ libgl1-mesa-dev \ libglew-dev \ libglfw3-dev \ @@ -422,12 +454,17 @@ jobs: https://github.com/kcat/openal-soft.git \ /tmp/openal-soft + # the backends are loaded with dlopen at run time (ALSOFT_DLOPEN), so the bundled library needs none of them; + # REQUIRE makes a missing header fail the build instead of shipping a library without sound cmake \ -S /tmp/openal-soft \ -B /tmp/openal-soft/build \ -DCMAKE_BUILD_TYPE=Release \ -DALSOFT_EXAMPLES=OFF \ - -DALSOFT_UTILS=OFF + -DALSOFT_UTILS=OFF \ + -DALSOFT_REQUIRE_PIPEWIRE=ON \ + -DALSOFT_REQUIRE_PULSEAUDIO=ON \ + -DALSOFT_REQUIRE_ALSA=ON cmake \ --build /tmp/openal-soft/build \ @@ -455,6 +492,7 @@ jobs: -DWITH_ZMQ=OFF \ -DWITH_OPENVR=OFF \ -DUSE_LTO=OFF \ + ${{ matrix.variant.cmake_flags }} \ -DPython3_EXECUTABLE="${{ steps.python.outputs.python-path }}" \ -DCMAKE_CXX_FLAGS="-Wno-attributes -fno-inline-functions-called-once" @@ -520,7 +558,7 @@ jobs: - name: Upload Linux build uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: - name: maszyna-linux-x64-${{ env.CONFIG_LINUX }} + name: maszyna-linux-x64-${{ matrix.variant.suffix }}-${{ env.CONFIG_LINUX }} path: | build/bin/ if-no-files-found: error @@ -543,29 +581,47 @@ jobs: cancel-in-progress: false steps: - - name: Download Windows build + # the AVX2 build keeps the old name of the download, so the links already handed out still work + - name: Download Windows build (AVX2) uses: actions/download-artifact@v4 with: - name: maszyna-windows-x64-${{ env.CONFIG_WIN }} + name: maszyna-windows-x64-avx2-${{ env.CONFIG_WIN }} path: dist/maszyna-windows-x64 - - name: Download Linux build + - name: Download Windows build (no AVX2) uses: actions/download-artifact@v4 with: - name: maszyna-linux-x64-${{ env.CONFIG_LINUX }} + name: maszyna-windows-x64-noavx2-${{ env.CONFIG_WIN }} + path: dist/maszyna-windows-x64-noavx2 + + - name: Download Linux build (AVX2) + uses: actions/download-artifact@v4 + with: + name: maszyna-linux-x64-avx2-${{ env.CONFIG_LINUX }} path: dist/maszyna-linux-x64 + - name: Download Linux build (no AVX2) + uses: actions/download-artifact@v4 + with: + name: maszyna-linux-x64-noavx2-${{ env.CONFIG_LINUX }} + path: dist/maszyna-linux-x64-noavx2 + - name: Pack run: | cd dist - find maszyna-linux-x64 -type f -exec sh -c 'file -b "$1" | grep -q "^ELF" && chmod +x "$1"' _ {} \; - if [ -d maszyna-linux-x64/linuxpython64/bin ]; then - chmod +x maszyna-linux-x64/linuxpython64/bin/* - fi + # the artifacts lose the executable bit + for dir in maszyna-linux-x64 maszyna-linux-x64-noavx2; do + find "$dir" -type f -exec sh -c 'file -b "$1" | grep -q "^ELF" && chmod +x "$1"' _ {} \; + if [ -d "$dir/linuxpython64/bin" ]; then + chmod +x "$dir"/linuxpython64/bin/* + fi + done (cd maszyna-windows-x64 && zip -qr9 ../maszyna-windows-x64.zip .) + (cd maszyna-windows-x64-noavx2 && zip -qr9 ../maszyna-windows-x64-noavx2.zip .) tar -czf maszyna-linux-x64.tar.gz -C maszyna-linux-x64 . + tar -czf maszyna-linux-x64-noavx2.tar.gz -C maszyna-linux-x64-noavx2 . ls -la - name: Publish rolling release of the branch @@ -585,14 +641,18 @@ jobs: "" \ "Download without a GitHub account:" \ "- Windows: $base/maszyna-windows-x64.zip" \ + "- Windows, CPUs without AVX2 (older than Haswell, 2013): $base/maszyna-windows-x64-noavx2.zip" \ "- Linux: $base/maszyna-linux-x64.tar.gz" \ + "- Linux, CPUs without AVX2: $base/maszyna-linux-x64-noavx2.tar.gz" \ "" \ "Unpack over a MaSzyna installation (the game data isn't included). Build log: $RUN_URL")" gh release delete "$tag" --yes --cleanup-tag || true gh release create "$tag" \ dist/maszyna-windows-x64.zip \ + dist/maszyna-windows-x64-noavx2.zip \ dist/maszyna-linux-x64.tar.gz \ + dist/maszyna-linux-x64-noavx2.tar.gz \ --target "$SHA" \ --prerelease \ --latest=false \ @@ -601,4 +661,6 @@ jobs: echo "### Public download" >> "$GITHUB_STEP_SUMMARY" echo "- Windows: $base/maszyna-windows-x64.zip" >> "$GITHUB_STEP_SUMMARY" + echo "- Windows, no AVX2: $base/maszyna-windows-x64-noavx2.zip" >> "$GITHUB_STEP_SUMMARY" echo "- Linux: $base/maszyna-linux-x64.tar.gz" >> "$GITHUB_STEP_SUMMARY" + echo "- Linux, no AVX2: $base/maszyna-linux-x64-noavx2.tar.gz" >> "$GITHUB_STEP_SUMMARY" diff --git a/CMakeLists.txt b/CMakeLists.txt index 4b98ae937..78abf46a2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -478,6 +478,11 @@ if (ADD_VERSION_SUFFIX) set (SUFFIX "_${SRC_SHORT_DATE}_${GIT_HASH}") endif() +# a build without AVX2 says so in its name, so a starter can pick it on a CPU without AVX2 +if (NOT ENABLE_AVX2) + set (SUFFIX "${SUFFIX}_noavx2") +endif() + set(OPENVR_LIBRARY "openvr_api") set(OPENVR_INCLUDE_DIR "") @@ -553,6 +558,7 @@ set(CORE_SOURCES "scripting/scriptscreendrawing.cpp" "simulation/simulationtestrules.cpp" "vehicle/blackbox.cpp" +"utilities/physicslog.cpp" "vehicle/enginestart.cpp" "vehicle/brakesetting.cpp" "vehicle/drivingaid.cpp" diff --git a/EU07.cpp b/EU07.cpp index 20f24aa5a..a76564663 100644 --- a/EU07.cpp +++ b/EU07.cpp @@ -22,11 +22,17 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others #include "simulation/simulationtest.h" #include "utilities/Globals.h" #include "utilities/Logs.h" +#include "utilities/physicslog.h" #include #include #include #include #include +#ifdef _WIN32 +#include +#else +#include +#endif #ifdef WITHDUMPGEN #ifdef _WIN32 #include @@ -107,6 +113,8 @@ void finish_log() [[noreturn]] void end_test_run(std::string_view const Reason) { simulation::test().conclude(simulation::test_result::error, Reason); + // the last seconds of the physics logs, which the runner of the tests reads: a second at most is waited for them + PhysicsLogs.stop(); finish_log(); fflush(stdout); fflush(stderr); @@ -136,10 +144,29 @@ void finish_log() end_test_run("the simulator stopped before the test ended"); } +// the physics logs used to keep a file open for every vehicle with a driver, and on a scenery with some five hundred +// of them they took all the files the C library of Windows lets a process have open by default (512): the files +// opened after them, the shaders of the map among them, couldn't be read. they keep none open now (physicslog.h), +// but the limit is raised to the most either system allows still, for whatever else opens many files at once +void raise_open_files_limit() +{ +#ifdef _WIN32 + _setmaxstdio(8192); +#else + rlimit limit{}; + if (getrlimit(RLIMIT_NOFILE, &limit) == 0 && limit.rlim_cur < limit.rlim_max) + { + limit.rlim_cur = limit.rlim_max; + setrlimit(RLIMIT_NOFILE, &limit); + } +#endif +} + } // namespace int main(int argc, char *argv[]) { + raise_open_files_limit(); #ifdef WITHDUMPGEN #ifdef _WIN32 SetUnhandledExceptionFilter(CrashHandler); @@ -215,6 +242,9 @@ int main(int argc, char *argv[]) MessageBoxA(nullptr, msg.c_str(), "Simulator crashed :(", MB_ICONERROR); } #endif + // the last seconds of the physics logs, a second at most, also after an error caught above; Application.exit() stops them + // otherwise, and a second stop only writes what came since + PhysicsLogs.stop(); } #ifndef _WIN32 fflush(stdout); diff --git a/application/application.cpp b/application/application.cpp index 96f578514..140475b60 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -34,6 +34,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/dictionary.h" #include "version_info.h" #include "simulation/simulationtest.h" +#include "utilities/physicslog.h" #include #include #include @@ -745,6 +746,9 @@ void eu07_application::exit() track_sleepers::stop_background(); step("the black box"); simulation::Blackbox.close(); + step("the physics logs"); + // what is kept of them, the black box's written last, waited for a second at most: the rest is dropped + PhysicsLogs.stop(); step("the modes"); for (auto &mode : m_modes) mode.reset(); @@ -1323,6 +1327,21 @@ int eu07_application::init_settings(int Argc, char *Argv[]) simulation::apply_test_mode_settings(); } + // a renderer this build doesn't have gets the full one: the starter writes the words of every build it knows + // ("vulkan" for the vulkan builds), and any word not known here used to start the legacy renderer. + // "simpleshader" and "off" of the older starters keep the legacy one they always had + auto const &renderer{Global.GfxRenderer}; + auto const known{renderer == "default" || renderer == "legacy" || renderer == "simple" || renderer == "null" || renderer == "simpleshader" || + renderer == "off" || (renderer == "experimental" && gfx_renderer_factory::get_instance()->has_backend(renderer))}; + if (false == known) + { + WriteLog("gfxrenderer \"" + renderer + "\" isn't in this build, the full renderer is used instead"); + Global.GfxRenderer = "default"; + Global.NvRenderer = false; + Global.LegacyRenderer = false; + Global.BasicRenderer = false; + } + return 0; } diff --git a/application/editormode.cpp b/application/editormode.cpp index e08e1f0e7..ab150cb7b 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -1398,6 +1398,7 @@ bool editor_mode::update() Global.editor_tracks = (current_work_area() == work_area::tracks); selftest_step(); steps.step("selftest"); + thumbnails_trim(); // the drives of the switches go to the tips of their blades once, as the templates of the scenery are known if (false == m_drives_checked) { diff --git a/application/editormode.h b/application/editormode.h index bcf22592c..81347c950 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -745,13 +745,23 @@ class editor_mode : public application_mode, private editor_track::observer, pri char filter[64]{}; float size{96.f}; // of the images, pixels std::string selected; - std::map thumbnails; // texture shown for the item of the name, 0: none + struct thumbnail + { + int texture{0}; // 0: none + int material{0}; // the material the texture is the first of, 0: a texture alone + double shown{0.0}; // when it was last asked for, ImGui time + }; + std::map thumbnails; // texture shown for the item of the name + bool refresh{false}; // all the images to be let go of and read again int loads{0}; // textures read in the frame, a few at most so the browser doesn't stall the editor int loadsframe{-1}; } m_textures; void render_texture_browser(); // texture of the image of the item of the browser, 0 while there's none std::uint64_t texture_thumbnail(texture_browser::item const &Item); + // the textures of the images out of sight for a while taken out of the memory: a picker of thousands of them scrolled + // through would keep them all, full size, until the memory ran out + void thumbnails_trim(); // takes a material dragged from the texture browser onto the item drawn last. returns: true if one was dropped, its name in Name static bool material_drop(std::string &Name); // the same, for a text field diff --git a/application/editormodetextures.cpp b/application/editormodetextures.cpp index 155210a87..e3423de5e 100644 --- a/application/editormodetextures.cpp +++ b/application/editormodetextures.cpp @@ -93,25 +93,53 @@ std::uint64_t editor_mode::texture_thumbnail(texture_browser::item const &Item) if (browser.loads >= 2) return 0; ++browser.loads; - texture_handle texture{null_handle}; + texture_browser::thumbnail thumbnail; if (Item.material) { - auto const material{GfxRenderer->Fetch_Material(Item.name)}; - if (auto const *data{GfxRenderer->Material(material)}; material != null_handle && data != nullptr) - texture = data->GetTexture(0); + // a material reads all its textures, the normal maps and the rest with the one shown + thumbnail.material = GfxRenderer->Fetch_Material(Item.name); + if (auto const *data{GfxRenderer->Material(thumbnail.material)}; thumbnail.material != null_handle && data != nullptr) + thumbnail.texture = data->GetTexture(0); } else - texture = GfxRenderer->Fetch_Texture(Item.name, true); - lookup = browser.thumbnails.emplace(Item.name, texture).first; + thumbnail.texture = GfxRenderer->Fetch_Texture(Item.name, true); + lookup = browser.thumbnails.emplace(Item.name, thumbnail).first; } - if (lookup->second == null_handle) + lookup->second.shown = ImGui::GetTime(); + if (lookup->second.texture == null_handle) return 0; - auto &texture{GfxRenderer->Texture(lookup->second)}; + auto &texture{GfxRenderer->Texture(lookup->second.texture)}; if (false == texture.get_is_ready()) texture.create(); return texture.get_is_ready() ? static_cast(texture.get_id()) : 0; } +void editor_mode::thumbnails_trim() +{ + // a few seconds out of sight, so scrolling back and forth doesn't read them over and over + // all of them after the browser's Refresh, here before any image is drawn: not while the panels drawn earlier in the + // frame still refer to them + auto constexpr kept{3.0}; + auto const now{ImGui::GetTime()}; + auto &browser{m_textures}; + for (auto entry{browser.thumbnails.begin()}; entry != browser.thumbnails.end();) + { + auto const &thumbnail{entry->second}; + if (false == browser.refresh && ((thumbnail.texture == null_handle && thumbnail.material == null_handle) || now - thumbnail.shown < kept)) + { + ++entry; + continue; + } + // the scene's own textures stay; shown again, the image is read anew within the few a frame + if (thumbnail.material != null_handle) + GfxRenderer->Unload_Material(thumbnail.material); + else + GfxRenderer->Unload_Texture(thumbnail.texture); + entry = browser.thumbnails.erase(entry); + } + browser.refresh = false; +} + void editor_mode::render_texture_browser() { auto &browser{m_textures}; @@ -173,7 +201,8 @@ void editor_mode::render_texture_browser() if (ImGui::Button(STR_C("Refresh"))) { browser.listed = false; - browser.thumbnails.clear(); + // the images let go of at the start of the next frame, see thumbnails_trim() + browser.refresh = true; } ImGui::SameLine(); ImGui::TextUnformatted((std::string{paths::textures} + browser.folder).c_str()); diff --git a/application/editormodetrackprops.cpp b/application/editormodetrackprops.cpp index 13a9d2a49..4542d0225 100644 --- a/application/editormodetrackprops.cpp +++ b/application/editormodetrackprops.cpp @@ -1043,8 +1043,10 @@ void editor_mode::textures_index() { if (entry->is_directory(ignored)) { - // the normal maps go with their textures, not on a track by themselves - if (lowered(entry->path().filename().string()) == "normals") + // the normal maps go with their textures, not on a track by themselves; the previews of the node bank, thousands of + // them, are images of models and not textures of anything + auto const folder{lowered(entry->path().filename().string())}; + if (folder == "normals" || (folder == "previews" && entry.depth() == 0)) entry.disable_recursion_pending(); continue; } diff --git a/audio/audio.cpp b/audio/audio.cpp index 845fba9e7..cd053f682 100644 --- a/audio/audio.cpp +++ b/audio/audio.cpp @@ -35,7 +35,8 @@ decoded_sound decode_sound( std::string const &File ) { SF_INFO si; si.format = 0; - SNDFILE *sf = sf_open(File.c_str(), SFM_READ, &si); + // the file as it's named on the disk, the name of the buffer is in lowercase + SNDFILE *sf = sf_open(FileOnDisk(File).c_str(), SFM_READ, &si); if (sf == nullptr) throw std::runtime_error("sound: sf_open failed"); @@ -216,9 +217,9 @@ openal_buffer::fetch_caption() { std::string captionfilename { name }; captionfilename.erase( captionfilename.rfind( '.' ) ); // obcięcie rozszerzenia captionfilename += "-" + Global.asLang + ".txt"; // już może być w różnych językach - if( true == FileExists( captionfilename ) ) { + if( auto const casedfilename { FileCased( captionfilename ) }; false == casedfilename.empty() ) { // wczytanie - std::ifstream inputfile( captionfilename ); + std::ifstream inputfile( casedfilename ); caption.assign( std::istreambuf_iterator( inputfile ), std::istreambuf_iterator() ); } } diff --git a/blackbox_doc.md b/blackbox_doc.md index ab330dc2e..126cea033 100644 --- a/blackbox_doc.md +++ b/blackbox_doc.md @@ -7,14 +7,42 @@ done at the same moment, every command the user gave, when the autopilot took ov the timetable and how the train kept to it at each station, and where it was told to sound the horn. From it another program (the starter, a viewer) can replay the session on the map, or set the user's driving against the AI's. -It is written along with the physics logs: `physicslog yes` in `eu07.ini`, not in an editor session. -`blackbox no` turns it off while the physics logs are kept (it is on by default). The file goes next to -them, `physicslog/_.blackbox` (the local time the recording started at). -The `.dat` logs stay as they are. +`blackbox yes` in `eu07.ini` writes it, with the physics logs on or off; `blackbox no` never does. With no +`blackbox` entry it is written along with the physics logs, `physicslog yes` or `physicslog.trains yes`. +The former writes the `.dat` log of every driver but those of the road vehicles, which on a big scenery are +hundreds and nobody reads. The latter writes the `.dat` logs of the trains only: of each driver who drives rail +vehicles, not of the passengers either, so a big scenery gives far fewer of them still. It is never written in an +editor session. The file goes to `physicslog/_.blackbox` (the local time the +recording started at), next to the `.dat` logs of the vehicles when those are on; they stay as they are. + +With the physics logs off it still gives the `.dat` log of each vehicle the user was in, as it goes: +`physicslog/.dat`, the same file name, the same columns and the same line every 0.05 s as +`physicslog yes` would write. In the name of a file, of these logs and of those of `physicslog yes`, the +characters no file name may have on Windows, `< > : " / \ | ? *` and the control characters, are `_`, on +every system: a spawned vehicle, named `:`, has its log as `_.dat`. A name +Windows keeps for a device (`con`, `nul`, `com1` and the like) gets a `_` before it. A log is the driver's, named after the vehicle that driver began in: it +begins the first time the user is with that driver, and goes on while the user looks around outside, or +moves to another cab of the unit or another vehicle of the same train. Taking a vehicle of another driver +goes on in that driver's log, begun then if it is the first time. Back with a driver, the log goes on after +the gap in its time. A vehicle with no driver of its own, or whose own driver is passive, takes the log of +the driver of its train. So the speed recorder's tape can be read from them as before, also while the +simulator runs, without a log of every vehicle. A driver who writes a log of its own, with +`physicslog.trains yes` or `physicslog yes`, isn't written twice; with `physicslog yes` it is a road vehicle the +user drives whose log the black box writes, so with the black box off (`blackbox no`, or in the editor) a car the +user drives has no log. Like those of `physicslog yes`, they are written every +two seconds, each file opened only for the moment it is written to; a crash loses the last two seconds +of real time of them (at a higher time speed, more of the simulated time), up to ten on a disk which can't keep up. A file another program holds +for a while doesn't lose its lines: they are written once it can be, the last 64 MB of all such logs at most. +The writing of all the logs goes after the simulator's own reading of the disk. When it takes over a third of +those two seconds, hundreds of logs on a hard disk say, they are written less often from then on, three times as +long after a writing as it took and every ten seconds at most, and the simulator's log tells it once. +Closing the simulator waits for the logs' last lines a second at most: what isn't written by then is lost, +and the simulator's log tells how many logs were left unwritten. The recording starts once the scenery is loaded and ends when the simulator closes. Going into the editor (F11) ends it too, since the editor may take away the tracks and the vehicles it refers to; no -new one starts when driving goes on after that. +new one starts when driving goes on after that. The `.dat` logs it gives with the physics logs off go on +then, after the gap of the time in the editor, until the simulator closes: they are files of their own. It is written as the session goes and flushed once a second, so the file can be read while the simulator still writes it, and after a crash all but the last second is there. A file without the `end` record @@ -162,14 +190,15 @@ record. ### 0x20 cab -The vehicle the user is in, every 0.1 s, also while the user looks around outside it. 190 bytes. +The vehicle the user is in, every 0.1 s, also while the user looks around outside it. 194 bytes (190 in the +files written before the speed of the wheels was added at the end). | type | field | |---------|------------------------------------------------------------------------| | `f64` | t | | `u32` | number of the vehicle | | `dvec3` | position | -| `f32` | speed [km/h], positive along the front of the vehicle | +| `f32` | speed of the vehicle [km/h], positive along its front | | `f32` | acceleration along the track [m/s²] | | `f32` | odometer [km] | | `u8` | driver: 0 none, 1 the user, 2 the AI (the autopilot) | @@ -221,6 +250,7 @@ The vehicle the user is in, every 0.1 s, also while the user looks around outsid | `f32` | the clutch of a diesel's gearbox, 0 open .. 1 closed | | `f32` | the filling of a diesel's hydraulic torque converter, 0..1 | | `f32` | the highest brake cylinder pressure of the vehicles of the train [bar] | +| `f32` | speed of the wheels [km/h], as the speedometer shows it: those of the powered vehicle (in a unit driven from an unpowered car, its motor car), signed as the speed of the vehicle: apart from it while the wheels slip, 0 while they are locked in a skid | The lights the train is to show follow from the movement and the two patterns after it: in a train run the head the pattern asked for, the usual one Pc 1 (both headlights and the upper one; Pc 2 is the left red marker with the right and the @@ -285,7 +315,8 @@ whose motors the cab drives (the motor car of a unit). | 0x0800'0000 | the cruise control holds a speed | The doors, their permits and steps, the departure signal and the releaser are of the vehicle the user is -in; the pumps, the fans, the engine's heat and the cruise control of the one whose motors the cab drives. +in. Left and right are those of the vehicle, seen from its front: from the rear cab (the cab -1) the driver's +left doors are the vehicle's right, as the simulator works them from there. The pumps, the fans, the engine's heat and the cruise control of the one whose motors the cab drives. The lights: 0x001 left headlight, 0x002 left red marker, 0x004 upper headlight, 0x010 right headlight, 0x020 right red marker, 0x040 rear-end signals, 0x080 left and 0x100 right auxiliary diff --git a/editor/editorHttp.cpp b/editor/editorHttp.cpp index 12569ebd0..81a195aeb 100644 --- a/editor/editorHttp.cpp +++ b/editor/editorHttp.cpp @@ -16,7 +16,10 @@ http://mozilla.org/MPL/2.0/. #include #endif +#include +#include #include +#include namespace editor_http { @@ -160,6 +163,37 @@ bool client::get(std::string const &Url, std::vector &Out, std::st #elif defined(EU07_WITH_CURL) +namespace +{ +// the file of the certificates https is checked with. the libcurl bundled with the game knows only the one of the system it +// was built on (/etc/ssl/certs/ca-certificates.crt of Debian and Ubuntu), which Fedora, RHEL and openSUSE don't have: there +// every download failed. the file named by the user first, then the ones the distributions keep; empty leaves libcurl's own +std::string const &certificates_file() +{ + static std::string const file{[]() { + std::error_code error; + for (char const *variable : {"SSL_CERT_FILE", "CURL_CA_BUNDLE"}) + { + if (char const *value{std::getenv(variable)}; (value != nullptr) && (*value != '\0') && std::filesystem::is_regular_file(value, error)) + return std::string{value}; + } + for (char const *candidate : { + "/etc/ssl/certs/ca-certificates.crt", // Debian, Ubuntu, Arch, SteamOS, Gentoo, NixOS + "/etc/pki/tls/certs/ca-bundle.crt", // Fedora, RHEL + "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", // Fedora, RHEL + "/etc/ssl/ca-bundle.pem", // openSUSE + "/etc/ssl/cert.pem", // Alpine, the BSDs, macOS + }) + { + if (std::filesystem::is_regular_file(candidate, error)) + return std::string{candidate}; + } + return std::string{}; + }()}; + return file; +} +} // namespace + client::client() : m_platform(std::make_unique()) { @@ -204,6 +238,14 @@ bool client::get(std::string const &Url, std::vector &Out, std::st ::curl_easy_reset(m_platform->curl); ::curl_easy_setopt(m_platform->curl, CURLOPT_URL, Url.c_str()); ::curl_easy_setopt(m_platform->curl, CURLOPT_USERAGENT, "MaSzyna-editor"); + if (auto const &certificates{certificates_file()}; false == certificates.empty()) + { + ::curl_easy_setopt(m_platform->curl, CURLOPT_CAINFO, certificates.c_str()); +#if LIBCURL_VERSION_NUM >= 0x073400 + // an https proxy is checked with the same file + ::curl_easy_setopt(m_platform->curl, CURLOPT_PROXY_CAINFO, certificates.c_str()); +#endif + } ::curl_easy_setopt(m_platform->curl, CURLOPT_FOLLOWLOCATION, 1L); ::curl_easy_setopt(m_platform->curl, CURLOPT_MAXREDIRS, 10L); // http kept for the services the user types; nothing else, also where a redirect leads diff --git a/editor/editorPreviews.cpp b/editor/editorPreviews.cpp index 27f84a9fe..68164460c 100644 --- a/editor/editorPreviews.cpp +++ b/editor/editorPreviews.cpp @@ -298,7 +298,9 @@ void image_cache::work() m_queue.pop_front(); } int width{0}, height{0}, components{0}; - auto *pixels{stbi_load(image.path.c_str(), &width, &height, &components, 4)}; + // the file as it's named on the disk, the path stays the key of the cache + auto const file{FileCased(image.path)}; + auto *pixels{file.empty() ? nullptr : stbi_load(file.c_str(), &width, &height, &components, 4)}; if (pixels != nullptr && width > 0 && height > 0) { // scaled down by the average of the pixels which make each one, the longer side to the size of the cache diff --git a/gl/shader.cpp b/gl/shader.cpp index 31a3e6a87..c276cdef8 100644 --- a/gl/shader.cpp +++ b/gl/shader.cpp @@ -1,8 +1,10 @@ #include "stdafx.h" +#include #include #include #include +#include #include "shader.h" #include "glsl_common.h" #include "utilities/Logs.h" @@ -58,6 +60,12 @@ std::string gl::shader::read_file(const std::string &filename) const std::ifstream f; f.open(filename); + if (false == f.is_open()) + { + // with the reason the system gives: a file which is there but can't be opened (too many files open) looks + // the same as a missing one otherwise + throw shader_exception("cannot open shader: " + filename + " (" + std::generic_category().message(errno) + ")"); + } stream << f.rdbuf(); f.close(); diff --git a/global_include/interfaces/IMaterial.h b/global_include/interfaces/IMaterial.h index c6f3d1237..2d16a43b0 100644 --- a/global_include/interfaces/IMaterial.h +++ b/global_include/interfaces/IMaterial.h @@ -3,6 +3,7 @@ #include #include #include +#include #include "ITexture.h" @@ -17,6 +18,11 @@ struct IMaterial virtual std::optional GetSelfillum() const = 0; virtual int GetShadowRank() const = 0; virtual texture_handle GetTexture(int slot) const = 0; + // every texture the material draws with, those of all its variants included. materials which don't tell give none + virtual std::vector GetAllTextures() const + { + return {}; + } static IMaterial *null_material() { struct NullMaterial : public IMaterial diff --git a/lang/editor_pl.po b/lang/editor_pl.po index 668792f28..4a5bc4759 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -12248,15 +12248,11 @@ msgstr "Wierzchołek %zu: krzywa przejściowa między łukiem przylegającego to msgid "Download area" msgstr "Obszar pobierania" -msgid "A polygon drawn on the map: what the settings ask for inside it, the orthophoto and the terrain model, -goes to the disk cache in the background, and nothing outside it is downloaded, also around the camera" -msgstr "Wielokąt narysowany na mapie: to, co wybrano w ustawieniach, ortofotomapa i model terenu, pobiera się w nim w tle -do pamięci podręcznej na dysku, a poza nim nic się nie pobiera, także wokół kamery" +msgid "A polygon drawn on the map: what the settings ask for inside it, the orthophoto and the terrain model,\ngoes to the disk cache in the background, and nothing outside it is downloaded, also around the camera" +msgstr "Wielokąt narysowany na mapie: to, co wybrano w ustawieniach, ortofotomapa i model terenu, pobiera się w nim w tle\ndo pamięci podręcznej na dysku, a poza nim nic się nie pobiera, także wokół kamery" -msgid "Click the points of the area on the map. Enter closes it, Backspace takes the last point back, Esc gives up; -a point dragged moves, Shift+click removes it" -msgstr "Klikaj na mapie punkty obszaru. Enter go zamyka, Backspace cofa ostatni punkt, Esc rezygnuje; -przeciągnięty punkt się przesuwa, Shift+klik go usuwa" +msgid "Click the points of the area on the map. Enter closes it, Backspace takes the last point back, Esc gives up;\na point dragged moves, Shift+click removes it" +msgstr "Klikaj na mapie punkty obszaru. Enter go zamyka, Backspace cofa ostatni punkt, Esc rezygnuje;\nprzeciągnięty punkt się przesuwa, Shift+klik go usuwa" msgid "%zu points" msgstr "punktów: %zu" diff --git a/model/MdlMngr.cpp b/model/MdlMngr.cpp index 680f67c42..52bc4047e 100644 --- a/model/MdlMngr.cpp +++ b/model/MdlMngr.cpp @@ -137,15 +137,19 @@ TModelsManager::find_in_databank( std::string const &Name ) { } // checks whether specified file exists. returns name of the located file, or empty string. +// the file is found in any case, as the scenery made on Windows names it, but the name is given back as asked for: it's the key of +// the bank, and TModel3d::LoadFromFile() opens the file as it's named on the disk std::string TModelsManager::find_on_disk( std::string const &Name ) { std::vector extensions { { ".e3d" }, { ".t3d" } }; for( auto const &extension : extensions ) { - auto lookup = FileExists(Name + extension) ? Name : FileExists(paths::models + Name + extension) ? paths::models + Name : ""; - if( false == lookup.empty() ) { - return lookup; + if( false == FileCased( Name + extension ).empty() ) { + return Name; + } + if( false == FileCased( paths::models + Name + extension ).empty() ) { + return paths::models + Name; } } diff --git a/model/Model3d.cpp b/model/Model3d.cpp index 44f5f6255..e3507e216 100644 --- a/model/Model3d.cpp +++ b/model/Model3d.cpp @@ -1702,24 +1702,27 @@ bool TModel3d::LoadFromFile(std::string const &FileName, bool dynamic) m_filename = name; asBinary = name + ".e3d"; + // the files as they're named on the disk, the name given is in lowercase + auto const textfile{FileCased(name + ".t3d")}; + auto const binaryfile{FileCased(asBinary)}; // Hirek: Jesli mamy ustawione priorityLoadText3D na yes to wpierw ladujemy t3d - if (Global.priorityLoadText3D && FileExists(name + ".t3d")) + if (Global.priorityLoadText3D && (false == textfile.empty())) { - WriteLog("Forced loading text model \"" + name + ".t3d\""); - LoadFromTextFile(name + ".t3d", dynamic); + WriteLog("Forced loading text model \"" + textfile + "\""); + LoadFromTextFile(textfile, dynamic); if (!dynamic) Init(); } - else if (FileExists(asBinary)) + else if (false == binaryfile.empty()) { - LoadFromBinFile(asBinary, dynamic); + LoadFromBinFile(binaryfile, dynamic); asBinary = ""; Init(); } - else if (FileExists(name + ".t3d")) + else if (false == textfile.empty()) { - LoadFromTextFile(name + ".t3d", dynamic); + LoadFromTextFile(textfile, dynamic); if (!dynamic) Init(); } diff --git a/model/Texture.cpp b/model/Texture.cpp index cd275c9e0..9b428202b 100644 --- a/model/Texture.cpp +++ b/model/Texture.cpp @@ -640,7 +640,7 @@ void opengl_texture::load_STBI() { int x, y, n; stbi_set_flip_vertically_on_load(1); - uint8_t *image = stbi_load((name + type).c_str(), &x, &y, &n, 4); + uint8_t *image = stbi_load(FileOnDisk(name + type).c_str(), &x, &y, &n, 4); if (!image) { data_state = resource_state::failed; @@ -818,7 +818,7 @@ DDSURFACEDESC2 opengl_texture::deserialize_ddsd(std::istream &s) void opengl_texture::load_DDS() { - std::ifstream file( name + type, std::ios::binary | std::ios::ate ); file.unsetf( std::ios::skipws ); + std::ifstream file( FileOnDisk( name + type ), std::ios::binary | std::ios::ate ); file.unsetf( std::ios::skipws ); std::size_t filesize = static_cast(file.tellg()); // ios::ate already positioned us at the end of the file file.seekg( 0, std::ios::beg ); // rewind the caret afterwards @@ -938,7 +938,7 @@ opengl_texture::load_DDS() { if( true == Global.gfx_texture_streaming ) { // the data is read by a worker thread, everything else about the texture is known already request = std::make_shared(); - request->file = name + type; + request->file = FileOnDisk( name + type ); request->offset = static_cast( file.tellg() ) + offset; request->size = datasize; request->flip = flip; @@ -1000,7 +1000,7 @@ opengl_texture::load_DDS() { void opengl_texture::load_KTX() { - std::ifstream file( name + type, std::ios::binary | std::ios::ate ); file.unsetf( std::ios::skipws ); + std::ifstream file( FileOnDisk( name + type ), std::ios::binary | std::ios::ate ); file.unsetf( std::ios::skipws ); std::size_t filesize = static_cast(file.tellg()); // ios::ate already positioned us at the end of the file file.seekg( 0, std::ios::beg ); // rewind the caret afterwards @@ -1061,7 +1061,7 @@ opengl_texture::load_KTX() { void opengl_texture::load_TEX() { - std::ifstream file( name + type, std::ios::binary ); file.unsetf( std::ios::skipws ); + std::ifstream file( FileOnDisk( name + type ), std::ios::binary ); file.unsetf( std::ios::skipws ); char head[ 5 ]; file.read( head, 4 ); @@ -1108,7 +1108,7 @@ opengl_texture::load_TEX() { void opengl_texture::load_TGA() { - std::ifstream file( name + type, std::ios::binary ); file.unsetf( std::ios::skipws ); + std::ifstream file( FileOnDisk( name + type ), std::ios::binary ); file.unsetf( std::ios::skipws ); // Read the header of the TGA, compare it with the known headers for compressed and uncompressed TGAs unsigned char tgaheader[ 18 ]; @@ -1886,6 +1886,52 @@ texture_manager::mark_as_needed( texture_handle const Texture, bool const Near ) } } +void +texture_manager::unload( texture_handle const Texture ) { + + if( ( Texture <= 0 ) + || ( Texture >= static_cast( m_textures.size() ) ) ) { + return; + } + auto const &record { m_textures[ Texture ] }; + auto &texture { *record.first }; + if( ( record.second != resource_timestamp() ) + || ( texture.id == 0 ) // failed to load + || ( true == texture.is_static ) + || ( true == texture.is_rendertarget ) + || ( texture.type == "make:" ) + || ( texture.type == "internalsrc:" ) ) { + return; + } + if( ( texture.data_state == resource_state::loading ) + && ( texture.request != nullptr ) ) { + // read by a worker thread: taken over first, to be dropped with the rest + texture.complete_data(); + if( texture.data_state == resource_state::failed ) { + return; + } + } + auto const created { texture.id != opengl_texture::invalid_id }; + if( ( false == created ) + && ( texture.data_state != resource_state::good ) ) { + // nothing read nor made, e.g. the textures of a material asked for without loading + return; + } + if( true == created ) { + // deleted outright: release() would read the texture back from the card with gfx.resource.move, only for it to be dropped + ::glDeleteTextures( 1, &texture.id ); + texture.id = opengl_texture::invalid_id; + texture.is_ready = false; + // the released gl name can be given to a new texture, the unit cache can't trust it + for( auto &unit : opengl_texture::units ) { + unit = -1; + } + } + texture.data = std::vector(); + texture.data_state = resource_state::none; + texture.reload_on_use = true; +} + // releases gl textures of vehicles not needed nor drawn for a while void texture_manager::release_unneeded() { diff --git a/model/Texture.h b/model/Texture.h index 313d0f6f4..20221fcea 100644 --- a/model/Texture.h +++ b/model/Texture.h @@ -181,6 +181,10 @@ public: // releases gl textures of vehicles not needed nor drawn for a while void release_unneeded(); + // takes a texture the scene has never drawn out of both the gfx card and the memory, e.g. the image of a picker scrolled + // past, or one read and not made yet; it's read again when it's used. textures the scene draws are left to the resource sweep + void + unload( texture_handle const Texture ); // debug performance string std::string info() const; diff --git a/model/material.h b/model/material.h index 82d14557c..4b7323f76 100644 --- a/model/material.h +++ b/model/material.h @@ -66,6 +66,13 @@ struct opengl_material : public IMaterial { { return textures[slot]; } + virtual std::vector GetAllTextures() const override + { + std::vector all(textures.begin(), textures.end()); + for (auto const &variant : texture_variants) + all.insert(all.end(), variant.begin(), variant.end()); + return all; + } // returns texture set to use for model instance identified by provided variant id texture_set const &GetTextures(std::uint32_t const Variant) const { diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp index 5eb98222b..800f33dcf 100644 --- a/rendering/opengl33renderer.cpp +++ b/rendering/opengl33renderer.cpp @@ -2570,6 +2570,11 @@ ITexture const &opengl33_renderer::Texture(texture_handle const Texture) const return m_textures.texture(Texture); } +void opengl33_renderer::Unload_Texture(texture_handle const Texture) +{ + m_textures.unload(Texture); +} + void opengl33_renderer::Update_AnimModel(TAnimModel *model) { model->RaAnimate(m_framestamp); diff --git a/rendering/opengl33renderer.h b/rendering/opengl33renderer.h index 807563c40..4322cc2db 100644 --- a/rendering/opengl33renderer.h +++ b/rendering/opengl33renderer.h @@ -110,6 +110,8 @@ class opengl33_renderer : public gfx_renderer { Texture( texture_handle const Texture ) override; ITexture const & Texture( texture_handle const Texture ) const override; + void + Unload_Texture( texture_handle const Texture ) override; // utility methods void Pick_Control_Callback( std::function Callback ) override; diff --git a/rendering/openglrenderer.cpp b/rendering/openglrenderer.cpp index 71bd7d0ef..5083c6f2f 100644 --- a/rendering/openglrenderer.cpp +++ b/rendering/openglrenderer.cpp @@ -419,6 +419,15 @@ opengl_renderer::Render() { // add user interface setup_units( true, false, false ); ::glPushClientAttrib( GL_CLIENT_VERTEX_ARRAY_BIT ); + // the arrays the scene left enabled point into the buffer of whatever was drawn last; the ui sets up + // the vertex, colour and texture coordinates of the active unit only, so the driver would go on reading + // the rest with the indices of the ui, past the end of that buffer once the ui has more vertices than it + for( auto const unit : m_geometry.units().texture ) { + ::glClientActiveTexture( GL_TEXTURE0 + unit ); + ::glDisableClientState( GL_TEXTURE_COORD_ARRAY ); + } + ::glDisableClientState( GL_NORMAL_ARRAY ); + ::glDisableClientState( GL_COLOR_ARRAY ); ::glClientActiveTexture( GL_TEXTURE0 + m_diffusetextureunit ); // clear state for ui @@ -1922,6 +1931,12 @@ opengl_renderer::Texture( texture_handle const Texture ) const { return m_textures.texture( Texture ); } +void +opengl_renderer::Unload_Texture( texture_handle const Texture ) { + + m_textures.unload( Texture ); +} + void opengl_renderer::Pick_Control_Callback( std::function Callback ) { diff --git a/rendering/openglrenderer.h b/rendering/openglrenderer.h index ecb8a3c50..ef3a9f0f3 100644 --- a/rendering/openglrenderer.h +++ b/rendering/openglrenderer.h @@ -95,6 +95,8 @@ public: Texture( texture_handle const Texture ) override; ITexture const & Texture( texture_handle const Texture ) const override; + void + Unload_Texture( texture_handle const Texture ) override; // utility methods void Pick_Control_Callback( std::function Callback ) override; diff --git a/rendering/renderer.cpp b/rendering/renderer.cpp index d9d4b5df0..7c4098ef0 100644 --- a/rendering/renderer.cpp +++ b/rendering/renderer.cpp @@ -29,6 +29,11 @@ std::unique_ptr gfx_renderer_factory::create(const std::string &ba return nullptr; } +bool gfx_renderer_factory::has_backend(const std::string &name) const +{ + return backends.contains(name); +} + gfx_renderer_factory *gfx_renderer_factory::get_instance() { if (!instance) @@ -39,6 +44,16 @@ gfx_renderer_factory *gfx_renderer_factory::get_instance() gfx_renderer_factory *gfx_renderer_factory::instance; +void gfx_renderer::Unload_Material( material_handle const Material ) +{ + if( Material == null_handle ) { + return; + } + for( auto const texture : this->Material( Material )->GetAllTextures() ) { + Unload_Texture( texture ); + } +} + material_handle gfx_renderer::Terrain_Material( material_handle const Reuse, std::vector const &Layers, int const Samples, std::uint8_t const *Weights, glm::vec3 const &Placement ) { // without blending the chunk gets the material which covers the most of it diff --git a/rendering/renderer.h b/rendering/renderer.h index 5ad805c4a..c72dcaea9 100644 --- a/rendering/renderer.h +++ b/rendering/renderer.h @@ -102,6 +102,11 @@ public: virtual void Bind_Texture( std::size_t const Unit, texture_handle const Texture ) = 0; virtual auto Texture( texture_handle const Texture ) -> ITexture & = 0; virtual auto Texture( texture_handle const Texture ) const -> ITexture const & = 0; + // a texture the scene has never drawn taken out of the gfx card and the memory, read again when it's used: the image of a + // texture picker scrolled past. backends which keep their textures otherwise leave it + virtual void Unload_Texture( texture_handle const Texture ) {} + // the same for all the textures of a material, those of its variants with them + void Unload_Material( material_handle const Material ); // utility methods virtual void Pick_Control_Callback( std::function Callback ) = 0; virtual void Pick_Node_Callback( std::function Callback ) = 0; @@ -151,6 +156,7 @@ public: bool register_backend(const std::string &backend, create_method func); std::unique_ptr create(const std::string &name); + bool has_backend(const std::string &name) const; static gfx_renderer_factory* get_instance(); diff --git a/scripting/PyInt.cpp b/scripting/PyInt.cpp index 666609b0e..fac540019 100644 --- a/scripting/PyInt.cpp +++ b/scripting/PyInt.cpp @@ -443,7 +443,7 @@ auto python_taskqueue::run_file(std::string const &File, std::string const &Path return false; } - std::ifstream inputfile{filepath + fileextension}; + std::ifstream inputfile{FileOnDisk(filepath + fileextension)}; std::string input; input.assign(std::istreambuf_iterator(inputfile), std::istreambuf_iterator()); diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index 608b07586..9e979e2ca 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -23,6 +23,7 @@ http://mozilla.org/MPL/2.0/. #include "world/Track.h" #include "utilities/Globals.h" #include "utilities/Logs.h" +#include "utilities/physicslog.h" #include "utilities/utilities.h" #include "world/stationnames.h" @@ -43,6 +44,7 @@ namespace { // [s] between the samples of the user's train, the looks at everything else and the full looks at the vehicles constexpr double cabinterval{0.1}; +constexpr double tapeinterval{0.05}; // as the physics logs (deltalog of Driver.cpp) constexpr double lookinterval{1.0}; constexpr double slowlook{20.0}; // [ms] a look around taking longer is told in the log, part by part constexpr double keyframeinterval{60.0}; @@ -234,15 +236,26 @@ void blackbox_recorder::update(double const Deltatime) { if (false == simulation::is_ready) return; m_started = true; - if (false == WriteLogFlag || false == Global.BlackBox || Global.editor_session) + // "blackbox yes" or "no" of eu07.ini decides by itself, with no entry it goes with the physics logs + if (false == Global.BlackBox.value_or(WriteLogFlag || WriteTrainLogFlag) || Global.editor_session) return; + m_taping = true; open(); } - if (m_writer == nullptr) + if (false == m_taping) return; std::scoped_lock lock{m_mutex}; m_time += Deltatime; + // the tape of the driver the user is with, unless it writes its own: with "physicslog yes" each driver but one of a + // road vehicle does. the tapes are files of their own: they go on after the recording ends in the editor, and with + // a recording which couldn't be made + if (m_time >= m_tapedue) { + keep_tape_line(); + m_tapedue = std::max(m_tapedue + tapeinterval, m_time); + } + if (m_writer == nullptr) + return; if (m_time >= m_cabdue) { write_cab(); m_cabdue = std::max(m_cabdue + cabinterval, m_time); @@ -412,6 +425,13 @@ void blackbox_recorder::write_cab() { sample.vehicle = vehicle_id(vehicle); sample.position = vehicle->GetPosition(); sample.speed_kmh = static_cast(occupied->V * 3.6); + // of the wheels as they turn, which the speedometer shows: apart from that of the vehicle when they slip or skid. + // those of the powered vehicle, as the speedometer has it (TTrain::DynamicSet), which in a unit driven from an + // unpowered car is another one, maybe facing the other way: signed as the occupied one's speed + // the vehicle itself, if none in the unit is powered + auto const *powered{train->Dynamic()->FindPowered()}; + auto const facing{powered->DirectionGet() * vehicle->DirectionGet()}; + sample.wheel_speed_kmh = static_cast(facing * M_PI * powered->MoverParameters->WheelDiameter * powered->MoverParameters->nrot * 3.6); sample.acceleration = static_cast(controlling->AccS); sample.lateral_acceleration = static_cast(occupied->AccN); if (owner != nullptr && owner->is_train()) { @@ -480,6 +500,30 @@ void blackbox_recorder::write_cab() { m_writer->cab(sample); } +void blackbox_recorder::keep_tape_line() { + auto const *train{simulation::Train}; + if (train == nullptr || train->Dynamic() == nullptr) + return; + auto const *vehicle{train->Dynamic()}; + // the driver of the vehicle, whose log it would be: it keeps the name of its first vehicle, so a change of the cab + // in a unit goes on in the same log. a passive one stands still (its clock too), so then the driver of the train + auto const *driver{vehicle->Mechanik != nullptr && vehicle->Mechanik->primary() ? vehicle->Mechanik : vehicle->ctOwner}; + if (driver == nullptr) + return; + auto const &name{driver->physicslog_name()}; + // its log, the driver's own or written here, before the logs of the other drivers: the closing drops those it has + // no time for, on a hard disk with hundreds of them + PhysicsLogs.put_first(name); + // a driver writing its own, of a train with "physicslog.trains yes", isn't written twice + if (driver->writes_physicslog()) + return; + if (m_tapes.insert(name).second) { + PhysicsLogs.begin(name, TController::physicslog_header()); + WriteLog(std::format("Black box: the physics log \"{}\" begun", PhysicsLogs.shown(name))); + } + PhysicsLogs.append(name, driver->physicslog_line()); +} + void blackbox_recorder::look_around(bool const Keyframe) { auto const &time{simulation::Time.data()}; m_writer->clock(m_time, static_cast(time.wYear), static_cast(simulation::Time.year_day()), second_of_day()); diff --git a/simulation/blackboxrecorder.h b/simulation/blackboxrecorder.h index 677c680b0..18ee052c4 100644 --- a/simulation/blackboxrecorder.h +++ b/simulation/blackboxrecorder.h @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include #include @@ -31,13 +32,14 @@ enum class user_command; namespace simulation { // the black box of the session (see blackbox_doc.md): written along with the physics logs, in driver mode, -// from the moment the scenario is loaded until the simulator closes or the editor is entered +// from the moment the scenario is loaded until the simulator closes or the editor is entered. the tapes of the user's +// vehicles, with the physics logs off, go on after the editor until the simulator closes class blackbox_recorder { public: // starts the recording once the scenario is ready, if it is to be made, then records what is due. // Deltatime: simulation time passed since the last call void update(double Deltatime); - // writes the end of the recording and closes the file. a recording closed isn't started again + // writes the end of the recording and closes the file. a recording closed isn't started again; its tapes go on void close(); // what happens between the looks, from wherever it happens; the cabs may run on threads of their own. @@ -86,6 +88,11 @@ private: void write_map(); static std::vector> stop_point_headings(); void write_cab(); + // the line of the log of the driver the user is with, unless that driver writes its own (the physics logs, a road + // vehicle's driver not even with "physicslog yes"), to its log, physicslog/.dat, as the physics logs would + // have it. a driver's log is begun at the first line given for that driver, and goes on + // while the user looks around outside or is in another vehicle of that driver; back with it, after the gap + void keep_tape_line(); // the clock, the user's vehicle, the vehicles, the switches and the signals void look_around(bool Keyframe); void look_at_vehicles(bool Keyframe); @@ -107,8 +114,12 @@ private: std::ofstream m_file; std::unique_ptr m_writer; bool m_started{false}; // tried to start, made or not + bool m_taping{false}; // the recording was to be made: its tapes are kept from then on, the file made or not, closed or not double m_time{0.0}; double m_cabdue{0.0}; + double m_tapedue{0.0}; + // the names of the logs begun by the recording + std::set m_tapes; double m_lookdue{0.0}; double m_keyframedue{0.0}; std::unordered_map m_vehicles; diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index 41f67398c..60854482c 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -1205,6 +1205,8 @@ include_terrain_file( std::string File, std::string &Includes, scene::scratch_da replace_slashes( File ); erase_extension( File ); + // the parser gives the name in lowercase, the files may be named in another case; the binary file is made next to the text + File = FileStemOnDisk( Global.asCurrentSceneryPath, File, { ".txtf", ".btf" } ); if( std::find( binary.terrain_textfiles.begin(), binary.terrain_textfiles.end(), File ) != binary.terrain_textfiles.end() ) { WriteLog( "Terrain file: " + File + " is already in use, ignored" ); return; diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp index 89a8a1046..2efa57291 100644 --- a/simulation/simulationtest.cpp +++ b/simulation/simulationtest.cpp @@ -15,7 +15,9 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulation.h" #include "utilities/Globals.h" #include "utilities/Logs.h" +#include "utilities/physicslog.h" #include "utilities/utilities.h" +#include "vehicle/Driver.h" #include "vehicle/DynObj.h" #include "world/Event.h" #include "world/MemCell.h" @@ -44,6 +46,15 @@ double elapsed_wall_time() return std::chrono::duration(std::chrono::steady_clock::now() - Global.startTimestamp).count(); } +// the physics log of the driver of the vehicle, or of its train's when that one is passive, written before the logs of +// the other drivers: the closing at the end of the run drops those it has no time for +void put_physicslog_first(TDynamicObject const &Vehicle) +{ + auto const *driver { Vehicle.Mechanik != nullptr && Vehicle.Mechanik->primary() ? Vehicle.Mechanik : Vehicle.ctOwner }; + if (driver != nullptr) + PhysicsLogs.put_first(driver->physicslog_name()); +} + } // namespace namespace simulation { @@ -124,11 +135,13 @@ void test_manager::start() } for (auto const &name : Global.test.vehicles) { - if (simulation::Vehicles.find(name) == nullptr) + auto const *vehicle { simulation::Vehicles.find(name) }; + if (vehicle == nullptr) { finish(test_result::error, std::format("the scenery has no vehicle {} (test.vehicle)", name)); return; } + put_physicslog_first(*vehicle); } // a pause set by the scenery or the settings would never be lifted, nobody is there to press the key Global.iPause = 0; @@ -261,7 +274,9 @@ void test_manager::check_wall_clock(double const Elapsed) // but which doesn't close ends with its result if (false == conclude(test_result::timeout, std::format("still running after {:.0f} s of real time (test.wall_timeout)", limit))) ErrorLog(std::format("test: the simulator was still running {:.0f} s of real time after the start, ended", limit)); - // what was logged last gets written, unless the log is held up by a hung thread + // what was logged last gets written, unless the log is held up by a hung thread, or the physics logs by a writer + // holding their files or a disk which doesn't answer: the run ends anyway, two seconds later at most + PhysicsLogs.flush_for(std::chrono::seconds{2}); StopLogService(); std::this_thread::sleep_for(std::chrono::milliseconds(250)); std::_Exit(exit_code()); diff --git a/tests/unit/test_blackbox.cpp b/tests/unit/test_blackbox.cpp index b11253b49..cad1920a1 100644 --- a/tests/unit/test_blackbox.cpp +++ b/tests/unit/test_blackbox.cpp @@ -127,6 +127,7 @@ blackbox::cab_sample sample() { s.clutch = 0.75f; s.converter_fill = 0.25f; s.consist_brake_cylinder = 3.5f; + s.wheel_speed_kmh = 71.5f; return s; } @@ -285,6 +286,8 @@ TEST_CASE("blackbox: a sample of the user's train has the documented size and or CHECK(cab.get() == 0.25f); // the highest brake cylinder pressure of the train CHECK(cab.get() == 3.5f); + // the speed of the wheels + CHECK(cab.get() == 71.5f); CHECK(cab.done()); } diff --git a/tests/unit/test_physicslog.cpp b/tests/unit/test_physicslog.cpp new file mode 100644 index 000000000..32fadec03 --- /dev/null +++ b/tests/unit/test_physicslog.cpp @@ -0,0 +1,385 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "utilities/physicslog.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// the physics logs are kept and written by a thread of their own every so often, each file opened only to be written to + +namespace { + +// a folder of its own for the logs of a test, in the build folder of the tests, removed with the object. the writer +// makes it itself +class log_folder { +public: + explicit log_folder(std::string const &Name) : m_path{std::filesystem::path{EU07_UNIT_TESTS_SCRATCH} / std::format("eu07_physicslog_test_{}", Name)} { + std::filesystem::remove_all(m_path); + } + ~log_folder() { + std::error_code error; + std::filesystem::remove_all(m_path, error); + } + log_folder(log_folder const &) = delete; + log_folder &operator=(log_folder const &) = delete; + + std::filesystem::path const &path() const { return m_path; } + // the log as it stands, read in text mode as it is written: what was given to it + std::string read(std::string const &Name) const { return read_file(m_path / (Name + ".dat")); } + static std::string read_file(std::filesystem::path const &File) { + std::ifstream file{File}; + if (false == file.is_open()) + return {}; + std::ostringstream text; + text << file.rdbuf(); + return text.str(); + } + // waits up to five seconds for the log to read Text + bool reads(std::string const &Name, std::string const &Text) const { + auto const until{std::chrono::steady_clock::now() + std::chrono::seconds{5}}; + while (read(Name) != Text && std::chrono::steady_clock::now() < until) + std::this_thread::sleep_for(std::chrono::milliseconds{10}); + return read(Name) == Text; + } + +private: + std::filesystem::path m_path; +}; + +constexpr auto header{"Time[s] Velocity[m/s]\r\n"}; + +} // namespace + +TEST_CASE("physicslog: a log begun is emptied and given its header, and its lines follow it at each writing") { + log_folder folder{"begin"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + logs.begin("EU07-424", header); + logs.append("EU07-424", "0.0500 0.0000\r\n"); + CHECK(folder.read("EU07-424").empty()); + logs.flush(); + CHECK(folder.read("EU07-424") == std::string{header} + "0.0500 0.0000\r\n"); + + logs.append("EU07-424", "0.1000 1.5000\r\n"); + logs.flush(); + CHECK(folder.read("EU07-424") == std::string{header} + "0.0500 0.0000\r\n0.1000 1.5000\r\n"); + + // begun again: the lines not written yet are dropped along with those written + logs.append("EU07-424", "0.1500 3.0000\r\n"); + logs.begin("EU07-424", header); + logs.flush(); + CHECK(folder.read("EU07-424") == header); +} + +TEST_CASE("physicslog: no file is kept open between the writings, and a log not begun is added to as it stands") { + log_folder folder{"closed"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + logs.begin("SM42-001", header); + logs.flush(); + // Windows doesn't let a file open in a program be removed. Linux does, so there it checks nothing; the log is + // written again below anyway + std::error_code error; + CHECK(std::filesystem::remove(folder.path() / "SM42-001.dat", error)); + CHECK_FALSE(error); + + logs.append("SM42-001", "0.0500 0.0000\r\n"); + logs.flush(); + CHECK(folder.read("SM42-001") == "0.0500 0.0000\r\n"); +} + +TEST_CASE("physicslog: the thread writes the logs by itself") { + log_folder folder{"thread"}; + physicslog_writer logs{folder.path(), std::chrono::milliseconds{20}}; + + logs.begin("ET22-001", header); + logs.append("ET22-001", "0.0500 0.0000\r\n"); + CHECK(folder.reads("ET22-001", std::string{header} + "0.0500 0.0000\r\n")); + logs.append("ET22-001", "0.1000 0.0000\r\n"); + CHECK(folder.reads("ET22-001", std::string{header} + "0.0500 0.0000\r\n0.1000 0.0000\r\n")); +} + +TEST_CASE("physicslog: stopping writes what is kept at once, and what comes after waits for a writing") { + log_folder folder{"stop"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + logs.begin("EN57-1001", header); + logs.append("EN57-1001", "0.0500 0.0000\r\n"); + logs.stop(); + CHECK(folder.read("EN57-1001") == std::string{header} + "0.0500 0.0000\r\n"); + + logs.append("EN57-1001", "0.1000 0.0000\r\n"); + std::this_thread::sleep_for(std::chrono::milliseconds{50}); + CHECK(folder.read("EN57-1001") == std::string{header} + "0.0500 0.0000\r\n"); + logs.flush(); + CHECK(folder.read("EN57-1001") == std::string{header} + "0.0500 0.0000\r\n0.1000 0.0000\r\n"); +} + +TEST_CASE("physicslog: stopping drops the logs past the time it waits for them") { + log_folder folder{"closingwait"}; + { + physicslog_writer logs{folder.path(), std::chrono::hours{1}, std::chrono::milliseconds{0}}; + logs.begin("EU07-005", header); + logs.append("EU07-005", "0.0500 0.0000\r\n"); + logs.stop(); + // the writing of the stop, left behind, is waited for by the writer going + } + CHECK_FALSE(std::filesystem::exists(folder.path() / "EU07-005.dat")); +} + +TEST_CASE("physicslog: the lines of a log whose file can't be written are kept, with its header, for the next try") { + log_folder folder{"failed"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + // a folder in the way of the file: it can't be opened, as one held by another program + std::filesystem::create_directories(folder.path() / "EU07-005.dat"); + logs.begin("EU07-005", header); + logs.append("EU07-005", "0.0500 0.0000\r\n"); + logs.flush(); + logs.append("EU07-005", "0.1000 0.5000\r\n"); + logs.flush(); + CHECK(std::filesystem::is_directory(folder.path() / "EU07-005.dat")); + + std::filesystem::remove(folder.path() / "EU07-005.dat"); + logs.append("EU07-005", "0.1500 1.0000\r\n"); + logs.flush(); + CHECK(folder.read("EU07-005") == std::string{header} + "0.0500 0.0000\r\n0.1000 0.5000\r\n0.1500 1.0000\r\n"); +} + +TEST_CASE("physicslog: a log whose file can't be written keeps the lines given as values too, in the order given with the text") { + log_folder folder{"failedvalues"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + physicslog_values first; + first.time = 0.05; + physicslog_values second; + second.time = 0.10; + physicslog_values last; + last.time = 0.20; + std::filesystem::create_directories(folder.path() / "EU07-008.dat"); + logs.begin("EU07-008", header); + logs.append("EU07-008", first); + logs.flush(); + // given while the file can't be written: after the lines kept, as text and as values + logs.append("EU07-008", second); + logs.append("EU07-008", "text\r\n"); + logs.append("EU07-008", last); + logs.flush(); + CHECK(std::filesystem::is_directory(folder.path() / "EU07-008.dat")); + + std::filesystem::remove(folder.path() / "EU07-008.dat"); + logs.flush(); + auto const text{folder.read("EU07-008")}; + CHECK(text.starts_with(std::string{header} + "0.0500 ")); + CHECK(text.find("\r\n0.1000 ") != std::string::npos); + CHECK(text.find("\r\ntext\r\n0.2000 ") != std::string::npos); + CHECK(text.find("0.1000 ") < text.find("\r\ntext\r\n")); +} + +TEST_CASE("physicslog: the logs put first are written before the others, each in the order of the names") { + // the logs of a writing as the writer has them, by their names + std::map taken{{"EN57-1001", 0}, {"EU07-005", 0}, {"SM42-002", 0}, {"ST44-001", 0}, {"ET22-001", 0}}; + std::vector *> order; + for (auto &log : taken) + order.push_back(&log); + physicslog_writer::writing_order(order, {"ST44-001", "SM42-002", "SP42-001"}); + std::vector names; + for (auto const *log : order) + names.push_back(log->first); + CHECK(names == std::vector{"SM42-002", "ST44-001", "EN57-1001", "ET22-001", "EU07-005"}); +} + +TEST_CASE("physicslog: a log put first is written as the others are") { + log_folder folder{"first"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + logs.put_first("SM42-002"); + logs.begin("EU07-005", header); + logs.append("EU07-005", "0.0500 0.0000\r\n"); + logs.begin("SM42-002", header); + logs.append("SM42-002", "0.0500 1.0000\r\n"); + logs.flush(); + CHECK(folder.read("EU07-005") == std::string{header} + "0.0500 0.0000\r\n"); + CHECK(folder.read("SM42-002") == std::string{header} + "0.0500 1.0000\r\n"); +} + +TEST_CASE("physicslog: a log begun anew while its file can't be written drops what was kept for it") { + log_folder folder{"failedbegun"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + std::filesystem::create_directories(folder.path() / "SU45-001.dat"); + logs.begin("SU45-001", header); + logs.append("SU45-001", "0.0500 0.0000\r\n"); + logs.flush(); + std::filesystem::remove(folder.path() / "SU45-001.dat"); + logs.begin("SU45-001", header); + logs.append("SU45-001", "0.0500 2.0000\r\n"); + logs.flush(); + CHECK(folder.read("SU45-001") == std::string{header} + "0.0500 2.0000\r\n"); +} + +TEST_CASE("physicslog: a log whose file can't be written doesn't keep the others from theirs") { + log_folder folder{"failedother"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + std::filesystem::create_directories(folder.path() / "EU07-006.dat"); + logs.begin("EU07-006", header); + logs.append("EU07-006", "0.0500 0.0000\r\n"); + logs.begin("EU07-007", header); + logs.append("EU07-007", "0.0500 1.0000\r\n"); + logs.flush(); + CHECK(std::filesystem::is_directory(folder.path() / "EU07-006.dat")); + CHECK(folder.read("EU07-007") == std::string{header} + "0.0500 1.0000\r\n"); +} + +TEST_CASE("physicslog: a vehicle named in the code page of its scenery has its log, whatever the code page of the system") { + log_folder folder{"codepage"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + // "SM42-Łódź" in 1250, as the sceneries have it: not UTF-8, which a Windows set to it would have thrown on + std::string const name{"SM42-\xA3\xF3" "d\x9F"}; // apart, or the d would be read as a digit of the \xF3 + logs.begin(name, header); + logs.append(name, "0.0500 0.0000\r\n"); + logs.flush(); + CHECK(logs.file(name).parent_path() == folder.path()); + CHECK(log_folder::read_file(logs.file(name)) == std::string{header} + "0.0500 0.0000\r\n"); +} + +TEST_CASE("physicslog: what no file name may have on Windows is replaced in the name of the file, on every system") { + log_folder folder{"filename"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + // a spawned vehicle's name has a ':', which on NTFS would write into a stream of the file "spawn_ezt" + CHECK(logs.file("spawn_ezt:12").filename() == "spawn_ezt_12.dat"); + CHECK(logs.file("ac\"d/e\\f|g?h*i\tj").filename() == "a_b_c_d_e_f_g_h_i_j.dat"); + CHECK(logs.file("EN57-1001 'a'.2").filename() == "EN57-1001 'a'.2.dat"); + // the devices of Windows, with an extension too, aren't files + CHECK(logs.file("nul").filename() == "_nul.dat"); + CHECK(logs.file("Com1.2").filename() == "_Com1.2.dat"); + CHECK(logs.file("con ").filename() == "_con .dat"); + CHECK(logs.file("console").filename() == "console.dat"); + CHECK(logs.file("com0").filename() == "com0.dat"); + CHECK(logs.shown("spawn_ezt:12") == folder.path().generic_string() + "/spawn_ezt_12.dat"); + + logs.begin("spawn_ezt:12", header); + logs.append("spawn_ezt:12", "0.0500 0.0000\r\n"); + logs.flush(); + CHECK(folder.read("spawn_ezt_12") == std::string{header} + "0.0500 0.0000\r\n"); + CHECK(false == std::filesystem::exists(folder.path() / "spawn_ezt")); +} + +TEST_CASE("physicslog: stopping twice, from two threads at once, writes once and ends") { + log_folder folder{"stoptwice"}; + physicslog_writer logs{folder.path(), std::chrono::milliseconds{20}}; + + logs.begin("EP09-001", header); + logs.append("EP09-001", "0.0500 0.0000\r\n"); + { + std::jthread other{[&logs] { logs.stop(); }}; + logs.stop(); + } + CHECK(folder.read("EP09-001") == std::string{header} + "0.0500 0.0000\r\n"); +} + +TEST_CASE("physicslog: a flush with a time limit writes, as flush does") { + log_folder folder{"flushfor"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + logs.begin("ET41-001", header); + logs.append("ET41-001", "0.0500 0.0000\r\n"); + CHECK(logs.flush_for(std::chrono::seconds{1})); + CHECK(folder.read("ET41-001") == std::string{header} + "0.0500 0.0000\r\n"); +} + +TEST_CASE("physicslog: what is kept is written when the writer goes") { + log_folder folder{"end"}; + { + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + logs.begin("ST44-001", header); + logs.append("ST44-001", "0.0500 0.0000\r\n"); + } + CHECK(folder.read("ST44-001") == std::string{header} + "0.0500 0.0000\r\n"); +} + +TEST_CASE("physicslog: a log written by someone else before is added to after what it holds") { + log_folder folder{"after"}; + std::filesystem::create_directories(folder.path()); + { + std::ofstream before{folder.path() / "SU45-001.dat"}; + before << "earlier run\n"; + } + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + logs.append("SU45-001", "0.0500 0.0000\r\n"); + logs.flush(); + logs.append("SU45-001", "0.1000 0.0000\r\n"); + logs.flush(); + CHECK(folder.read("SU45-001") == "earlier run\n0.0500 0.0000\r\n0.1000 0.0000\r\n"); +} + +TEST_CASE("physicslog: the writings go on every interval while they're quick, and less often once they take long") { + using namespace std::chrono_literals; + using duration = std::chrono::steady_clock::duration; + // quick: the interval + CHECK(physicslog_writer::wait_after(2000ms, duration{0}) == duration{2000ms}); + CHECK(physicslog_writer::wait_after(2000ms, duration{500ms}) == duration{2000ms}); + // a third of the interval: still the interval + CHECK(physicslog_writer::wait_after(2100ms, duration{700ms}) == duration{2100ms}); + // longer: three times the writing, the disk busy with the logs a quarter of the time + CHECK(physicslog_writer::wait_after(2000ms, duration{1s}) == duration{3s}); + CHECK(physicslog_writer::wait_after(2000ms, duration{3s}) == duration{9s}); + // five intervals at most, however long the writing took: the lines of a longer wait would make it longer still + CHECK(physicslog_writer::wait_after(2000ms, duration{4s}) == duration{10s}); + CHECK(physicslog_writer::wait_after(2000ms, duration{60s}) == duration{10s}); +} + +TEST_CASE("physicslog: a line given as its values is written as the stream of them always wrote it") { + log_folder folder{"values"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + physicslog_values line; + line.time = 0.05; + line.wheelspeed = 1.23456; + line.acceleration = -0.5; + line.mainctrl = 3; + line.direction = 1; + line.command = "ShuntVelocity"; + line.value1 = 40.0; + // a float of the vehicle, widened as the stream widened it + line.enginetemperature = 50.1f; + line.vehiclespeed = 36.0; + logs.begin("SM31-001", header); + logs.append("SM31-001", line); + logs.flush(); + CHECK(folder.read("SM31-001") == std::string{header} + + "0.0500 1.2346 -0.5000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 3 0 0.0000 0.0000 1 " + "ShuntVelocity 40.0000 0.0000 0 0 50.1000 0.0000 0.0000 0.0000 36.0000\r\n"); +} + +TEST_CASE("physicslog: lines given as values and as text are written in the order given") { + log_folder folder{"order"}; + physicslog_writer logs{folder.path(), std::chrono::hours{1}}; + + physicslog_values first; + first.time = 0.05; + physicslog_values last; + last.time = 0.15; + logs.append("EP09-001", first); + logs.append("EP09-001", "text\r\n"); + logs.append("EP09-001", last); + logs.flush(); + auto const text{folder.read("EP09-001")}; + CHECK(text.starts_with("0.0500 ")); + CHECK(text.find("\r\ntext\r\n0.1500 ") != std::string::npos); +} diff --git a/tests/unit/test_utilities.cpp b/tests/unit/test_utilities.cpp index 11acb9b8f..48d10e8b1 100644 --- a/tests/unit/test_utilities.cpp +++ b/tests/unit/test_utilities.cpp @@ -578,6 +578,56 @@ TEST_CASE("utilities: a file is found by its name in another case") { CHECK(FileCased("eu07_unit_test_no_such_file.xyz").empty()); } +TEST_CASE("utilities: a file is found in folders named in another case, the way the parser gives the names in lowercase") { + test::scratch_folder const folder{"utilities_cased_folders"}; + folder.write("Scenery/Braniewo/rozklady/Os91121.txt", "x"); + folder.write("Textures/Tabl/L101-2m.BMP", "x"); + + // every part of the path in lowercase: the file as it's on the disk where the case matters, the name given where it doesn't + auto const timetable{FileCased(folder.path("scenery/braniewo/rozklady/os91121.txt"))}; + REQUIRE_FALSE(timetable.empty()); + CHECK(std::filesystem::exists(timetable)); + CHECK(ToLower(timetable) == ToLower(folder.path("Scenery/Braniewo/rozklady/Os91121.txt"))); + CHECK(FileOnDisk(folder.path("scenery/braniewo/rozklady/os91121.txt")) == timetable); + // the folders written the Windows way as well + CHECK_FALSE(FileCased(folder.path() + "scenery\\braniewo\\rozklady\\os91121.txt").empty()); + // a folder missing in any case + CHECK(FileCased(folder.path("scenery/nowhere/rozklady/os91121.txt")).empty()); + CHECK(FileOnDisk(folder.path("scenery/nowhere/rozklady/os91121.txt")) == folder.path("scenery/nowhere/rozklady/os91121.txt")); + + // among names and extensions: found in any case, given back as named, the name being the key of the banks + auto const texture{FileExists(std::vector{folder.path("textures/tabl/l101-2m")}, std::vector{".dds", ".bmp"})}; + REQUIRE_FALSE(texture.first.empty()); + CHECK(texture.first == folder.path("textures/tabl/l101-2m")); + CHECK(texture.second == ".bmp"); + CHECK(std::filesystem::exists(FileOnDisk(texture.first + texture.second))); + + // a file written after the folder was gone through is found as well + CHECK(FileCased(folder.path("textures/tabl/l7-2m.bmp")).empty()); + folder.write("Textures/Tabl/L7-2m.bmp", "x"); + auto const added{FileCased(folder.path("textures/tabl/l7-2m.bmp"))}; + REQUIRE_FALSE(added.empty()); + CHECK(std::filesystem::exists(added)); +} + +TEST_CASE("utilities: a terrain file is found in another case, by its text or by its binary file") { + test::scratch_folder const folder{"utilities_cased_terrain"}; + folder.write("Scenery/L204/Teren/Woda_ter.txtf", "x"); + folder.write("Scenery/Nmt/Gory_ter.btf", "x"); + auto const scenery{folder.path("Scenery/")}; + std::vector const extensions{".txtf", ".btf"}; + + // the name as the parser gives it: the files are there under the name given back, which differs only in case + auto const text{FileStemOnDisk(scenery, "l204/teren/woda_ter", extensions)}; + CHECK(ToLower(text) == "l204/teren/woda_ter"); + CHECK(std::filesystem::exists(scenery + text + ".txtf")); + auto const binary{FileStemOnDisk(scenery, "nmt/gory_ter", extensions)}; + CHECK(ToLower(binary) == "nmt/gory_ter"); + CHECK(std::filesystem::exists(scenery + binary + ".btf")); + // neither file in any case: the name stays as given + CHECK(FileStemOnDisk(scenery, "nmt/nowhere_ter", extensions) == "nmt/nowhere_ter"); +} + TEST_CASE("utilities: the time a file was changed is given, zero for a file which isn't there") { test::scratch_folder const folder{"utilities_modified"}; auto const name{folder.write("fresh.txt", "x")}; diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index c6816f850..90c206dfa 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -381,6 +381,8 @@ bool global_settings::ConfigParseGraphics(cParser& Parser, const std::string& to if (token == "gfxrenderer") { ParseOne(Parser, GfxRenderer); + // read in any case, as the starter does: "Legacy" written by hand is the legacy renderer + GfxRenderer = ToLower(GfxRenderer); if (GfxRenderer == "full") GfxRenderer = "default"; @@ -605,9 +607,18 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + // the physics logs of the trains only, of the drivers of rail vehicles; "physicslog yes" writes them all anyway + if (token == "physicslog.trains") + { + ParseOne(Parser, WriteTrainLogFlag); + return true; + } + if (token == "blackbox") { - ParseOne(Parser, BlackBox); + bool blackbox{false}; + ParseOne(Parser, blackbox); + BlackBox = blackbox; return true; } @@ -1872,7 +1883,10 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "sound.efx.lowpass", AudioLowpass ); export_as_text( Output, "sound.efx.airabsorption", AudioAirAbsorption ); export_as_text( Output, "physicslog", WriteLogFlag ); - export_as_text( Output, "blackbox", BlackBox ); + export_as_text( Output, "physicslog.trains", WriteTrainLogFlag ); + if( BlackBox ) { + export_as_text( Output, "blackbox", *BlackBox ); + } export_as_text( Output, "fullphysics", FullPhysics ); export_as_text( Output, "debuglog", iWriteLogEnabled ); export_as_text( Output, "multiplelogs", MultipleLogs ); diff --git a/utilities/Globals.h b/utilities/Globals.h index 7bb2833bc..ceb9948c4 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -119,7 +119,9 @@ struct global_settings { bool priorityLoadText3D{false}; // ladowanie T3D priorytetowo int iWriteLogEnabled{ 3 }; // maska bitowa: 1-zapis do pliku, 2-okienko, 4-nazwy torów bool MultipleLogs{ false }; - bool BlackBox{ true }; // with the physics logs on, the black box of the session is written as well (blackbox_doc.md) + // the black box of the session (blackbox_doc.md): "blackbox yes" writes it whatever the physics logs, "blackbox no" + // never, and with no entry it is written along with the physics logs + std::optional BlackBox; bool ShowSystemConsole{ false }; // toggle visibility of the OS console window with log output unsigned int DisabledLogTypes{ 0 }; bool ParserLogIncludes{ true }; diff --git a/utilities/physicslog.cpp b/utilities/physicslog.cpp new file mode 100644 index 000000000..d37ea69e7 --- /dev/null +++ b/utilities/physicslog.cpp @@ -0,0 +1,491 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "utilities/physicslog.h" +#include "utilities/Logs.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__linux__) +#include +#include +#endif + +physicslog_writer PhysicsLogs; + +namespace { + +// the most of all the logs kept while their files can't be written, shared by those, a log never less than the +// least: the oldest lines go beyond it +constexpr std::size_t keptwhilefailing{64 * 1024 * 1024}; +constexpr std::size_t keptwhilefailingleast{64 * 1024}; + +// the text cut to its last lines within Most +void keep_last(std::string &Text, std::size_t const Most) { + if (Text.size() <= Most) + return; + auto const cut{Text.find('\n', Text.size() - Most)}; + Text.erase(0, cut == std::string::npos ? Text.size() : cut + 1); +} + +// the name of the file of the log Name, its extension too. what no file name may have on Windows is replaced, on every +// system, so the logs are named alike everywhere: a spawned vehicle is named :, and on NTFS "a:1.dat" +// isn't even an error but the stream 1.dat of the file a, which nothing lists +std::string file_name(std::string const &Name) { + std::string name{Name}; + for (auto &character : name) { + if (static_cast(character) < 0x20 || std::string_view{R"(<>:"/\|?*)"}.find(character) != std::string_view::npos) + character = '_'; + } + // a device rather than a file, with any extension: con.dat is the console. told by the name before its first dot + auto stem{name.substr(0, name.find('.'))}; + while (false == stem.empty() && stem.back() == ' ') + stem.pop_back(); + std::ranges::transform(stem, stem.begin(), [](unsigned char const Character) { return static_cast(std::toupper(Character)); }); + auto const numbered{stem.size() == 4 && (stem.starts_with("COM") || stem.starts_with("LPT")) && stem[3] >= '1' && stem[3] <= '9'}; + if (numbered || stem == "CON" || stem == "PRN" || stem == "AUX" || stem == "NUL") + name.insert(0, 1, '_'); + return name + ".dat"; +} + +// told in the log of the simulator, if there's the memory for it +void tell(std::string const &Text) noexcept { + try { + ErrorLog(Text); + } catch (...) { + // out of memory for a line of the log too: nothing more to be done about it + } +} + +// the disk work of the calling thread after everyone else's: the simulation reading its textures and sounds, and the +// pages of its memory, from the same disk doesn't wait behind the logs, which on a hard disk are seconds of seeking +// when there are hundreds of them +void lower_disk_priority() noexcept { +#ifdef _WIN32 + // the background mode: the thread's disk work at the very low priority, its memory pages the first to be let go of + // and, the documentation doesn't say, maybe its processor time lower too. a disk the simulation keeps busy without a + // pause serves the logs slowly then, the more lines waiting in memory meanwhile; a game reads in bursts, not without + // end. a thread which can't have it writes as it did before + static_cast(::SetThreadPriority(::GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN)); +#elif defined(__linux__) && defined(SYS_ioprio_set) + // the lowest of the best effort class rather than the idle one, which a disk always busy would never serve: the + // lines would be kept in memory with no end. the constants of linux/ioprio.h, which not every system has + constexpr int whothread{1}; // IOPRIO_WHO_PROCESS, of the calling thread with 0 + constexpr int classbesteffort{2}; + constexpr int classshift{13}; + constexpr int lowest{7}; + static_cast(::syscall(SYS_ioprio_set, whothread, 0, (classbesteffort << classshift) | lowest)); +#endif +} + +} // namespace + +void physicslog_values::append_to(std::string &Text) const { + std::ostringstream line; + line << std::fixed << std::setprecision(4) << time << " " << wheelspeed << " " << acceleration << " " << couplerdistance << " " << couplerforce << " " + << tractionforce << " " << frictionforce << " " << brakeforce << " " << brakepressure << " " << pipepressure << " " << motorcurrent << " " + << mainctrl << " " << scndctrl << " " << brakectrl << " " << localbrake << " " << direction << " " << command << " " << value1 << " " + << value2 << " " << security << " " << wheelslip << " " << enginetemperature << " " << oiltemperature << " " << watertemperature << " " + << wateraux << " " << vehiclespeed << "\r\n"; + Text.append(line.str()); +} + +void physicslog_writer::pending::to_text() { + if (values.empty()) + return; + // made aside and added at once: a text which can't be made, out of memory, leaves the log as it was + std::string lines; + for (auto const &line : values) + line.append_to(lines); + text.append(lines); + values.clear(); +} + +physicslog_writer::physicslog_writer(std::filesystem::path Folder, std::chrono::milliseconds const Interval, std::chrono::milliseconds const ClosingWait) : + m_folder{std::move(Folder)}, m_shownfolder{m_folder.generic_string()}, m_interval{Interval}, m_closingwait{ClosingWait} {} + +physicslog_writer::~physicslog_writer() { + try { + stop(); + // the writings left behind by the stops use the object, which goes + std::vector> closings; + { + std::scoped_lock lock{m_mutex}; + closings.swap(m_closings); + } + for (auto const &closing : closings) + closing.wait(); + } catch (...) { + // at the end of the process: what the logs couldn't keep, memory or a file, isn't to end it worse + } +} + +void physicslog_writer::begin(std::string const &Name, std::string_view const Header) { + std::scoped_lock lock{m_mutex}; + auto &lines{m_pending[Name]}; + lines.fresh = true; + lines.header.assign(Header); + lines.text.clear(); + lines.values.clear(); + start(); +} + +void physicslog_writer::append(std::string const &Name, std::string_view const Line) { + std::scoped_lock lock{m_mutex}; + auto &lines{m_pending[Name]}; + // after the lines given as values before it + lines.to_text(); + lines.text.append(Line); + start(); +} + +void physicslog_writer::append(std::string const &Name, physicslog_values Values) { + std::scoped_lock lock{m_mutex}; + m_pending[Name].values.push_back(std::move(Values)); + start(); +} + +void physicslog_writer::put_first(std::string const &Name) { + std::scoped_lock lock{m_mutex}; + m_first.insert(Name); +} + +void physicslog_writer::flush() { + std::scoped_lock files{m_filemutex}; + write(writing::flush); +} + +bool physicslog_writer::flush_for(std::chrono::milliseconds const Timeout) { + // on a thread of its own, left behind if it doesn't end in time: a disk which doesn't answer holds it up in the + // writing, not only the lock. for the end of the process, which doesn't wait for it + auto done{std::make_shared>()}; + auto ended{done->get_future()}; + std::thread([this, done] { + flush_safely(writing::flush); + done->set_value(); + }).detach(); + return ended.wait_for(Timeout) == std::future_status::ready; +} + +void physicslog_writer::stop() { + std::jthread thread; + bool itself; + closing_time closeby; + { + std::scoped_lock lock{m_mutex}; + m_stopped = true; + // taken by the first to stop, so it's joined once + thread = std::move(m_thread); + itself = m_writer == std::this_thread::get_id(); + // the time the closing's writing has: the logs not written by then are dropped. a writing the thread has begun + // ends at the log at hand, leaving the others to it + closeby = closing_begun(); + } + // the stop asked outside the lock, which waking the writer takes + if (thread.joinable()) + thread.request_stop(); + // stopped from the writer itself, by the end of a run which failed in it: the files may be held by it + if (itself) { + if (thread.joinable()) + thread.detach(); + return; + } + if (close_aside(thread, closeby)) + return; + // no thread for it, out of memory say: written here, the logs past the time dropped all the same + if (thread.joinable()) + thread.join(); + flush_safely(writing::closing); +} + +physicslog_writer::closing_time physicslog_writer::closing_begun() { + std::erase_if(m_closings, [](std::shared_future const &Closing) { return Closing.wait_for(std::chrono::seconds{0}) == std::future_status::ready; }); + // a closing not done yet keeps its time: a stop after it (the simulator stops the logs twice) doesn't wait the + // longer, nor give the writing of the first more of it + if (auto const before{m_closeby.load()}; before != 0 && false == m_closings.empty()) + return {std::chrono::steady_clock::time_point{std::chrono::steady_clock::duration{before}}, false}; + auto const closeby{std::chrono::steady_clock::now() + m_closingwait}; + m_closeby = closeby.time_since_epoch().count(); + return {closeby, true}; +} + +bool physicslog_writer::close_aside(std::jthread &Thread, closing_time const Closeby) noexcept { + // the thread ended and the rest written on a thread of its own, left behind if it isn't done in time: a disk which + // doesn't answer holds up the writing of a file, which no time given cuts short. the simulator ends with _Exit then, + // the writing with it + auto started{false}; + try { + auto done{std::make_shared>()}; + std::shared_future const closing{done->get_future()}; + { + std::scoped_lock lock{m_mutex}; + m_closings.push_back(closing); + } + // the writer moved into the lambda: if its thread can't be started, the writer is ended (joined) with it + std::thread([this, done, writer = std::move(Thread)]() mutable { + if (writer.joinable()) + writer.join(); + flush_safely(writing::closing); + done->set_value(); + }).detach(); + started = true; + // told by the stop which gave the time, not again by one after it + if (closing.wait_until(Closeby.by) != std::future_status::ready && Closeby.fresh) + tell(std::format("Bad physics log: the closing doesn't wait for the writing longer than {:.1f} s, the logs not written by then are lost", + std::chrono::duration{m_closingwait}.count())); + return true; + } catch (...) { + // out of memory, or no thread to be had: the writer, if it wasn't moved, is ended by the caller. a thread begun + // already, the line of the log failing after it, does the writing: not the caller as well, which would wait for it + return started; + } +} + +std::filesystem::path physicslog_writer::file(std::string const &Name) const { + auto const name{file_name(Name)}; +#ifdef _WIN32 + // in the code page of the system, as the standard library would convert it, but with the bytes not of it replaced + // instead of an exception thrown: a vehicle of a scenery written in 1250 on a Windows set to UTF-8, say + auto const size{static_cast(name.size())}; + std::wstring wide(static_cast(::MultiByteToWideChar(CP_ACP, 0, name.data(), size, nullptr, 0)), L'\0'); + ::MultiByteToWideChar(CP_ACP, 0, name.data(), size, wide.data(), static_cast(wide.size())); + return m_folder / wide; +#else + // the bytes are the name of the file as they are + return m_folder / name; +#endif +} + +std::string physicslog_writer::shown(std::string const &Name) const { + return m_shownfolder + '/' + file_name(Name); +} + +std::chrono::steady_clock::duration physicslog_writer::wait_after(std::chrono::milliseconds const Interval, std::chrono::steady_clock::duration const Took) { + // no longer than five intervals: the lines of a longer wait would make the next writing take the longer still, the + // waits growing with no end, and a crash would lose more of them + return std::clamp(Took * 3, Interval, Interval * 5); +} + +void physicslog_writer::start() { + if (m_stopped || m_thread.joinable()) + return; + m_thread = std::jthread([this](std::stop_token const &Stop) { run(Stop); }); + m_writer = m_thread.get_id(); +} + +void physicslog_writer::run(std::stop_token const &Stop) { + lower_disk_priority(); + // woken by every stop asked, by stop() or by the end of the thread itself. the lock taken once first: the writer is + // either about to wait, and sees the stop, or waiting already + std::stop_callback const wake{Stop, [this] { + { std::scoped_lock lock{m_mutex}; } + m_wake.notify_all(); + }}; + std::chrono::steady_clock::duration wait{m_interval}; + while (false == Stop.stop_requested()) { + { + std::unique_lock lock{m_mutex}; + // woken early only to stop, which writes the rest itself + if (m_wake.wait_for(lock, wait, [&Stop] { return Stop.stop_requested(); })) + return; + } + auto const start{std::chrono::steady_clock::now()}; + // a stop come meanwhile ends the writing at the log at hand, the others left to the closing's + auto const logs{flush_safely(writing::thread)}; + auto const took{std::chrono::steady_clock::now() - start}; + wait = wait_after(m_interval, took); + if (wait > m_interval && false == m_slowtold) { + m_slowtold = true; + using seconds = std::chrono::duration; + try { + WriteLog(std::format("Physics logs: writing {} of them took {:.1f} s, over a third of the {:.1f} s between writings; they're " + "written less often from now on, every {:.1f} s at most", + logs, seconds{took}.count(), seconds{m_interval}.count(), seconds{m_interval * 5}.count())); + } catch (...) { + // out of memory for a line of the log: the logs are written all the same + } + } + } +} + +std::size_t physicslog_writer::flush_safely(writing const Mode) noexcept { + try { + std::scoped_lock files{m_filemutex}; + return write(Mode); + } catch (std::exception const &Error) { + tell(std::string{"Bad physics log: the writing failed ("} + Error.what() + "), the lines taken for it are lost"); + } catch (...) { + tell("Bad physics log: the writing failed, the lines taken for it are lost"); + } + return 0; +} + +bool physicslog_writer::past_closing() const { + auto const closeby{m_closeby.load()}; + return closeby != 0 && std::chrono::steady_clock::now().time_since_epoch().count() >= closeby; +} + +void physicslog_writer::keep(std::map &Failed, std::vector *> const &Left) { + // cut before the lock, which the simulation waits on to give its lines: only what came since is added under it + auto const most{std::max(keptwhilefailingleast, keptwhilefailing / std::max(Failed.size(), 1))}; + for (auto &[name, lines] : Failed) { + // the values the writing failed to make into text, out of memory say, made into it again, before the lock: as + // text they go before what came since + try { + lines.to_text(); + } catch (std::exception const &) { + // kept as values, below + } + keep_last(lines.text, most); + } + // tried again the next time, before what came since; a file held by another program for a while doesn't lose + // them, nor its header + std::scoped_lock lock{m_mutex}; + for (auto &[name, lines] : Failed) + put_back(name, lines); + for (auto *log : Left) + put_back(log->first, log->second); +} + +void physicslog_writer::put_back(std::string const &Name, pending &Lines) { + auto &now{m_pending[Name]}; + // a log begun anew since drops them + if (now.fresh) + return; + // the lines in the order given: those kept, then those come since, as text and as values. values kept before text + // come since are made into text first, as those before a line given as text are; values which can't be, out of + // memory, are dropped then, as the order can't be kept otherwise + if (false == now.text.empty() && false == Lines.values.empty()) { + try { + Lines.to_text(); + } catch (std::exception const &) { + Lines.values.clear(); + } + } + Lines.text.append(now.text); + // added at once, allocated first: one failing moves none of them + if (Lines.values.empty()) + Lines.values = std::move(now.values); + else + Lines.values.insert(Lines.values.end(), std::make_move_iterator(now.values.begin()), std::make_move_iterator(now.values.end())); + now = std::move(Lines); +} + +std::size_t physicslog_writer::write(writing const Mode) { + std::map taken; + std::set first; + std::vector *> order; + { + std::scoped_lock lock{m_mutex}; + if (m_pending.empty()) + return 0; + // a stop come before the thread's writing: the lines are all the closing's, left as they are + if (Mode == writing::thread && m_closeby.load() != 0) + return 0; + // had before the lines are taken: without the memory for it they're left for the next writing + first = m_first; + order.reserve(m_pending.size()); + taken.swap(m_pending); + } + auto const logs{taken.size()}; + std::error_code error; + std::filesystem::create_directories(m_folder, error); + std::ranges::transform(taken, std::back_inserter(order), [](auto &Log) { return &Log; }); + writing_order(order, first); + std::map failed; + std::size_t dropped{0}; + std::size_t reached{0}; + for (auto *log : order) { + // a stop come while the thread writes: the logs it hasn't come to are left to the closing's writing, which has + // them with the lines given since, those put first first + if (Mode == writing::thread && m_closeby.load() != 0) + break; + ++reached; + auto &[name, lines]{*log}; + // past the time the closing gives the writing: dropped, as the closing doesn't wait for it any longer + if (Mode == writing::closing && past_closing()) { + ++dropped; + continue; + } + if (false == write_taken(name, lines)) + failed.emplace(name, std::move(lines)); + } + if (dropped > 0) + tell(std::format("Bad physics log: {} of them not written, past the {:.1f} s the closing waits for them", dropped, + std::chrono::duration{m_closingwait}.count())); + // what is left of the order: the logs the thread hasn't come to + order.erase(order.begin(), order.begin() + static_cast(reached)); + if (false == failed.empty() || false == order.empty()) + keep(failed, order); + return logs; +} + +bool physicslog_writer::write_taken(std::string const &Name, pending &Lines) { + // a log going wrong otherwise, out of memory say, is kept for the next try as one whose file can't be written: + // the others are written still, and the writer goes on + auto written{false}; + std::string problem{"can't write"}; + try { + // the text of the lines given as values, here on the writer's thread rather than the simulation's + Lines.to_text(); + if (Lines.text.empty() && false == Lines.fresh) + return true; + written = write_log(Name, Lines); + } catch (std::exception const &Error) { + problem = std::string{"failed ("} + Error.what() + ") to write"; + } + if (written) { + if (m_failed.erase(Name) > 0) + WriteLog("Physics log: " + shown(Name) + " written again"); + return true; + } + if (m_failed.insert(Name).second) + ErrorLog("Bad physics log: " + problem + " " + shown(Name) + ", its last lines are kept for the next try"); + return false; +} + +bool physicslog_writer::write_log(std::string const &Name, pending const &Lines) const { + auto const path{file(Name)}; + // one write to the file: the header of a log begun with its lines, not the one after the other + std::string begun; + if (Lines.fresh) + begun = Lines.header + Lines.text; + std::string_view const text{Lines.fresh ? std::string_view{begun} : std::string_view{Lines.text}}; + // in text mode, as the logs were always written: on Windows their lines, which end with "\r\n", end with "\r\r\n". + // a log added to is opened at its end (ate), and where that is, its length, is what it's cut back to if the lines + // are written in part only, a disk filling up say: else they'd be written twice, the next time. the disk isn't + // asked for the length before, one access less of hundreds of logs + std::ofstream stream{path, Lines.fresh ? std::ios::out | std::ios::trunc : std::ios::out | std::ios::app | std::ios::ate}; + if (false == stream.is_open()) + return false; + auto const before{Lines.fresh ? std::streamoff{0} : static_cast(stream.tellp())}; + stream.write(text.data(), static_cast(text.size())); + stream.close(); + if (false == stream.fail()) + return true; + // a log begun is written anew from its header the next time anyway + if (false == Lines.fresh && before >= 0) { + std::error_code error; + std::filesystem::resize_file(path, static_cast(before), error); + } + return false; +} diff --git a/utilities/physicslog.h b/utilities/physicslog.h new file mode 100644 index 000000000..286df7e87 --- /dev/null +++ b/utilities/physicslog.h @@ -0,0 +1,189 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// a line of a driver's physics log as its values, taken as the simulation goes and made into text by the thread which +// writes the logs: the text, a stream of 26 values, is what a line costs, and the drivers of a big scenery give twenty +// lines a second each. the columns as physicslog_header of the driver names them +struct physicslog_values { + double time{0.0}; + double wheelspeed{0.0}; + double acceleration{0.0}; + double couplerdistance{0.0}; + double couplerforce{0.0}; + double tractionforce{0.0}; + double frictionforce{0.0}; + double brakeforce{0.0}; + double brakepressure{0.0}; + double pipepressure{0.0}; + double motorcurrent{0.0}; + int mainctrl{0}; + int scndctrl{0}; + double brakectrl{0.0}; + double localbrake{0.0}; + int direction{0}; + std::string command; + double value1{0.0}; + double value2{0.0}; + int security{0}; + int wheelslip{0}; + double enginetemperature{0.0}; + double oiltemperature{0.0}; + double watertemperature{0.0}; + double wateraux{0.0}; + double vehiclespeed{0.0}; + + // the line, as the logs always had it, at the end of Text + void append_to(std::string &Text) const; +}; + +// the physics logs, /.dat, what no file name may have on Windows replaced in the name (a spawned vehicle's +// has a ':'), the same on every system. the lines given are kept, and written every two seconds by a thread of its own, +// each file opened only for the moment it is written to: the logs of hundreds of vehicles hold no files open, and the +// simulation doesn't wait for the disk. a crash loses the last two seconds of real time of them, up to ten on a disk +// which can't keep up (below). lines whose file can't be written, held by another program say, are kept for the next +// try: the last 64 MB of them all at most. the thread's disk work goes after everyone else's, and a disk slower than the +// logs need (a hard disk, hundreds of them) gets them less often, so the simulation reading from it doesn't wait behind +// them. the closing waits for the writing a second at most (below) +class physicslog_writer { +public: + explicit physicslog_writer(std::filesystem::path Folder = "physicslog", std::chrono::milliseconds Interval = std::chrono::seconds{2}, + std::chrono::milliseconds ClosingWait = std::chrono::seconds{1}); + physicslog_writer(physicslog_writer const &) = delete; + physicslog_writer &operator=(physicslog_writer const &) = delete; + // stops, writing what is kept, and waits for the writings a stop left behind: the object goes. the simulator's, + // global, never goes this way: the process ends with _Exit + ~physicslog_writer(); + + // starts the log Name anew: its file is emptied and Header written into it, the next time the logs are written. + // the lines of it not written yet are dropped + void begin(std::string const &Name, std::string_view Header); + // Line at the end of the log Name. a log not begun is added to as its file stands + void append(std::string const &Name, std::string_view Line); + // the same, a line of the values, made into text by the writer's thread when it writes the log + void append(std::string const &Name, physicslog_values Values); + // the log Name written before the others, at each writing: the logs of the vehicles the user was in, and of the + // tested trains, which a closing short of time would otherwise drop by the order of their names + void put_first(std::string const &Name); + // writes what is kept, now + void flush(); + // as flush, waited for no longer than Timeout: then false, and the writing goes on by itself, on a thread left + // behind. for the end of the process, the files held up or the disk not answering + bool flush_for(std::chrono::milliseconds Timeout); + // writes what is kept and ends the thread, waiting for it ClosingWait at most: the logs whose turn hasn't come by + // then are dropped, and the writing of the one at hand (a disk not answering) is left behind, going on by itself. a + // writing of the thread under way ends at the log at hand, leaving the others to the closing's, which has them with + // the lines given since, those put first first. what is given after is written by a flush, or by the next stop + void stop(); + // the file of the log Name: /.dat, with < > : " / \ | ? * and the control characters of the name + // replaced by _, and _ before a name Windows keeps for a device (con, nul, com1...). the bytes of the code page of a + // scenery (1250) stay as they are, also on a Windows set to UTF-8, where the standard library would throw making a + // path of them: there they become U+FFFD + std::filesystem::path file(std::string const &Name) const; + // the same, for the log of the simulator + std::string shown(std::string const &Name) const; + // the wait of the thread before its next writing, after one which took Took: the interval, or three times as long + // as the writing was when that's longer, five intervals at most. a disk which can't keep up is then busy with the + // logs a quarter of the time rather than all of it, and their lines wait in memory the longer + static std::chrono::steady_clock::duration wait_after(std::chrono::milliseconds Interval, std::chrono::steady_clock::duration Took); + // the logs taken for a writing, pointers to the entries of a map by their names, put in the order they're written: + // those put first (First) before the others, each in the order they were + template static void writing_order(std::vector &Logs, std::set const &First) { + std::ranges::stable_partition(Logs, [&First](Log const *Each) { return First.contains(Each->first); }); + } + +private: + // a writing: a flush; the thread's, which a stop ends at the log at hand, leaving the others to the closing's; or the + // closing's, which drops the logs past the time the stop gives it + enum class writing { flush, thread, closing }; + + // the end of the time a stop gives the writing. fresh: given by this stop, not by one before it still under way + struct closing_time { + std::chrono::steady_clock::time_point by; + bool fresh{true}; + }; + + struct pending { + bool fresh{false}; // its file is to be emptied first, and the header written into it + std::string header; + std::string text; + // the lines given as values since, after the text: made into text when written + std::vector values; + + // the lines of the values at the end of the text + void to_text(); + }; + + // the time of a stop: the one of a closing still under way, if there's one. called with m_mutex held + closing_time closing_begun(); + // the writer ended and the rest written by a thread of its own, waited for until Closeby. returns: false if no + // thread could be had for it, out of memory say; Thread may be the writer still then + bool close_aside(std::jthread &Thread, closing_time Closeby) noexcept; + // the thread, on the first line given, unless stopped. called with m_mutex held + void start(); + void run(std::stop_token const &Stop); + // as flush, letting nothing out: on the writer's thread, or at the end of the process, an exception would end the + // simulator. what was taken for a writing which failed as a whole is lost, the next one goes on with what came since. + // returns: the number of logs there were to write + std::size_t flush_safely(writing Mode) noexcept; + // called with m_filemutex held. returns: the number of logs there were to write + std::size_t write(writing Mode); + // the log Name taken for a writing written into its file, the problem told once if it can't be. returns: false if + // it wasn't, its lines to be kept for the next try + bool write_taken(std::string const &Name, pending &Lines); + // whether the time a stop gave the writing is over + bool past_closing() const; + // the logs taken for a writing and not written kept for the next, before what came since, their values too: Failed, + // whose file couldn't be written, cut to their last lines, and Left, which a stop left to the closing's writing, as + // they were taken: their values are made into text by that writing, which drops them past its time, not on the way + // unless text was given since + void keep(std::map &Failed, std::vector *> const &Left); + // Lines of the log Name, taken for a writing, put back before the lines given since. called with m_mutex held + void put_back(std::string const &Name, pending &Lines); + // the lines of the log Name written into its file. returns: true if they all were + bool write_log(std::string const &Name, pending const &Lines) const; + + std::filesystem::path const m_folder; + std::string const m_shownfolder; + std::chrono::milliseconds const m_interval; + std::chrono::milliseconds const m_closingwait; + // the end of the time the last stop gave the writing, of the steady clock; 0 before the first stop + std::atomic m_closeby{0}; + std::mutex m_mutex; // the lines kept and the thread + std::map m_pending; + std::set m_first; // the logs put first + bool m_stopped{false}; + std::condition_variable m_wake; + std::jthread m_thread; + std::thread::id m_writer; // of the thread, kept after it is taken to be joined: the writer knows itself by it + std::vector> m_closings; // the writings of the stops, which may outlast them + std::mutex m_filemutex; // the files are written one batch at a time, so the lines of a log stay in order + std::set m_failed; // the logs whose file couldn't be written, told once + bool m_slowtold{false}; // the writings were told to take longer than the interval allows, once; the thread's own +}; + +// the physics logs of the drivers (physicslog yes), and those the black box writes of the user's vehicles +extern physicslog_writer PhysicsLogs; diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index 238e276f5..edc694852 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -633,6 +633,140 @@ bool FileExists(std::string const &Filename) return std::filesystem::exists(Filename); } +#ifndef _WIN32 +namespace +{ + +// the names in a folder by their lowercase, the time the folder was changed and the time they were read +struct cased_folder +{ + bool read{false}; + std::filesystem::file_time_type changed{}; + std::filesystem::file_time_type listed{}; + // when the time of the change was last looked at + std::chrono::steady_clock::time_point checked{}; + std::unordered_map names; +}; + +std::mutex cased_mutex; +std::unordered_map cased_folders; +// a folder by the name it's given with (parts split by '/', a '/' at the end): as it's named on the disk, or missing in any case +// since the time given +struct cased_path +{ + std::string name; + bool missing{false}; + std::chrono::steady_clock::time_point checked{}; +}; +std::unordered_map cased_paths; + +// the names in the folder into Cached by their lowercase, with the time the folder was changed and the time they were read. a named +// function rather than a lambda capturing Cached, which Sonar takes for a reference to null (S2259) +void read_cased_folder(cased_folder &Cached, std::filesystem::path const &Folder, std::filesystem::file_time_type const Changed) +{ + Cached.names.clear(); + Cached.changed = Changed; + Cached.listed = std::filesystem::file_time_type::clock::now(); + std::error_code error; + for (std::filesystem::directory_iterator entry{Folder, error}, end; (false == bool(error)) && (entry != end); entry.increment(error)) + { + auto const name{entry->path().filename().string()}; + Cached.names.try_emplace(ToLower(name), name); + } + // a listing cut short isn't kept + Cached.read = (false == bool(error)); +} + +// the name in the folder matching the one given in any case, empty when there's none. the folder is read again once it was +// changed, as the editor writes files while it runs, the time of the change looked at once a second at most, which keeps a +// missing file as cheap as a single check; a name missing from a folder changed shortly before it was read is looked for again, +// the time of the change being as coarse as the clock of the file system. to be called with cased_mutex held +std::string cased_name(std::string const &Folder, std::string const &Name) +{ + std::filesystem::path const folder{Folder.empty() ? std::string{"."} : Folder}; + std::error_code error; + auto &cached{cased_folders[Folder]}; + auto const now{std::chrono::steady_clock::now()}; + auto changed{cached.changed}; + if ((false == cached.read) || (now - cached.checked >= std::chrono::seconds{1})) + { + changed = std::filesystem::last_write_time(folder, error); + if (error) + { + // a folder found before may have been renamed or removed since + cased_folders.erase(Folder); + cased_paths.clear(); + return {}; + } + cached.checked = now; + } + auto const wanted{ToLower(Name)}; + if ((false == cached.read) || (cached.changed != changed)) + read_cased_folder(cached, folder, changed); + auto found{cached.names.find(wanted)}; + // a folder changed in the future, as from another clock, isn't read again on every miss + if (auto const age{cached.listed - cached.changed}; (found == cached.names.end()) && (age >= std::chrono::seconds{0}) && (age < std::chrono::seconds{2})) + { + read_cased_folder(cached, folder, changed); + found = cached.names.find(wanted); + } + return found != cached.names.end() ? found->second : std::string{}; +} + +// keeps the folder by the name it's given with as Name, or as missing since the time given when Name is empty, and puts Name into +// Cased; false when it's missing +bool keep_cased_path(std::string const &Folder, std::string const &Name, std::chrono::steady_clock::time_point const Now, std::string &Cased) +{ + auto &path{cased_paths[Folder]}; + path.name = Name; + path.missing = Name.empty(); + path.checked = Now; + Cased = Name; + return false == Name.empty(); +} + +// the folder as it's named on the disk into Cased, from the one given with '/' between its parts and at its end ("" the current +// folder); false when it's missing in any case. the folders found are kept, and the missing ones for a second, so a file missing +// costs a check of its folder alone. to be called with cased_mutex held +bool cased_folder_path(std::string const &Folder, std::string &Cased) +{ + if (Folder.empty() || (Folder == "/")) + { + Cased = Folder; + return true; + } + auto const now{std::chrono::steady_clock::now()}; + if (auto const found{cased_paths.find(Folder)}; found != cased_paths.end()) + { + if (false == found->second.missing) + { + Cased = found->second.name; + return true; + } + if (now - found->second.checked < std::chrono::seconds{1}) + return false; + } + std::error_code error; + if (std::filesystem::is_directory(Folder, error)) + { + // named as it is on the disk + return keep_cased_path(Folder, Folder, now, Cased); + } + // the parent, then the last part among the names in it + auto const last{Folder.size() - 1}; + auto const split{Folder.rfind('/', last - 1)}; + auto const parent{split == std::string::npos ? std::string{} : Folder.substr(0, split + 1)}; + auto const part{Folder.substr(parent.size(), last - parent.size())}; + std::string casedparent; + if (false == cased_folder_path(parent, casedparent)) + return keep_cased_path(Folder, {}, now, Cased); + auto const name{((part == ".") || (part == "..")) ? part : cased_name(casedparent, part)}; + return keep_cased_path(Folder, name.empty() ? std::string{} : casedparent + name + '/', now, Cased); +} + +} // namespace +#endif + std::string FileCased(std::filesystem::path const &Filename) { std::error_code error; @@ -643,16 +777,59 @@ std::string FileCased(std::filesystem::path const &Filename) // code page to throw on return {}; #else - // only the name of the file itself, a folder named in another case isn't found - auto const directory{Filename.has_parent_path() ? Filename.parent_path() : std::filesystem::path{"."}}; - auto const wanted{ToLower(Filename.filename().string())}; - for (std::filesystem::directory_iterator entry{directory, error}, end; entry != end; entry.increment(error)) - if (ToLower(entry->path().filename().string()) == wanted) - return Filename.has_parent_path() ? (directory / entry->path().filename()).string() : entry->path().filename().string(); - return {}; + // the folder, then the file in it: the folders can be named in another case as well as the file + auto text{Filename.string()}; + std::replace(text.begin(), text.end(), '\\', '/'); + std::string folder{(false == text.empty()) && (text.front() == '/') ? "/" : ""}; + std::string file; + for (std::size_t start{0}; start < text.size();) + { + auto end{text.find('/', start)}; + if (end == std::string::npos) + end = text.size(); + if (end > start) + { + if (false == file.empty()) + folder += file + '/'; + file = text.substr(start, end - start); + } + start = end + 1; + } + if (file.empty()) + return {}; + std::string cased; + { + std::scoped_lock const lock{cased_mutex}; + if (false == cased_folder_path(folder, cased)) + return {}; + auto const name{((file == ".") || (file == "..")) ? file : cased_name(cased, file)}; + if (name.empty()) + return {}; + cased += name; + } + return std::filesystem::exists(cased, error) ? cased : std::string{}; #endif } +std::string FileOnDisk(std::string const &Filename) +{ + auto cased{FileCased(Filename)}; + return cased.empty() ? Filename : cased; +} + +std::string FileStemOnDisk(std::string const &Folder, std::string const &Name, std::vector const &Extensions) +{ + for (auto const &extension : Extensions) + { + auto const cased{FileCased(Folder + Name + extension)}; + if (cased.size() > Folder.size() + extension.size() && cased.starts_with(Folder) && cased.ends_with(extension)) + { + return cased.substr(Folder.size(), cased.size() - Folder.size() - extension.size()); + } + } + return Name; +} + std::pair FileExists(std::vector const &Names, std::vector const &Extensions) { @@ -660,7 +837,8 @@ std::pair FileExists(std::vector const &N { for (auto const &extension : Extensions) { - if (FileExists(name + extension)) + // found in any case, given back as named here: the name stays the key of the banks, the file is opened by FileOnDisk() + if (false == FileCased(name + extension).empty()) { return {name, extension}; } diff --git a/utilities/utilities.h b/utilities/utilities.h index 7e3a227f1..25ee3882c 100644 --- a/utilities/utilities.h +++ b/utilities/utilities.h @@ -233,10 +233,17 @@ template bool extract_value(Type_ &Variable, std::string const template <> bool extract_value(bool &Variable, std::string const &Key, std::string const &Input, std::string const &Default); bool FileExists(std::string const &Filename); -// the file as it's named on the disk when only the case of its name differs, as in the sceneries made on Windows; empty when -// there's none. the folders have to be named in their case; on Windows, finding the names in any case itself, the file given or none +// the file as it's named on the disk when only the case of its name or of its folders differs, as in the sceneries made on Windows; +// empty when there's none. on Windows, finding the names in any case itself, the file given or none std::string FileCased(std::filesystem::path const &Filename); +// the file to open: as it's named on the disk, the name given when there's none +std::string FileOnDisk(std::string const &Filename); +// the name (relative to the folder, without extension) as it's named on the disk with the first of the extensions it has a file with, +// found in any case; the name given when there's none +std::string FileStemOnDisk(std::string const &Folder, std::string const &Name, std::vector const &Extensions); +// the first name with one of the extensions which has a file in any case, in the order given; given back as named here, the file +// is opened by FileOnDisk() std::pair FileExists(std::vector const &Names, std::vector const &Extensions); // returns time of last modification for specified file diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index bfa0e70c7..2b3633433 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Globals.h" #include "utilities/translation.h" #include "utilities/Logs.h" +#include "utilities/physicslog.h" #include "vehicle/Train.h" #include "vehicle/brakesetting.h" #include "vehicle/handover.h" @@ -170,6 +171,7 @@ const double FSOverchargeCRP = 0.05; const double FSMaxTime = 10.0; const double DepartBlockedFSDelay = 10.0; bool WriteLogFlag = false; +bool WriteTrainLogFlag = false; double const deltalog = 0.05; // przyrost czasu std::string StopReasonTable[] = { @@ -2339,33 +2341,16 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, iDrivigFlags |= movePrimary; // aktywnie prowadzące pojazd } - SetDriverPsyche(); // na końcu, bo wymaga ustawienia zmiennych + if( mvOccupied != nullptr ) { + SetDriverPsyche(); // na końcu, bo wymaga ustawienia zmiennych + } TableClear(); - if( WriteLogFlag ) { -#ifdef _WIN32 - CreateDirectory( "physicslog", nullptr); -#elif __unix__ - mkdir( "physicslog", 0740 ); -#endif - LogFile.open( std::string( "physicslog/" + VehicleName + ".dat" ), - std::ios::in | std::ios::out | std::ios::trunc ); -#if LOGPRESS == 0 - LogFile - << "Time[s] Velocity[m/s] Acceleration[m/ss] " - << "Coupler.Dist[m] Coupler.Force[N] TractionForce[kN] FrictionForce[kN] BrakeForce[kN] " - << "BrakePress[MPa] PipePress[MPa] MotorCurrent[A] " - << "MCP SCP BCP LBP Direction Command CVal1 CVal2 " - << "Security Wheelslip " - << "EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg] " - << "VehicleVelocity[km/h]" - << "\r\n"; - LogFile << std::fixed << std::setprecision( 4 ); -#endif -#if LOGPRESS == 1 - LogFile << string( "t\tVel\tAcc\tPP\tVVP\tBP\tBVP\tCVP" ).c_str() << "\n"; -#endif - LogFile.flush(); + // the logs of all but the road vehicles, begun at once as they always were. one of a train only at its first line + // (update_logs): every crew is made primary here, and the drivers but one of a train with crews in more vehicles + // are made passive before it starts, so they get no file with only the header + if( WriteLogFlag && false == drives_road_vehicle() ) { + begin_physicslog(); } // HACK: give the simulation a small window to potentially replace the AI with a human driver @@ -2374,7 +2359,6 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, TController::~TController() { // wykopanie mechanika z roboty - // LogFile is closed by its own destructor }; // zamiana kodu rozkazu na opis @@ -5390,58 +5374,80 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N return false; // nierozpoznana - wysłać bezpośrednio do pojazdu }; -void TController::PhysicsLog() -{ // zapis logu - na razie tylko wypisanie parametrów - if (LogFile.is_open()) - { +std::string_view TController::physicslog_header() { + // the columns of the readers of these logs, the Hasler tape of the starter among them, stay where they are: + // a new one goes at the end + return "Time[s] Velocity[m/s] Acceleration[m/ss] " + "Coupler.Dist[m] Coupler.Force[N] TractionForce[kN] FrictionForce[kN] BrakeForce[kN] " + "BrakePress[MPa] PipePress[MPa] MotorCurrent[A] " + "MCP SCP BCP LBP Direction Command CVal1 CVal2 " + "Security Wheelslip " + "EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg] " + "VehicleVelocity[km/h]" + "\r\n"; +} + +physicslog_values TController::physicslog_line() const { + // the values only: the writer of the logs makes them into text on its own thread + physicslog_values line; + line.time = ElapsedTime; + line.wheelspeed = fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot); + line.acceleration = mvControlling->AccS; + line.couplerdistance = mvOccupied->Couplers[1].Dist; + line.couplerforce = mvOccupied->Couplers[1].CForce; + line.tractionforce = mvOccupied->Ft; + line.frictionforce = mvOccupied->Ff; + line.brakeforce = mvOccupied->Fb; + line.brakepressure = mvOccupied->BrakePress; + line.pipepressure = mvOccupied->PipePress; + line.motorcurrent = mvControlling->Im; + line.mainctrl = static_cast(mvControlling->MainCtrlPos); + line.scndctrl = static_cast(mvControlling->ScndCtrlPos); + line.brakectrl = mvOccupied->fBrakeCtrlPos; + line.localbrake = mvOccupied->LocalBrakePosA; + line.direction = static_cast(mvControlling->DirActive); + line.command = ( mvOccupied->CommandIn.Command.empty() ? "none" : mvOccupied->CommandIn.Command.c_str() ); + line.value1 = mvOccupied->CommandIn.Value1; + line.value2 = mvOccupied->CommandIn.Value2; + line.security = static_cast(mvControlling->SecuritySystem.is_blinking()); + line.wheelslip = static_cast(mvControlling->SlippingWheels); + // floats, as the stream wrote them: widened to double + line.enginetemperature = mvControlling->dizel_heat.Ts; + line.oiltemperature = mvControlling->dizel_heat.To; + line.watertemperature = mvControlling->dizel_heat.temperatura1; + line.wateraux = mvControlling->dizel_heat.temperatura2; + // vehicle speed [km/h], the second column is the wheel speed, which stays at 0 while the wheels are locked in a skid + line.vehiclespeed = mvOccupied->V * 3.6; + return line; +} + +void TController::begin_physicslog() +{ + // physicslog/.dat, written every two seconds along with the logs of the other drivers #if LOGPRESS == 0 -/* -<< "Time[s] Velocity[m/s] Acceleration[m/ss] " -<< "Coupler.Dist[m] Coupler.Force[N] TractionForce[kN] FrictionForce[kN] BrakeForce[kN] " -<< "BrakePress[MPa] PipePress[MPa] MotorCurrent[A] " -<< "MCP SCP BCP LBP DmgFlag Command CVal1 CVal2 " -<< "EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg]" -*/ - LogFile - << ElapsedTime << " " - << fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot) << " " - << mvControlling->AccS << " " - << mvOccupied->Couplers[1].Dist << " " - << mvOccupied->Couplers[1].CForce << " " - << mvOccupied->Ft << " " - << mvOccupied->Ff << " " - << mvOccupied->Fb << " " - << mvOccupied->BrakePress << " " - << mvOccupied->PipePress << " " - << mvControlling->Im << " " - << int(mvControlling->MainCtrlPos) << " " - << int(mvControlling->ScndCtrlPos) << " " - << mvOccupied->fBrakeCtrlPos << " " - << mvOccupied->LocalBrakePosA << " " - << int(mvControlling->DirActive) << " " - << ( mvOccupied->CommandIn.Command.empty() ? "none" : mvOccupied->CommandIn.Command.c_str() ) << " " - << mvOccupied->CommandIn.Value1 << " " - << mvOccupied->CommandIn.Value2 << " " - << int(mvControlling->SecuritySystem.is_blinking()) << " " - << int(mvControlling->SlippingWheels) << " " - << mvControlling->dizel_heat.Ts << " " - << mvControlling->dizel_heat.To << " " - << mvControlling->dizel_heat.temperatura1 << " " - << mvControlling->dizel_heat.temperatura2 << " " - // vehicle speed [km/h], the second column is the wheel speed, which stays at 0 while the wheels are locked in a skid - << mvOccupied->V * 3.6 - << "\r\n"; + PhysicsLogs.begin( VehicleName, physicslog_header() ); #endif #if LOGPRESS == 1 - LogFile << ElapsedTime << "\t" << fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot) - << "\t"; - LogFile << Controlling->AccS << "\t"; - LogFile << mvOccupied->PipePress << "\t" << mvOccupied->CntrlPipePress << "\t" - << mvOccupied->BrakePress << "\t"; - LogFile << mvOccupied->Volume << "\t" << mvOccupied->Hamulec->GetCRP() << "\n"; + PhysicsLogs.begin( VehicleName, "t\tVel\tAcc\tPP\tVVP\tBP\tBVP\tCVP\n" ); +#endif + PhysicsLogBegun = true; +} + +void TController::PhysicsLog() +{ // zapis logu - na razie tylko wypisanie parametrów +#if LOGPRESS == 0 + PhysicsLogs.append( VehicleName, physicslog_line() ); +#endif +#if LOGPRESS == 1 + std::ostringstream line; + line << ElapsedTime << "\t" << fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot) + << "\t"; + line << mvControlling->AccS << "\t"; + line << mvOccupied->PipePress << "\t" << mvOccupied->CntrlPipePress << "\t" + << mvOccupied->BrakePress << "\t"; + line << mvOccupied->Volume << "\t" << mvOccupied->Hamulec->GetCRP() << "\n"; + PhysicsLogs.append( VehicleName, line.str() ); #endif - LogFile.flush(); - } }; void @@ -6392,6 +6398,10 @@ void TController::ControllingSet() // problematyczne jest sterowanie z członu biernego, dlatego damy AI silnikowy // dzięki temu będzie wirtualna kabina w silnikowym, działająca w rozrządczym // w plikach FIZ zostały zgubione ujemne maski sprzęgów, stąd problemy z EZT + if( pVehicle == nullptr ) { + // a driver of no vehicle has nothing to control + return; + } mvOccupied = pVehicle->MoverParameters; // domyślny skrót do obiektu parametrów BrakeSystem = mvOccupied->BrakeSystem; // domyślny sposób hamowania mvControlling = pVehicle->FindPowered()->MoverParameters; // poszukiwanie członu sterowanego @@ -6493,10 +6503,18 @@ TController::update_timers( double dt ) { void TController::update_logs( double const dt ) { // log vehicle data + if( false == writes_physicslog() ) { + // not counted while it isn't logged (the driver of a road vehicle, or no logs on): were the logs turned on, + // it would write a line every 0.05 s from then on, not one each update to make up for the time before + LastUpdatedTime = 0.0; + return; + } LastUpdatedTime += dt; - if( WriteLogFlag - && LastUpdatedTime > deltalog ) { + if( LastUpdatedTime > deltalog ) { // zapis do pliku DAT + if( false == PhysicsLogBegun ) { + begin_physicslog(); + } PhysicsLog(); LastUpdatedTime -= deltalog; } diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 2ed51b6a1..113be3b94 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #pragma once #include +#include #include "utilities/Classes.h" #include "utilities/utilities.h" #include "MOVER.h" @@ -19,6 +20,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/translation.h" #include "application/driverhints.h" #include "vehicle/blackbox.h" +#include "utilities/physicslog.h" auto const EU07_AI_ACCELERATION = 0.05; auto const EU07_AI_NOACCELERATION = -0.05; @@ -197,6 +199,9 @@ static const bool Humandriver = false; static const int maxorders = 64; // ilość rozkazów w tabelce static const int maxdriverfails = 4; // ile błędów może zrobić AI zanim zmieni nastawienie extern bool WriteLogFlag; // logowanie parametrów fizycznych +// the physics logs of the trains only (physicslog.trains yes): of each driver of rail vehicles who drives them, not +// of the passengers nor of the vehicles of the roads +extern bool WriteTrainLogFlag; static const int BrakeAccTableSize = 20; static const int gbh_NP = -2; //odciecie w hamulcu ogolnym @@ -721,9 +726,12 @@ private: // logs // methods + // the line of the log, to PhysicsLogs (utilities/physicslog.h) void PhysicsLog(); + // its log begun anew, its file emptied and given the header + void begin_physicslog(); // members - std::ofstream LogFile; // zapis parametrow fizycznych + bool PhysicsLogBegun = false; // its log was begun, by this driver double LastUpdatedTime = 0.0; // czas od ostatniego logu double ElapsedTime = 0.0; // czas od poczatku logu @@ -731,6 +739,22 @@ private: public: TDynamicObject const *Vehicle() const { return pVehicle; } + // the physics log (physicslog/.dat): the name of its file without the extension, its first line, with + // its line end, and the values of a line of it as the vehicle is now, which the writer of the logs makes into text. + // the black box keeps the lines of the vehicle the user is in when its driver doesn't write its own + std::string const &physicslog_name() const { + return VehicleName; } + // whether it writes its physics log itself: with "physicslog yes" all but the drivers of road vehicles, with + // "physicslog.trains yes" one who drives rail vehicles. a driver made primary later begins its log then. the cars of + // a big scenery are hundreds, whose logs nobody reads and which a hard disk can't keep up with; the black box writes + // the log of one the user is in + bool writes_physicslog() const { + return ( WriteLogFlag && false == drives_road_vehicle() ) || ( WriteTrainLogFlag && is_train() && primary() ); } + // a driver of a road vehicle; not one of no vehicle + bool drives_road_vehicle() const { + return mvOccupied != nullptr && is_car(); } + static std::string_view physicslog_header(); + physicslog_values physicslog_line() const; TDynamicObject *Vehicle( end const Side ) const { return pVehicles[ Side ]; } private: diff --git a/vehicle/blackbox.cpp b/vehicle/blackbox.cpp index 8612df1bd..fc05f7483 100644 --- a/vehicle/blackbox.cpp +++ b/vehicle/blackbox.cpp @@ -205,6 +205,7 @@ void writer::cab(cab_sample const &Sample) { out.f32(Sample.clutch); out.f32(Sample.converter_fill); out.f32(Sample.consist_brake_cylinder); + out.f32(Sample.wheel_speed_kmh); emit(record::cab); } diff --git a/vehicle/blackbox.h b/vehicle/blackbox.h index 58735ff60..55ee06ca3 100644 --- a/vehicle/blackbox.h +++ b/vehicle/blackbox.h @@ -257,6 +257,9 @@ struct cab_sample { float clutch{0.0f}; // the clutch of a diesel's gearbox, 0 open .. 1 closed float converter_fill{0.0f}; // the filling of a diesel's hydraulic torque converter, 0..1 float consist_brake_cylinder{0.0f}; // the highest brake cylinder pressure of the vehicles of the train [bar] + // [km/h] of the wheels as they turn, which the speedometer shows, signed as speed_kmh: apart from it while the wheels + // slip, and 0 while they are locked in a skid + float wheel_speed_kmh{0.0f}; }; // a station of the timetable of the user's train; the times in minutes of the day, -1 none @@ -354,7 +357,7 @@ struct signal_passing { // sizes of the parts of fixed size, as the readers expect them inline constexpr std::size_t header_size{12}; inline constexpr std::size_t record_header_size{5}; -inline constexpr std::size_t cab_sample_size{190}; +inline constexpr std::size_t cab_sample_size{194}; inline constexpr std::size_t vehicle_state_size{25}; // writes the records to a stream. nothing is written until header() is diff --git a/world/mtable.cpp b/world/mtable.cpp index ce10eaafd..23a48e3a7 100644 --- a/world/mtable.cpp +++ b/world/mtable.cpp @@ -310,6 +310,15 @@ bool TTrainParameters::LoadTTfile(std::string const &scnpath, int iPlus, double // Ra 2014-09: ustalić zasady wyznaczenia pierwotnego pliku przy przesuniętych rozkładach // (kolejny pociąg dostaje numer +2) fin.open(s.c_str()); // otwieranie pliku + if (false == fin.is_open()) + { + // the name of the train comes in lowercase, the file can be named in another case + if (auto const cased{FileCased(s)}; false == cased.empty()) + { + fin.clear(); + fin.open(cased); + } + } replace_slashes(s); if (!fin.is_open()) From 7f2c611772fc7fd7c0a6341f4be193f7a1f57d7e Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 03:42:23 +0100 Subject: [PATCH 077/136] refactor(materials): clear small Sonar smells in material.cpp (#361) texture_slot: contains() for the shader texture lookup (S6171) and the binding lookup declared in the if init-statement (S6004). deserialize_texture_mapping: try_emplace builds the tex_def from its arguments (S6011). is_season/is_weather: contains() (S6171). deserialize_mapping: drop the empty statements in the while loops that only parse (S1116). Behaviour unchanged; finalize() left as it is. Follows up the review note on #175. --- model/material.cpp | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/model/material.cpp b/model/material.cpp index 4e96ddd8c..fbd58bd70 100644 --- a/model/material.cpp +++ b/model/material.cpp @@ -86,11 +86,11 @@ int opengl_material::texture_slot( std::string const &Key ) // named binding, the slot it fills is up to the shader key.erase( 0, 1 ); key.pop_back(); - if( shader && ( shader->texture_conf.find( key ) != shader->texture_conf.end() ) ) { + if( shader && shader->texture_conf.contains( key ) ) { return static_cast( shader->texture_conf[ key ].id ); } - auto const lookup { texture_bindings.find( key ) }; - if( ( shader == nullptr ) && ( lookup != texture_bindings.end() ) ) { + if( auto const lookup { texture_bindings.find( key ) }; + ( shader == nullptr ) && ( lookup != texture_bindings.end() ) ) { return lookup->second; } // ignore unrecognized texture bindings in legacy render mode, it's most likely data for more advanced shaders @@ -318,7 +318,7 @@ std::unordered_set seasons = { bool is_season( std::string const &String ) { - return seasons.find(String) != seasons.end(); + return seasons.contains(String); } std::unordered_set weather = { @@ -326,7 +326,7 @@ std::unordered_set weather = { bool is_weather( std::string const &String ) { - return weather.find(String) != weather.end(); + return weather.contains(String); } // imports member data pair from the config file @@ -362,7 +362,7 @@ void opengl_material::deserialize_texture_mapping( cParser &Input, std::string c value = variants.front(); } - auto const [ it, inserted ] { parse_info->tex_mapping.try_emplace( key, parse_info_s::tex_def{ value, Priority, variants } ) }; + auto const [ it, inserted ] { parse_info->tex_mapping.try_emplace( key, value, Priority, variants ) }; if( ( false == inserted ) && ( Priority > it->second.priority ) ) { it->second = parse_info_s::tex_def{ value, Priority, variants }; } @@ -389,7 +389,7 @@ opengl_material::deserialize_mapping( cParser &Input, int const Priority, bool c // skip the opening bracket auto const value { Input.getToken( true, "\n\r\t ;" ) }; while( true == deserialize_mapping( Input, Priority + 2, Loadnow ) ) { - ; // all work is done in the header + // all work is done in the header } } else if( key == Global.Season ) { @@ -397,7 +397,7 @@ opengl_material::deserialize_mapping( cParser &Input, int const Priority, bool c // skip the opening bracket auto const value { Input.getToken( true, "\n\r\t ;" ) }; while( true == deserialize_mapping( Input, Priority + 1, Loadnow ) ) { - ; // all work is done in the header + // all work is done in the header } } @@ -477,7 +477,7 @@ opengl_material::deserialize_mapping( cParser &Input, int const Priority, bool c // unrecognized or ignored token, but comes with attribute block and potential further nesting // go through it and discard the content while( true == deserialize_mapping( Input, -1, Loadnow ) ) { - ; // all work is done in the header + // all work is done in the header } } } @@ -489,7 +489,7 @@ opengl_material::deserialize_mapping( cParser &Input, int const Priority, bool c // ignored tokens can come with their own blocks, ignore these recursively // go through it and discard the content while( true == deserialize_mapping( Input, -1, Loadnow ) ) { - ; // all work is done in the header + // all work is done in the header } } } From 357ccabd0c19bff8cc09c0937556c6e65040c4e4 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 03:42:41 +0100 Subject: [PATCH 078/136] refactor: rename the import methods and the module variables (Sonar S1669) (#363) import and module are contextual keywords of C++20 modules. The text loaders of the scene nodes (shape_node, lines_node, road_node, junction_node, roadpoint_node, sweep_node) become import_from(), the WASM module of the screen host's cache entry and of load() becomes wasm_module, and the path of the written test module becomes module_path. Renames only. --- scene/scenenode.cpp | 4 ++-- scene/scenenode.h | 4 ++-- scene/sceneterrain.cpp | 4 ++-- scripting/wasmprogram.cpp | 20 ++++++++++---------- simulation/simulationstateserializer.cpp | 12 ++++++------ tests/unit/test_script_screen_host.cpp | 18 +++++++++--------- world/Road.cpp | 4 ++-- world/Road.h | 4 ++-- world/RoadPoint.cpp | 2 +- world/RoadPoint.h | 2 +- world/Sweep.cpp | 2 +- world/Sweep.h | 2 +- 12 files changed, 39 insertions(+), 39 deletions(-) diff --git a/scene/scenenode.cpp b/scene/scenenode.cpp index 426f0e077..18b1905a4 100644 --- a/scene/scenenode.cpp +++ b/scene/scenenode.cpp @@ -143,7 +143,7 @@ shape_node::deserialize( std::istream &Input ) { // restores content of the node from provided input stream shape_node & -shape_node::import( cParser &Input, scene::node_data const &Nodedata ) { +shape_node::import_from( cParser &Input, scene::node_data const &Nodedata ) { // import common data m_name = Nodedata.name; @@ -561,7 +561,7 @@ lines_node::deserialize( std::istream &Input ) { // restores content of the node from provded input stream lines_node & -lines_node::import( cParser &Input, scene::node_data const &Nodedata ) { +lines_node::import_from( cParser &Input, scene::node_data const &Nodedata ) { // import common data m_name = Nodedata.name; diff --git a/scene/scenenode.h b/scene/scenenode.h index 237056669..a534f0631 100644 --- a/scene/scenenode.h +++ b/scene/scenenode.h @@ -122,7 +122,7 @@ public: deserialize( std::istream &Input ); // restores content of the node from provided input stream shape_node & - import( cParser &Input, scene::node_data const &Nodedata ); + import_from( cParser &Input, scene::node_data const &Nodedata ); // imports data from provided submodel shape_node & convert( TSubModel const *Submodel ); @@ -254,7 +254,7 @@ public: deserialize( std::istream &Input ); // restores content of the node from provided input stream lines_node & - import( cParser &Input, scene::node_data const &Nodedata ); + import_from( cParser &Input, scene::node_data const &Nodedata ); // adds content of provided node to already enclosed geometry. returns: true if merge could be performed bool merge( lines_node &Lines ); diff --git a/scene/sceneterrain.cpp b/scene/sceneterrain.cpp index d0453f2b3..585912a2b 100644 --- a/scene/sceneterrain.cpp +++ b/scene/sceneterrain.cpp @@ -455,7 +455,7 @@ bool terrain_file::write(std::string const &Text, std::string const &Binaryfile, Message = "node of type \"" + nodedata.type + "\" (line " + std::to_string(input.Line()) + ") can't be a part of binary terrain"; return false; } - auto shape{shape_node().import(input, nodedata)}; + auto shape{shape_node().import_from(input, nodedata)}; // the shapes are all sent to the section cells, which groups them the way it'd be done for translucent geometry. // whether they can be merged into section-wide pieces instead is decided when the file is loaded, see the layout notes shape.m_data.translucent = true; @@ -799,7 +799,7 @@ bool read_text_triangles(std::string const &Text, terrain_reference const &Refer input >> nodedata.range_max >> nodedata.range_min >> nodedata.name >> nodedata.type; if (nodedata.type == "triangles" || nodedata.type == "triangle_strip" || nodedata.type == "triangle_fan") { - auto const shape{shape_node().import(input, nodedata)}; + auto const shape{shape_node().import_from(input, nodedata)}; auto const &data{shape.data()}; auto const *material{GfxRenderer->Material(data.material)}; auto const name{material != nullptr ? material->GetName() : std::string{}}; diff --git a/scripting/wasmprogram.cpp b/scripting/wasmprogram.cpp index 422ce70dc..1a1751732 100644 --- a/scripting/wasmprogram.cpp +++ b/scripting/wasmprogram.cpp @@ -523,9 +523,9 @@ class wasm_runtime_host final : public runtime { for (auto const &[script, entry] : m_modules) { - if (entry.module != nullptr) + if (entry.wasm_module != nullptr) { - wasm_runtime_unload(entry.module); + wasm_runtime_unload(entry.wasm_module); } } if (m_started) @@ -551,7 +551,7 @@ class wasm_runtime_host final : public runtime struct module_entry { std::vector bytes; // the runtime reads the module from here as long as it is loaded - wasm_module_t module{nullptr}; + wasm_module_t wasm_module{nullptr}; }; wasm_module_t load_module(std::string const &Script); @@ -584,7 +584,7 @@ wasm_module_t wasm_runtime_host::load_module(std::string const &Script) { if (auto const lookup{m_modules.find(Script)}; lookup != m_modules.end()) { - return lookup->second.module; + return lookup->second.wasm_module; } // a failure is kept as well, so the module isn't tried again for every screen using it auto &entry{m_modules[Script]}; @@ -601,23 +601,23 @@ wasm_module_t wasm_runtime_host::load_module(std::string const &Script) return nullptr; } std::array error{}; - entry.module = wasm_runtime_load(entry.bytes.data(), static_cast(entry.bytes.size()), error.data(), static_cast(error.size())); - if (entry.module == nullptr) + entry.wasm_module = wasm_runtime_load(entry.bytes.data(), static_cast(entry.bytes.size()), error.data(), static_cast(error.size())); + if (entry.wasm_module == nullptr) { ErrorLog(std::format("WASM screen \"{}\": failed to load the module: {}", Script, error.data())); } - return entry.module; + return entry.wasm_module; } std::unique_ptr wasm_runtime_host::load(std::string const &Script, script_screen_kind const Kind) { - auto *module{load_module(Script)}; - if (module == nullptr) + auto *wasm_module{load_module(Script)}; + if (wasm_module == nullptr) { return nullptr; } auto loaded{std::make_unique(Script, Kind)}; - if (false == loaded->instantiate(module)) + if (false == loaded->instantiate(wasm_module)) { return nullptr; } diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index 60854482c..da3e075ef 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -576,7 +576,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch else if( nodedata.type == "road" ) { auto *road { new road_node( nodedata ) }; - road->import( + road->import_from( Input, ( Scratchpad.location.offset.empty() ? glm::dvec3 { 0.0 } : @@ -592,7 +592,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch else if( nodedata.type == "sweep" ) { auto *sweep { new sweep_node( nodedata ) }; - sweep->import( + sweep->import_from( Input, ( Scratchpad.location.offset.empty() ? glm::dvec3 { 0.0 } : @@ -606,7 +606,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch else if( nodedata.type == "junction" ) { auto *junction { new junction_node( nodedata ) }; - junction->import( + junction->import_from( Input, ( Scratchpad.location.offset.empty() ? glm::dvec3 { 0.0 } : @@ -638,7 +638,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch else if( roadpoint_node::is_keyword( nodedata.type ) ) { // level crossing, or a point where road vehicles appear or are taken away auto *point { new roadpoint_node( nodedata ) }; - point->import( + point->import_from( Input, ( Scratchpad.location.offset.empty() ? glm::dvec3 { 0.0 } : @@ -739,7 +739,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch if( false == skip ) { ++Scratchpad.binary.geometry_imported; - auto shape { scene::shape_node().import( Input, nodedata ) }; + auto shape { scene::shape_node().import_from( Input, nodedata ) }; material = shape.data().material; if( true == Global.editor_session ) { shape.source_file( scene::terrain_file::reference_of( Input.Name() ) ); @@ -777,7 +777,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch ++Scratchpad.binary.geometry_imported; simulation::Region->insert( - scene::lines_node().import( + scene::lines_node().import_from( Input, nodedata ), Scratchpad ); } diff --git a/tests/unit/test_script_screen_host.cpp b/tests/unit/test_script_screen_host.cpp index c4226da40..6add4f008 100644 --- a/tests/unit/test_script_screen_host.cpp +++ b/tests/unit/test_script_screen_host.cpp @@ -285,16 +285,16 @@ constexpr std::array flood_module{ 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)}; + auto const module_path{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))}; + auto const screen{queue.acquire(request(script_language::wasm, module_path, "cab", &texture))}; REQUIRE(screen != nullptr); // the same key, the same screen - CHECK(queue.acquire(request(script_language::wasm, module, "cab", &texture)) == screen); + CHECK(queue.acquire(request(script_language::wasm, module_path, "cab", &texture)) == screen); refresh(queue, screen, speed(5.0), 42); REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0 && false == sent_commands().empty(); })); @@ -321,13 +321,13 @@ TEST_CASE("wasm screens: a cab screen draws from its input and sends commands to 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)}; + auto const module_path{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))}; + auto const screen{queue.acquire(request(script_language::wasm, module_path, "cab", &texture))}; refresh(queue, screen, speed(9.0), 1); REQUIRE(run_until(queue, [] { return false == sent_commands().empty(); })); queue.update(); @@ -350,12 +350,12 @@ TEST_CASE("wasm screens: the image goes up again when the texture is made anew, 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)}; + auto const module_path{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))}; + auto const screen{queue.acquire(request(script_language::wasm, module_path, "sign", &texture, script_screen_kind::external))}; refresh(queue, screen, speed(3.0), 0); REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0; })); queue.update(); @@ -388,13 +388,13 @@ TEST_CASE("wasm screens: a screen stuck in a loop is stopped, and the others kee 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)}; + auto const module_path{folder.write("paint.wasm", paint_module)}; std::shared_ptr screen; recording_texture texture; { script_screen_queue queue; REQUIRE(queue.init()); - screen = queue.acquire(request(script_language::wasm, module, "cab", &texture)); + screen = queue.acquire(request(script_language::wasm, module_path, "cab", &texture)); refresh(queue, screen, speed(4.0), 1); REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0; })); } diff --git a/world/Road.cpp b/world/Road.cpp index 26b458c16..79fc54f84 100644 --- a/world/Road.cpp +++ b/world/Road.cpp @@ -875,7 +875,7 @@ glm::dvec3 road_node::state::tangent(double const T) const road_node::road_node(scene::node_data const &Nodedata) : basic_node(Nodedata) {} // restores content of the node from provided input stream; reads up to and including the closing 'endroad' -void road_node::import(cParser &Input, glm::dvec3 const &Offset) +void road_node::import_from(cParser &Input, glm::dvec3 const &Offset) { auto const label{m_name.empty() ? std::string{"unnamed road"} : "road \"" + m_name + "\""}; @@ -2307,7 +2307,7 @@ std::vector junction_node::state::outline(std::vector roadpoint_node::parse_vehicles(std::st } // restores content of the node from provided input stream; reads up to and including the closing statement -void roadpoint_node::import(cParser &Input, glm::dvec3 const &Offset) +void roadpoint_node::import_from(cParser &Input, glm::dvec3 const &Offset) { auto const type{keyword(m_state.kind)}; auto const label{type + " \"" + m_name + "\""}; diff --git a/world/RoadPoint.h b/world/RoadPoint.h index 3ad45b4c3..670eb0fb1 100644 --- a/world/RoadPoint.h +++ b/world/RoadPoint.h @@ -97,7 +97,7 @@ class roadpoint_node : public scene::basic_node explicit roadpoint_node(scene::node_data const &Nodedata); // methods // restores content of the node from provided input stream; reads up to and including the closing statement - void import(cParser &Input, glm::dvec3 const &Offset); + void import_from(cParser &Input, glm::dvec3 const &Offset); state const &definition() const { return m_state; diff --git a/world/Sweep.cpp b/world/Sweep.cpp index 31587fe7d..9c5638cf3 100644 --- a/world/Sweep.cpp +++ b/world/Sweep.cpp @@ -404,7 +404,7 @@ bool sweep_node::state::operator==(state const &Other) const sweep_node::sweep_node(scene::node_data const &Nodedata) : basic_node(Nodedata) {} -void sweep_node::import(cParser &Input, glm::dvec3 const &Offset) +void sweep_node::import_from(cParser &Input, glm::dvec3 const &Offset) { m_state = state{}; m_state.model = Input.getToken(); diff --git a/world/Sweep.h b/world/Sweep.h index 2e65f5fa9..b83b7fa12 100644 --- a/world/Sweep.h +++ b/world/Sweep.h @@ -91,7 +91,7 @@ class sweep_node : public scene::basic_node explicit sweep_node(scene::node_data const &Nodedata); - void import(cParser &Input, glm::dvec3 const &Offset); + void import_from(cParser &Input, glm::dvec3 const &Offset); void define(state const &State); state const &definition() const { From c2b034ddcdf3978ba452429c7fe217f9bc9d54b4 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 03:42:49 +0100 Subject: [PATCH 079/136] refactor: no side effects in the right operand of && and || (Sonar S912) (#364) The ogl initialisation, the -resolution/-margin values of the standalone previews and the submodel lookups of TGauge::Load assign or increment in the right operand of && or ||. Each becomes plain statements which run exactly when the operand ran before: init_ogl() only when needs_ogl(), i advanced only when a value follows (and accepted), and the lookups by name and then by name + "_off" per model, in the same order, leaving submodel, submodelon and m_sourcemodel with the same values. --- application/application.cpp | 10 +++++++--- nodebank_previews_standalone.cpp | 6 ++++-- vehicle/Gauge.cpp | 23 +++++++++++++---------- 3 files changed, 24 insertions(+), 15 deletions(-) diff --git a/application/application.cpp b/application/application.cpp index 140475b60..2a024bfd6 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -393,10 +393,14 @@ int eu07_application::init(int Argc, char *Argv[]) ErrorLog("Failed to initialize glfw!"); return result; } - if (needs_ogl() && (result = init_ogl()) != 0) + if (needs_ogl()) { - ErrorLog("Failed to initialize ogl!"); - return result; + result = init_ogl(); + if (result != 0) + { + ErrorLog("Failed to initialize ogl!"); + return result; + } } if (crashreport_is_pending() && false == Global.test.enabled) diff --git a/nodebank_previews_standalone.cpp b/nodebank_previews_standalone.cpp index d94eb13ed..65c5e07f3 100644 --- a/nodebank_previews_standalone.cpp +++ b/nodebank_previews_standalone.cpp @@ -76,19 +76,21 @@ bool parse_arguments(int const Argc, char *Argv[], preview_settings &Settings) } else if (token == "-resolution") { - if ((i + 1 >= Argc) || (false == parse_number(Argv[++i], Settings.resolution)) || (Settings.resolution < 16)) + if ((i + 1 >= Argc) || (false == parse_number(Argv[i + 1], Settings.resolution)) || (Settings.resolution < 16)) { report("-resolution needs a number of pixels, 16 or more", true); return false; } + ++i; } else if (token == "-margin") { - if ((i + 1 >= Argc) || (false == parse_number(Argv[++i], Settings.margin)) || (Settings.margin < 0)) + if ((i + 1 >= Argc) || (false == parse_number(Argv[i + 1], Settings.margin)) || (Settings.margin < 0)) { report("-margin needs a number of pixels, 0 or more", true); return false; } + ++i; } else if (token == "-no-shadows") { diff --git a/vehicle/Gauge.cpp b/vehicle/Gauge.cpp index 6289fe5a2..c99448eed 100644 --- a/vehicle/Gauge.cpp +++ b/vehicle/Gauge.cpp @@ -211,15 +211,15 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu m_sourcemodel = nullptr; std::array sources { Owner->mdKabina, Owner->mdLowPolyInt }; for( auto const *source : sources ) { - if( source != nullptr - && ( submodel = source->GetFromName( submodelname ) ) != nullptr ) { - // got what we wanted, bail out - m_sourcemodel = source; - break; + if( source == nullptr ) { + continue; } - // there's a possibility the default submodel was named with _off suffix - if( source != nullptr - && ( submodel = source->GetFromName( submodelname + "_off" ) ) != nullptr ) { + submodel = source->GetFromName( submodelname ); + if( submodel == nullptr ) { + // there's a possibility the default submodel was named with _off suffix + submodel = source->GetFromName( submodelname + "_off" ); + } + if( submodel != nullptr ) { // got what we wanted, bail out m_sourcemodel = source; break; @@ -231,8 +231,11 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu // see if we can locate optional submodel for active state, with _on suffix TSubModel *submodelon { nullptr }; for( auto const *source : sources ) { - if( source != nullptr - && ( submodelon = source->GetFromName( submodelname + "_on" ) ) != nullptr ) { + if( source == nullptr ) { + continue; + } + submodelon = source->GetFromName( submodelname + "_on" ); + if( submodelon != nullptr ) { // got what we wanted, bail out break; } From 4a52b5affc23ecfc41eccd1045cfb091dc375c3a Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 03:43:01 +0100 Subject: [PATCH 080/136] refactor: no fields shadowing the base class's (Sonar S2387) (#366) TSt113 declared its own CP, which hid TH14K1::CP. TSt113 overrides every TH14K1 method that touches CP (GetPF sets it from PP before reading it, GetCP, Init), so the base field was never used in it; the derived one is deleted and the St113 uses the inherited field. A new test records the control chamber, brake pipe, cylinder and EP of the EN57's St113 over an application and a release; it was written and passed on the code before the change and passes unchanged after it. perfgraph_panel::pos, the write index of the timings' ring buffer, hid ui_panel::pos, the window position; it becomes history_pos. --- McZapkie/hamulce.h | 2 - tests/unit/test_brake_handles.cpp | 78 +++++++++++++++++++++++++++++++ widgets/perfgraphs.cpp | 12 ++--- widgets/perfgraphs.h | 2 +- 4 files changed, 85 insertions(+), 9 deletions(-) diff --git a/McZapkie/hamulce.h b/McZapkie/hamulce.h index 7de34ea23..097a164d7 100644 --- a/McZapkie/hamulce.h +++ b/McZapkie/hamulce.h @@ -1458,8 +1458,6 @@ class TSt113 : public TH14K1 static double const BEP_K[/*?*/ /*-1..5*/ 5 - -1 + 1]; /// Lookup of bh_* function codes to handle position values. static double const pos_table[11]; // = {-1, 5, -1, 0, 2, 3, 4, 5, 0, 0, 1}; - /// Local control pressure (mirrors PP). - double CP = 0; public: /// Computes brake pipe flow for the St113 handle (with EP). diff --git a/tests/unit/test_brake_handles.cpp b/tests/unit/test_brake_handles.cpp index 889beb338..f74edfc03 100644 --- a/tests/unit/test_brake_handles.cpp +++ b/tests/unit/test_brake_handles.cpp @@ -265,3 +265,81 @@ TEST_CASE("brake handles: the Knorr St113 EP brake needs the control of the cab unit.run(0.1); CHECK(ep_brake(unit, 0.0, 10.0) < 0.1); } + +// the Knorr St113 of the EN57 (TSt113, derived from TH14K1) over a service application, lap and release: its +// control chamber (GetCP), the brake pipe and the cylinder, against the values the code gave when the test was +// written, at 1e-9. a change of the handle's code which shouldn't alter anything has to keep them +namespace { + +struct st113_sample { + double cp; // the handle's control chamber + double pipe; // the brake pipe + double cylinder; + double ep; // the EP intensity the handle gives +}; + +std::vector st113_run() { + test::reseed_random(); + vehicle real{definition::fiz("en57_v1/6bai")}; + REQUIRE(real->BrakeHandle == TBrakeHandle::St113); + REQUIRE(real->Handle != nullptr); + real.hold_main_reservoir(std::max(real->MaxCompressor, 8.0)); + auto &handle{*real->Handle}; + std::vector samples; + auto const sample{[&] { samples.push_back({handle.GetCP(), real->PipePress, real->BrakePress, handle.GetEP()}); }}; + auto const hold{[&](double Position, std::initializer_list Seconds) { + real->BrakeLevelSet(Position); + for (auto const seconds : Seconds) { + real.run(seconds); + sample(); + } + }}; + sample(); // before the first step: the chamber as Init left it + hold(handle.GetPos(bh_RP), {1.0, 30.0, 30.0}); // charged in the running position + hold(handle.GetPos(bh_MB), {1.0, 5.0}); // the first step of the service brake + hold(handle.GetPos(bh_FB), {1.0, 2.0, 5.0, 10.0}); // full service + hold(handle.GetPos(bh_NP), {5.0}); // lap + hold(handle.GetPos(bh_RP), {1.0, 5.0, 10.0, 30.0}); // released + hold(handle.GetPos(bh_EB), {1.0, 5.0}); // emergency + hold(handle.GetPos(bh_FS), {1.0, 3.0}); // filling stroke + hold(handle.GetPos(bh_RP), {10.0, 60.0}); // released again + return samples; +} + +} // namespace + +TEST_CASE("brake handles: the pressures of the Knorr St113 of the EN57 over an application and a release") { + // {control chamber, brake pipe, cylinder, EP} after each hold of st113_run(), as the code gave them + std::vector const expected{ + {0, 3.5, 6, 0}, + {4.9984786171489723, 4.9985239614132073, 3.8589217414374479, -1}, + {4.9987671731417445, 4.9988125312381184, 9.6079198677899244e-17, -1}, + {4.9991258752288621, 4.9991713394295099, 9.6079198677899244e-17, -1}, + {4.9533680060376426, 4.9530025463238161, 9.6079198677899244e-17, 0}, + {4.8311329228109479, 4.8310446333333399, 9.6079198677899244e-17, 0}, + {4.7310321436160523, 4.7325637973526726, 9.6079198677899244e-17, 0}, + {4.5872331917154092, 4.5890657213751611, 9.6079198677899244e-17, 0}, + {4.1778305377419631, 4.1793406294291415, 1.6739519661380537, 0}, + {3.355298669598576, 3.3569433138107754, 2.5006765921012648, 0}, + {3.340608574818968, 3.3406062128010463, 2.5006765921012648, 0}, + {4.9982940431020717, 4.9983393759288948, 1.805897475684926, -1}, + {4.9983349224059745, 4.9983802579817755, 0.096548127644583259, -1}, + {4.9984201641741199, 4.9984655050733862, 0.062980447840665657, -1}, + {4.9987011353434028, 4.998746490639209, 9.2221356484789066e-17, -1}, + {0.005419548331438478, 0.0049542946616295885, 2.0688047473966584, 0}, + {1.1051369154140042e-16, 1.1051359148828238e-16, 2.5210994451474482, 0}, + {7.9894372542519436, 7.9895176172361353, 1.9107481967960043, 0}, + {7.9894891501326404, 7.9895615214846529, 0.36406880055594204, 0}, + {6.2299691431411732, 6.2285260180794131, 0.068969473862745739, -1}, + {4.9988917107669719, 4.9989370736220264, 1.0102243333979078e-16, -1}, + }; + auto const samples{st113_run()}; + REQUIRE(samples.size() == expected.size()); + for (std::size_t i = 0; i < samples.size(); ++i) { + CAPTURE(i); + CHECK(samples[i].cp == doctest::Approx(expected[i].cp).epsilon(1e-9)); + CHECK(samples[i].pipe == doctest::Approx(expected[i].pipe).epsilon(1e-9)); + CHECK(samples[i].cylinder == doctest::Approx(expected[i].cylinder).epsilon(1e-9)); + CHECK(samples[i].ep == doctest::Approx(expected[i].ep).epsilon(1e-9)); + } +} diff --git a/widgets/perfgraphs.cpp b/widgets/perfgraphs.cpp index 041a25134..83221d696 100644 --- a/widgets/perfgraphs.cpp +++ b/widgets/perfgraphs.cpp @@ -49,13 +49,13 @@ void perfgraph_panel::render_contents() { if (!stopwatch) return; - history[pos] = static_cast(static_cast(stopwatch->last().count()) / 1000.0); - const std::string label = std::to_string(history[pos]) + "ms"; + history[history_pos] = static_cast(static_cast(stopwatch->last().count()) / 1000.0); + const std::string label = std::to_string(history[history_pos]) + "ms"; - pos++; - if (pos >= history.size()) - pos = 0; + history_pos++; + if (history_pos >= history.size()) + history_pos = 0; ImGui::SliderFloat(STR_C("Range"), &max, 0.1f, 250.0f); - ImGui::PlotLines("##timer", &history[0], static_cast(history.size()), static_cast(pos), label.c_str(), 0.0f, max, ImVec2(500, 200)); + ImGui::PlotLines("##timer", &history[0], static_cast(history.size()), static_cast(history_pos), label.c_str(), 0.0f, max, ImVec2(500, 200)); } diff --git a/widgets/perfgraphs.h b/widgets/perfgraphs.h index d3ddb3c6d..961f98fcd 100644 --- a/widgets/perfgraphs.h +++ b/widgets/perfgraphs.h @@ -3,7 +3,7 @@ class perfgraph_panel : public ui_panel { std::array history = { 0 }; - size_t pos = 0; + size_t history_pos = 0; enum timers_e { gfx_total = 0, From cf94a39e9f5e16c27d1995869356d2d3bbbe6804 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 03:43:44 +0100 Subject: [PATCH 081/136] refactor(ai): one span test for the pantographs and the AI, a wire query and the stop solver (#357) Step 1 of 2 for the AI stopping with its pantograph past the end of the overhead wire. Nothing changes in what the vehicles or the AI do. - vehicle/aiwire.{h,cpp} (core): span_contact(), the geometry of a pantograph against a span of the wire, moved out of basic_cell::update_traction with the same operations in the same order; reaches(); wire_shortfall(), how far short of its target a train stops to keep its rear pantograph under the wire (3 m margin, 2 m steps, up to 300 m back, 0 when nothing is found); stops_under_wire(), which stops this applies to. - basic_cell::update_traction calls span_contact(). - basic_cell/basic_section/basic_region::wire_over(): is there a wire over a point of the track within reach of a pantograph. Not called yet. - tests/unit/test_ai_wire.cpp, including a check that span_contact() gives the very numbers of the code it replaced. --- CMakeLists.txt | 1 + scene/scene.cpp | 80 +++++++++--- scene/scene.h | 13 ++ tests/unit/test_ai_wire.cpp | 254 ++++++++++++++++++++++++++++++++++++ vehicle/aiwire.cpp | 78 +++++++++++ vehicle/aiwire.h | 75 +++++++++++ 6 files changed, 485 insertions(+), 16 deletions(-) create mode 100644 tests/unit/test_ai_wire.cpp create mode 100644 vehicle/aiwire.cpp create mode 100644 vehicle/aiwire.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 78abf46a2..c78515f1d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -557,6 +557,7 @@ set(CORE_SOURCES "scripting/scriptscreenkernels.cpp" "scripting/scriptscreendrawing.cpp" "simulation/simulationtestrules.cpp" +"vehicle/aiwire.cpp" "vehicle/blackbox.cpp" "utilities/physicslog.cpp" "vehicle/enginestart.cpp" diff --git a/scene/scene.cpp b/scene/scene.cpp index b31c1749a..eed3f6438 100644 --- a/scene/scene.cpp +++ b/scene/scene.cpp @@ -22,6 +22,7 @@ http://mozilla.org/MPL/2.0/. #include "scene/sceneterrain.h" #include "rendering/renderer.h" #include "widgets/map_objects.h" +#include "vehicle/aiwire.h" namespace scene { @@ -57,25 +58,15 @@ basic_cell::update_traction( TDynamicObject *Vehicle, int const Pantographindex for( auto *traction : m_directories.traction ) { - // współczynniki równania parametrycznego - auto const paramfrontdot = glm::dot( traction->vParametric, vFront ); - auto const fRaParam = - -( glm::dot( traction->pPoint1, vFront ) - glm::dot( pantographposition, vFront ) ) - / ( paramfrontdot != 0.0 ? - paramfrontdot : - 0.001 ); // div0 trap - - if( fRaParam < -0.001 - || fRaParam > 1.001 ) { continue; } + // the span against the pantograph, the geometry the AI uses to find the wire as well + auto const contact = ai_wire::span_contact( + traction->pPoint1, traction->vParametric, pantographposition, vFront, vUp, vLeft, pantograph->fWidth ); // jeśli tylko jest w przedziale, wyznaczyć odległość wzdłuż wektorów vUp i vLeft - // punkt styku płaszczyzny z drutem (dla generatora łuku el.) - auto const vStyk = traction->pPoint1 + fRaParam * traction->vParametric; - // wektor musi się mieścić w przedziale ruchu pantografu - auto const vGdzie = vStyk - pantographposition; - auto fVertical = glm::dot( vGdzie, vUp ); + if( false == contact.within ) { continue; } + auto fVertical = contact.vertical; if( fVertical >= 0.0 ) { // jeśli ponad pantografem (bo może łapać druty spod wiaduktu) - auto const fHorizontal = std::abs( glm::dot( vGdzie, vLeft ) ) - pantograph->fWidth; + auto const fHorizontal = contact.horizontal; if (Global.bEnableTraction && fVertical < pantograph->PantWys - 0.15 ) { @@ -120,6 +111,24 @@ basic_cell::update_traction( TDynamicObject *Vehicle, int const Pantographindex } } +// checks whether a wire of the cell, not broken, is within reach of a pantograph at specified point +bool +basic_cell::wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double const Halfwidth, double const Minheight, double const Maxheight ) const { + + for( auto const *traction : m_directories.traction ) { + if( ( traction->DamageFlag & 128 ) != 0 ) { + // a broken wire powers nothing + continue; + } + if( ai_wire::reaches( + ai_wire::span_contact( traction->pPoint1, traction->vParametric, Point, Front, Up, Left, Halfwidth ), + Minheight, Maxheight ) ) { + return true; + } + } + return false; +} + // legacy method, updates sounds and polls event launchers within radius around specified point void basic_cell::update_events() { @@ -785,6 +794,22 @@ basic_section::update_traction( TDynamicObject *Vehicle, int const Pantographind } } +// checks whether a wire of the section's cells around specified point is within reach of a pantograph at the point +bool +basic_section::wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double const Halfwidth, double const Minheight, double const Maxheight ) const { + + auto const radius { EU07_CELLSIZE * 0.5 }; // the same area of interest the pantographs look for their wire in + + for( auto const &cell : m_cells ) { + // we reject early cells which aren't within our area of interest + if( glm::length2( cell.area().center - Point ) < sq( cell.area().radius + radius ) + && cell.wire_over( Point, Front, Up, Left, Halfwidth, Minheight, Maxheight ) ) { + return true; + } + } + return false; +} + // legacy method, polls event launchers within radius around specified point void basic_section::update_events( glm::dvec3 const &Location, float const Radius ) { @@ -1168,6 +1193,29 @@ basic_region::update_traction( TDynamicObject *Vehicle, int const Pantographinde } } +// checks whether there's a contact wire over specified point, within reach of a pantograph there +bool +basic_region::wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, double const Halfwidth, double const Minheight, double const Maxheight ) const { + + // the vertical up and the horizontal left of the heading. the tilt of the track in curves is left out + auto const up { glm::dvec3 { 0.0, 1.0, 0.0 } }; + auto const left { glm::cross( up, Front ) }; + auto const leftlength { glm::length( left ) }; + if( leftlength <= 0.0 ) { + // no heading along the ground + return false; + } + // a list of its own, not the shared scratchpad of the region + std::vector sectionlist; + sections( Point, EU07_CELLSIZE * 0.5, sectionlist ); + for( auto const *section : sectionlist ) { + if( section->wire_over( Point, Front, up, left / leftlength, Halfwidth, Minheight, Maxheight ) ) { + return true; + } + } + return false; +} + // checks whether specified file is a valid region data file bool basic_region::is_scene( std::string const &Scenariofile ) const { diff --git a/scene/scene.h b/scene/scene.h index 1c3f8064c..b8256e257 100644 --- a/scene/scene.h +++ b/scene/scene.h @@ -109,6 +109,10 @@ public: // legacy method, finds and assigns traction piece to specified pantograph of provided vehicle void update_traction( TDynamicObject *Vehicle, int const Pantographindex ); + // checks whether a wire, not broken, is within reach of a pantograph at specified point: the plane of the pantograph's + // movement, normal to Front, crosses it over the slide of half width Halfwidth, between Minheight and Maxheight along Up + bool + wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double const Halfwidth, double const Minheight, double const Maxheight ) const; // legacy method, polls event launchers within radius around specified point void update_events(); @@ -320,6 +324,10 @@ public: // legacy method, finds and assigns traction piece to specified pantograph of provided vehicle void update_traction( TDynamicObject *Vehicle, int const Pantographindex ); + // checks whether a wire, not broken, is within reach of a pantograph at specified point: the plane of the pantograph's + // movement, normal to Front, crosses it over the slide of half width Halfwidth, between Minheight and Maxheight along Up + bool + wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double const Halfwidth, double const Minheight, double const Maxheight ) const; // legacy method, updates sounds and polls event launchers within radius around specified point void update_events( glm::dvec3 const &Location, float const Radius ); @@ -446,6 +454,11 @@ public: // legacy method, finds and assigns traction piece to specified pantograph of provided vehicle void update_traction( TDynamicObject *Vehicle, int const Pantographindex ); + // checks whether there's a contact wire, not broken, over specified point of a track with heading Front, within reach of + // a pantograph there: over its slide of half width Halfwidth, between Minheight and Maxheight above the point. the + // geometry is the one the pantographs find their wire with (ai_wire::span_contact), with the vertical up + bool + wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, double const Halfwidth, double const Minheight, double const Maxheight ) const; // legacy method, polls event launchers around camera void update_events(); diff --git a/tests/unit/test_ai_wire.cpp b/tests/unit/test_ai_wire.cpp new file mode 100644 index 000000000..070f8618f --- /dev/null +++ b/tests/unit/test_ai_wire.cpp @@ -0,0 +1,254 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/aiwire.h" + +#include +#include +#include + +// where the overhead wire is for the AI driver (vehicle/aiwire.h): a pantograph against a span of the wire, and how far +// short of its target a train stops to keep its pantograph under the wire. the scene query over these +// (basic_region::wire_over) needs the scene, which the unit tests don't link + +namespace { + +// a vehicle running along +z on level track, the pantograph's base point 4 m above the origin +glm::dvec3 const front{0.0, 0.0, 1.0}; +glm::dvec3 const up{0.0, 1.0, 0.0}; +glm::dvec3 const left{1.0, 0.0, 0.0}; +glm::dvec3 const pantograph{0.0, 4.0, 0.0}; +double const halfwidth{0.5}; + +// a 100 m span along the track, at height Height and Offset to the side, its middle at Middle along the track +ai_wire::contact along(double const Offset, double const Height, double const Middle = 0.0) { + return ai_wire::span_contact({Offset, Height, Middle - 50.0}, {0.0, 0.0, 100.0}, pantograph, front, up, left, + halfwidth); +} + +// the wire over the route up to Last metres from the head of the train +auto wire_to(double const Last) { + return [Last](double const Distance) { return Distance <= Last; }; +} + +} // namespace + +TEST_CASE("ai wire: a span centred over the pantograph is on the slide") { + auto const contact{along(0.0, 6.0)}; + + CHECK(contact.within); + CHECK(contact.vertical == doctest::Approx(2.0)); + CHECK(contact.horizontal == doctest::Approx(-halfwidth)); + CHECK(ai_wire::reaches(contact, 1.0, 3.0)); +} + +TEST_CASE("ai wire: a span at the very edge of the slide still touches it, one beyond it doesn't") { + auto const edge{along(halfwidth, 6.0)}; + CHECK(edge.horizontal == doctest::Approx(0.0)); + CHECK(ai_wire::reaches(edge, 1.0, 3.0)); + // either side + CHECK(ai_wire::reaches(along(-halfwidth, 6.0), 1.0, 3.0)); + + auto const beyond{along(halfwidth + 0.1, 6.0)}; + CHECK(beyond.within); + CHECK(beyond.horizontal == doctest::Approx(0.1)); + CHECK_FALSE(ai_wire::reaches(beyond, 1.0, 3.0)); +} + +TEST_CASE("ai wire: the wire is reached only within the given heights") { + auto const contact{along(0.0, 6.0)}; + + CHECK_FALSE(ai_wire::reaches(contact, 3.0, 9.0)); // too low: below the lowest height + CHECK_FALSE(ai_wire::reaches(contact, 0.0, 1.5)); // too high: a bridge's wire above the line + CHECK(ai_wire::reaches(contact, 2.0, 2.0)); // the limits are included +} + +TEST_CASE("ai wire: a span below the pantograph is crossed but out of reach") { + auto const contact{along(0.0, 3.0)}; + + CHECK(contact.within); + CHECK(contact.vertical == doctest::Approx(-1.0)); + CHECK_FALSE(ai_wire::reaches(contact, 0.0, 9.0)); +} + +TEST_CASE("ai wire: a span ahead of or behind the pantograph isn't crossed") { + auto const ahead{along(0.0, 6.0, 60.0)}; + CHECK_FALSE(ahead.within); + CHECK_FALSE(ai_wire::reaches(ahead, 0.0, 9.0)); + + CHECK_FALSE(along(0.0, 6.0, -60.0).within); + // the ends of the span have the tolerance of the vehicles: 0.001 of the span's length + CHECK(along(0.0, 6.0, 50.05).within); + CHECK(along(0.0, 6.0, -50.05).within); + CHECK_FALSE(along(0.0, 6.0, 50.2).within); +} + +TEST_CASE("ai wire: a span skewed against the track is met where it crosses the plane of the pantograph") { + // the zigzag of the wire: from 0.3 m to the right to 0.3 m to the left over 100 m + auto const zigzag{ai_wire::span_contact({-0.3, 6.0, -50.0}, {0.6, 0.0, 100.0}, pantograph + glm::dvec3{0, 0, 25.0}, + front, up, left, halfwidth)}; + CHECK(zigzag.within); + CHECK(zigzag.horizontal == doctest::Approx(0.15 - halfwidth)); + CHECK(ai_wire::reaches(zigzag, 1.0, 3.0)); + + // a sloping span from a tunnel portal, 1 m lower at its far end: the height where the plane crosses it + auto const sloping{ai_wire::span_contact({0.0, 6.0, -50.0}, {0.0, -1.0, 100.0}, pantograph + glm::dvec3{0, 0, 25.0}, + front, up, left, halfwidth)}; + CHECK(sloping.vertical == doctest::Approx(1.25)); + + // a span of a wire crossing the line at a right angle lies in the plane of the pantograph over the track, and is + // out of reach a step along the track (the division by zero trap) + auto const across{ai_wire::span_contact({-5.0, 6.0, 0.0}, {10.0, 0.0, 0.0}, pantograph, front, up, left, halfwidth)}; + CHECK(across.within); + CHECK(std::isfinite(across.vertical)); + CHECK_FALSE(ai_wire::reaches(across, 0.0, 9.0)); // its end, 5 m to the side + CHECK_FALSE(ai_wire::span_contact({-5.0, 6.0, 0.0}, {10.0, 0.0, 0.0}, pantograph + glm::dvec3{0, 0, 1.0}, front, up, + left, halfwidth) + .within); +} + +TEST_CASE("ai wire: the direction of travel doesn't change what the pantograph meets") { + auto const forward{along(0.3, 6.0)}; + auto const backward{ai_wire::span_contact({0.3, 6.0, -50.0}, {0.0, 0.0, 100.0}, pantograph, -front, up, -left, + halfwidth)}; + + CHECK(backward.within); + CHECK(backward.vertical == forward.vertical); + CHECK(backward.horizontal == forward.horizontal); +} + +TEST_CASE("ai wire: the span test gives the very numbers of the code the vehicles had before it was moved here") { + // the math of basic_cell::update_traction before it called span_contact, as it was there + struct legacy { + bool within; + double vertical; + double horizontal; + }; + auto const legacy_contact{[](glm::dvec3 const &pPoint1, glm::dvec3 const &vParametric, + glm::dvec3 const &pantographposition, glm::dvec3 const &vFront, glm::dvec3 const &vUp, + glm::dvec3 const &vLeft, double const fWidth) { + auto const paramfrontdot = glm::dot(vParametric, vFront); + auto const fRaParam = + -(glm::dot(pPoint1, vFront) - glm::dot(pantographposition, vFront)) / (paramfrontdot != 0.0 ? paramfrontdot : 0.001); + if (fRaParam < -0.001 || fRaParam > 1.001) { + return legacy{false, 0.0, 0.0}; + } + auto const vStyk = pPoint1 + fRaParam * vParametric; + auto const vGdzie = vStyk - pantographposition; + auto const fVertical = glm::dot(vGdzie, vUp); + auto const fHorizontal = std::abs(glm::dot(vGdzie, vLeft)) - fWidth; + return legacy{true, fVertical, fHorizontal}; + }}; + + // pseudo-random vehicles and spans around a point far from the origin, as in a real scenery + std::uint32_t seed{12345}; + auto const next{[&seed](double const Low, double const High) { + seed = seed * 1664525u + 1013904223u; + return Low + (High - Low) * (seed >> 8) / double(1u << 24); + }}; + int within{0}; + for (int sample = 0; sample < 2000; ++sample) { + auto const heading{next(0.0, 6.283185307179586)}; + auto const cant{next(-0.1, 0.1)}; + glm::dvec3 const vFront{std::sin(heading), next(-0.03, 0.03), std::cos(heading)}; + glm::dvec3 const vUp{std::sin(cant) * std::cos(heading), std::cos(cant), -std::sin(cant) * std::sin(heading)}; + auto const vLeft{glm::cross(vUp, vFront)}; + glm::dvec3 const position{next(-20000.0, 20000.0), next(100.0, 300.0), next(-20000.0, 20000.0)}; + auto const pantographposition{position + vUp * 4.2}; + auto const spanheading{heading + next(-0.05, 0.05)}; + glm::dvec3 const vParametric{60.0 * std::sin(spanheading), next(-0.5, 0.5), 60.0 * std::cos(spanheading)}; + auto const pPoint1{position + glm::dvec3{next(-1.0, 1.0), next(5.0, 7.0), next(-1.0, 1.0)} - vParametric * next(-0.2, 1.2)}; + auto const fWidth{next(0.4, 0.7)}; + + auto const old{legacy_contact(pPoint1, vParametric, pantographposition, vFront, vUp, vLeft, fWidth)}; + auto const now{ai_wire::span_contact(pPoint1, vParametric, pantographposition, vFront, vUp, vLeft, fWidth)}; + CAPTURE(sample); + REQUIRE(now.within == old.within); + if (old.within) { + ++within; + // bit for bit + REQUIRE(now.vertical == old.vertical); + REQUIRE(now.horizontal == old.horizontal); + } + } + // both kinds were tried + CHECK(within > 200); + CHECK(within < 1800); +} + +TEST_CASE("ai wire: a stop with the wire over the pantograph stays where it is") { + auto const everywhere{[](double) { return true; }}; + CHECK(ai_wire::wire_shortfall(everywhere, 20.0, 130.0) == 0.0); + + // the wire ends between the pantographs: the rear one the train relies on is under it, with the margin ahead + CHECK(ai_wire::wire_shortfall(wire_to(118.0), 20.0, 130.0) == 0.0); + // gaps behind the pantograph don't matter + auto const gap_behind{[](double const Distance) { return Distance <= 90.0 || Distance >= 95.0; }}; + CHECK(ai_wire::wire_shortfall(gap_behind, 20.0, 130.0) == 0.0); +} + +TEST_CASE("ai wire: a stop past the end of the wire is moved back to put the pantograph under the wire") { + // the head stops at 130 m, the pantograph 20 m behind it at 110 m; the wire ends at 100 m. 2 m steps back to the + // first place with the wire over the pantograph and 3 m ahead of it: 96 m + CHECK(ai_wire::wire_shortfall(wire_to(100.0), 20.0, 130.0) == doctest::Approx(14.0)); + // the wire ends right at the pantograph: no margin ahead + CHECK(ai_wire::wire_shortfall(wire_to(110.0), 20.0, 130.0) == doctest::Approx(4.0)); + // a gap in the wire at the pantograph: the stop goes before the gap + auto const gap{[](double const Distance) { return Distance <= 107.0 || Distance >= 112.0; }}; + CHECK(ai_wire::wire_shortfall(gap, 20.0, 130.0) == doctest::Approx(6.0)); +} + +TEST_CASE("ai wire: the margin of wire ahead of the pantograph") { + // exactly the margin ahead: fine + CHECK(ai_wire::wire_shortfall(wire_to(113.0), 20.0, 130.0) == 0.0); + // a little less: one step back + CHECK(ai_wire::wire_shortfall(wire_to(112.9), 20.0, 130.0) == doctest::Approx(2.0)); + // other margins and steps + CHECK(ai_wire::wire_shortfall(wire_to(100.0), 20.0, 130.0, 0.0, 1.0) == doctest::Approx(10.0)); + CHECK(ai_wire::wire_shortfall(wire_to(100.0), 20.0, 130.0, 5.0, 1.0) == doctest::Approx(15.0)); +} + +TEST_CASE("ai wire: without the wire within the walk back the stop stays where it is") { + auto const nowhere{[](double) { return false; }}; + CHECK(ai_wire::wire_shortfall(nowhere, 20.0, 130.0) == 0.0); + + // the pantograph at 110 m: the wire ends more than 300 m back + CHECK(ai_wire::wire_shortfall(wire_to(-200.0), 20.0, 130.0) == 0.0); + // the last place looked at is 300 m back + CHECK(ai_wire::wire_shortfall(wire_to(-187.0), 20.0, 130.0) == doctest::Approx(300.0)); + CHECK(ai_wire::wire_shortfall(wire_to(-187.0), 20.0, 130.0, 3.0, 2.0, 298.0) == 0.0); +} + +TEST_CASE("ai wire: a stop without a coverage or a step to walk with stays where it is") { + CHECK(ai_wire::wire_shortfall({}, 20.0, 130.0) == 0.0); + CHECK(ai_wire::wire_shortfall(wire_to(100.0), 20.0, 130.0, 3.0, 0.0) == 0.0); + CHECK(ai_wire::wire_shortfall(wire_to(100.0), 20.0, 130.0, 3.0, -2.0) == 0.0); +} + +TEST_CASE("ai wire: the walk back asks for the places the 2 m steps give") { + std::vector asked; + auto const recording{[&asked](double const Distance) { + asked.push_back(Distance); + return Distance <= 100.0; + }}; + ai_wire::wire_shortfall(recording, 20.0, 130.0); + + // the pantograph's place and the margin ahead, then the steps back; the margin is asked only where the place is + // under the wire + std::vector const expected{110.0, 108.0, 106.0, 104.0, 102.0, 100.0, 103.0, 98.0, 101.0, 96.0, 99.0}; + CHECK(asked == expected); +} + +TEST_CASE("ai wire: which stops keep the pantograph under the wire") { + using ai_wire::stop_kind; + // the stops of a train that runs with the wire + CHECK(ai_wire::stops_under_wire(true, true, false, stop_kind::track_end)); + CHECK(ai_wire::stops_under_wire(true, true, false, stop_kind::timetable_stop)); + // a signal is a wait, the vehicle to couple to may stand without the wire + CHECK_FALSE(ai_wire::stops_under_wire(true, true, false, stop_kind::signal)); + CHECK_FALSE(ai_wire::stops_under_wire(true, true, false, stop_kind::coupling)); + // without a current collector, with the voltage made up, where the scenery says to coast or lower the pantographs + CHECK_FALSE(ai_wire::stops_under_wire(false, true, false, stop_kind::track_end)); + CHECK_FALSE(ai_wire::stops_under_wire(true, false, false, stop_kind::track_end)); + CHECK_FALSE(ai_wire::stops_under_wire(true, true, true, stop_kind::timetable_stop)); +} diff --git a/vehicle/aiwire.cpp b/vehicle/aiwire.cpp new file mode 100644 index 000000000..999d69075 --- /dev/null +++ b/vehicle/aiwire.cpp @@ -0,0 +1,78 @@ +/* +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/aiwire.h" + +#include + +namespace ai_wire { + +contact span_contact(glm::dvec3 const &Point1, glm::dvec3 const &Parametric, glm::dvec3 const &Point, + glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double const Halfwidth) { + // Winger 170204: the parameter of the span's point in the plane of the pantograph's movement (the plane normal to + // Front through Point). the operations and their order are those the vehicles always had, so they find the same wire + auto const paramfrontdot = glm::dot(Parametric, Front); + auto const parameter = -(glm::dot(Point1, Front) - glm::dot(Point, Front)) / (paramfrontdot != 0.0 ? paramfrontdot : 0.001); + + contact result; + if (parameter < -0.001 || parameter > 1.001) { + return result; + } + // the point where the wire crosses the plane, against the pantograph + auto const crossing = Point1 + parameter * Parametric; + auto const offset = crossing - Point; + result.within = true; + result.vertical = glm::dot(offset, Up); + result.horizontal = std::abs(glm::dot(offset, Left)) - Halfwidth; + return result; +} + +bool reaches(contact const &Contact, double const Minheight, double const Maxheight) { + return Contact.within && Contact.horizontal <= 0.0 && Contact.vertical >= Minheight && Contact.vertical <= Maxheight; +} + +double wire_shortfall(std::function const &Covered, double const Pantograph, double const Stop, + double const Margin, double const Step, double const Walkback) { + if (!Covered || Step <= 0.0) { + return 0.0; + } + auto const fine{[&](double const Place) { return Covered(Place) && Covered(Place + Margin); }}; + // the pantograph at the target of the head + auto const target{Stop - Pantograph}; + if (fine(target)) { + return 0.0; + } + // the places back are counted from the target, not added up, so the steps don't drift + auto const steps{static_cast(std::floor(Walkback / Step + 1e-9))}; + for (int step = 1; step <= steps; ++step) { + auto const back{step * Step}; + if (fine(target - back)) { + return back; + } + } + return 0.0; +} + +bool stops_under_wire(bool const Collector, bool const Livetraction, bool const Overheadrestricted, stop_kind const Kind) { + if (!Collector || !Livetraction || Overheadrestricted) { + return false; + } + switch (Kind) { + case stop_kind::track_end: + case stop_kind::timetable_stop: + return true; + case stop_kind::signal: + case stop_kind::coupling: + default: + return false; + } +} + +} // namespace ai_wire diff --git a/vehicle/aiwire.h b/vehicle/aiwire.h new file mode 100644 index 000000000..89ccb1ecc --- /dev/null +++ b/vehicle/aiwire.h @@ -0,0 +1,75 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include + +#include + +// where the overhead contact wire is, for the AI driver to stop its train with the pantograph under the wire, not past +// the end of it. the geometry of a pantograph against a span of the wire is the one the vehicles use to find their wire +// (basic_cell::update_traction), so the AI sees the wire where the pantographs do +namespace ai_wire { + +// a pantograph against one span of the wire +struct contact { + // the plane of the pantograph's movement (across the vehicle, at the pantograph) cuts the span, between its ends + bool within{false}; + // height of the wire above the pantograph's base point, along the up vector. negative for a wire below it + double vertical{0.0}; + // sideways distance of the wire from the working part of the slide: |offset along the left vector| less the slide's + // half width. the wire is on the slide when it's not positive + double horizontal{0.0}; +}; + +// the pantograph with its base point at Point, on a vehicle whose front, up and left vectors are Front, Up and Left, and +// a slide of half width Halfwidth, against the span from Point1 along Parametric (the span's other end is Point1 + +// Parametric). for a span parallel to the plane of the pantograph's movement the distance to the plane is divided by +// 0.001 in place of 0 (the division by zero trap the vehicles always had), which puts the crossing outside the span +// unless the span lies in the plane +contact span_contact(glm::dvec3 const &Point1, glm::dvec3 const &Parametric, glm::dvec3 const &Point, + glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double Halfwidth); + +// the span is a wire the pantograph can reach: it crosses the plane of the pantograph's movement on the slide, between +// Minheight and Maxheight above the pantograph's base point. the heights keep out the wires of the bridges above the +// line and of the lines below it +bool reaches(contact const &Contact, double Minheight, double Maxheight); + +// the default margin of wire ahead of the pantograph at a stop, the step and the farthest distance back the stop is +// looked for under the wire, in metres +double const stop_margin{3.0}; +double const stop_step{2.0}; +double const stop_walk_back{300.0}; + +// how far short of its target a train has to stop so its pantograph stays under the wire, in metres along the route. +// the distances are along the route from the head of the train: Stop the target of the head, Pantograph the pantograph +// the train relies on (the rearmost one it raises) behind the head. Covered tells whether there's a wire over the +// route at the given distance. the pantograph at the stop is fine when there's wire over it and Margin ahead of it; +// otherwise it's moved back by Step at a time, up to Walkback, to the first place it's fine at. 0 when it's fine at the +// target, and when no place within Walkback is (not an electrified stretch, or a gap too long to tell about: stopping +// short won't help there) +double wire_shortfall(std::function const &Covered, double Pantograph, double Stop, + double Margin = stop_margin, double Step = stop_step, double Walkback = stop_walk_back); + +// what makes the train stop at a place +enum class stop_kind { + track_end, // the end of the track, e.g. a buffer stop, in train or shunting mode + timetable_stop, // a stop of the timetable (W4 indicator) + signal, // a signal at stop + coupling, // a vehicle to couple to or to uncouple from +}; + +// the train stops with its pantograph under the wire. not when it runs without the wire: without a current collector, +// with the voltage made up (livetraction off), on a stretch the scenery tells to coast or to run with the pantographs +// down. not for a signal (a wait, the wire ending before a signal is a fault of the scenery) and not for a coupling +// (the vehicle to couple to may stand on a siding without the wire) +bool stops_under_wire(bool Collector, bool Livetraction, bool Overheadrestricted, stop_kind Kind); + +} // namespace ai_wire From f398c0039d3024061ffce3bfe911ee41a5fdfda6 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 03:43:57 +0100 Subject: [PATCH 082/136] fix(odometer): a save lost to another simulation's save is written again (#354) Two simulations sharing eu07_odometers.txt could lose a save: A reads the file, B renames its file in, A renames its own over it. B had already cleared its modified flag, so its next save returned at once and its states stayed lost (known limit from the review of #283). A write now leaves the store unconfirmed. The next save with nothing recorded reads and merges the file as before, and writes again only when the file lacks a state of the process, the same or newer by the merge rule (compared as written, rounded to the file's digits). Otherwise the store is confirmed and later saves return at once, as before. A process holding an older state takes the file's one, so two processes settle instead of rewriting each other. --- tests/unit/test_odometer.cpp | 135 ++++++++++++++++++++++++++++++++++- vehicle/odometer.cpp | 36 ++++++++-- vehicle/odometer.h | 17 ++++- 3 files changed, 180 insertions(+), 8 deletions(-) diff --git a/tests/unit/test_odometer.cpp b/tests/unit/test_odometer.cpp index 067e31037..295d722cd 100644 --- a/tests/unit/test_odometer.cpp +++ b/tests/unit/test_odometer.cpp @@ -355,13 +355,146 @@ TEST_CASE("odometer: two simulations saving one file keep each other's states") } CHECK(files == 1); } - SUBCASE("a store with nothing recorded since doesn't write") { + SUBCASE("a store with nothing recorded since doesn't write, once the file showed what it saved") { + REQUIRE(odometer::save(second, path)); write_file(path, "1 replaced by hand\n"); REQUIRE(odometer::save(second, path)); CHECK(load().size() == 1); } } +namespace { + +odometer::store load_store(std::filesystem::path const &Path) { + odometer::store store; + std::ifstream input{Path, std::ios::binary}; + store.read(input); + return store; +} + +// a comment line added to the file; a save that writes the file drops it +void mark(std::filesystem::path const &Path) { + std::ofstream{Path, std::ios::binary | std::ios::app} << "# not written since\n"; +} + +bool marked(std::filesystem::path const &Path) { + std::ifstream input{Path, std::ios::binary}; + std::stringstream content; + content << input.rdbuf(); + return content.str().find("# not written since") != std::string::npos; +} + +// the save of Late reads the file before the save of Early writes it, and puts its own file in place after: Late +// writes the file as it was before Early's save, Early's states are gone from it +void interleave(odometer::store &Early, odometer::store &Late, std::filesystem::path const &Path) { + auto const view{Path.parent_path() / "late_view" / Path.filename()}; + std::filesystem::create_directories(view.parent_path()); + std::filesystem::copy_file(Path, view, std::filesystem::copy_options::overwrite_existing); + REQUIRE(odometer::save(Early, Path)); + REQUIRE(odometer::save(Late, view)); + std::filesystem::rename(view, Path); +} + +} // namespace + +TEST_CASE("odometer: a save another simulation's save put its file over is written again") { + scratch_directory directory{"odometer_lost_save"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, "1000 shared\n"); + auto first{load_store(path)}; + auto second{load_store(path)}; + first.record("first only", run(70.0, 1000.0)); + second.record("second only", run(80.0, 1000.0)); + + interleave(second, first, path); + // the race of the two saves: the second one's state is gone from the file + REQUIRE_FALSE(load_store(path).find("second only").has_value()); + REQUIRE(load_store(path).find("first only").has_value()); + + // the second one's next save, nothing recorded since, finds the file without its state and writes it again + CHECK_FALSE(second.modified()); + REQUIRE(odometer::save(second, path)); + auto const saved{load_store(path)}; + CHECK(saved.size() == 3); + CHECK(saved.find("second only").value_or(0.0) == doctest::Approx(81.0)); + CHECK(saved.find("first only").value_or(0.0) == doctest::Approx(71.0)); + CHECK(saved.find("shared").value_or(0.0) == 1000.0); + + // both find their states in the file now: their next saves don't write it + mark(path); + for (auto round{0}; round < 3; ++round) { + REQUIRE(odometer::save(first, path)); + REQUIRE(odometer::save(second, path)); + } + CHECK(marked(path)); + CHECK(load_store(path).size() == 3); +} + +TEST_CASE("odometer: two simulations with different states of a vehicle settle on the newer one") { + scratch_directory directory{"odometer_lost_save_conflict"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, "1000 shared\n~20000 guessed by both\n"); + auto first{load_store(path)}; + auto second{load_store(path)}; + // the first one ran the shared vehicle further, and the made up one further from its made up state; the second + // one has a known state of the made up one, from a cab's counter + first.record("shared", run(1000.0, 10000.0)); + second.record("shared", run(1000.0, 5000.0)); + odometer::reading guessed; + guessed.begin(20000.0, odometer::origin::guessed); + guessed.run(9000.0); + first.record("guessed by both", guessed); + odometer::reading seeded; + seeded.begin(300.0, odometer::origin::counter); + second.record("guessed by both", seeded); + + // the second one's save is lost to the first one's, which holds the made up state + interleave(second, first, path); + REQUIRE(load_store(path).guessed("guessed by both")); + + // the second one writes its known state again. the first one takes it, and the second one the larger state of + // the shared vehicle the first one saved + REQUIRE(odometer::save(second, path)); + REQUIRE(odometer::save(first, path)); + auto const settled{load_store(path)}; + CHECK(settled.find("shared").value_or(0.0) == doctest::Approx(1010.0)); + CHECK(settled.find("guessed by both").value_or(0.0) == 300.0); + CHECK_FALSE(settled.guessed("guessed by both")); + CHECK(first.find("guessed by both").value_or(0.0) == 300.0); + CHECK(second.find("shared").value_or(0.0) == doctest::Approx(1010.0)); + + // neither one keeps writing the file over to have its own state there + mark(path); + for (auto round{0}; round < 3; ++round) { + REQUIRE(odometer::save(first, path)); + REQUIRE(odometer::save(second, path)); + } + CHECK(marked(path)); +} + +TEST_CASE("odometer: a save with nothing recorded since doesn't write the file again") { + scratch_directory directory{"odometer_saved_once"}; + auto const path{directory.path / "eu07_odometers.txt"}; + odometer::store store; + // states the file holds rounded to its digits + store.record("known", run(1000.0, 1234.56789)); + odometer::reading guessed; + guessed.begin(12345.678912, odometer::origin::guessed); + guessed.run(98.76543); + store.record("guessed", guessed); + REQUIRE(odometer::save(store, path)); + CHECK_FALSE(store.modified()); + + // the next save finds the file holding the states, rounded as they are: it doesn't write it + mark(path); + REQUIRE(odometer::save(store, path)); + CHECK(marked(path)); + // and the saves after it don't look at the file any more + std::filesystem::remove(path); + REQUIRE(odometer::save(store, path)); + CHECK_FALSE(std::filesystem::exists(path)); +} + TEST_CASE("odometer: a test run neither reads nor saves the player's store") { if (false == Global.test.enabled) CHECK(odometer::persistent()); diff --git a/vehicle/odometer.cpp b/vehicle/odometer.cpp index 8f98cb084..484998e40 100644 --- a/vehicle/odometer.cpp +++ b/vehicle/odometer.cpp @@ -176,6 +176,13 @@ void store::merge(store const &Other) { } } +bool store::holds(store const &Other) const { + return std::all_of(Other.m_states.begin(), Other.m_states.end(), [this](auto const &Entry) { + auto const lookup{m_states.find(Entry.first)}; + return lookup != m_states.end() && false == newer(Entry.second, lookup->second); + }); +} + std::optional read_legacy(std::istream &Input) { std::stringstream content; content << Input.rdbuf(); @@ -277,8 +284,21 @@ store &states() { return odometers; } +namespace { + +// the states as the file holds them once written, the km rounded to the digits written +store as_written(store const &States) { + std::stringstream text; + States.write(text); + store result; + result.read(text); + return result; +} + +} // namespace + bool save(store &States, std::filesystem::path const &File) { - if (false == States.modified()) + if (false == States.modified() && false == States.unconfirmed()) return true; std::error_code error; if (File.has_parent_path()) @@ -286,11 +306,19 @@ bool save(store &States, std::filesystem::path const &File) { // other simulations on the machine (multiplayer, parallel runs) keep their states in the same file: what they // saved since this one read it is merged in, not overwritten { + store saved; std::ifstream input{File, std::ios::binary}; - if (input.is_open()) { - store saved; + if (input.is_open()) saved.read(input); - States.merge(saved); + States.merge(saved); + // another simulation that read the file before the last save of this one and put its own in place after it + // dropped the states this one wrote. when the file holds them all, the same or newer, there's nothing to write + if (false == States.modified()) { + if (saved.holds(as_written(States))) { + States.confirmed(); + return true; + } + WriteLog("Odometer states saved to \"" + File.string() + "\" are missing from it, saving them again"); } } // written aside first, a crash in the middle of a write doesn't lose the states. the file aside is this process' diff --git a/vehicle/odometer.h b/vehicle/odometer.h index 9708311f4..c7aa0950f 100644 --- a/vehicle/odometer.h +++ b/vehicle/odometer.h @@ -46,10 +46,19 @@ public: // the odometers only count up, so of two states of a vehicle the larger is the newer one. they aren't added // up: two simulations on one machine (multiplayer) count the same runs of the same vehicles void merge(store const &Other); + // this store holds every state of the other one, the same or a newer one + bool holds(store const &Other) const; // there are states recorded since they were last saved bool modified() const { return m_modified; } - void saved() { m_modified = false; } + // the states were written to the file. until a later save finds them there (confirmed()), they may have been lost to + // another simulation's save, which read the file before this one wrote it and put its own in place after + void saved() { + m_modified = false; + m_unconfirmed = true; + } + bool unconfirmed() const { return m_unconfirmed; } + void confirmed() { m_unconfirmed = false; } std::size_t size() const { return m_states.size(); } private: @@ -62,6 +71,7 @@ private: std::map m_states; bool m_modified{false}; + bool m_unconfirmed{false}; }; // the vehicle is one the store keeps: one with a driver's cab, which can show its odometer on the cab's counter or a @@ -113,8 +123,9 @@ bool persistent(); store &states(); std::filesystem::path file(); // writes the store to the file when anything was recorded since, merged with what other simulations saved in the -// file meanwhile. it's written to a file of this process aside first, then put in place. returns false when the -// write failed +// file meanwhile. it's written to a file of this process aside first, then put in place. with nothing recorded since, +// the file is read once more after a write, and written again when it lacks any of the states (another simulation's +// save put its file over this one's); otherwise left as it is. returns false when the write failed bool save(store &States, std::filesystem::path const &File); // saves the store of the simulation to its file. a test run doesn't save it bool save(); From b9737fe76db56b1230ca721fb78cd3a82d407090 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 03:44:50 +0100 Subject: [PATCH 083/136] docs: coverage of the parser, the helpers and the PLC with their tests (#338) Numbers of the Coverage run of master bac9954a, after #333: ladderlogic.cpp 4.1% -> 98.2% of its lines, parser.cpp 40.0% -> 97.6%, utilities.cpp 28.2% -> 95.5%; and the first numbers of brakesetting.cpp and odometer.cpp. --- tests/unit/COVERAGE.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/tests/unit/COVERAGE.md b/tests/unit/COVERAGE.md index ffb849ffd..9b677fbed 100644 --- a/tests/unit/COVERAGE.md +++ b/tests/unit/COVERAGE.md @@ -81,7 +81,15 @@ These are run by the game, by vehicles it has or by the cab, the AI or the scene The core library (`eu07_core`) and the test binary hold more than the physics: the parser of the game's text files, the helpers of `utilities.cpp`, the PLC of a vehicle, the parts of the vehicles and of the simulation moved out of the big classes to be tested, and the hosts of the script screens. The sections above don't cover them. Their numbers are lines run, from the report of the Coverage workflow. -The tables show the run before the tests of the parser, the helpers and the PLC (`test_parser.cpp`, `test_utilities.cpp`, `test_ladder_logic.cpp`) were written. What those tests add is measured by the Coverage run of the pull request which brings them, and shown in the summary of that run. +The per-file table further down is from the run before the tests of the parser, the helpers and the PLC (`test_parser.cpp`, `test_utilities.cpp`, `test_ladder_logic.cpp`) were written. With them, in the Coverage run of master `bac9954a` (2026-11-11, after #333; GCC 13.3, unoptimised, gcov): + +| File | Lines run, before | Lines run, with the tests | Functions run, with the tests | +|---|---|---|---| +| `scripting/ladderlogic.cpp` | 4.1% (9 of 217) | 98.2% (213 of 217) | 11 of 11 | +| `utilities/parser.cpp` | 40.0% (170 of 425) | 97.6% (415 of 425) | 41 of 41 | +| `utilities/utilities.cpp` | 28.2% (82 of 291) | 95.5% (299 of 313) | 51 of 51 | + +`utilities.cpp` grew by 22 lines on master between the two runs (`user_cache_path`, `utf8_to_win1250`). All 62 files of the game in that report together: lines 83.5% (15411 of 18464), functions 85.5% (1378 of 1612), branches 59.5% (15503 of 26046). The totals aren't comparable with the run below: the report holds 13 more files, from the merges in between. **The run measured:** pull request #325 on 2026-11-11 (its commit `33cedc45` merged into master `10c7527a`), GCC 13.3, unoptimised, gcov lines. All 49 files of the game in the report together: lines 84.4% (10305 of 12204), functions 85.0% (927 of 1090), branches 62.3% (10325 of 16578). @@ -114,7 +122,7 @@ The tables show the run before the tests of the parser, the helpers and the PLC Notes to the table: - The small headers with the logic of a single part are all run in full: `vehicle/doorwings.h`, `gaugeduplicates.h`, `gaugepositions.h`, `holdcoillever.h`, `lightsprogrammer.h`, `mainctrlact.h`, `mirrors.h`, `scripting/scriptscreendrawing.h`, `scriptscreenkernels.h`, `scriptscreenprogram.h`, `scriptscreens.h`, `utilities/dictionary.h` and `vehicle/blackbox.h`. -- `vehicle/brakesetting.cpp` and `vehicle/odometer.cpp` (the brake setting of the wagons, the odometer store) joined the library on master after that run. They have tests (`test_brake_setting.cpp`, `test_odometer.cpp`) and no numbers yet. +- `vehicle/brakesetting.cpp` and `vehicle/odometer.cpp` (the brake setting of the wagons, the odometer store) joined the library on master after that run. In the run of `bac9954a` their tests (`test_brake_setting.cpp`, `test_odometer.cpp`) run 94.1% (144 of 153) and 87.9% (189 of 215) of their lines, and all 14 and 26 of 28 of their functions. - The script hosts (`scriptscreens.cpp`, `luaprogram.cpp`, `wasmprogram.cpp`) aren't in the library. The test binary compiles them itself, with the real runtimes. - `scene/scenelayers.h`, `scene/scenenode.h` and `scene/scenenodegroups.h` are in the report with a few lines each: the parser reports the files it includes to the scenery, which the tests replace with stubs (`engine_stubs.cpp`). From 18143c2254b923988632cc2c28aaede629a7a8a9 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 04:24:48 +0100 Subject: [PATCH 084/136] feat(event): putvalues Crew: 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: (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: puts an AI driver in a vehicle or takes it off event putvalues none 0 0 0 Crew: 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 --- CMakeLists.txt | 2 + tests/scenarios/README.md | 58 +++- .../scenarios/cases/en57_td_crew_parted.json | 34 ++ .../scenarios/cases/en57_td_crew_remove.json | 29 ++ tests/scenarios/cases/eu07_td_crew_add.json | 31 ++ .../cases/eu07_td_crew_add_rear.json | 33 ++ .../scenarios/cases/eu07_td_crew_refused.json | 40 +++ .../scenarios/cases/eu07_td_crew_remove.json | 27 ++ tests/scenarios/cases/eu07_td_crew_swap.json | 34 ++ tests/scenarios/cases/golf_td_crew_swap.json | 30 ++ .../scenarios/cases/sm42_td_crew_remove.json | 27 ++ tests/scenarios/cases/td_crew.scn | 22 ++ .../cases/vectron_td_crew_remove.json | 27 ++ tests/scenarios/run.py | 127 +++++++ tests/unit/test_crew.cpp | 313 ++++++++++++++++++ vehicle/crew.cpp | 134 ++++++++ vehicle/crew.h | 82 +++++ vehicle/crewchange.cpp | 138 ++++++++ vehicle/crewchange.h | 24 ++ world/Event.cpp | 7 + 20 files changed, 1218 insertions(+), 1 deletion(-) create mode 100644 tests/scenarios/cases/en57_td_crew_parted.json create mode 100644 tests/scenarios/cases/en57_td_crew_remove.json create mode 100644 tests/scenarios/cases/eu07_td_crew_add.json create mode 100644 tests/scenarios/cases/eu07_td_crew_add_rear.json create mode 100644 tests/scenarios/cases/eu07_td_crew_refused.json create mode 100644 tests/scenarios/cases/eu07_td_crew_remove.json create mode 100644 tests/scenarios/cases/eu07_td_crew_swap.json create mode 100644 tests/scenarios/cases/golf_td_crew_swap.json create mode 100644 tests/scenarios/cases/sm42_td_crew_remove.json create mode 100644 tests/scenarios/cases/td_crew.scn create mode 100644 tests/scenarios/cases/vectron_td_crew_remove.json create mode 100644 tests/unit/test_crew.cpp create mode 100644 vehicle/crew.cpp create mode 100644 vehicle/crew.h create mode 100644 vehicle/crewchange.cpp create mode 100644 vehicle/crewchange.h diff --git a/CMakeLists.txt b/CMakeLists.txt index c78515f1d..4bb63e935 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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" diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index 6156828de..d8bdd160b 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -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: `: 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. diff --git a/tests/scenarios/cases/en57_td_crew_parted.json b/tests/scenarios/cases/en57_td_crew_parted.json new file mode 100644 index 000000000..f75a99179 --- /dev/null +++ b/tests/scenarios/cases/en57_td_crew_parted.json @@ -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: 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 } + ] +} diff --git a/tests/scenarios/cases/en57_td_crew_remove.json b/tests/scenarios/cases/en57_td_crew_remove.json new file mode 100644 index 000000000..4ca053a47 --- /dev/null +++ b/tests/scenarios/cases/en57_td_crew_remove.json @@ -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" } + ] +} diff --git a/tests/scenarios/cases/eu07_td_crew_add.json b/tests/scenarios/cases/eu07_td_crew_add.json new file mode 100644 index 000000000..eb3c3637c --- /dev/null +++ b/tests/scenarios/cases/eu07_td_crew_add.json @@ -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: 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" } + ] +} diff --git a/tests/scenarios/cases/eu07_td_crew_add_rear.json b/tests/scenarios/cases/eu07_td_crew_add_rear.json new file mode 100644 index 000000000..a4a677807 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_crew_add_rear.json @@ -0,0 +1,33 @@ +{ + "description": "Crew event, a driver appears in cab B (eu07/maszyna#510): as eu07_td_crew_add, with Crew: -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" } + ] +} diff --git a/tests/scenarios/cases/eu07_td_crew_refused.json b/tests/scenarios/cases/eu07_td_crew_refused.json new file mode 100644 index 000000000..4dc273e03 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_crew_refused.json @@ -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)" } + ] +} diff --git a/tests/scenarios/cases/eu07_td_crew_remove.json b/tests/scenarios/cases/eu07_td_crew_remove.json new file mode 100644 index 000000000..8f1968eaa --- /dev/null +++ b/tests/scenarios/cases/eu07_td_crew_remove.json @@ -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: 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" } + ] +} diff --git a/tests/scenarios/cases/eu07_td_crew_swap.json b/tests/scenarios/cases/eu07_td_crew_swap.json new file mode 100644 index 000000000..4614c4622 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_crew_swap.json @@ -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: 0 0 takes the driver off, which leaves the locomotive braked; 20 s later Crew: 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" } + ] +} diff --git a/tests/scenarios/cases/golf_td_crew_swap.json b/tests/scenarios/cases/golf_td_crew_swap.json new file mode 100644 index 000000000..9eca8c05c --- /dev/null +++ b/tests/scenarios/cases/golf_td_crew_swap.json @@ -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: 0 0 takes the driver off: the car is left with its own brake applied in full, stops and stands. 40 s later Crew: 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" } + ] +} diff --git a/tests/scenarios/cases/sm42_td_crew_remove.json b/tests/scenarios/cases/sm42_td_crew_remove.json new file mode 100644 index 000000000..42e55d9d1 --- /dev/null +++ b/tests/scenarios/cases/sm42_td_crew_remove.json @@ -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" } + ] +} diff --git a/tests/scenarios/cases/td_crew.scn b/tests/scenarios/cases/td_crew.scn new file mode 100644 index 000000000..33def0f24 --- /dev/null +++ b/tests/scenarios/cases/td_crew.scn @@ -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: " 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 diff --git a/tests/scenarios/cases/vectron_td_crew_remove.json b/tests/scenarios/cases/vectron_td_crew_remove.json new file mode 100644 index 000000000..e677b8a3a --- /dev/null +++ b/tests/scenarios/cases/vectron_td_crew_remove.json @@ -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" } + ] +} diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py index dbe13d869..52ff6cf2a 100644 --- a/tests/scenarios/run.py +++ b/tests/scenarios/run.py @@ -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 () .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(" 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, } diff --git a/tests/unit/test_crew.cpp b/tests/unit/test_crew.cpp new file mode 100644 index 000000000..d70cbfb4e --- /dev/null +++ b/tests/unit/test_crew.cpp @@ -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:" 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(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(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); +} diff --git a/vehicle/crew.cpp b/vehicle/crew.cpp new file mode 100644 index 000000000..d32bcc82c --- /dev/null +++ b/vehicle/crew.cpp @@ -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(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(Cab); + } + result.flags = static_cast(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 diff --git a/vehicle/crew.h b/vehicle/crew.h new file mode 100644 index 000000000..f2ab938f1 --- /dev/null +++ b/vehicle/crew.h @@ -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 +#include + +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 putvalues none 0 0 0 Crew: 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 diff --git a/vehicle/crewchange.cpp b/vehicle/crewchange.cpp new file mode 100644 index 000000000..e7bf4abe8 --- /dev/null +++ b/vehicle/crewchange.cpp @@ -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 +void for_each_in_consist(TDynamicObject &Vehicle, Function_ const Function) { + auto side{static_cast(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 diff --git a/vehicle/crewchange.h b/vehicle/crewchange.h new file mode 100644 index 000000000..3b348edaa --- /dev/null +++ b/vehicle/crewchange.h @@ -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 diff --git a/world/Event.cpp b/world/Event.cpp index 94f528589..c007b91dd 100644 --- a/world/Event.cpp +++ b/world/Event.cpp @@ -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 From da1f10d6b7a0edf6b5b22dc88ecdc63f1b954778 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 04:38:31 +0100 Subject: [PATCH 085/136] feat(cab): i-compartmentlights: lamp showing the compartment lighting (#352) A cab lamp keyword for the .mmd, lit while the compartment lighting of the cab's own vehicle (mvOccupied) is on: CompartmentLights.is_active, which LightsCheck() works out from the low voltage power and the compartment lights switches. Bound like i-cablight: in the autolights table, so it is bound again whenever the cab's .mmd is read on a change of the occupied vehicle. No vehicle uses it yet. Unit tests of the state the lamp shows on the real Elf definition. Refs eu07/maszyna#456. --- tests/unit/test_compartment_lights.cpp | 80 ++++++++++++++++++++++++++ vehicle/Train.cpp | 1 + 2 files changed, 81 insertions(+) create mode 100644 tests/unit/test_compartment_lights.cpp diff --git a/tests/unit/test_compartment_lights.cpp b/tests/unit/test_compartment_lights.cpp new file mode 100644 index 000000000..bff60e440 --- /dev/null +++ b/tests/unit/test_compartment_lights.cpp @@ -0,0 +1,80 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +using test::definition; +using test::vehicle; + +// the compartment lights lamp of the cab (i-compartmentlights:) shows CompartmentLights.is_active of the cab's own +// vehicle, which LightsCheck() works out from the low voltage power and the compartment lights switch (eu07/maszyna#456) +// NOTE: the checks call LightsCheck() the way the vehicle update does, after setting the power by hand + +namespace { + +void lights_check(vehicle &Car) { + Car->LightsCheck(0.01); +} + +} // namespace + +TEST_CASE("compartment lights: the lights need low voltage power and the switch") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + REQUIRE(car->CompartmentLights.start_type == start_t::manual); + car->Power24vIsAvailable = false; + car->Power110vIsAvailable = false; + + car->CompartmentLightsSwitch(true, range_t::local); // switch on, no power + lights_check(car); + CHECK_FALSE(car->CompartmentLights.is_active); + + car->Power110vIsAvailable = true; // converter on + lights_check(car); + CHECK(car->CompartmentLights.is_active); + CHECK(car->CompartmentLights.intensity == doctest::Approx(1.0)); + + car->Power110vIsAvailable = false; // battery only: the lights stay on, dimmed + car->Power24vIsAvailable = true; + lights_check(car); + CHECK(car->CompartmentLights.is_active); + CHECK(car->CompartmentLights.intensity == doctest::Approx(0.5)); + + car->Power24vIsAvailable = false; // no power at all + lights_check(car); + CHECK_FALSE(car->CompartmentLights.is_active); +} + +TEST_CASE("compartment lights: the off switch turns the lights off, the on switch back on") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + car->Power110vIsAvailable = true; + + lights_check(car); + CHECK_FALSE(car->CompartmentLights.is_active); // manual start: off until switched on + + // push buttons: the on button latches the lights, they stay on once it is released + car->CompartmentLightsSwitch(true, range_t::local); + lights_check(car); + car->CompartmentLightsSwitch(false, range_t::local); + lights_check(car); + CHECK(car->CompartmentLights.is_active); + + car->CompartmentLightsSwitchOff(true, range_t::local); + lights_check(car); + CHECK_FALSE(car->CompartmentLights.is_active); + car->CompartmentLightsSwitchOff(false, range_t::local); + lights_check(car); + CHECK_FALSE(car->CompartmentLights.is_active); // still off once the off button is released +} + +TEST_CASE("compartment lights: lights started automatically come on with the power alone") { + vehicle car{definition::fiz("elf_v1/21we-a").set("Cntrl", "CompartmentLightsStart", "Automatic")}; + REQUIRE(car->CompartmentLights.start_type == start_t::automatic); + car->Power24vIsAvailable = false; + car->Power110vIsAvailable = false; + + lights_check(car); + CHECK_FALSE(car->CompartmentLights.is_active); + + car->Power110vIsAvailable = true; + lights_check(car); + CHECK(car->CompartmentLights.is_active); +} diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 9c5c9d500..4ed2a6b67 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -12237,6 +12237,7 @@ bool TTrain::initialize_button(cParser &Parser, std::string const &Label, int co {"i-mainpipelock:", &mvOccupied->LockPipe}, {"i-battery:", &mvOccupied->Power24vIsAvailable}, {"i-cablight:", &Cabine[iCabn].bLight}, + {"i-compartmentlights:", &mvOccupied->CompartmentLights.is_active}, }; { auto lookup = autolights.find(Label); From af3d5d9b9fefcc7a2c9d3b40818cc08c0054cc8a Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 08:06:04 +0100 Subject: [PATCH 086/136] CI: one pin of each GitHub Action in all workflows, Dependabot updates for them (#331) * ci: one pin of actions/checkout and actions/download-artifact in all workflows build.yml moves from actions/checkout v5.1.0 to the v6.1.0 pin build_bin.yml already uses, and the two unpinned actions/download-artifact@v4 in the publish job of build_bin.yml get the v4.3.0 hash sonar.yml already uses (the commit the v4 tag points at today, so nothing changes at run time). * ci: Dependabot updates for the GitHub Actions One grouped pull request a week for all actions, so the hash pins and their version comments move together in every workflow. --- .github/dependabot.yml | 13 +++++++++++++ .github/workflows/build.yml | 2 +- .github/workflows/build_bin.yml | 8 ++++---- 3 files changed, 18 insertions(+), 5 deletions(-) create mode 100644 .github/dependabot.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..0a520876d --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,13 @@ +# Keeps the GitHub Actions used by the workflows up to date. The actions are pinned by commit hash, with the +# version in a comment; Dependabot updates both. One pull request a week for all of them, so the workflows +# stay on the same versions. +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + groups: + github-actions: + patterns: + - "*" diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 758b4c8d5..7eaf891fe 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -31,7 +31,7 @@ jobs: env: BUILD_WRAPPER_OUT_DIR: bw-output steps: - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 0 submodules: recursive diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index 12c5c5866..230e814cf 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -583,25 +583,25 @@ jobs: steps: # the AVX2 build keeps the old name of the download, so the links already handed out still work - name: Download Windows build (AVX2) - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: maszyna-windows-x64-avx2-${{ env.CONFIG_WIN }} path: dist/maszyna-windows-x64 - name: Download Windows build (no AVX2) - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: maszyna-windows-x64-noavx2-${{ env.CONFIG_WIN }} path: dist/maszyna-windows-x64-noavx2 - name: Download Linux build (AVX2) - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: maszyna-linux-x64-avx2-${{ env.CONFIG_LINUX }} path: dist/maszyna-linux-x64 - name: Download Linux build (no AVX2) - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: maszyna-linux-x64-noavx2-${{ env.CONFIG_LINUX }} path: dist/maszyna-linux-x64-noavx2 From 040e600bf63d52b76c1d521dd725cdbcb791cdc6 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 16:31:47 +0100 Subject: [PATCH 087/136] Test the 6Dg's power demand in steps of 5% on its real definition (#336) * test: the 6Dg's power demand in steps of 5% on its real definition The 6Dg's definition from the game data (6dg_v1/6dg.fiz, converted alone with test_fiz.cpp; SVN r9630 gave its UCList line CtrlValStep=0.05) joins the real vehicles of tests/unit/data/fiz. On it: - the key loads as shipped, and the demand of the universal controller (eimic) moves by 0.05 per tap or per step of the held raise and lower positions, 20 steps from 0 to 1 and back, never in between nor past the ends of the table; - with the engine running, the engine revolutions, generator power, tractive force and speed reached grow with the demand (0.25 to 1); - without the key the demand moves continuously, as before #273. * test: no empty loop bodies and emplace_back in the 6Dg power steps test (Sonar S1116, S6003) --- tests/unit/test_6dg_power_steps.cpp | 219 ++++++++++++++++++++++++++++ 1 file changed, 219 insertions(+) create mode 100644 tests/unit/test_6dg_power_steps.cpp diff --git a/tests/unit/test_6dg_power_steps.cpp b/tests/unit/test_6dg_power_steps.cpp new file mode 100644 index 000000000..d8444d7e5 --- /dev/null +++ b/tests/unit/test_6dg_power_steps.cpp @@ -0,0 +1,219 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "drive.h" + +#include +#include + +// the 6Dg shunter as the game ships it (data/fiz/6dg_v1/6dg.json): the power demand of its universal controller +// (EIMCtrlType 3, UCList) moves in steps of 5% (UCList CtrlValStep=0.05, eu07/maszyna#412), and its diesel-electric +// drive follows the demand. the controller's positions in the 6Dg's table: 3 holds no power, 4 lowers the power +// to 0, 5 holds it, 6 raises it to 1, each at 0.15 a second after IniCDelay (0.5 s) + +using test::definition; +using test::vehicle; + +namespace { + +constexpr int no_power{3}; +constexpr int lower{4}; +constexpr int hold{5}; +constexpr int raise{6}; + +definition shipped() { + return definition::fiz("6dg_v1/6dg"); +} + +void move_to(vehicle &Loco, int const Position) { + // one notch at a time, as far as the controller goes + while (Loco->MainCtrlPos < Position) { + if (false == Loco->IncMainCtrl(1)) { + break; + } + } + while (Loco->MainCtrlPos > Position) { + if (false == Loco->DecMainCtrl(1)) { + break; + } + } + REQUIRE(Loco->MainCtrlPos == Position); +} + +// the 6Dg started up (engine running), its brakes released and its direction set, its controller holding no power +void get_ready(vehicle &Loco, test::track const &Track) { + auto driven{test::driving(Loco)}; + REQUIRE(test::start_up(driven, Track)); + test::release_brakes(driven.cab); + move_to(Loco, no_power); + for (int i = 0; i < 3 && Loco->DirActive <= 0; ++i) { + Loco->DirectionForward(); + } + REQUIRE(Loco->DirActive > 0); + // the brake pipe was charged during the start-up: the brakes release slowly (about a minute), and the pressure + // switch keeps the line contactors open while the brake cylinders hold over 2 bar + for (int second = 0; second < 180 && Loco->BrakePress > 0.1; ++second) { + test::drive(driven, Track, 1.0); + } + REQUIRE(Loco->BrakePress <= 0.1); + // the line contactors close on the first position past the ones with no power, as the driver passes it + move_to(Loco, lower); + test::drive(driven, Track, 1.0); + move_to(Loco, hold); + test::drive(driven, Track, 5.0); + REQUIRE(Loco->Mains); // the engine running + REQUIRE(Loco->StLinFlag); // the line contactors closed + REQUIRE(false == Loco->SpeedCtrlUnit.IsActive); // the demand of the controller drives, not the speed control + REQUIRE(Loco->eimic == doctest::Approx(0.0)); +} + +// a tap of the controller onto the given position and back onto holding, then a second of running +void tap(vehicle &Loco, int const Position, test::track const &Track) { + move_to(Loco, Position); + Loco.step(Track); + move_to(Loco, hold); + test::drive(test::driving(Loco), Track, 1.0); +} + +// the changes of the demand while the controller stays on the given position for Seconds +std::vector changes_held(vehicle &Loco, int const Position, double const Seconds, test::track const &Track) { + std::vector changes; + move_to(Loco, Position); + auto previous{Loco->eimic}; + for (int i = 0; i < std::lround(Seconds / 0.01); ++i) { + if (Loco->SecuritySystem.is_blinking()) { + Loco->SecuritySystemReset(); // the driver acknowledging the vigilance + } + Loco.step(Track); + if (std::abs(Loco->eimic - previous) > 1e-9) { + changes.push_back(Loco->eimic - previous); + previous = Loco->eimic; + } + } + return changes; +} + +} // namespace + +TEST_CASE("6Dg: the shipped definition sets the controller's power demand in steps of 5%") { + test::track const line{0.15, 0.0}; + vehicle loco{shipped(), 0.0, "test", 1}; + // the key as the game data has it, on the controller it acts on + REQUIRE(loco->EIMCtrlType == 3); + CHECK(loco->UniCtrlValStep == doctest::Approx(0.05)); + // the ends of the table: raising goes up to 1, lowering down to 0, 20 steps of 0.05 between them + auto const top{loco->UniCtrlList[raise].SetCtrlVal}; + auto const bottom{loco->UniCtrlList[lower].SetCtrlVal}; + REQUIRE(top == doctest::Approx(1.0)); + REQUIRE(bottom == doctest::Approx(0.0)); + REQUIRE(loco->UniCtrlList[raise].MaxCtrlVal == doctest::Approx(top)); + REQUIRE(loco->UniCtrlList[lower].MinCtrlVal == doctest::Approx(bottom)); + auto const steps{static_cast(std::lround((top - bottom) / 0.05))}; + CHECK(steps == 20); + get_ready(loco, line); + + SUBCASE("tapped: every tap moves the demand by one step, up to the top and down to the bottom, and no further") { + auto changed{0}; + for (int i = 1; i <= steps + 3; ++i) { + auto const before{loco->eimic}; + tap(loco, raise, line); + CAPTURE(i); + CHECK(loco->eimic == doctest::Approx(std::min(top, before + 0.05))); + CHECK(loco->eimic <= top + 1e-9); + CHECK(loco->eimic_real == doctest::Approx(loco->eimic)); // the demand reaching the drive + changed += std::abs(loco->eimic - before) > 1e-9 ? 1 : 0; + } + CHECK(changed == steps); + CHECK(loco->eimic == doctest::Approx(top)); + + changed = 0; + for (int i = 1; i <= steps + 3; ++i) { + auto const before{loco->eimic}; + tap(loco, lower, line); + CAPTURE(i); + CHECK(loco->eimic == doctest::Approx(std::max(bottom, before - 0.05))); + CHECK(loco->eimic >= bottom - 1e-9); + changed += std::abs(loco->eimic - before) > 1e-9 ? 1 : 0; + } + CHECK(changed == steps); + CHECK(loco->eimic == doctest::Approx(bottom)); + } + + SUBCASE("held: the demand goes over the whole range in steps of 0.05, never in between nor past the ends") { + // 20 steps of 0.05 at 0.15 a second take under 7 s, after the initial delay + auto const up{changes_held(loco, raise, 12.0, line)}; + CHECK(up.size() == static_cast(steps)); + for (auto const change : up) { + CHECK(change == doctest::Approx(0.05)); + } + CHECK(loco->eimic == doctest::Approx(top)); + auto const down{changes_held(loco, lower, 12.0, line)}; + CHECK(down.size() == static_cast(steps)); + for (auto const change : down) { + CHECK(change == doctest::Approx(-0.05)); + } + CHECK(loco->eimic == doctest::Approx(bottom)); + } +} + +TEST_CASE("6Dg: the diesel-electric drive follows the stepped demand") { + test::track const line{0.15, 0.0}; + struct reading { + double demand; + double revolutions; // of the engine, after the demand is set + double force; // tractive + double power; // of the generator + double speed; // reached after the same time + }; + std::vector readings; + for (auto const taps : {5, 10, 15, 20}) { + CAPTURE(taps); + test::reseed_random(); + vehicle loco{shipped(), 0.0, "test", 1}; + get_ready(loco, line); + for (int i = 0; i < taps; ++i) { + move_to(loco, raise); + loco.step(line); + move_to(loco, hold); + loco.step(line); + } + REQUIRE(loco->eimic == doctest::Approx(0.05 * taps)); + REQUIRE(loco->eimic_real == doctest::Approx(0.05 * taps)); + test::drive(test::driving(loco), line, 10.0); + readings.emplace_back(loco->eimic_real, loco->enrot, std::abs(loco->Ft), loco->EnginePower, std::abs(loco.speed())); + } + // at 0.25, 0.5, 0.75 and 1: the engine at 897, 1198, 1499 and (still running up to) 1800 rpm as the WWList table + // gives, about 28, 37, 48 and 59 kN, 87, 261, 445 and 663 kW, 14, 24, 28 and 30 km/h + for (std::size_t i = 1; i < readings.size(); ++i) { + CAPTURE(i); + INFO("demand " << readings[i].demand << ": " << readings[i].revolutions * 60.0 << " rpm, " << readings[i].force << " N, " << readings[i].power << " kW, " << readings[i].speed + << " km/h; before it " << readings[i - 1].revolutions * 60.0 << " rpm, " << readings[i - 1].force << " N, " << readings[i - 1].power << " kW, " + << readings[i - 1].speed << " km/h"); + CHECK(readings[i].demand > readings[i - 1].demand); + CHECK(readings[i].revolutions > readings[i - 1].revolutions); + CHECK(readings[i].force > readings[i - 1].force); + CHECK(readings[i].power > readings[i - 1].power); + CHECK(readings[i].speed > readings[i - 1].speed); + } +} + +TEST_CASE("6Dg: without CtrlValStep the demand moves continuously between the rows of the table, as before") { + test::track const line{0.15, 0.0}; + vehicle loco{shipped().remove("UCList", "CtrlValStep"), 0.0, "test", 1}; + REQUIRE(loco->UniCtrlValStep == 0.0); + get_ready(loco, line); + // a tap moves it by 0.01 only + tap(loco, raise, line); + CHECK(loco->eimic == doctest::Approx(0.01)); + // held, it goes on at the row's 0.15 a second after the initial delay, a little every step + auto const up{changes_held(loco, raise, 12.0, line)}; + CHECK(up.size() > 100); + for (auto const change : up) { + CHECK(change > 0.0); + CHECK(change < 0.05 - 1e-6); + } + CHECK(loco->eimic == doctest::Approx(1.0)); // up to the top of the table, as with the steps + auto const down{changes_held(loco, lower, 12.0, line)}; + CHECK(down.size() > 100); + CHECK(loco->eimic == doctest::Approx(0.0)); +} From 791281b306f8d549a4ee7046b5a9159978e2bee5 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 16:32:06 +0100 Subject: [PATCH 088/136] Refactor/mover long functions (#239) * test: real vehicles and golden traces in the unit tests The game's own vehicles (dynamic/ of the release used for the tests) as JSON of what the game's vehicle loader reads of their .fiz files, includes expanded: test_fiz.cpp converts them on demand and checks the loader reads the same sections, values and rows as of the game's file (fiz.h). Chosen to cover every engine type, brake valve, brake handle, local brake, coupler type, door type and brake delay set the game data uses. Golden traces (golden.h) characterise the simulation, compared within a relative tolerance or exactly, re-recorded with EU07_UNIT_TESTS_UPDATE_GOLDEN=1: - the parameters of every real vehicle as loaded, - the brakes of every real vehicle through charge, service steps, release, overcharge and emergency, on every brake delay setting, - every position of every driver's and local brake handle, - every powered vehicle started up the way the AI does it, driven to full power and braked to a stop (drive.h), - the real electric units and a locomotive with wagons driven whole, as trains of coupled vehicles stepped the way the game steps them (consist.h), - scenarios of the controls (scenario.h): doors, reversing and cab change, slip and sand, emergency stops, releasers, the ep and the electrodynamic brake, heating, loading, a collision, and frames of several physics iterations. * test: commands passed between vehicles Every command RunCommand knows run on every real vehicle and recorded, commands travelling through a train with a vehicle facing backwards, a coupling without the control cable, and loading and unloading by commands. * test: every switch of the cab, sent to the next vehicle Each switch sending its state to the train, each way and to each range, with the controllers and direction among them, on every real vehicle driving another of its kind, recorded for both. * test: the switches of the cab worked on a pair under the catenary The same switches with two seconds for the vehicles to act on each, so the pantographs rise, the main switch closes and the auxiliaries start. * test: gauges of trains in multiple and the damage descriptions The ammeters and the brake force the AI expects, recorded on the electric units and locomotives in multiple driven, the damage described on the driver's panel and ammeters showing the current of controlled vehicles. * test: give load commands their place, as the game does The loading test set its commands with SetInternalCommand, which leaves TCommand::Location as it is: uninitialised in a fresh vehicle, so the distance check of Load= and UnLoad= read garbage and the test failed now and then. The game gives them through PutCommand with the place of the platform, and so do the tests now. * test: brake valves and handles no vehicle of the game data has Fitted to a wagon and to an EU07: the valve variants and handles the loader knows that no real vehicle uses, the CV1 ones and the test handle among them, and a name the loader doesn't know. * test: braking from speed with the automatic ED brake, and a draisine Trains with the EP09, the E6ACT and the EW58 braked by ep, light and full service applications from speed, and the draisine pumped from rest and rolling. Only the E6ACT brings its electrodynamic brake in here. * test: the EP09's electrodynamic brake in service braking held to a stop start_up() took a vehicle for ready once its line breaker was closed and its reservoir full, which a train made already moving is at once: the EP09's manually started converter was never switched on, so there was no 110 V and no electrodynamic brake. It now waits for the converter. The EP09 with wagons is braked from 120 km/h by light, medium, high and full service applications held to a stop: the motors brake, the air of its cylinders is let out and given back as the train slows down. The flag of the electrodynamic brake stays on at a standstill below 2.1 bar. C strings given to CAPTURE are shown as text. * test: the converter switched on before a train is ready, the EW58's ep-staged electrodynamic brake start_up() called a train ready as soon as its line breaker closed and the air was there, so the converter of a unit having it in another car than the cab (the EW58's middle car) was never switched on, and its electrodynamic brake, gated by the 110 V, never came in. The converter and the compressor now always get switched on first. The EW58 brakes electrically by the stages of the ep brake, not by the pipe alone. * test: the ET42 and the 214M railbus among the real vehicles The ET42's halves (its own series motor branch: the motors in series at the high current setting) and the 214MA, a diesel railbus with the hydraulic torque converter, the retarder and the controller of an induction motor drive, converted from the game data and recorded in every sweep of the real vehicles. * test: the wagons' hand brakes released with the train's brakes; the 754, SM31 and SU46 release_brakes() released the hand brake of the driver's vehicle only, so every wagon set up braked kept its hand brake on and got dragged along. It now releases the hand and spring brakes of the whole train, as TController::AutoRewident() does when the AI takes it over, and the traces of the trains with wagons are recorded anew. The 754, the SM31 and the SU46 join the real vehicles for the kinds of the diesel-electrics' field shunting relays the others lack (RelayType 0, 1 and 46). * test: traction on a lost and too high catenary voltage, the ET42, the diesel-electrics' shunting relays The line breaker opened by the voltage relays of a series motor locomotive and by the limits of an induction motor one. The ET42 at the high current setting, which keeps its halves' motors in series, and its switched electrodynamic brake, whose current trips the overload relay from the top speed of the low setting. The field shunting of the diesel-electrics through each kind of their relays, at full power and notched back. * test: the EW58's electrodynamic brake stages, the EU47's speed control and braking at the voltage's limit The stages of the EW58's motor brake set by the positions of its ep handle, the first one alone over 100 km/h. The EU47's second controller holding, raising and lowering the speed set, its local brake setting the flag of the electrodynamic brake without the motors braking, and its brake feeding back less current into a catenary over the drive's MaxV. * test: diesel engines too cold and too hot to start, the 214M railbus's controller and retarder The heat of the diesel engines: at -10 degrees the ones with the lowest water temperature set don't start until the heater warms them, at 88 degrees the ones with a second water circuit don't start while it cools, and the SM42 run hot at full power is kept under its highest temperature by its fans and shutters. The 214M railbus's controller from the air brake through the retarder and neutral to power, its torque converter's lock-up and its gearbox. The controller helpers of the traction tests (full power, waiting for the line contactors, and notching back) move to test::scenario. * test: couplers coupled, uncoupled, broken and colliding; loads assigned, loaded and unloaded Coupling by hand touching or apart and of the same kind or not, with the sounds of what changes; uncoupling a screw coupler pressed together, stretched, with the hoses alone or broken; the automatic couplers of electric units coupling on contact, without the control cable between two kinds; a coupler broken with its brake hose; collisions over 15 km/h derailing. The pantographs set up by the pantstate load, a load of one kind at a time up to the capacity, and the steps of loading and unloading. * test: the battery drained and charged, the pantographs' tank and pressure switch, the 214M's speed control The EU07's battery drained without the converter by the lights and the small compressor until it opens the line breaker and nothing starts, charged by the converter, and switched off. The pantographs on their own leaking tank until the pressure switch opens the line breaker, and the small compressor pumping it up and priming the switch. The 214M railbus's speed control set by its buttons, steps and power limit, braking down with the retarder, and standing by. * test: the MHZ handles' buttons, the valves at speed, every brake material, the NESt3's relays The overload and the high pressure buttons of the MHZ handles. The KE and the LSt at speed in the R and P settings, under the anti-slip request and the releaser button. Every material of the brake shoes and disks the loader takes, braking a wagon from speed, the ones no game vehicle has among them. The CV1_R and the Oerlikon valve's relays set by its name (-ED, AL2 without ESt3) fitted to a wagon. * test: the loader's lists and lines: the 218M, SA134 and 22WEc, a compressor list, Pmax by speed, skipped lines The 218M (V2NList), the SA134 (HTCList) and the Elf 22WEc (ffBrakeList) join the real vehicles for the lists the others lack. Definitions made by the tests for what no game file has: a compressor list, whose table of whole numbers reads a factor of 0.9 as 0; the compressor's limits apart for the rear cab; the highest power of an induction motor drive by the speed, extrapolated past the table; and the lines the loader skips or trims (comments, a hash anywhere, leading spaces, carriage returns). * test: what the cab and the AI call on a vehicle: gauges of the train, the split ED brake, spring brake, cut-off The engine rotation of up to three vehicles in multiple and the lamps of the overload relay and the starting resistors read through the control cable; the engine's idle speed and the ET42's second controller shown in its dynamic brake; the controller of the electrodynamic brake apart from the local brake, which no game vehicle has yet; the spring brake shut off and released, the ep brake's fuse and the handle stepped by the AI; damaged motors cut off; the cab activated by itself; a road vehicle moved across a road, for which the tests' track gets a width; and the lamps and the buzzer of the security system left unattended. * test: the EP05 and its camshaft among the real vehicles, the headlights' colour and brightness The EP05, whose camshaft closes the line breaker and the line contactors by the camshaft's own position, converted from the game data and recorded in every sweep of the real vehicles. The Headlights section, which only the 214M's own file has, in a definition made by the test. * test: what the unit tests reach of the simulation core, what's dead or left, and what they found COVERAGE.md: the blocks of Mover.cpp, hamulce.cpp, Oerlikon_ESt.cpp and friction.cpp the tests run, the code nothing in the game runs, the code only data no game vehicle has would run, what's reachable and left, and the behaviour the tests found that may deserve a look. * test: check invariants of the physics on every step of every golden trace Rules any vehicle keeps whatever a test does (no NaN, cylinders and pipes within their limits, no current with the line breaker or contactors open, no force without power, distance as the speed runs, no acceleration over 5 g), checked on every step, with no comparison to a recorded file. The traces where a test or a game vehicle breaks one are excused with the reason; the vehicles' cases are in the findings of COVERAGE.md. * test: key figures of every golden trace, per part of the run Duration, speeds, distance, time to stop, the brake pipe's lowest pressure and time to recover, the peaks of the cylinders, the motor current and the tractive force, for each part between two events, in data/golden/.figures. Compared within 0.5% or the last decimal, so they hold on any compiler, and an intended change of behaviour shows in a few readable lines. Traces sampled by hand keep none. * test: keep the golden samples out of the repository, recorded on the code before a change The samples of the golden traces are 29 MB and only mean something against the code before the change they check, so they're recorded locally before it (EU07_UNIT_TESTS_UPDATE_GOLDEN=1) and compared after it, and ignored by git. The key figures and the invariants stay, and are what the CI checks. Without samples recorded a trace compares only its key figures, but with EU07_UNIT_TESTS_GOLDEN_EXACT=1, the check of a change which shouldn't alter anything, it fails, so the check can't pass by having nothing to compare. * fix: draw the noise of the control pipe pressure in one order on every compiler The order of the two Random(10) calls in 'Random(10) - Random(10)' is unspecified: GCC draws them the other way round than MSVC Release, which mirrored the control pipe pressure around 5 bar and failed 32 unit tests on the Linux CI. The draws are sequenced in the order of MSVC Release, which the golden traces were recorded with. * test: count the start-up rounds with an integer, not a double (SonarCloud S2193) * test: behaviour in CHECKs, the key figures out of the repository The key figures of the golden traces are recorded with their samples on the code before a change, and compared after it, instead of being kept: a trace without them checks the invariants and its test's CHECKs, which is what the CI runs. The scenarios of the controls state what they show in CHECKs, and the runs of every real vehicle what holds for each of them. Writing them showed scenarios which didn't do what they were named for: the cab change stopped in the engine room, the slip runs put the controller to full power at once and never got the line contactors closed, and the train stopped by the alarm chain never got its pipe charged again. They do it now; the rest went to the findings. * refactor: TractionForce split into its parts and a function per kind of engine TractionForce() makes the engine's revolutions, the ventilators, the engine power and the voltage relays in turn, then the tractive force of its kind of engine, each in a function of its own: the dumb, wheels driven, series motor (with its dynamic brake by stages), diesel, diesel-electric (with the shunt field relays) and induction motor drives (its speed control, brake blending, motor model and the drive without power). The blocks moved line for line; the golden traces of the unit tests, recorded on the code before, compare bit for bit. * refactor: the shunt field relays of types 45 and 46 in functions of their own * refactor: RunCommand split by the area of its commands The controllers, the brakes, the auxiliaries, the power, the doors and the load each in a function of its own; RunCommand() asks them in turn. The branches moved line for line, and the commands are distinct, so the order of the groups changes nothing; the golden traces compare bit for bit. * refactor: the line loop of LoadFIZ_Parse split into table ends, sections and table rows Each part returns where the loop went on to the next line; the dimmer list's row, which never did, still falls through to the next table. The blocks moved line for line, continue became return; every real vehicle loads the same parameters. * refactor: CheckEIMIC split by the kind of the integrated controller The controller, the steps, the four positions and the universal controller each in a function of its own, besides the TRAXX local brake and the limit of the value. The blocks moved line for line; the golden traces compare bit for bit. * refactor: update_doors split into the requests, the movement and the timers of the doors The blocks moved line for line; the golden traces, the doors of the units and wagons among them, compare bit for bit. * refactor: UpdatePipePressure split into its valves The local brake valve, the driver's handle with the pipe lock, the emergency valve, the settings of the distributor and the ep brake of the FVel6 handles each in a function of its own. The blocks moved line for line; the golden traces compare bit for bit. * refactor: PowerCouplersCheck split into the local voltage, the voltages and the currents of the couplers The circuit of a coupler for the coupling being checked comes from TCoupling::power() instead of a nested conditional repeated five times. The blocks moved line for line; the golden traces compare bit for bit. * refactor: CheckLocomotiveParameters split into the brake parts it creates and the state it starts in The distributor valve, the handles, the pipes, and the vehicle ready to depart or braked each in a function of its own; the main pipe's starting pressure comes from InitialScndPipePress() instead of a nested conditional. The blocks moved line for line; every real vehicle loads and runs the same, bit for bit. * refactor: AutoRelayCheck split into the steps of the shunt field, the main relays and the line contactors Each step returns whether it moved, as OK was; the early returns of the main relays' step give false as before, so the relay timer isn't reset after them either. The blocks moved line for line; the golden traces compare bit for bit. * refactor: LoadFIZ_Cntrl and LoadFIZ_Engine split into their parts Cntrl. into the brakes, the controllers and the starts of the devices; Engine: into the diesel, diesel-electric and induction motor parts and what both diesels share. The blocks moved line for line; every real vehicle loads the same, and the golden traces compare bit for bit. * refactor: the steps of the main controller by the kind of the engine in functions of their own IncMainCtrl() and DecMainCtrl() keep the conditions common to all, the switch on the engine moved line for line to IncMainCtrlByEngine() and DecMainCtrlByEngine(). An early return false there gives OK false, after which nothing else happened before either. The golden traces compare bit for bit. * refactor: dizel_AutoGearCheck and Current split into their parts The automatic gearbox's shift and its clutch; the series motors' dynamic brake flag, their current when connected and their failures. The blocks moved line for line; the golden traces compare bit for bit. * refactor: dizel_fillcheck split into the integrated controller's fill and the governor The blocks moved line for line; the golden traces compare bit for bit. * refactor: the diesel-electric's generator and the camshaft's run-down in functions of their own DieselElectricTractionForce() keeps the tractive force, the generator's current and voltage and the shunting mode's power limit moved out; AutoRelayLineContactorsStep() keeps the line contactors, the camshaft's run back to zero moved out, which only ever sets OK. The blocks moved line for line; the golden traces compare bit for bit. * refactor: the battery's drain in a function of its own UpdateBatteryVoltage() takes the drop BatteryDrain() sums up as it did. The blocks moved line for line; the golden traces, the drained battery's among them, compare bit for bit. * refactor: the speed control's regulator, and the couplers' stretch and automatic coupling, in functions of their own CheckSpeedCtrl() keeps the standby and the turn-off, its PI regulator moved out; CouplerForce() keeps the forces, the breaking of a stretched coupler and the coupling on contact moved out. The blocks moved line for line; the golden traces, the couplers tests' among them, compare bit for bit. * refactor: the pantographs' pressure switch and the torque converter in functions of their own UpdatePantVolume() keeps the pantographs' air, its pressure switch moved out; dizel_Momentum() keeps the engine's and clutches' moments, the converter's fill and lockup and its moments moved out. The blocks moved line for line; the golden traces compare bit for bit. * test: the SonarCloud findings in the unit tests std::format for the texts put together, emplace_back, const references, string_view parameters, std::array and std::vector for the C arrays, the ranges algorithms, names no longer shadowing the coupler ends, comments in the empty loops; start_up(), trace::check() and the converter of the definitions split up. BrakeForceR() is const, which it always was in effect, so the gauges test needs no const_cast. The golden traces compare bit for bit. * refactor: the simple SonarCloud findings in Mover.cpp const where the functions change nothing of the vehicle, using enum, a const reference, init-statements, a value never read and an unused parameter dropped, the never read lines of the definition kept in a map with a transparent comparator, the cooling power's default set before it's read. The golden traces compare bit for bit. * refactor: the command groups and the sections of the definition split further RunCommand() asks the pumps, the blowers, the cab and the brake equipment as groups of their own; the doors' permit and remote opening and closing are functions of their own, the latter one for both; LoadFIZ_Section() keeps the sections of values, those opening tables moved to LoadFIZ_TableSection(). No section name begins another, so the order of the checks changes nothing. The golden traces compare bit for bit. * refactor: the doors' requests and the main relays' steps split further update_door_requests() asks door_open_request(), door_close_request(), doors_powered(), door_step_folding() and door_open_duration() for what its nested expressions worked out; AutoRelayMainStep() asks AutoRelayMainUp(), AutoRelayMainNotchUp() and AutoRelayMainDown(), and is indented as it should be. The golden traces compare bit for bit. * refactor: the battery's drain by its state, and the series motors' notches, in functions of their own BatteryDrain() asks BatteryDrainCharged(), BatteryDrainLow() and BatteryDrainSwitchedOff(), each summing the drains as before; the series motors' cases of IncMainCtrlByEngine() and DecMainCtrlByEngine() moved out, and the condition of a notch down by one which was true either way made plain. The golden traces compare bit for bit. * refactor: the universal controller's brake, the clutch, the EN57's camshaft and the driver's handle's supply in functions of their own The blocks moved line for line; the golden traces compare bit for bit. * refactor: the induction motors' speed control, brake blending and drive split further The speed control by time and by position, the electrodynamic brake's flag and share, the motors' force limits and the inverters' frequency each in a function of its own. The blocks moved line for line; the golden traces compare bit for bit. * refactor: the diesel-electric's characteristic in a function of its own The straight part and the hyperbola of the tractive force, worked out the same way for the integrated controller and the train mode, in DieselElectricForce(). The golden traces compare bit for bit. * refactor: the resistor blowers, the diesel-electric's target revolutions, the gearbox's request and the governor's revolutions in functions of their own The blocks moved line for line, and the governor's body is indented as it should be; the golden traces compare bit for bit. * refactor: the series motors' driving current, the pressure switch's trip, the shunt relays, the Cntrl. train brake and the couplers' current split further The blocks moved line for line; the anti-slip brake's kinds read without the nested conditions, the circuit's current picked by PowerCircuitCurrent() instead of a nested conditional, and the couplers' voltage summed through TCoupling::power(). The golden traces compare bit for bit. * refactor: the nesting Sonar found left in the series motors' current, the pressure switch and the diesel-electric The series motors' dynamic brake without the condition every braking vehicle passed, the pressure switch's priming as an else-if, the integrated controller's force of the diesel-electric in a function of its own. The golden traces compare bit for bit. * refactor: the GetPF() of the EStED and LSt valves split into their state, releaser and cylinders The blocks moved line for line; the golden traces of every real vehicle's brakes compare bit for bit. * refactor: the KE valve's cylinders and its held state in functions of their own The blocks moved line for line; the golden traces compare bit for bit. * refactor: the FV4a handle's chambers, wave and reductor in functions of their own The blocks moved line for line; the golden traces of every handle position compare bit for bit. * refactor: the MHZ_EN57 handle's time reservoir and supply pressure in functions of their own The blocks moved line for line; the golden traces compare bit for bit. * refactor: the EP2 valve's state and the ESt valve's held state in functions of their own The blocks moved line for line; the golden traces compare bit for bit. * refactor: the relays' commands and the diesel-electric's shunting force split out The blocks moved line for line; the golden traces compare bit for bit. * test: the SonarCloud findings in the unit tests std::format for the texts put together, emplace_back, const references, string_view parameters, std::array and std::vector for the C arrays, the ranges algorithms, names no longer shadowing the coupler ends, comments in the empty loops; start_up(), trace::check() and the converter of the definitions split up. BrakeForceR() is const, which it always was in effect, so the gauges test needs no const_cast. The golden traces compare bit for bit. * refactor: the SonarCloud findings left in Mover.cpp and hamulce.cpp The EStED's intermediate flow is computed by a const function and its caller fills the reservoir; the anti-slip brake's kind is read from a string_view; the doors' remote command no longer shadows the enumerator control; the diesel-electric's tractive force and the camshaft's run-down nest less. The golden traces compare bit for bit. * refactor: the door helpers aren't const, the door they change is the vehicle's own * refactor: the power couplers' voltage and current return early for a coupling which isn't a power one --- McZapkie/MOVER.h | 169 + McZapkie/Mover.cpp | 7639 +++++++++++++++++++++++------------------- McZapkie/hamulce.cpp | 732 ++-- McZapkie/hamulce.h | 31 + 4 files changed, 4844 insertions(+), 3727 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index ad9f34271..e34dbc252 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include "hamulce.h" #include "couplerphysics.h" #include "derailment.h" @@ -1292,6 +1293,35 @@ struct TCoupling power_coupling power_high; power_coupling power_110v; power_coupling power_24v; + // the circuit of the power coupling given, nullptr for a coupling which isn't one + power_coupling *power(coupling const Coupling) + { + switch (Coupling) + { + case coupling::highvoltage: + return &power_high; + case coupling::power110v: + return &power_110v; + case coupling::power24v: + return &power_24v; + default: + return nullptr; + } + } + power_coupling const *power(coupling const Coupling) const + { + switch (Coupling) + { + case coupling::highvoltage: + return &power_high; + case coupling::power110v: + return &power_110v; + case coupling::power24v: + return &power_24v; + default: + return nullptr; + } + } // the physical model of the coupling (couplerphysics in eu07.ini), see couplerphysics.h: the parameters of this end, // and the state of the coupling with the vehicle at this end, which that vehicle keeps alike on its own end @@ -2559,6 +2589,10 @@ class TMoverParameters bool CurrentSwitch(bool const State); bool IsMotorOverloadRelayHighThresholdOn() const; void UpdateBatteryVoltage(double dt); + double BatteryDrain(double dt, bool converteractive) const; + double BatteryDrainCharged(double dt, bool converteractive) const; + double BatteryDrainLow(double dt, bool converteractive) const; + double BatteryDrainSwitchedOff(double dt) const; double ComputeMovement(double dt, double dt1, const TTrackShape &Shape, TTrackParam const &Track, TTractionParam const &ElectricTraction, TLocation const &NewLoc, TRotation const &NewRot); // oblicza przesuniecie pojazdu double FastComputeMovement(double dt, const TTrackShape &Shape, TTrackParam &Track, TLocation const &NewLoc, TRotation const &NewRot); // oblicza przesuniecie pojazdu - wersja zoptymalizowana @@ -2583,6 +2617,20 @@ class TMoverParameters bool SetInternalCommand(std::string const &NewCommand, double NewValue1, double NewValue2, int const Couplertype = coupling::control); double GetExternalCommand(std::string &Command) const; bool RunCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype = coupling::control); + // the parts of RunCommand(), by the area of the commands + bool RunControllerCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunRelaysCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunCabCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunBrakeCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunBrakeEquipmentCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunAuxiliariesCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunPumpsCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunBlowersCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunPowerCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunDoorsCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + void DoorPermitCommand(double CValue1, double CValue2); + void DoorRemoteCommand(bool Open, double CValue1, double CValue2); + bool RunLoadCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); bool RunInternalCommand(); void PutCommand(std::string const &NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation); bool CabActivisation(bool const Enforce = false); @@ -2594,6 +2642,11 @@ class TMoverParameters /*! glowny nastawnik:*/ bool IncMainCtrl(int CtrlSpeed); bool DecMainCtrl(int CtrlSpeed); + // the parts of IncMainCtrl() and DecMainCtrl() which depend on the kind of the engine + bool IncMainCtrlByEngine(int CtrlSpeed); + bool IncMainCtrlSeriesMotor(int CtrlSpeed); + bool DecMainCtrlByEngine(int CtrlSpeed); + bool DecMainCtrlSeriesMotor(int CtrlSpeed); bool IsMainCtrlActualNoPowerPos() const; // whether the master controller is actually set to position which won't generate any extra power bool IsMainCtrlNoPowerPos() const; // whether the master controller is set to position which won't generate any extra power bool IsMainCtrlMaxPowerPos() const; @@ -2674,8 +2727,18 @@ class TMoverParameters /*pomocnicze funkcje dla ukladow pneumatycznych*/ void UpdateBrakePressure(double dt); void UpdatePipePressure(double dt); + // the parts of UpdatePipePressure() + void UpdateLocalBrakeValve(double dt); + void UpdateMainValve(double dt); + double MainValveSupply(); + double MainValveHandlePosition() const; + void UpdateEmergencyValve(double dt); + void UpdateDistributorSettings(); + void UpdateEPBrake(); void CompressorCheck(double dt); /*wlacza, wylacza kompresor, laduje zbiornik*/ void UpdatePantVolume(double dt); // Ra + void PantPressureSwitchCheck(); + void PantPressureSwitchTrip(); void UpdateScndPipePressure(double dt); void UpdateSpringBrake(double dt); double GetDVc(double dt); @@ -2691,6 +2754,42 @@ class TMoverParameters void ComputeTotalForce(double dt); double Adhesive(double staticfriction) const; double TractionForce(double dt); + // the parts of TractionForce(), in the order it makes them + double UpdateEngineRevolutions(double dt, double &dtrans, double &dmoment); + double DieselElectricTargetRevolutions(); + void UpdateVentilators(double dt); + void UpdateResistorBlowers(double dt); + double UpdateEnginePower(); + void VoltageRelaysCheck(); + void DumbTractionForce(double PosRatio); + void WheelsDrivenTractionForce(double dt); + void SeriesMotorTractionForce(double dt); + void SeriesMotorDynamicBrake(double dt); + void DieselEngineTractionForce(double dt, double dmoment, double dtrans); + void DieselElectricTractionForce(double tmp); + void DieselElectricShuntForce(double tmpV, double &tmp); + double DieselElectricDigitalForce(double tmpV, double &tempUmax, double &tempImax); + double DieselElectricForce(double tmpV, double LinePower, double Ratio, double HyperbolaPower) const; + void DieselElectricShuntPower(double tmp); + void DieselElectricGenerator(double tmp, double tempUmax, double tempImax); + void ShuntFieldRelaysCheck(double tmpV, double PosRatio, double tmp); + void ShuntFieldRelaysType2(double tmp); + void ShuntFieldRelaysType41(double tmpV); + void ShuntFieldRelaysType45(); + void ShuntFieldRelaysType46(); + void ShuntFieldRelaysType46Up(); + void ShuntFieldRelaysType46Down(); + void InductionMotorTractionForce(double dt); + void InductionMotorSpeedControl(double dt); + void SpeedControlByTime(double dt); + void SpeedControlByPosition(double dt); + void InductionMotorBrakeBlending(double ActiveInverters, double &PosRatio, double &tmp); + void InductionMotorDynamicBrakeFlag(); + double InductionMotorBrakeRatio(double ActiveInverters, double edBCP); + void InductionMotorDrive(double dt); + void InductionMotorForceLimits(); + void UpdateInverterFrequency(); + void InductionMotorOff(); // the dynamic brake of a diesel-electric vehicle: the effort following the demand, the force it gives at the speed void update_dieselelectric_dynamic_brake(double dt); double dieselelectric_dynamic_brake_demand() const; // 0..1, the effort the driver asks for @@ -2702,6 +2801,7 @@ class TMoverParameters double BrakeForceP(double press, double velocity) const; double BrakeForce(const TTrackParam &Track); double CouplerForce(int const End, double dt); + void CouplerStretchCheck(int End, double CF, double dt); // whether the coupling at the end is computed by the physical model: couplerphysics set in eu07.ini, and this // vehicle or the one at the end covered by it (CouplerPhysics), or every vehicle with couplerphysics all bool coupler_physics_at(int const End) const; @@ -2840,6 +2940,11 @@ class TMoverParameters void LowVoltagePowerCheck(double const Deltatime); void MainsCheck(double const Deltatime); void PowerCouplersCheck(double const Deltatime, coupling const Coupling); + // the parts of PowerCouplersCheck() + double LocalPowerVoltage(coupling Coupling); + void PowerCouplersVoltage(coupling Coupling, double abslocalvoltage, bool localpowersource); + void PowerCouplersCurrent(coupling Coupling, bool localpowersource); + double *PowerCircuitCurrent(coupling Coupling); void ConverterCheck(double const Timestep); // przetwornica void HeatingCheck(double const Timestep); void WaterPumpCheck(double const Timestep); @@ -2864,6 +2969,11 @@ class TMoverParameters /*funkcje uzalezniajace sile pociagowa od predkosci: v2n, n2r, current, momentum*/ double v2n(void); double Current(double n, double U); + // the parts of Current() + void UpdateSeriesMotorDynamicBrakeFlag(); + double SeriesMotorCurrent(double n, double U, double R, double Mn) const; + double SeriesMotorDrivingCurrent(double n, double U, double Rz, double Mn, int SP) const; + void MotorFailuresCheck(double n); double Momentum(double I) const; double MomentumF(double I, double Iw, int SCP) const; @@ -2873,6 +2983,15 @@ class TMoverParameters bool MinCurrentSwitch(bool State); // przelacznik pradu automatycznego rozruchu bool AutoRelaySwitch(bool State); // przelacznik automatycznego rozruchu bool AutoRelayCheck(); // symulacja automatycznego rozruchu + // the parts of AutoRelayCheck() + bool AutoRelayShuntStep(bool ARFASI2); + bool AutoRelayMainStep(bool ARFASI); + bool AutoRelayMainUp(bool ARFASI); + bool AutoRelayMainNotchUp(); + bool AutoRelayMainDown(); + bool AutoRelayLineContactorsStep(bool motorconnectorsoff); + bool CamshaftRunDown(); + bool CamshaftRunDownEMU(); bool MotorConnectorsCheck(); bool ResistorsFlagCheck(void) const; // sprawdzenie kontrolki oporow rozruchowych NBMX @@ -2881,10 +3000,19 @@ class TMoverParameters bool DropAllPantographs(bool const State, range_t const Notify = range_t::consist); void CheckEIMIC(double dt); // sprawdzenie i zmiana nastawy zintegrowanego nastawnika jazdy/hamowania + // the parts of CheckEIMIC(), by the kind of the controller + void EIMICFromController(double brakeDemand, double offset, double multiplier); + void EIMICFromSteps(double dt); + void EIMICFromFourPositions(double dt); + void EIMICFromUniversalController(double dt, double brakeDemand); + void UniversalControllerTrainBrake(); + void EIMICTraxxLocalBrake(double dt); + void EIMICLimit(); // whether the holding brake (StopBrakeDecc) lets go at the power demand (eimic, above 0 when power is demanded) of this step of // Dt seconds: once the demand has stayed above 0 for StopBrakeReleaseDelay. a demand of 0 or less starts the count again bool UpdateStopBrakeRelease(double Demand, double Dt); void CheckSpeedCtrl(double dt); + void SpeedCtrlRegulator(double dt, double accfactor); // whether the cruise control has a switch of its own: the secondary controller doubles as its switch unless it // shunts the field of the traction motors already, or there's none (the 6Dg, the ST45; eu07/maszyna#69) bool IsSpeedCtrlSeparate() const; @@ -2903,8 +3031,18 @@ class TMoverParameters bool dizel_EngageSwitch(double state); bool dizel_EngageChange(double dt); bool dizel_AutoGearCheck(void); + bool dizel_GearShiftCheck(double VelUp, double VelDown); + bool dizel_GearShiftRequest(double VelUp, double VelDown); + void dizel_ClutchCheck(); + void dizel_ClutchByController(); + void dizel_ClutchByIntegratedController(); double dizel_fillcheck(int mcp, double dt); + double dizel_DigitalFill(double dt); + double dizel_GovernorFill(int mcp, double realfill) const; + double dizel_GovernorRevolutions(int mcp, double &realfill) const; double dizel_Momentum(double dizel_fill, double n, double dt); + void hydro_TCFillCheck(double dt); + void hydro_TCTorque(); double dizel_MomentumRetarder(double n, double dt); // moment hamowania retardera void dizel_HeatSet(float const Value); void dizel_Heat(double const dt); @@ -2927,6 +3065,16 @@ class TMoverParameters // whether the door closure lamp in the cab of this vehicle is lit: with DoorClosureSignal, for the given state of the // consist; without it, for the lock of the vehicle's own doors, as the lamp always worked bool door_closure_lamp_lit(door_closure_t const Consist, bool const BlinkLit) const; + // the parts of update_doors() + // not const: the door they change is one of Doors.instances + void update_door_requests(basic_door &door, bool localopencontrol, bool remoteopencontrol, bool localclosecontrol, bool remoteclosecontrol); + void move_door(basic_door &door, double Deltatime); + bool door_open_request(basic_door const &door, bool localopencontrol, bool remoteopencontrol) const; + bool door_close_request(basic_door const &door, bool localclosecontrol, bool remoteclosecontrol) const; + bool doors_powered() const; + bool door_step_folding(basic_door const &door) const; + float door_open_duration(basic_door const &door, bool localopencontrol, bool remoteopencontrol) const; + void update_door_timers(double Deltatime); /* funkcje dla samochodow*/ bool ChangeOffsetH(double DeltaOffset); @@ -2935,12 +3083,24 @@ class TMoverParameters bool LoadFIZ(std::string const &chkpath); // Q 20160717 bool LoadChkFile(std::string chkpath); bool LoadFIZ_Text(std::string const &Text); // the same, from text in the .fiz format bool CheckLocomotiveParameters(bool ReadyFlag, int Dir); + // the parts of CheckLocomotiveParameters() + void CreateBrakeValve(); + void CreateBrakeHandles(); + void CreateBrakePipes(); + double InitialScndPipePress(double HosePressure) const; + void SetReadyToDepart(); + void SetBraked(); std::string EngineDescription(int what) const; // the cab interior light the light preset at given position (1-based, as LightsPos) sets, if it sets one std::optional LightsPresetCabLight(int Position) const; private: bool LoadFIZ_Parse(cParser &Parser); // reads the definition from either of the above + // the parts of LoadFIZ_Parse(), for a line of the definition + bool LoadFIZ_TableEnd(std::string const &inputline) const; + bool LoadFIZ_Section(std::string const &inputline, std::map> &fizlines); + bool LoadFIZ_TableSection(std::string const &inputline, std::map> &fizlines); + void LoadFIZ_TableRow(std::string const &inputline); void LoadFIZ_Param(std::string const &line); void LoadFIZ_Load(std::string const &line); void LoadFIZ_Dimensions(std::string const &line); @@ -2950,6 +3110,11 @@ class TMoverParameters void LoadFIZ_BuffCoupl(std::string const &line, int const Index); void LoadFIZ_TurboPos(std::string const &line); void LoadFIZ_Cntrl(std::string const &line); + void LoadFIZ_CntrlBrakes(std::string const &line); + void LoadFIZ_CntrlTrainBrake(std::string const &line); + void LoadFIZ_CntrlAntiSlipBrake(std::string_view asb); + void LoadFIZ_CntrlControllers(std::string const &line); + void LoadFIZ_CntrlStarts(std::string const &line); void LoadFIZ_Blending(std::string const &line); void LoadFIZ_DCEMUED(std::string const &line); void LoadFIZ_SpringBrake(std::string const &line); @@ -2959,6 +3124,10 @@ class TMoverParameters void LoadFIZ_Power(std::string const &Line); void LoadFIZ_SpeedControl(std::string const &Line); void LoadFIZ_Engine(std::string const &Input); + void LoadFIZ_EngineDiesel(std::string const &Input); + void LoadFIZ_EngineDieselElectric(std::string const &Input); + void LoadFIZ_EngineInductionMotor(std::string const &Input); + void LoadFIZ_EngineDieselShared(std::string const &Input); void LoadFIZ_Switches(std::string const &Input); void LoadFIZ_MotorParamTable(std::string const &Input); void LoadFIZ_Circuit(std::string const &Input); diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 0af76eb81..b4ba8478d 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -333,44 +333,10 @@ double TMoverParameters::Current(double n, double U) double R; double MotorCurrent; - double Rz; - double Delta; - double Isf; double Mn; // przujmuje int, ale dla poprawnosci obliczeń double Bn; - int SP = 0; - double U1; // napiecie z korekta - MotorCurrent = 0; - // i dzialanie hamulca ED w EP09 - if (DynamicBrakeType == dbrake_automatic && TrainType != dt_EZT) - { - if ((Hamulec->GetEDBCP() < 0.25 && Vadd < 1) || BrakePress > 2.1) - DynamicBrakeFlag = false; - else if (BrakePress > 0.25 && Hamulec->GetEDBCP() > 0.25) - DynamicBrakeFlag = true; - DynamicBrakeFlag = DynamicBrakeFlag && Power110vIsAvailable; - } - if (DynamicBrakeType == dbrake_automatic && TrainType == dt_EZT) - { - DynamicBrakeFlag = Power110vIsAvailable && (TUHEX_Active || Vadd > TUHEX_MinIw) && DynamicBrakeEMUStatus; - } - - // wylacznik cisnieniowy yBARC - to jest chyba niepotrzebne tutaj Q: no to usuwam... - - // BrakeSubsystem = ss_LSt; - // if (BrakeSubsystem == ss_LSt) WriteLog("LSt"); - // if (BrakeSubsystem == ss_LSt) // zrobiona funkcja virtualna - if (DynamicBrakeFlag) - { - Hamulec->SetED(abs(Im / 350)); // hamulec ED na EP09 dziala az do zatrzymania lokomotywy - //- WriteLog("A"); - } - else - { - Hamulec->SetED(0); - //- WriteLog("B"); - } + UpdateSeriesMotorDynamicBrakeFlag(); ResistorsFlag = RList[MainCtrlActualPos].R > 0.01; // and (!DelayCtrlFlag) ResistorsFlag = ResistorsFlag || (DynamicBrakeFlag == true && DynamicBrakeType == dbrake_automatic); @@ -408,65 +374,7 @@ double TMoverParameters::Current(double n, double U) } else { // wlaczone... - SP = ScndCtrlActualPos; - - if (ScndCtrlActualPos < 255) // tak smiesznie bede wylaczal - { - if (ScndInMain && RList[MainCtrlActualPos].ScndAct != 255) - { - SP = RList[MainCtrlActualPos].ScndAct; - } - - Rz = Mn * WindingRes + R; - - if (DynamicBrakeFlag) // hamowanie - { - if (DynamicBrakeType > 1) - { - // if DynamicBrakeType<>dbrake_automatic then - // MotorCurrent:=-fi*n/Rz {hamowanie silnikiem na oporach rozruchowych} - /* begin - U:=0; - Isf:=Isat; - Delta:=SQR(Isf*Rz+Mn*fi*n-U)+4*U*Isf*Rz; - MotorCurrent:=(U-Isf*Rz-Mn*fi*n+SQRT(Delta))/(2*Rz) - end*/ - if (DynamicBrakeType == dbrake_switch && TrainType == dt_ET42) - { // z Megapacka - Rz = WindingRes + R; - MotorCurrent = -motor_param(SP).fi * n / Rz; //{hamowanie silnikiem na oporach rozruchowych} - } - } - else - MotorCurrent = 0; // odciecie pradu od silnika - } - else - { - U1 = U + Mn * n * motor_param(SP).fi0 * motor_param(SP).fi; - // writepaslog("U1 ", FloatToStr(U1)); - // writepaslog("Isat ", FloatToStr(MotorParam[SP].Isat)); - // writepaslog("fi ", FloatToStr(MotorParam[SP].fi)); - Isf = Sign(U1) * motor_param(SP).Isat; - // writepaslog("Isf ", FloatToStr(Isf)); - Delta = square(Isf * Rz + Mn * motor_param(SP).fi * n - U1) + 4.0 * U1 * Isf * Rz; // 105 * 1.67 + Mn * 140.9 * 20.532 - U1 - // DeltaQ = Isf * Rz + Mn * MotorParam[SP].fi * n - U1 + 4 * U1 * Isf * Rz; - // writepaslog("Delta ", FloatToStr(Delta)); - // writepaslog("DeltaQ ", FloatToStr(DeltaQ)); - // writepaslog("U ", FloatToStr(U)); - if (MainCircuitPowered()) - { - if (U > 0) - MotorCurrent = (U1 - Isf * Rz - Mn * motor_param(SP).fi * n + std::sqrt(Delta)) / (2.0 * Rz); - else - MotorCurrent = (U1 - Isf * Rz - Mn * motor_param(SP).fi * n - std::sqrt(Delta)) / (2.0 * Rz); - } - else - MotorCurrent = 0; - } // else DBF - - } // 255 - else - MotorCurrent = 0; + MotorCurrent = SeriesMotorCurrent(n, U, R, Mn); } // writepaslog("MotorCurrent ", FloatToStr(MotorCurrent)); @@ -481,6 +389,125 @@ double TMoverParameters::Current(double n, double U) EnginePower = abs(Itot) * (1 + RList[MainCtrlActualPos].Mn) * abs(U) / 1000.0; + MotorFailuresCheck(n); + + return Im; +} + +// the automatic dynamic brake of the series motors (EP09, the units) on or off, and the distributor told of it +void TMoverParameters::UpdateSeriesMotorDynamicBrakeFlag() +{ + // i dzialanie hamulca ED w EP09 + if (DynamicBrakeType == dbrake_automatic && TrainType != dt_EZT) + { + if ((Hamulec->GetEDBCP() < 0.25 && Vadd < 1) || BrakePress > 2.1) + DynamicBrakeFlag = false; + else if (BrakePress > 0.25 && Hamulec->GetEDBCP() > 0.25) + DynamicBrakeFlag = true; + DynamicBrakeFlag = DynamicBrakeFlag && Power110vIsAvailable; + } + if (DynamicBrakeType == dbrake_automatic && TrainType == dt_EZT) + { + DynamicBrakeFlag = Power110vIsAvailable && (TUHEX_Active || Vadd > TUHEX_MinIw) && DynamicBrakeEMUStatus; + } + + // wylacznik cisnieniowy yBARC - to jest chyba niepotrzebne tutaj Q: no to usuwam... + + // BrakeSubsystem = ss_LSt; + // if (BrakeSubsystem == ss_LSt) WriteLog("LSt"); + // if (BrakeSubsystem == ss_LSt) // zrobiona funkcja virtualna + if (DynamicBrakeFlag) + { + Hamulec->SetED(abs(Im / 350)); // hamulec ED na EP09 dziala az do zatrzymania lokomotywy + //- WriteLog("A"); + } + else + { + Hamulec->SetED(0); + //- WriteLog("B"); + } +} + +// the current of the series motors connected, at the revolutions n and the voltage U, through the resistance R of +// Mn motors in series +double TMoverParameters::SeriesMotorCurrent(double const n, double const U, double const R, double const Mn) const +{ + double MotorCurrent{0.0}; + double Rz; + int SP = ScndCtrlActualPos; + + if (ScndCtrlActualPos < 255) // tak smiesznie bede wylaczal + { + if (ScndInMain && RList[MainCtrlActualPos].ScndAct != 255) + { + SP = RList[MainCtrlActualPos].ScndAct; + } + + Rz = Mn * WindingRes + R; + + if (DynamicBrakeFlag) // hamowanie + { + // if DynamicBrakeType<>dbrake_automatic then + // MotorCurrent:=-fi*n/Rz {hamowanie silnikiem na oporach rozruchowych} + /* begin + U:=0; + Isf:=Isat; + Delta:=SQR(Isf*Rz+Mn*fi*n-U)+4*U*Isf*Rz; + MotorCurrent:=(U-Isf*Rz-Mn*fi*n+SQRT(Delta))/(2*Rz) + end*/ + // only the ET42's switched brake brakes on the starting resistors, otherwise the current is cut off (0) + if (DynamicBrakeType == dbrake_switch && TrainType == dt_ET42) + { // z Megapacka + Rz = WindingRes + R; + MotorCurrent = -motor_param(SP).fi * n / Rz; //{hamowanie silnikiem na oporach rozruchowych} + } + } + else + { + MotorCurrent = SeriesMotorDrivingCurrent(n, U, Rz, Mn, SP); + } // else DBF + + } // 255 + else + MotorCurrent = 0; + return MotorCurrent; +} + +// the current of the series motors driving, at the revolutions n, the voltage U and the resistance Rz of Mn motors in +// series, by the motor parameters of the shunt field SP +double TMoverParameters::SeriesMotorDrivingCurrent(double const n, double const U, double const Rz, double const Mn, int const SP) const +{ + double MotorCurrent; + double Delta; + double Isf; + double U1; // napiecie z korekta + U1 = U + Mn * n * motor_param(SP).fi0 * motor_param(SP).fi; + // writepaslog("U1 ", FloatToStr(U1)); + // writepaslog("Isat ", FloatToStr(MotorParam[SP].Isat)); + // writepaslog("fi ", FloatToStr(MotorParam[SP].fi)); + Isf = Sign(U1) * motor_param(SP).Isat; + // writepaslog("Isf ", FloatToStr(Isf)); + Delta = square(Isf * Rz + Mn * motor_param(SP).fi * n - U1) + 4.0 * U1 * Isf * Rz; // 105 * 1.67 + Mn * 140.9 * 20.532 - U1 + // DeltaQ = Isf * Rz + Mn * MotorParam[SP].fi * n - U1 + 4 * U1 * Isf * Rz; + // writepaslog("Delta ", FloatToStr(Delta)); + // writepaslog("DeltaQ ", FloatToStr(DeltaQ)); + // writepaslog("U ", FloatToStr(U)); + if (MainCircuitPowered()) + { + if (U > 0) + MotorCurrent = (U1 - Isf * Rz - Mn * motor_param(SP).fi * n + std::sqrt(Delta)) / (2.0 * Rz); + else + MotorCurrent = (U1 - Isf * Rz - Mn * motor_param(SP).fi * n - std::sqrt(Delta)) / (2.0 * Rz); + } + else + MotorCurrent = 0; + return MotorCurrent; +} + +// the line breaker opened, and the motors damaged, by too high revolutions or current +void TMoverParameters::MotorFailuresCheck(double const n) +{ + double MotorCurrent; // awarie MotorCurrent = abs(Im); // zmienna pomocnicza @@ -495,8 +522,6 @@ double TMoverParameters::Current(double n, double U) EventFlag = true; /*! dorobic grzanie oporow rozruchowych i silnika*/ } - - return Im; } // ************************************************************************************************* @@ -932,55 +957,7 @@ void TMoverParameters::UpdatePantVolume(double dt) if (!PantCompFlag && PantVolume > 0.1) PantVolume -= dt * 0.0003 * std::max(1.0, PantPress * 0.5); // nieszczelności: 0.0003=0.3l/s - if (PantPress < EnginePowerSource.CollectorParameters.MinPress) - { - // 3.5 wg http://www.transportszynowy.pl/eu06-07pneumat.php - if (true == PantPressSwitchActive) - { - // opuszczenie pantografów przy niskim ciśnieniu - if (TrainType != dt_EZT) - { - // pressure switch safety measure -- open the line breaker, unless there's alternate source of traction voltage - if (GetTrainsetHighVoltage() < EnginePowerSource.CollectorParameters.MinV) - { - // TODO: check whether line breaker should be open EMU-wide - MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); - } - } - else - { - // specialized variant for EMU -- pwr system disables converter and heating, - // and prevents their activation until pressure switch is set again - PantPressLockActive = true; - // TODO: separate 'heating allowed' from actual heating flag, so we can disable it here without messing up heating toggle - ConverterSwitch(false, range_t::unit); - } - // mark the pressure switch as spent - PantPressSwitchActive = false; - } - } - else - { - if (PantPress >= 4.6) - { - // NOTE: we require active low power source to prime the pressure switch - // this is a work-around for potential isssues caused by the switch activating on otherwise idle vehicles, but should check whether it's accurate - if (true == Power24vIsAvailable || true == Power110vIsAvailable) - { - // prime the pressure switch - PantPressSwitchActive = true; - // turn off the subsystems lock - PantPressLockActive = false; - } - - if (PantPress >= 4.8) - { - // Winger - automatyczne wylaczanie malej sprezarki - // TODO: governor lock, disables usage until pressure drop below 3.8 (should really make compressor object we could reuse) - PantCompFlag = false; - } - } - } + PantPressureSwitchCheck(); } else { // a tu coś dla SM42 i SM31, aby pokazywać na manometrze @@ -988,80 +965,78 @@ void TMoverParameters::UpdatePantVolume(double dt) } }; +// the pantographs' pressure switch: low, it opens the line breaker (or locks the converter of a unit) once; +// primed again over 4.6 bar, where the pantographs' compressor stops at 4.8 +void TMoverParameters::PantPressureSwitchCheck() +{ + if (PantPress < EnginePowerSource.CollectorParameters.MinPress) + { + // 3.5 wg http://www.transportszynowy.pl/eu06-07pneumat.php + if (true == PantPressSwitchActive) + { + PantPressureSwitchTrip(); + } + } + else if (PantPress >= 4.6) + { + // NOTE: we require active low power source to prime the pressure switch + // this is a work-around for potential isssues caused by the switch activating on otherwise idle vehicles, but should check whether it's accurate + if (true == Power24vIsAvailable || true == Power110vIsAvailable) + { + // prime the pressure switch + PantPressSwitchActive = true; + // turn off the subsystems lock + PantPressLockActive = false; + } + + if (PantPress >= 4.8) + { + // Winger - automatyczne wylaczanie malej sprezarki + // TODO: governor lock, disables usage until pressure drop below 3.8 (should really make compressor object we could reuse) + PantCompFlag = false; + } + } +} + +// the pantographs' pressure switch tripped by the low pressure: the line breaker opened, unless the voltage comes from +// elsewhere, or the converter of a unit locked; spent until primed again +void TMoverParameters::PantPressureSwitchTrip() +{ + // opuszczenie pantografów przy niskim ciśnieniu + if (TrainType != dt_EZT) + { + // pressure switch safety measure -- open the line breaker, unless there's alternate source of traction voltage + if (GetTrainsetHighVoltage() < EnginePowerSource.CollectorParameters.MinV) + { + // TODO: check whether line breaker should be open EMU-wide + MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); + } + } + else + { + // specialized variant for EMU -- pwr system disables converter and heating, + // and prevents their activation until pressure switch is set again + PantPressLockActive = true; + // TODO: separate 'heating allowed' from actual heating flag, so we can disable it here without messing up heating toggle + ConverterSwitch(false, range_t::unit); + } + // mark the pressure switch as spent + PantPressSwitchActive = false; +} + void TMoverParameters::UpdateBatteryVoltage(double dt) { // przeliczenie obciążenia baterii - double sn1 = 0.0; - double sn2 = 0.0; - double sn3 = 0.0; - double sn4 = 0.0; - double sn5 = 0.0; // Ra: zrobić z tego amperomierz NN - if (BatteryVoltage > 0 && EngineType != TEngineType::DieselEngine && EngineType != TEngineType::WheelsDriven && NominalBatteryVoltage > 0) + using enum TEngineType; + if (BatteryVoltage > 0 && EngineType != DieselEngine && EngineType != WheelsDriven && NominalBatteryVoltage > 0) { // HACK: allow to draw power also from adjacent converter, applicable for EMUs // TODO: expand power cables system to include low voltage power transfers // HACK: emulate low voltage generator powered directly by the diesel engine - auto const converteractive{Power110vIsAvailable || (EngineType == TEngineType::DieselElectric && true == Mains) || (EngineType == TEngineType::DieselEngine && true == Mains)}; + auto const converteractive{Power110vIsAvailable || (EngineType == DieselElectric && true == Mains) || (EngineType == DieselEngine && true == Mains)}; - if (NominalBatteryVoltage / BatteryVoltage < 1.22 && Battery) - { // 110V - if (!converteractive) - sn1 = dt * 2.0; // szybki spadek do ok 90V - else - sn1 = 0; - if (converteractive) - sn2 = -(dt * 2.0); // szybki wzrost do 110V - else - sn2 = 0; - if (Mains) - sn3 = dt * 0.05; - else - sn3 = 0; - if (iLights[0] & 63) // 64=blachy, nie ciągną prądu //rozpisać na poszczególne żarówki... - sn4 = dt * 0.003; - else - sn4 = 0; - if (iLights[1] & 63) // 64=blachy, nie ciągną prądu - sn5 = dt * 0.001; - else - sn5 = 0; - } - if (NominalBatteryVoltage / BatteryVoltage >= 1.22 && Battery) - { // 90V - if (PantCompFlag) - sn1 = dt * 0.0046; - else - sn1 = 0; - if (converteractive) - sn2 = -(dt * 50); // szybki wzrost do 110V - else - sn2 = 0; - if (Mains) - sn3 = dt * 0.001; - else - sn3 = 0; - if (iLights[0] & 63) // 64=blachy, nie ciągną prądu - sn4 = dt * 0.0030; - else - sn4 = 0; - if (iLights[1] & 63) // 64=blachy, nie ciągną prądu - sn5 = dt * 0.0010; - else - sn5 = 0; - } - if (!Battery) - { - if (NominalBatteryVoltage / BatteryVoltage < 1.22) - sn1 = dt * 50; - else - sn1 = 0; - sn2 = dt * 0.000001; - sn3 = dt * 0.000001; - sn4 = dt * 0.000001; - sn5 = dt * 0.000001; // bardzo powolny spadek przy wyłączonych bateriach - } - BatteryVoltage -= sn1 + sn2 + sn3 + sn4 + sn5; - if (NominalBatteryVoltage / BatteryVoltage > 1.57 && MainSwitch(false) && EngineType != TEngineType::DieselEngine && EngineType != TEngineType::WheelsDriven) + BatteryVoltage -= BatteryDrain(dt, converteractive); + if (NominalBatteryVoltage / BatteryVoltage > 1.57 && MainSwitch(false) && EngineType != DieselEngine && EngineType != WheelsDriven) EventFlag = true; // wywalanie szybkiego z powodu zbyt niskiego napiecia if (BatteryVoltage > NominalBatteryVoltage) BatteryVoltage = NominalBatteryVoltage; // wstrzymanie ładowania pow. 110V @@ -1075,6 +1050,105 @@ void TMoverParameters::UpdateBatteryVoltage(double dt) } }; +// the drop of the battery's voltage in dt, by what draws from it, or its rise by the converter charging it +double TMoverParameters::BatteryDrain(double dt, bool const converteractive) const +{ + if (NominalBatteryVoltage / BatteryVoltage < 1.22 && Battery) + { // 110V + return BatteryDrainCharged(dt, converteractive); + } + if (NominalBatteryVoltage / BatteryVoltage >= 1.22 && Battery) + { // 90V + return BatteryDrainLow(dt, converteractive); + } + if (!Battery) + { + return BatteryDrainSwitchedOff(dt); + } + return 0.0; +} + +// the drain of a battery at its voltage, the converter charging it +double TMoverParameters::BatteryDrainCharged(double dt, bool const converteractive) const +{ + double sn1; + double sn2; + double sn3; + double sn4; + double sn5; + if (!converteractive) + sn1 = dt * 2.0; // szybki spadek do ok 90V + else + sn1 = 0; + if (converteractive) + sn2 = -(dt * 2.0); // szybki wzrost do 110V + else + sn2 = 0; + if (Mains) + sn3 = dt * 0.05; + else + sn3 = 0; + if (iLights[0] & 63) // 64=blachy, nie ciągną prądu //rozpisać na poszczególne żarówki... + sn4 = dt * 0.003; + else + sn4 = 0; + if (iLights[1] & 63) // 64=blachy, nie ciągną prądu + sn5 = dt * 0.001; + else + sn5 = 0; + return sn1 + sn2 + sn3 + sn4 + sn5; +} + +// the drain of a battery run down to 90 V, the converter charging it +double TMoverParameters::BatteryDrainLow(double dt, bool const converteractive) const +{ + double sn1; + double sn2; + double sn3; + double sn4; + double sn5; + if (PantCompFlag) + sn1 = dt * 0.0046; + else + sn1 = 0; + if (converteractive) + sn2 = -(dt * 50); // szybki wzrost do 110V + else + sn2 = 0; + if (Mains) + sn3 = dt * 0.001; + else + sn3 = 0; + if (iLights[0] & 63) // 64=blachy, nie ciągną prądu + sn4 = dt * 0.0030; + else + sn4 = 0; + if (iLights[1] & 63) // 64=blachy, nie ciągną prądu + sn5 = dt * 0.0010; + else + sn5 = 0; + return sn1 + sn2 + sn3 + sn4 + sn5; +} + +// the drain of a battery switched off, very slow +double TMoverParameters::BatteryDrainSwitchedOff(double dt) const +{ + double sn1; + double sn2; + double sn3; + double sn4; + double sn5; + if (NominalBatteryVoltage / BatteryVoltage < 1.22) + sn1 = dt * 50; + else + sn1 = 0; + sn2 = dt * 0.000001; + sn3 = dt * 0.000001; + sn4 = dt * 0.000001; + sn5 = dt * 0.000001; // bardzo powolny spadek przy wyłączonych bateriach + return sn1 + sn2 + sn3 + sn4 + sn5; +} + /* Ukrotnienie EN57: 1 //układ szeregowy 2 //układ równoległy @@ -2543,10 +2617,41 @@ void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling c return; } + auto const localvoltage{LocalPowerVoltage(Coupling)}; + + auto const abslocalvoltage{std::abs(localvoltage)}; + auto const localpowersource{(abslocalvoltage > 1.0)}; + + // przekazywanie napiec + PowerCouplersVoltage(Coupling, abslocalvoltage, localpowersource); + + // przekazywanie pradow + PowerCouplersCurrent(Coupling, localpowersource); +} + +// the current the vehicle draws from the circuit of the power coupling given +double *TMoverParameters::PowerCircuitCurrent(coupling const Coupling) +{ + switch (Coupling) + { + case coupling::highvoltage: + return &TotalCurrent; + case coupling::power110v: + return &PowerCircuits[1].second; + case coupling::power24v: + return &PowerCircuits[0].second; + default: + return nullptr; + } +} + +// the voltage of the vehicle's own source for the coupling given; notes the low voltage circuits' too +double TMoverParameters::LocalPowerVoltage(coupling const Coupling) +{ auto localvoltage{0.0}; // local power sources - // TODO: make local voltage calculations a separate method, store results in PowerCircuit fields + // the results could be kept in the PowerCircuit fields switch (Coupling) { @@ -2615,10 +2720,17 @@ void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling c } } - auto const abslocalvoltage{std::abs(localvoltage)}; - auto const localpowersource{(abslocalvoltage > 1.0)}; + return localvoltage; +} - // przekazywanie napiec +// the voltage passed through the vehicle to the coupler at its other end, from the coupled vehicle or its own source +void TMoverParameters::PowerCouplersVoltage(coupling const Coupling, double const abslocalvoltage, bool const localpowersource) +{ + if (Couplers[end::front].power(Coupling) == nullptr) + { + // not a power coupling, there's no voltage to pass + return; + } for (auto side = 0; side < 2; ++side) { @@ -2662,14 +2774,8 @@ void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling c } } - auto const *coupling = Coupling == coupling::highvoltage ? &thiscoupler.power_high : - Coupling == coupling::power110v ? &thiscoupler.power_110v : - Coupling == coupling::power24v ? &thiscoupler.power_24v : - nullptr; - auto *oppositecoupling = Coupling == coupling::highvoltage ? &oppositecoupler.power_high : - Coupling == coupling::power110v ? &oppositecoupler.power_110v : - Coupling == coupling::power24v ? &oppositecoupler.power_24v : - nullptr; + auto const *coupling = thiscoupler.power(Coupling); + auto *oppositecoupling = oppositecoupler.power(Coupling); // start with base voltage oppositecoupling->voltage = abslocalvoltage; @@ -2679,10 +2785,7 @@ void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling c if (thiscoupler.Connected != nullptr) { auto const &connectedcoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr]}; - auto const *connectedcoupling = Coupling == coupling::highvoltage ? &connectedcoupler.power_high : - Coupling == coupling::power110v ? &connectedcoupler.power_110v : - Coupling == coupling::power24v ? &connectedcoupler.power_24v : - nullptr; + auto const *connectedcoupling = connectedcoupler.power(Coupling); auto const connectedvoltage{(connectedcoupling->is_live ? connectedcoupling->voltage : 0.0)}; oppositecoupling->voltage = std::max(oppositecoupling->voltage, connectedvoltage - coupling->current * 0.02); oppositecoupling->is_live = connectedvoltage > 0.1 && oppositecouplingispresent; @@ -2694,43 +2797,24 @@ void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling c oppositecoupling->is_live |= abslocalvoltage > 0.1 && localpowerexportisenabled; } } +} - // przekazywanie pradow - auto couplervoltage{0}; - switch (Coupling) +// the current drawn through the couplers, shared by their voltages, or added to the vehicle's own +void TMoverParameters::PowerCouplersCurrent(coupling const Coupling, bool const localpowersource) +{ + auto const *frontcoupling{Couplers[end::front].power(Coupling)}; + auto const *rearcoupling{Couplers[end::rear].power(Coupling)}; + auto *totalcurrent{PowerCircuitCurrent(Coupling)}; + if (frontcoupling == nullptr || rearcoupling == nullptr || totalcurrent == nullptr) { - case coupling::highvoltage: - { - couplervoltage = static_cast(Couplers[end::front].power_high.voltage + Couplers[end::rear].power_high.voltage); - break; + // not a power coupling, there's no current to share + return; } - case coupling::power110v: - { - couplervoltage = static_cast(Couplers[end::front].power_110v.voltage + Couplers[end::rear].power_110v.voltage); - break; - } - case coupling::power24v: - { - couplervoltage = static_cast(Couplers[end::front].power_24v.voltage + Couplers[end::rear].power_24v.voltage); - break; - } - default: - { - break; - } - } - - auto *totalcurrent = Coupling == coupling::highvoltage ? &TotalCurrent : - Coupling == coupling::power110v ? &PowerCircuits[1].second : - Coupling == coupling::power24v ? &PowerCircuits[0].second : - nullptr; + auto const couplervoltage{static_cast(frontcoupling->voltage + rearcoupling->voltage)}; for (auto &thiscoupler : Couplers) { - auto *coupling = Coupling == coupling::highvoltage ? &thiscoupler.power_high : - Coupling == coupling::power110v ? &thiscoupler.power_110v : - Coupling == coupling::power24v ? &thiscoupler.power_24v : - nullptr; + auto *coupling = thiscoupler.power(Coupling); coupling->current = 0.0; @@ -2740,10 +2824,7 @@ void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling c } auto const &connectedothercoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr == end::front ? end::rear : end::front]}; - auto const *connectedothercoupling = Coupling == coupling::highvoltage ? &connectedothercoupler.power_high : - Coupling == coupling::power110v ? &connectedothercoupler.power_110v : - Coupling == coupling::power24v ? &connectedothercoupler.power_24v : - nullptr; + auto const *connectedothercoupling = connectedothercoupler.power(Coupling); auto const extracurrent = Coupling == coupling::highvoltage ? std::abs(Itot) * IsVehicleEIMBrakingFactor() : 0.0; if (false == localpowersource) @@ -3177,114 +3258,7 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) bool OK = false; if (MainCtrlPos < MainCtrlPosNo) { - switch (EngineType) - { - case TEngineType::None: - case TEngineType::Dumb: - case TEngineType::DieselElectric: - case TEngineType::ElectricInductionMotor: - { - if (CtrlSpeed > 1) - { - OK = IncMainCtrl(1) && IncMainCtrl(CtrlSpeed - 1); // a fail will propagate up the recursion chain. should this be || instead? - break; - } - ++MainCtrlPos; - OK = true; - if (EIMCtrlType == 0 && ( SpeedCtrlAutoTurnOffFlag & 1 ) == 1 && MainCtrlActualPos != MainCtrlPos) - { - SpeedCtrlSwitch(false); - SpeedCtrlUnit.IsActive = false; - } - break; - } - - case TEngineType::ElectricSeriesMotor: - { - if (DirActive == 0) - { - return false; - } - - if (CtrlSpeed > 1) - { - // szybkie przejœcie na bezoporow¹ - if (TrainType == dt_ET40) - { - break; // this means ET40 won't react at all to fast acceleration command. should it issue just IncMainCtrl(1) instead? - } - while (RList[MainCtrlPos].R > 0.0 && IncMainCtrl(1)) - { - // all work is done in the loop header - } - OK = false; // shouldn't this be part of the loop above? - // if (TrainType=dt_ET40) then - // while Abs (Im)>IminHi do - // dec(MainCtrlPos); - // OK:=false ; - } - else - { // CtrlSpeed == 1 - ++MainCtrlPos; - OK = true; - if (Imax == ImaxHi && RList[MainCtrlPos].Bn > 1) - { - /* NOTE: disabled, relay configuration was moved to compute_movement_ - if( true == MaxCurrentSwitch( false )) { - // wylaczanie wysokiego rozruchu - SetFlag( SoundFlag, sound::relay ); - } - */ - if (TrainType == dt_ET42) - { - --MainCtrlPos; - OK = false; - } - } - // - // if (TrainType == "et40") - // if (Abs(Im) > IminHi) - // { - // MainCtrlPos--; //Blokada nastawnika po przekroczeniu minimalnego pradu - // OK = false; - // } - //} - } - - if (TrainType == dt_ET42 && true == DynamicBrakeFlag && MainCtrlPos > 20) - { - MainCtrlPos = 20; - OK = false; - } - break; - } - - case TEngineType::DieselEngine: - { - if (CtrlSpeed > 1) - { - while (MainCtrlPos < MainCtrlPosNo && IncMainCtrl(1)) - { - // all work is done in the loop header - } - } - else - { - ++MainCtrlPos; - } - CompressorAllow = MainCtrlPowerPos() > 0; - OK = true; - break; - } - - case TEngineType::WheelsDriven: - { - OK = AddPulseForce(CtrlSpeed); - break; - } - default: - break; - } // switch EngineType of + OK = IncMainCtrlByEngine(CtrlSpeed); } else { // MainCtrlPos>=MainCtrlPosNo @@ -3328,6 +3302,130 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) return OK; } +// a notch up, as the kind of the engine takes it; returns whether the controller moved +bool TMoverParameters::IncMainCtrlByEngine(int const CtrlSpeed) +{ + bool OK = false; + switch (EngineType) + { + case TEngineType::None: + case TEngineType::Dumb: + case TEngineType::DieselElectric: + case TEngineType::ElectricInductionMotor: + { + if (CtrlSpeed > 1) + { + OK = IncMainCtrl(1) && IncMainCtrl(CtrlSpeed - 1); // a fail will propagate up the recursion chain. should this be || instead? + break; + } + ++MainCtrlPos; + OK = true; + if (EIMCtrlType == 0 && ( SpeedCtrlAutoTurnOffFlag & 1 ) == 1 && MainCtrlActualPos != MainCtrlPos) + { + SpeedCtrlSwitch(false); + SpeedCtrlUnit.IsActive = false; + } + break; + } + + case TEngineType::ElectricSeriesMotor: + { + OK = IncMainCtrlSeriesMotor(CtrlSpeed); + break; + } + + case TEngineType::DieselEngine: + { + if (CtrlSpeed > 1) + { + while (MainCtrlPos < MainCtrlPosNo && IncMainCtrl(1)) + { + // all work is done in the loop header + } + } + else + { + ++MainCtrlPos; + } + CompressorAllow = MainCtrlPowerPos() > 0; + OK = true; + break; + } + + case TEngineType::WheelsDriven: + { + OK = AddPulseForce(CtrlSpeed); + break; + } + default: + break; + } // switch EngineType of + return OK; +} + +// a notch up of the series motors' controller: CtrlSpeed over 1 runs it to the first position without resistors; +// returns whether it moved as asked +bool TMoverParameters::IncMainCtrlSeriesMotor(int const CtrlSpeed) +{ + bool OK = false; + if (DirActive == 0) + { + return false; + } + + if (CtrlSpeed > 1) + { + // szybkie przejœcie na bezoporow¹ + if (TrainType == dt_ET40) + { + return false; // this means ET40 won't react at all to fast acceleration command. should it issue just IncMainCtrl(1) instead? + } + while (RList[MainCtrlPos].R > 0.0 && IncMainCtrl(1)) + { + // all work is done in the loop header + } + OK = false; // shouldn't this be part of the loop above? + // if (TrainType=dt_ET40) then + // while Abs (Im)>IminHi do + // dec(MainCtrlPos); + // OK:=false ; + } + else + { // CtrlSpeed == 1 + ++MainCtrlPos; + OK = true; + if (Imax == ImaxHi && RList[MainCtrlPos].Bn > 1) + { + /* NOTE: disabled, relay configuration was moved to compute_movement_ + if( true == MaxCurrentSwitch( false )) { + // wylaczanie wysokiego rozruchu + SetFlag( SoundFlag, sound::relay ); + } + */ + if (TrainType == dt_ET42) + { + --MainCtrlPos; + OK = false; + } + } + // + // if (TrainType == "et40") + // if (Abs(Im) > IminHi) + // { + // MainCtrlPos--; //Blokada nastawnika po przekroczeniu minimalnego pradu + // OK = false; + // } + //} + } + + if (TrainType == dt_ET42 && true == DynamicBrakeFlag && MainCtrlPos > 20) + { + MainCtrlPos = 20; + OK = false; + } + return OK; +} + // ***************************************************************************** // Q: 20160710 // zmniejszenie nastawnika @@ -3358,70 +3456,7 @@ bool TMoverParameters::DecMainCtrl(int CtrlSpeed) OK = true; } else - switch (EngineType) - { - case TEngineType::None: - case TEngineType::Dumb: - case TEngineType::DieselElectric: - case TEngineType::ElectricInductionMotor: - { - if ((CtrlSpeed == 1 && EngineType != TEngineType::DieselElectric) || (CtrlSpeed == 1 && EngineType == TEngineType::DieselElectric)) - { - MainCtrlPos--; - OK = true; - if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1 && MainCtrlActualPos != MainCtrlPos) - { - SpeedCtrlSwitch(false); - SpeedCtrlUnit.IsActive = false; - } - } - else if (CtrlSpeed > 1) - OK = DecMainCtrl(1) && DecMainCtrl(CtrlSpeed - 1); // CtrlSpeed-1); - break; - } - - case TEngineType::ElectricSeriesMotor: - { - if (CtrlSpeed == 1) /*and (ScndCtrlPos=0)*/ - { - MainCtrlPos--; - // if (MainCtrlPos=0) and (ScndCtrlPos=0) and - // (TrainType<>dt_ET40)and(TrainType<>dt_EP05) then - // StLinFlag:=false; - // if (MainCtrlPos=0) and (TrainType<>dt_ET40) and - // (TrainType<>dt_EP05) then - // MainCtrlActualPos:=0; //yBARC: co to tutaj robi? ;) - OK = true; - } - else if (CtrlSpeed > 1) /*and (ScndCtrlPos=0)*/ - { - OK = true; - if (RList[MainCtrlPos].R == 0) // Q: tu zrobilem = ;] - DecMainCtrl(1); - while (RList[MainCtrlPos].R > 0 && DecMainCtrl(1)) - ; // takie chamskie, potem poprawie} - } - break; - } - - case TEngineType::DieselEngine: - { - if (CtrlSpeed == 1) - { - MainCtrlPos--; - OK = true; - } - else if (CtrlSpeed > 1) - { - while (MainCtrlPos > 0 || RList[MainCtrlPos].Mn > 0) - DecMainCtrl(1); - OK = true; - } - break; - } - default: - break; - } // switch EngineType + OK = DecMainCtrlByEngine(CtrlSpeed); } } else if (EngineType == TEngineType::WheelsDriven) @@ -3451,6 +3486,85 @@ bool TMoverParameters::DecMainCtrl(int CtrlSpeed) return OK; } +// a notch down, as the kind of the engine takes it; returns whether the controller moved +bool TMoverParameters::DecMainCtrlByEngine(int const CtrlSpeed) +{ + bool OK = false; + switch (EngineType) + { + case TEngineType::None: + case TEngineType::Dumb: + case TEngineType::DieselElectric: + case TEngineType::ElectricInductionMotor: + { + if (CtrlSpeed == 1) + { + MainCtrlPos--; + OK = true; + if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1 && MainCtrlActualPos != MainCtrlPos) + { + SpeedCtrlSwitch(false); + SpeedCtrlUnit.IsActive = false; + } + } + else if (CtrlSpeed > 1) + OK = DecMainCtrl(1) && DecMainCtrl(CtrlSpeed - 1); // CtrlSpeed-1); + break; + } + + case TEngineType::ElectricSeriesMotor: + { + OK = DecMainCtrlSeriesMotor(CtrlSpeed); + break; + } + + case TEngineType::DieselEngine: + { + if (CtrlSpeed == 1) + { + MainCtrlPos--; + OK = true; + } + else if (CtrlSpeed > 1) + { + while (MainCtrlPos > 0 || RList[MainCtrlPos].Mn > 0) + DecMainCtrl(1); + OK = true; + } + break; + } + default: + break; + } // switch EngineType + return OK; +} + +// a notch down of the series motors' controller: CtrlSpeed over 1 runs it down to the first position without resistors +bool TMoverParameters::DecMainCtrlSeriesMotor(int const CtrlSpeed) +{ + bool OK = false; + if (CtrlSpeed == 1) /*and (ScndCtrlPos=0)*/ + { + MainCtrlPos--; + // if (MainCtrlPos=0) and (ScndCtrlPos=0) and + // (TrainType<>dt_ET40)and(TrainType<>dt_EP05) then + // StLinFlag:=false; + // if (MainCtrlPos=0) and (TrainType<>dt_ET40) and + // (TrainType<>dt_EP05) then + // MainCtrlActualPos:=0; //yBARC: co to tutaj robi? ;) + OK = true; + } + else if (CtrlSpeed > 1) /*and (ScndCtrlPos=0)*/ + { + OK = true; + if (RList[MainCtrlPos].R == 0) // Q: tu zrobilem = ;] + DecMainCtrl(1); + while (RList[MainCtrlPos].R > 0 && DecMainCtrl(1)) + ; // takie chamskie, potem poprawie} + } + return OK; +} + bool TMoverParameters::IsMainCtrlActualNoPowerPos() const { // TODO: wrap controller pieces into a class for potential specializations, similar to brake subsystems @@ -5358,100 +5472,181 @@ void TMoverParameters::UpdatePipePressure(double dt) if (BrakeCtrlPosNo > 1) { - // the local brake of a vehicle prepared for hauling (PulleeMode) is held released, whatever asks for it - if (EngineType != TEngineType::ElectricInductionMotor) - { - double lbpa = LocHandleTimeTraxx ? eim_localbrake : LocalBrakePosA; - if (EIMCtrlType > 0 && UniCtrlIntegratedLocalBrakeCtrl) - { - lbpa = std::max(0.0, -eimic_real); - } - if (SpeedCtrlUnit.Parking) - { - lbpa = std::max(lbpa, StopBrakeDecc); - } - dpLocalValve = LocHandle->GetPF(PulleeMode ? 0.0 : std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); - } - else - { - // in EIM stock the pneumatic local brake is normally driven only by the MED algorithm - // (LocalBrakePosAEIM). When SplitEDPneumaticBrake is active the dedicated LocalBrake - // lever should apply pneumatic pressure on the locomotive directly, bypassing MED. - // LocHandleTimeTraxx also bypasses MED, but has 3 positions (brake-hold-unbrake). - double lbpa; - if (LocHandleTimeTraxx) - { - lbpa = eim_localbrake; - } - else if (SplitEDPneumaticBrake) // When LocHandleTimeTraxx and SplitEDPneumaticBrake are both active, lbpa is taken from LocHandleTimeTraxx, which is the desired behavior. - { - lbpa = LocalBrakePosA; - } - else - { - lbpa = 0.0; - } - dpLocalValve = LocHandle->GetPF(PulleeMode ? 0.0 : std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); - } - - LockPipe = PipePress < (LockPipe ? LockPipeOff : LockPipeOn); - bool lock_new = (LockPipe && !UnlockPipe && BrakeCtrlPosR > HandleUnlock) || (EmergencyCutsOffHandle && EmergencyValveFlow > 0); // new simple codition based on .fiz - bool lock_old = BrakeHandle == TBrakeHandle::FV4a // old complex condition based on assumptions - && PipePress < 2.75 && (Hamulec->GetStatus() & b_rls) == 0 && BrakeSubsystem == TBrakeSubSystem::ss_LSt && TrainType != dt_EZT && !UnlockPipe; - - if (lock_old || lock_new) - { - temp = PipePress + 0.00001; - } - else - { - temp = ScndPipePress; - } - Handle->SetReductor(BrakeCtrlPos2); - - if (PulleeMode) - { - // the driver's valve of a vehicle prepared for hauling is cut out, whatever its handle shows - dpMainValve = 0; - } - else if ((BrakeOpModes & bom_PS) == 0 || (CabOccupied != 0 && BrakeOpModeFlag != bom_PS)) - { - - if (BrakeOpModeFlag < bom_EP || Handle->GetPos(bh_EB) - 0.5 < BrakeCtrlPosR || (BrakeHandle != TBrakeHandle::MHZ_EN57 && BrakeHandle != TBrakeHandle::MHZ_K8P)) - { - double pos = BrakeCtrlPosR; - if (SpeedCtrlUnit.IsActive && SpeedCtrlUnit.BrakeIntervention && !SpeedCtrlUnit.Standby && BrakeCtrlPos != Handle->GetPos(bh_EB)) - { - pos = Handle->GetPos(bh_NP); - if (SpeedCtrlUnit.BrakeInterventionBraking) - pos = Handle->GetPos(bh_FB); - if (SpeedCtrlUnit.BrakeInterventionUnbraking) - pos = Handle->GetPos(bh_RP); - } - dpMainValve = Handle->GetPF(pos, PipePress, temp, dt, EqvtPipePress); - } - else - { - dpMainValve = Handle->GetPF(0, PipePress, temp, dt, EqvtPipePress); - } - } - else if (BrakeCtrlPos == Handle->GetPos(bh_EB)) - { - dpMainValve = Handle->GetPF(BrakeCtrlPosR, PipePress, temp, dt, EqvtPipePress); - } - - if (dpMainValve < 0) // && (PipePressureVal > 0.01) //50 - { - if (Compressor > ScndPipePress) - { - CompressedVolume = CompressedVolume + dpMainValve / 1500.0; - Pipe2->Flow(dpMainValve / 3.0); - } - else - Pipe2->Flow(dpMainValve); - } + UpdateLocalBrakeValve(dt); + UpdateMainValve(dt); } + UpdateEmergencyValve(dt); + + // 0.2*Spg + Pipe->Flow(-dpMainValve); + Pipe->Flow(-PipePress * 0.001 * dt); + // if Heating then + // Pipe.Flow(PF(PipePress, 0, d2A(7)) * dt); + // if ConverterFlag then + // Pipe.Flow(PF(PipePress, 0, d2A(12)) * dt); + dpMainValve = dpMainValve / (Dim.L * Spg * 20); + + CntrlPipePress = Hamulec->GetVRP(); // ciśnienie komory wstępnej rozdzielacza + + // if (Hamulec is typeid(TWest)) return 0; + + UpdateDistributorSettings(); + + if ((BrakeHandle == TBrakeHandle::FVel6 || BrakeHandle == TBrakeHandle::FVE408) && CabOccupied != 0) + { + UpdateEPBrake(); + } + else if (BrakeHandle == TBrakeHandle::St113 && CabOccupied != 0 && std::abs(EpForce) > 0.001 && !EPBrakeControlPowered()) + { + // the EP brake switched on with the button drops out with the control's supply + SwitchEPBrake(0); + } + + Pipe->Act(); + PipePress = Pipe->P(); + if ((Hamulec->GetBrakeStatus() & b_dmg) == b_dmg) // jesli hamulec wyłączony + temp = 0.0; // odetnij + else + temp = 1.0; // połącz + Pipe->Flow(temp * Hamulec->GetPF(temp * PipePress, dt, Vel)); + // the air the brake hoses carry to and from the neighbours comes once all vehicles have stepped, UpdatePipeCouplers() + PipeCouplersPending = true; + + if (ASBType == 128) + Hamulec->ASB(int(SlippingWheels && Vel > 1) * (1 + 2 * int(nrot_eps < -0.01))); + + dpPipe = 0; + + // yB: jednokrokowe liczenie tego wszystkiego + Pipe->Act(); + PipePress = Pipe->P(); + + dpMainValve = dpMainValve / (100.0 * dt); // normalizacja po czasie do syczenia; + + if (PipePress < -1.0) + { + PipePress = -1.0; + Pipe->CreatePress(-1.0); + Pipe->Act(); + } + + if (CompressedVolume < 0.0) + CompressedVolume = 0.0; +} + +// the flow of the local brake valve, by the handle, the TRAXX's timed one, the integrated controller or the parking +void TMoverParameters::UpdateLocalBrakeValve(double dt) +{ + // the local brake of a vehicle prepared for hauling (PulleeMode) is held released, whatever asks for it + if (EngineType != TEngineType::ElectricInductionMotor) + { + double lbpa = LocHandleTimeTraxx ? eim_localbrake : LocalBrakePosA; + if (EIMCtrlType > 0 && UniCtrlIntegratedLocalBrakeCtrl) + { + lbpa = std::max(0.0, -eimic_real); + } + if (SpeedCtrlUnit.Parking) + { + lbpa = std::max(lbpa, StopBrakeDecc); + } + dpLocalValve = LocHandle->GetPF(PulleeMode ? 0.0 : std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); + } + else + { + // in EIM stock the pneumatic local brake is normally driven only by the MED algorithm + // (LocalBrakePosAEIM). When SplitEDPneumaticBrake is active the dedicated LocalBrake + // lever should apply pneumatic pressure on the locomotive directly, bypassing MED. + // LocHandleTimeTraxx also bypasses MED, but has 3 positions (brake-hold-unbrake). + double lbpa; + if (LocHandleTimeTraxx) + { + lbpa = eim_localbrake; + } + else if (SplitEDPneumaticBrake) // When LocHandleTimeTraxx and SplitEDPneumaticBrake are both active, lbpa is taken from LocHandleTimeTraxx, which is the desired behavior. + { + lbpa = LocalBrakePosA; + } + else + { + lbpa = 0.0; + } + dpLocalValve = LocHandle->GetPF(PulleeMode ? 0.0 : std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); + } +} + +// the lock of the brake pipe and the flow of the driver's handle, from the main reservoir or into the air +void TMoverParameters::UpdateMainValve(double dt) +{ + auto const temp{MainValveSupply()}; + Handle->SetReductor(BrakeCtrlPos2); + + if (PulleeMode) + { + // the driver's valve of a vehicle prepared for hauling is cut out, whatever its handle shows + dpMainValve = 0; + } + else if ((BrakeOpModes & bom_PS) == 0 || (CabOccupied != 0 && BrakeOpModeFlag != bom_PS)) + { + + if (BrakeOpModeFlag < bom_EP || Handle->GetPos(bh_EB) - 0.5 < BrakeCtrlPosR || (BrakeHandle != TBrakeHandle::MHZ_EN57 && BrakeHandle != TBrakeHandle::MHZ_K8P)) + { + dpMainValve = Handle->GetPF(MainValveHandlePosition(), PipePress, temp, dt, EqvtPipePress); + } + else + { + dpMainValve = Handle->GetPF(0, PipePress, temp, dt, EqvtPipePress); + } + } + else if (BrakeCtrlPos == Handle->GetPos(bh_EB)) + { + dpMainValve = Handle->GetPF(BrakeCtrlPosR, PipePress, temp, dt, EqvtPipePress); + } + + if (dpMainValve < 0) // && (PipePressureVal > 0.01) //50 + { + if (Compressor > ScndPipePress) + { + CompressedVolume = CompressedVolume + dpMainValve / 1500.0; + Pipe2->Flow(dpMainValve / 3.0); + } + else + Pipe2->Flow(dpMainValve); + } +} + +// the pressure the driver's handle is fed from: the main pipe's, or the brake pipe's own with the pipe locked +double TMoverParameters::MainValveSupply() +{ + LockPipe = PipePress < (LockPipe ? LockPipeOff : LockPipeOn); + bool lock_new = (LockPipe && !UnlockPipe && BrakeCtrlPosR > HandleUnlock) || (EmergencyCutsOffHandle && EmergencyValveFlow > 0); // new simple codition based on .fiz + bool lock_old = BrakeHandle == TBrakeHandle::FV4a // old complex condition based on assumptions + && PipePress < 2.75 && (Hamulec->GetStatus() & b_rls) == 0 && BrakeSubsystem == TBrakeSubSystem::ss_LSt && TrainType != dt_EZT && !UnlockPipe; + + if (lock_old || lock_new) + { + return PipePress + 0.00001; + } + return ScndPipePress; +} + +// the position the driver's handle works at: its own, or the one the speed control's brake intervention sets +double TMoverParameters::MainValveHandlePosition() const +{ + double pos = BrakeCtrlPosR; + if (SpeedCtrlUnit.IsActive && SpeedCtrlUnit.BrakeIntervention && !SpeedCtrlUnit.Standby && BrakeCtrlPos != Handle->GetPos(bh_EB)) + { + pos = Handle->GetPos(bh_NP); + if (SpeedCtrlUnit.BrakeInterventionBraking) + pos = Handle->GetPos(bh_FB); + if (SpeedCtrlUnit.BrakeInterventionUnbraking) + pos = Handle->GetPos(bh_RP); + } + return pos; +} + +void TMoverParameters::UpdateEmergencyValve(double dt) +{ // ulepszony hamulec bezp. EmergencyValveFlow = 0.0; @@ -5469,20 +5664,11 @@ void TMoverParameters::UpdatePipePressure(double dt) EmergencyValveFlow = PF(0, PipePress, 0.15) * dt; } dpMainValve += EmergencyValveFlow; +} - // 0.2*Spg - Pipe->Flow(-dpMainValve); - Pipe->Flow(-PipePress * 0.001 * dt); - // if Heating then - // Pipe.Flow(PF(PipePress, 0, d2A(7)) * dt); - // if ConverterFlag then - // Pipe.Flow(PF(PipePress, 0, d2A(12)) * dt); - dpMainValve = dpMainValve / (Dim.L * Spg * 20); - - CntrlPipePress = Hamulec->GetVRP(); // ciśnienie komory wstępnej rozdzielacza - - // if (Hamulec is typeid(TWest)) return 0; - +// what the distributor valve gets of the local brake and the load, by its kind +void TMoverParameters::UpdateDistributorSettings() +{ switch (BrakeValve) { @@ -5588,64 +5774,29 @@ void TMoverParameters::UpdatePipePressure(double dt) break; } } // switch +} - if ((BrakeHandle == TBrakeHandle::FVel6 || BrakeHandle == TBrakeHandle::FVE408) && CabOccupied != 0) - { - if (EPBrakeControlPowered()) // tu powinien byc jeszcze bezpiecznik EP i baterie - - // temp = (Handle as TFVel6).GetCP - EpForce = Handle->GetEP(); - else - EpForce = 0.0; - - DynamicBrakeEMUStatus = EpForce > 0.001 ? Power110vIsAvailable : true; - - double temp1 = EpForce; - if (DCEMUED_EP_max_Vel > 0.001 && Vel > DCEMUED_EP_max_Vel && DynamicBrakeEMUStatus) - temp1 = 0; - if (DCEMUED_EP_min_Im > 0.001 && abs(Im) > DCEMUED_EP_min_Im && DynamicBrakeEMUStatus) - temp1 = 0; - Hamulec->SetEPS(temp1); - TUHEX_StageActual = static_cast(EpForce); - TUHEX_Active = TUHEX_StageActual > 0; - // Ra 2014-11: na tym się wysypuje, ale nie wiem, w jakich warunkach - SendCtrlToNext("Brake", EpForce, CabActive); - } - else if (BrakeHandle == TBrakeHandle::St113 && CabOccupied != 0 && std::abs(EpForce) > 0.001 && !EPBrakeControlPowered()) - { - // the EP brake switched on with the button drops out with the control's supply - SwitchEPBrake(0); - } - - Pipe->Act(); - PipePress = Pipe->P(); - if ((Hamulec->GetBrakeStatus() & b_dmg) == b_dmg) // jesli hamulec wyłączony - temp = 0.0; // odetnij +// the ep brake of the FVel6 and FVE408 handles, passed along the unit +void TMoverParameters::UpdateEPBrake() +{ + if (EPBrakeControlPowered()) // tu powinien byc jeszcze bezpiecznik EP i baterie - + // temp = (Handle as TFVel6).GetCP + EpForce = Handle->GetEP(); else - temp = 1.0; // połącz - Pipe->Flow(temp * Hamulec->GetPF(temp * PipePress, dt, Vel)); - // the air the brake hoses carry to and from the neighbours comes once all vehicles have stepped, UpdatePipeCouplers() - PipeCouplersPending = true; + EpForce = 0.0; - if (ASBType == 128) - Hamulec->ASB(int(SlippingWheels && Vel > 1) * (1 + 2 * int(nrot_eps < -0.01))); + DynamicBrakeEMUStatus = EpForce > 0.001 ? Power110vIsAvailable : true; - dpPipe = 0; - - // yB: jednokrokowe liczenie tego wszystkiego - Pipe->Act(); - PipePress = Pipe->P(); - - dpMainValve = dpMainValve / (100.0 * dt); // normalizacja po czasie do syczenia; - - if (PipePress < -1.0) - { - PipePress = -1.0; - Pipe->CreatePress(-1.0); - Pipe->Act(); - } - - if (CompressedVolume < 0.0) - CompressedVolume = 0.0; + double temp1 = EpForce; + if (DCEMUED_EP_max_Vel > 0.001 && Vel > DCEMUED_EP_max_Vel && DynamicBrakeEMUStatus) + temp1 = 0; + if (DCEMUED_EP_min_Im > 0.001 && abs(Im) > DCEMUED_EP_min_Im && DynamicBrakeEMUStatus) + temp1 = 0; + Hamulec->SetEPS(temp1); + TUHEX_StageActual = static_cast(EpForce); + TUHEX_Active = TUHEX_StageActual > 0; + // Ra 2014-11: na tym się wysypuje, ale nie wiem, w jakich warunkach + SendCtrlToNext("Brake", EpForce, CabActive); } // ************************************************************************************************* @@ -6388,7 +6539,7 @@ double TMoverParameters::CouplerForce(int const End, double dt) auto &thiscoupler{Couplers[End]}; auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; auto const otherend{Neighbours[End].vehicle_end}; - auto &othercoupler{othervehicle->Couplers[otherend]}; + auto const &othercoupler{othervehicle->Couplers[otherend]}; auto const othervehiclemove{(othervehicle->dMoveLen * DirPatch(End, otherend))}; auto const initialdistance{Neighbours[End].distance}; // odległość od sprzęgu sąsiada @@ -6464,21 +6615,7 @@ double TMoverParameters::CouplerForce(int const End, double dt) // zderzenie thiscoupler.CheckCollision = true; } - if (std::abs(CF) > thiscoupler.FmaxC) - { - // coupler is stretched with excessive force, may break - thiscoupler.stretch_duration += static_cast(dt); - // give coupler 1 sec of leeway to account for simulation glitches, before checking whether it breaks - // (arbitrary) chance to break grows from 10-100% over 10 sec period - if (Global.crash_damage && thiscoupler.stretch_duration > 1.f && Random() < thiscoupler.stretch_duration * 0.1f * dt) - { - damage_coupler(End); - } - } - else - { - thiscoupler.stretch_duration = 0.f; - } + CouplerStretchCheck(End, CF, dt); } if (newdistance < 0) { @@ -6517,6 +6654,27 @@ double TMoverParameters::CouplerForce(int const End, double dt) return CF; } +// a coupler stretched with more than its strength for over a second breaks, the more likely the longer, with crash damage on +void TMoverParameters::CouplerStretchCheck(int const End, double const CF, double dt) +{ + auto &thiscoupler{Couplers[End]}; + if (std::abs(CF) > thiscoupler.FmaxC) + { + // coupler is stretched with excessive force, may break + thiscoupler.stretch_duration += static_cast(dt); + // give coupler 1 sec of leeway to account for simulation glitches, before checking whether it breaks + // (arbitrary) chance to break grows from 10-100% over 10 sec period + if (Global.crash_damage && thiscoupler.stretch_duration > 1.f && Random() < thiscoupler.stretch_duration * 0.1f * dt) + { + damage_coupler(End); + } + } + else + { + thiscoupler.stretch_duration = 0.f; + } +} + bool TMoverParameters::coupler_physics_at(int const End) const { if (false == Global.coupler_physics) @@ -6695,14 +6853,91 @@ bool TMoverParameters::coupler_stop_hit(int const End, TMoverParameters &Other, // ************************************************************************************************* double TMoverParameters::TractionForce(double dt) { - double PosRatio; - double dmoment; - double dtrans; - double tmp; - + using enum TEngineType; Ft = 0; - dtrans = 0; - dmoment = 0; + double dtrans{0.0}; + double dmoment{0.0}; + auto const revolutions{UpdateEngineRevolutions(dt, dtrans, dmoment)}; + + eAngle += enrot * dt; + if (eAngle > M_PI * 2.0) + eAngle = std::fmod(eAngle, M_PI * 2.0); + /* + while (eAngle > M_PI * 2.0) + // eAngle = Pirazy2 - eAngle; <- ABu: a nie czasem tak, jak nizej? + eAngle -= M_PI * 2.0; + */ + // hunter-091012: przeniesione z if DirActive<>0 (zeby po zejsciu z kierunku dalej spadala predkosc wentylatorow) + // wentylatory rozruchowe + // TBD, TODO: move this to update, it doesn't exactly have much to do with traction + UpdateVentilators(dt); + auto const PosRatio{UpdateEnginePower()}; + VoltageRelaysCheck(); + + if (EngineType == DieselElectric && DEDynamicBrake.source != diesel_electric_dynamic_brake::control::none) + { + update_dieselelectric_dynamic_brake(dt); + } + + if (DirActive != 0) + switch (EngineType) + { + case Dumb: + { + DumbTractionForce(PosRatio); + break; + } + case WheelsDriven: + { + WheelsDrivenTractionForce(dt); + break; + } + case ElectricSeriesMotor: + { + SeriesMotorTractionForce(dt); + break; + } + case DieselEngine: + { + DieselEngineTractionForce(dt, dmoment, dtrans); + break; + } + case DieselElectric: // youBy + { + DieselElectricTractionForce(revolutions); + if (DEDynamicBrake.level > 0.0) + { + // braking: no power asked for, so the drive above gave no force + apply_dieselelectric_dynamic_brake(dt); + } + break; + } + case ElectricInductionMotor: + { + InductionMotorTractionForce(dt); + break; + } + case None: + default: + { + break; + } + } // case EngineType + + if (EngineType == DieselElectric) + { + // rough approximation of extra effort to overcome friction etc + EnginePower += EngineRPMRatio() * 0.15 * DElist[MainCtrlPosNo].GenPower; + } + + return Ft; +} + +// the revolutions of the engine; returns those a diesel-electric engine aims at [1/s], 0 for the others. +// for a diesel engine, the ratio of the transmission and the engine's moment +double TMoverParameters::UpdateEngineRevolutions(double dt, double &dtrans, double &dmoment) +{ + double tmp{0.0}; // youBy switch (EngineType) { @@ -6710,19 +6945,7 @@ double TMoverParameters::TractionForce(double dt) { if (true == Mains && true == FuelPump.is_active) { - - if (EIMCtrlType > 0) // sterowanie cyfrowe - tmp = (DElist[0].RPM + (DElist[MainCtrlPosNo].RPM - DElist[0].RPM) * std::max(0.0, eimic_real)) / 60.0; - else - tmp = DElist[ControlPressureSwitch ? MainCtrlNoPowerPos() : MainCtrlPos].RPM / 60.0; - - if (true == HeatingAllow && HeatingPower > 0 && EngineHeatingRPM > 0) - { - // bump engine revolutions up if needed, when heating is on - tmp = std::max(tmp, std::min(EngineMaxRPM(), EngineHeatingRPM) / 60.0); - } - // NOTE: fake dizel_fill calculation for the sake of smoke emitter which uses this parameter to determine smoke opacity - dizel_fill = std::clamp(0.2 + 0.35 * (tmp - enrot) + 0.5 * (std::abs(Im) / DElist[MainCtrlPosNo].Imax), 0.05, 1.0); + tmp = DieselElectricTargetRevolutions(); } else { @@ -6758,17 +6981,32 @@ double TMoverParameters::TractionForce(double dt) } } - eAngle += enrot * dt; - if (eAngle > M_PI * 2.0) - eAngle = std::fmod(eAngle, M_PI * 2.0); - /* - while (eAngle > M_PI * 2.0) - // eAngle = Pirazy2 - eAngle; <- ABu: a nie czasem tak, jak nizej? - eAngle -= M_PI * 2.0; - */ - // hunter-091012: przeniesione z if DirActive<>0 (zeby po zejsciu z kierunku dalej spadala predkosc wentylatorow) - // wentylatory rozruchowe - // TBD, TODO: move this to update, it doesn't exactly have much to do with traction + return tmp; +} + +// the revolutions a diesel-electric's engine aims at [1/s], by the controller and the heating; the fill shown by the smoke +double TMoverParameters::DieselElectricTargetRevolutions() +{ + double tmp; + + if (EIMCtrlType > 0) // sterowanie cyfrowe + tmp = (DElist[0].RPM + (DElist[MainCtrlPosNo].RPM - DElist[0].RPM) * std::max(0.0, eimic_real)) / 60.0; + else + tmp = DElist[ControlPressureSwitch ? MainCtrlNoPowerPos() : MainCtrlPos].RPM / 60.0; + + if (true == HeatingAllow && HeatingPower > 0 && EngineHeatingRPM > 0) + { + // bump engine revolutions up if needed, when heating is on + tmp = std::max(tmp, std::min(EngineMaxRPM(), EngineHeatingRPM) / 60.0); + } + // NOTE: fake dizel_fill calculation for the sake of smoke emitter which uses this parameter to determine smoke opacity + dizel_fill = std::clamp(0.2 + 0.35 * (tmp - enrot) + 0.5 * (std::abs(Im) / DElist[MainCtrlPosNo].Imax), 0.05, 1.0); + return tmp; +} + +// the starting resistors' blowers, and the diesels' radiator fans +void TMoverParameters::UpdateVentilators(double dt) +{ switch (EngineType) { @@ -6776,50 +7014,7 @@ double TMoverParameters::TractionForce(double dt) { if (MainCircuitPowered()) { - switch (RVentType) - { - - case 1: - { // manual - if (true == RVentForceOn || (DirActive != 0 && RList[MainCtrlActualPos].R > RVentCutOff)) - { - RventRot += (RVentnmax - RventRot) * RVentSpeed * dt; - } - else - { - RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); - } - break; - } - - case 2: - { // automatic - auto const motorcurrent{std::min(ImaxHi, std::abs(Im))}; - if (std::abs(Itot) > RVentMinI && RList[MainCtrlActualPos].R > RVentCutOff) - { - - RventRot += (RVentnmax * std::min(1.0, motorcurrent / NPoweredAxles / RVentMinI) * motorcurrent / ImaxLo - RventRot) * RVentSpeed * dt; - } - else if (DynamicBrakeType == dbrake_automatic && true == DynamicBrakeFlag) - { - RventRot += (RVentnmax * motorcurrent / ImaxLo - RventRot) * RVentSpeed * dt; - } - else if (RVentForceOn) - { - RventRot += (RVentnmax - RventRot) * RVentSpeed * dt; - } - else - { - RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); - } - break; - } - - default: - { - break; - } - } // rventtype + UpdateResistorBlowers(dt); } // mains else { @@ -6868,7 +7063,61 @@ double TMoverParameters::TractionForce(double dt) break; } } +} +// the starting resistors' blowers of the series motors with the line breaker closed, worked by hand or by the current +void TMoverParameters::UpdateResistorBlowers(double dt) +{ + switch (RVentType) + { + + case 1: + { // manual + if (true == RVentForceOn || (DirActive != 0 && RList[MainCtrlActualPos].R > RVentCutOff)) + { + RventRot += (RVentnmax - RventRot) * RVentSpeed * dt; + } + else + { + RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); + } + break; + } + + case 2: + { // automatic + auto const motorcurrent{std::min(ImaxHi, std::abs(Im))}; + if (std::abs(Itot) > RVentMinI && RList[MainCtrlActualPos].R > RVentCutOff) + { + + RventRot += (RVentnmax * std::min(1.0, motorcurrent / NPoweredAxles / RVentMinI) * motorcurrent / ImaxLo - RventRot) * RVentSpeed * dt; + } + else if (DynamicBrakeType == dbrake_automatic && true == DynamicBrakeFlag) + { + RventRot += (RVentnmax * motorcurrent / ImaxLo - RventRot) * RVentSpeed * dt; + } + else if (RVentForceOn) + { + RventRot += (RVentnmax - RventRot) * RVentSpeed * dt; + } + else + { + RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); + } + break; + } + + default: + { + break; + } + } // rventtype +} + +// the power of a dumb or diesel engine; returns the ratio of the power a dumb engine is set to +double TMoverParameters::UpdateEnginePower() +{ + double PosRatio{0.0}; switch (EngineType) { case TEngineType::Dumb: @@ -6899,6 +7148,12 @@ double TMoverParameters::TractionForce(double dt) } } + return PosRatio; +} + +// the line breaker opened by a voltage out of the motors' range, and the line contactors of a diesel-electric +void TMoverParameters::VoltageRelaysCheck() +{ switch (EngineType) { @@ -6950,832 +7205,924 @@ double TMoverParameters::TractionForce(double dt) break; } } +} - if (EngineType == TEngineType::DieselElectric && DEDynamicBrake.source != diesel_electric_dynamic_brake::control::none) +void TMoverParameters::DumbTractionForce(double const PosRatio) +{ + if (Mains && CabActive != 0) { - update_dieselelectric_dynamic_brake(dt); + if (Vel > 0.1) + { + Ft = std::min(1000.0 * Power / std::abs(V), Ftmax) * PosRatio; + } + else + { + Ft = Ftmax * PosRatio; + } + Ft = Ft * DirAbsolute; // DirActive*CabActive; + } + else + { + Ft = 0; + } +} + +void TMoverParameters::WheelsDrivenTractionForce(double dt) +{ + if (EnginePowerSource.SourceType == TPowerSource::InternalSource && EnginePowerSource.PowerType == TPowerType::BioPower) + Ft = Sign(sin(eAngle)) * PulseForce * Transmision.Ratio; + PulseForceTimer = PulseForceTimer + dt; + if (PulseForceTimer > CtrlDelay) + { + PulseForce = 0; + if (PulseForceCount > 0) + PulseForceCount--; + } + EnginePower = Ft * (1.0 + Vel); +} + +void TMoverParameters::SeriesMotorTractionForce(double dt) +{ + // enrot:=Transmision.Ratio*nrot; + // yB: szereg dwoch sekcji w ET42 + if (TrainType == dt_ET42 && Imax == ImaxHi) + EngineVoltage = EngineVoltage / 2.0; + Mm = Momentum(Current(enrot, EngineVoltage)); // oblicza tez prad p/slinik + + if (TrainType == dt_ET42) + { + if (Imax == ImaxHi) + EngineVoltage = EngineVoltage * 2; + if (DynamicBrakeFlag && abs(Im) > 300) // przeiesione do mover.cpp + FuseOff(); + } + if (DynamicBrakeType == dbrake_automatic && DynamicBrakeFlag) + { + SeriesMotorDynamicBrake(dt); } - if (DirActive != 0) - switch (EngineType) + if (TrainType == dt_ET22 && DelayCtrlFlag) // szarpanie przy zmianie układu w byku + Mm = Mm * RList[MainCtrlActualPos].Bn / (RList[MainCtrlActualPos].Bn + 1); // zrobione w momencie, żeby nie dawac elektryki w przeliczaniu sił + + if (abs(Im) > Imax) + Vhyp += dt; //*(abs(Im) / Imax - 0.9) * 10; // zwieksz czas oddzialywania na PN + else + Vhyp = 0; + if (Vhyp > CtrlDelay / 2) // jesli czas oddzialywania przekroczony + FuseOff(); // wywalanie bezpiecznika z powodu przetezenia silnikow + + if ((DynamicBrakeType == dbrake_automatic || DynamicBrakeType == dbrake_switch) && DynamicBrakeFlag) + Itot = Im * 2; // 2x2 silniki w EP09 + else if (TrainType == dt_EZT && Imin == IminLo && ScndS) // yBARC - boczniki na szeregu poprawnie + Itot = Im; + else + Itot = Im * RList[MainCtrlActualPos].Bn; // prad silnika * ilosc galezi + Mw = Mm * Transmision.Ratio * Transmision.Efficiency; + Fw = Mw * 2.0 / WheelDiameter; + Ft = Fw * NPoweredAxles; // sila trakcyjna +} + +// the automatic dynamic brake of the series motors: the excitation current, by the stages of the ep brake (TUHEX) +void TMoverParameters::SeriesMotorDynamicBrake(double dt) +{ + if (TUHEX_Stages > 0) // hamowanie wielostopniowe, nadpisuje wartości domyślne + { + if (Vel > 100) + TUHEX_StageActual = std::min(TUHEX_StageActual, 1); + switch (TUHEX_StageActual) { - case TEngineType::Dumb: - { - if (Mains && CabActive != 0) + case 1: + TUHEX_Sum = TUHEX_Sum1; + DynamicBrakeRes = DynamicBrakeRes1; + break; + case 2: + TUHEX_Sum = TUHEX_Sum2; + DynamicBrakeRes = DynamicBrakeRes1; + break; + case 3: + TUHEX_Sum = TUHEX_Sum3; + if (Vadd > 0.99 * TUHEX_MaxIw && DynamicBrakeRes == DynamicBrakeRes1) + TUHEX_ResChange = true; + if (TUHEX_ResChange && Vadd < 0.5 * TUHEX_MaxIw) { - if (Vel > 0.1) - { - Ft = std::min(1000.0 * Power / std::abs(V), Ftmax) * PosRatio; - } - else - { - Ft = Ftmax * PosRatio; - } - Ft = Ft * DirAbsolute; // DirActive*CabActive; - } - else - { - Ft = 0; + TUHEX_ResChange = false; + DynamicBrakeRes = DynamicBrakeRes2; } break; - } // Dumb - - case TEngineType::WheelsDriven: - { - if (EnginePowerSource.SourceType == TPowerSource::InternalSource && EnginePowerSource.PowerType == TPowerType::BioPower) - Ft = Sign(sin(eAngle)) * PulseForce * Transmision.Ratio; - PulseForceTimer = PulseForceTimer + dt; - if (PulseForceTimer > CtrlDelay) - { - PulseForce = 0; - if (PulseForceCount > 0) - PulseForceCount--; - } - EnginePower = Ft * (1.0 + Vel); - break; - } // WheelsDriven - - case TEngineType::ElectricSeriesMotor: - { - // enrot:=Transmision.Ratio*nrot; - // yB: szereg dwoch sekcji w ET42 - if (TrainType == dt_ET42 && Imax == ImaxHi) - EngineVoltage = EngineVoltage / 2.0; - Mm = Momentum(Current(enrot, EngineVoltage)); // oblicza tez prad p/slinik - - if (TrainType == dt_ET42) - { - if (Imax == ImaxHi) - EngineVoltage = EngineVoltage * 2; - if (DynamicBrakeFlag && abs(Im) > 300) // przeiesione do mover.cpp - FuseOff(); - } - if (DynamicBrakeType == dbrake_automatic && DynamicBrakeFlag) - { - if (TUHEX_Stages > 0) // hamowanie wielostopniowe, nadpisuje wartości domyślne - { - if (Vel > 100) - TUHEX_StageActual = std::min(TUHEX_StageActual, 1); - switch (TUHEX_StageActual) - { - case 1: - TUHEX_Sum = TUHEX_Sum1; - DynamicBrakeRes = DynamicBrakeRes1; - break; - case 2: - TUHEX_Sum = TUHEX_Sum2; - DynamicBrakeRes = DynamicBrakeRes1; - break; - case 3: - TUHEX_Sum = TUHEX_Sum3; - if (Vadd > 0.99 * TUHEX_MaxIw && DynamicBrakeRes == DynamicBrakeRes1) - TUHEX_ResChange = true; - if (TUHEX_ResChange && Vadd < 0.5 * TUHEX_MaxIw) - { - TUHEX_ResChange = false; - DynamicBrakeRes = DynamicBrakeRes2; - } - break; - default: - DynamicBrakeRes = DynamicBrakeRes1; - TUHEX_Sum = 0; - break; - } - } - if (Vadd + abs(Im) > TUHEX_Sum + TUHEX_Diff || Hamulec->GetEDBCP() < 0.25 || TUHEX_ResChange || (TUHEX_StageActual == 0 && TUHEX_Stages > 0)) - { - Vadd -= 500.0 * dt; - if (Vadd < TUHEX_MinIw) - { - Vadd = 0; - DynamicBrakeFlag = false; - } - } - else if (DynamicBrakeFlag && Vadd + abs(Im) < TUHEX_Sum - TUHEX_Diff) - { - Vadd += 70.0 * dt; - Vadd = std::min(std::max(Vadd, TUHEX_MinIw), TUHEX_MaxIw); - } - if (Vadd > 0) - Mm = MomentumF(Im, Vadd, 0); - } - - if (TrainType == dt_ET22 && DelayCtrlFlag) // szarpanie przy zmianie układu w byku - Mm = Mm * RList[MainCtrlActualPos].Bn / (RList[MainCtrlActualPos].Bn + 1); // zrobione w momencie, żeby nie dawac elektryki w przeliczaniu sił - - if (abs(Im) > Imax) - Vhyp += dt; //*(abs(Im) / Imax - 0.9) * 10; // zwieksz czas oddzialywania na PN - else - Vhyp = 0; - if (Vhyp > CtrlDelay / 2) // jesli czas oddzialywania przekroczony - FuseOff(); // wywalanie bezpiecznika z powodu przetezenia silnikow - - if ((DynamicBrakeType == dbrake_automatic || DynamicBrakeType == dbrake_switch) && DynamicBrakeFlag) - Itot = Im * 2; // 2x2 silniki w EP09 - else if (TrainType == dt_EZT && Imin == IminLo && ScndS) // yBARC - boczniki na szeregu poprawnie - Itot = Im; - else - Itot = Im * RList[MainCtrlActualPos].Bn; // prad silnika * ilosc galezi - Mw = Mm * Transmision.Ratio * Transmision.Efficiency; - Fw = Mw * 2.0 / WheelDiameter; - Ft = Fw * NPoweredAxles; // sila trakcyjna - break; - } - - case TEngineType::DieselEngine: - { - Mw = dmoment * dtrans * Transmision.Efficiency; // dmoment i dtrans policzone przy okazji enginerotation - if (hydro_R && hydro_R_Placement == 0) - Mw -= dizel_MomentumRetarder(nrot * Transmision.Ratio, dt) * Transmision.Ratio * Transmision.Efficiency; - Fw = Mw * 2.0 / WheelDiameter / NPoweredAxles; - Ft = Fw * NPoweredAxles; // sila trakcyjna - Ft = Ft * DirAbsolute; // DirActive*CabActive; - break; - } - - case TEngineType::DieselElectric: // youBy - { - // tmpV:=V*CabActive*DirActive; - auto const tmpV{nrot * Pirazy2 * 0.5 * WheelDiameter * DirAbsolute}; //*CabActive*DirActive; - auto tempUmax = 0.0; - auto tempImax = 0.0; - auto tempPmax = 0.0; - // jazda manewrowa - if (EIMCtrlType > 0) // sterowanie cyfrowe - { - auto eimic_positive = std::max(0.0, eimic_real); - auto const rpmratio{EngineRPMRatio()}; - tempImax = DElist[MainCtrlPosNo].Imax * eimic_positive; - tempUmax = DElist[MainCtrlPosNo].Umax * std::min(eimic_positive, rpmratio); - tempPmax = DElist[MainCtrlPosNo].GenPower * std::min(eimic_positive, rpmratio); - tmp = tempPmax; - if (true == StLinFlag) - { - - if (tmpV < Vhyp * tempPmax / DElist[MainCtrlPosNo].GenPower) - { - // czy na czesci prostej, czy na hiperboli - Ft = - (Ftmax - (Ftmax - 1000.0 * DElist[MainCtrlPosNo].GenPower / (Vhyp + Vadd)) * (tmpV / Vhyp) / PowerCorRatio) * eimic_positive; // posratio - bo sila jakos tam sie rozklada - } - else - { - // na hiperboli - // 1.107 - wspolczynnik sredniej nadwyzki Ft w symku nad charakterystyka - Ft = 1000.0 * tempPmax / (tmpV + Vadd) / PowerCorRatio; // tu jest zawarty stosunek mocy - } - } - else - Ft = 0; // jak nastawnik na zero, to sila tez zero - - PosRatio = tempPmax / DElist[MainCtrlPosNo].GenPower; - } - else if (true == ShuntMode) - { - if (true == StLinFlag) - { - EngineVoltage = SST[MainCtrlPos].Umax * AnPos + SST[MainCtrlPos].Umin * (1.0 - AnPos); - // NOTE: very crude way to approximate power generated at current rpm instead of instant top output - // NOTE, TODO: doesn't take into account potentially increased revolutions if heating is on, fix it - tmp = EngineRPMRatio() * (SST[MainCtrlPos].Pmax * AnPos) + SST[MainCtrlPos].Pmin * (1.0 - AnPos); - Ft = tmp * 1000.0 / (abs(tmpV) + 1.6); - } - else - { - EngineVoltage = 0; - Ft = 0; - } - PosRatio = 1; - } - else // jazda ciapongowa - { - auto power = Power; - tempImax = DElist[MainCtrlPos].Imax; - tempUmax = DElist[MainCtrlPos].Umax; - if (true == Heating) - { - power -= HeatingPower; - } - if (power < 0.0) - { - power = 0.0; - } - // NOTE: very crude way to approximate power generated at current rpm instead of instant top output - // NOTE, TODO: doesn't take into account potentially increased revolutions if heating is on, fix it - auto const currentgenpower{(DElist[MainCtrlPos].RPM > 0 ? DElist[MainCtrlPos].GenPower * (60.0 * enrot / DElist[MainCtrlPos].RPM) : 0.0)}; - - tmp = std::min(power, currentgenpower); - - PosRatio = currentgenpower / DElist[MainCtrlPosNo].GenPower; - // stosunek mocy teraz do mocy max - // NOTE: Mains in this context is working diesel engine - if (true == StLinFlag) - { - - if (tmpV < Vhyp * power / DElist[MainCtrlPosNo].GenPower) - { - // czy na czesci prostej, czy na hiperboli - Ft = (Ftmax - (Ftmax - 1000.0 * DElist[MainCtrlPosNo].GenPower / (Vhyp + Vadd)) * (tmpV / Vhyp) / PowerCorRatio) * PosRatio; // posratio - bo sila jakos tam sie rozklada - } - else - { - // na hiperboli - // 1.107 - wspolczynnik sredniej nadwyzki Ft w symku nad charakterystyka - Ft = 1000.0 * tmp / (tmpV + Vadd) / PowerCorRatio; // tu jest zawarty stosunek mocy - } - } - else - Ft = 0; // jak nastawnik na zero, to sila tez zero - - PosRatio = tmp / DElist[MainCtrlPosNo].GenPower; - } - - if (FuseFlag) - Ft = 0; - else - Ft = Ft * DirAbsolute; // DirActive * CabActive; //zwrot sily i jej wartosc - Fw = Ft / NPoweredAxles; // sila na obwodzie kola - Mw = Fw * WheelDiameter / 2.0; // moment na osi kola - Mm = Mw / Transmision.Ratio; // moment silnika trakcyjnego - - Im = dieselelectric_motor_current(Mm); - - if (ShuntMode) - { - EnginePower = EngineVoltage * Im / 1000.0; - if (EnginePower > tmp) - { - EnginePower = tmp; - EngineVoltage = EnginePower * 1000.0 / Im; - } - if (EnginePower < tmp) - { - Ft *= EnginePower / tmp; - } - } - else - { - if (abs(Im) > tempImax) - { // nie ma nadmiarowego, tylko Imax i zwarcie na pradnicy - Ft = Ft / Im * tempImax; - Im = tempImax; - } - - if (Im > 0) - { - // jak pod obciazeniem - if (true == Flat) - { - // ograniczenie napiecia w pradnicy - plaszczak u gory - EngineVoltage = 1000.0 * tmp / std::abs(Im); - } - else - { - auto tempMCP = EIMCtrlType > 0 ? 1 + 99 * std::max(1.0, eimic_real) : MainCtrlPos; - auto tempMCPN = EIMCtrlType > 0 ? 100 : MainCtrlPosNo; - // charakterystyka pradnicy obcowzbudnej (elipsa) - twierdzenie Pitagorasa - EngineVoltage = std::sqrt(std::abs(square(tempUmax) - square(tempUmax * Im / tempImax))) * (tempMCP - 1) + (1.0 - Im / tempImax) * tempUmax * (tempMCPN - tempMCP); - EngineVoltage /= tempMCPN - 1; - EngineVoltage = safe_clamp(EngineVoltage, Im * 0.05, 1000.0 * tmp / std::abs(Im)); - } - } - - if (EngineVoltage > tempUmax || Im == 0) - { - // gdy wychodzi za duze napiecie albo przy biegu jalowym (jest cos takiego?) - EngineVoltage = tempUmax * (ConverterFlag ? 1 : 0); - } - - EnginePower = EngineVoltage * Im / 1000.0; - /* - // power curve drop - // NOTE: disabled for the time being due to side-effects - if( ( tmpV > 1 ) && ( EnginePower < tmp ) ) { - Ft = std::lerp( - Ft, EnginePower / tmp, - std::clamp( tmpV - 1.0, 0.0, 1.0 ) ); - } - */ - } - - if (Imax > 1 && Im > Imax) - FuseOff(); - if (FuseFlag) - EngineVoltage = 0; - - // przekazniki bocznikowania, kazdy inny dla kazdej pozycji - if (false == StLinFlag || ShuntMode) - { - ScndCtrlPos = 0; - } - else - { - if (AutoRelayFlag) - { - - auto const shuntfieldstate{ScndCtrlPos}; - - switch (RelayType) - { - - case 0: - { - - if (ScndCtrlPos < ScndCtrlPosNo && Im <= MPTRelay[ScndCtrlPos].Iup * PosRatio) - { - ++ScndCtrlPos; - } - if (ScndCtrlPos > 0 && Im >= MPTRelay[ScndCtrlPos].Idown * PosRatio) - { - --ScndCtrlPos; - } - break; - } - case 1: - { - - if (ScndCtrlPos < ScndCtrlPosNo && MPTRelay[ScndCtrlPos].Iup < Vel) - { - ++ScndCtrlPos; - } - if (ScndCtrlPos > 0 && MPTRelay[ScndCtrlPos].Idown > Vel) - { - --ScndCtrlPos; - } - break; - } - case 2: - { - - if (ScndCtrlPos < ScndCtrlPosNo && MPTRelay[ScndCtrlPos].Iup < Vel && EnginePower < tmp * 0.99) - { - ++ScndCtrlPos; - } - if (ScndCtrlPos > 0 && MPTRelay[ScndCtrlPos].Idown < Im) - { - --ScndCtrlPos; - } - break; - } - case 41: - { - if (ScndCtrlPos < ScndCtrlPosNo && MainCtrlPos == MainCtrlPosNo && tmpV * 3.6 > MPTRelay[ScndCtrlPos].Iup) - { - ++ScndCtrlPos; - enrot = enrot * 0.73; - } - if (ScndCtrlPos > 0 && Im > MPTRelay[ScndCtrlPos].Idown) - { - --ScndCtrlPos; - } - break; - } - case 45: - { - if (ScndCtrlPos < ScndCtrlPosNo && MainCtrlPos >= 11) - { - - if (Im < MPTRelay[ScndCtrlPos].Iup) - { - ++ScndCtrlPos; - } - // check for cases where the speed drops below threshold for level 2 or 3 - if (ScndCtrlPos > 1 && Vel < MPTRelay[ScndCtrlPos - 1].Idown) - { - --ScndCtrlPos; - } - } - // malenie - if (ScndCtrlPos > 0 && MainCtrlPos < 11) - { - - if (ScndCtrlPos == 1) - { - if (Im > MPTRelay[ScndCtrlPos - 1].Idown) - { - --ScndCtrlPos; - } - } - else - { - if (Vel < MPTRelay[ScndCtrlPos].Idown) - { - --ScndCtrlPos; - } - } - } - // 3rd level drops with master controller at position lower than 10... - if (MainCtrlPos < 11) - { - ScndCtrlPos = std::min(2, ScndCtrlPos); - } - // ...and below position 7 field shunt drops altogether - if (MainCtrlPos < 8) - { - ScndCtrlPos = 0; - } - /* - // crude woodward approximation; difference between rpm for consecutive positions is ~5% - // so we get full throttle until ~half way between desired and previous position, or zero on rpm reduction - auto const woodward { std::clamp( - ( DElist[ MainCtrlPos ].RPM / ( enrot * 60.0 ) - 1.0 ) * 50.0, - 0.0, 1.0 ) }; - */ - break; - } - case 46: - { - // wzrastanie - if (MainCtrlPos >= 12 && ScndCtrlPos < ScndCtrlPosNo) - { - if (ScndCtrlPos % 2 == 0) - { - if (MPTRelay[ScndCtrlPos].Iup > Im) - { - ++ScndCtrlPos; - } - } - else - { - if (MPTRelay[ScndCtrlPos - 1].Iup > Im && MPTRelay[ScndCtrlPos].Iup < Vel) - { - ++ScndCtrlPos; - } - } - } - // malenie - if (MainCtrlPos < 12 && ScndCtrlPos > 0 && Vel < 50.0) - { - // above 50 km/h already active shunt field can be maintained until lower controller setting - if (ScndCtrlPos % 2 == 0) - { - if (MPTRelay[ScndCtrlPos].Idown < Im) - { - --ScndCtrlPos; - } - } - else - { - if (MPTRelay[ScndCtrlPos + 1].Idown < Im && MPTRelay[ScndCtrlPos].Idown > Vel) - { - --ScndCtrlPos; - } - } - } - if (MainCtrlPos < 11) - { - ScndCtrlPos = std::min(2, ScndCtrlPos); - } - if (MainCtrlPos < 8) - { - ScndCtrlPos = 0; - } - break; - } - default: - { - break; - } - } // switch RelayType - - if (ScndCtrlPos != shuntfieldstate) - { - SetFlag(SoundFlag, sound::relay | sound::shuntfield); - } - } - } - if (DEDynamicBrake.level > 0.0) - { - // braking: no power asked for, so the drive above gave no force - apply_dieselelectric_dynamic_brake(dt); - } - break; - } // DieselElectric - - case TEngineType::ElectricInductionMotor: - { - if (MainCircuitPowered() && !SecuritySystem.is_engine_blocked()) - { - double ActiveInverters = 0.0; - for (auto const &inv : Inverters) - { - if (inv.IsActive) - ActiveInverters += 1.0; - } - InvertersRatio = ActiveInverters / (double)InvertersNo; - if (EIM_Pmax_Table.size() > 1) - { - eimc[eimc_p_Pmax] = TableInterpolation(EIM_Pmax_Table, Vel); - } - // tempomat - if (ScndCtrlPosNo == 4 && SpeedCtrlTypeTime) - { - SpeedCtrlUnit.IsActive = SpeedCtrlValue > 0; - switch (ScndCtrlPos) - { - case 0: - NewSpeed = 0; - SpeedCtrlValue = 0; - SpeedCtrlTimer = 10; - break; - case 1: - if (SpeedCtrlTimer > SpeedCtrlDelay) - { - SpeedCtrlTimer = 0; - NewSpeed -= 10; - if (NewSpeed < 0) - NewSpeed = 0; - } - else - SpeedCtrlTimer += dt; - break; - case 2: - SpeedCtrlTimer = 10; - SpeedCtrlValue = NewSpeed; - break; - case 3: - if (SpeedCtrlTimer > SpeedCtrlDelay) - { - SpeedCtrlTimer = 0; - NewSpeed += 10; - if (NewSpeed > Vmax) - NewSpeed = Vmax; - } - else - SpeedCtrlTimer += dt; - break; - case 4: - NewSpeed = Vmax; - SpeedCtrlValue = Vmax; - SpeedCtrlTimer = 10; - break; - default: - break; - } - } - else if (ScndCtrlPosNo > 1) - { - if (ScndCtrlPos != NewSpeed) - { - - SpeedCtrlTimer = 0; - NewSpeed = ScndCtrlPos; - } - else - { - SpeedCtrlTimer += dt; - if (SpeedCtrlTimer > SpeedCtrlDelay) - { - auto NewSCAP = static_cast((float)ScndCtrlPos / (float)ScndCtrlPosNo * Vmax); - if (NewSCAP != SpeedCtrlValue) - { - SpeedCtrlValue = NewSCAP; - // SendCtrlToNext("SpeedCntrl", SpeedCtrlValue, CabActive); - } - } - } - SpeedCtrlUnit.IsActive = SpeedCtrlValue > 0; - } - double edBCP = Hamulec->GetEDBCP(); - auto const localbrakeactive{CabOccupied != 0 && LocHandle->GetCP() > 0.25}; - // gdy SplitEDPneumaticBrake jest aktywne, hamulec pomocniczy (LocalBrake) NIE wymusza - // zalaczenia hamulca elektrodynamicznego - ED jest sterowany wlasnym nastawnikiem - auto const dynbrakectrlactive{SplitEDPneumaticBrake && DynamicBrakeRatio() > 0.01 && DynamicBrakeAvailable()}; - auto const localbrakeforED{SplitEDPneumaticBrake ? false : localbrakeactive}; - if (false == Doors.instances[side::left].is_closed || false == Doors.instances[side::right].is_closed || - (Doors.permit_needed && (Doors.instances[side::left].open_permit || Doors.instances[side::right].open_permit))) - { - DynamicBrakeFlag = true; - } - else if ((edBCP < 0.25 && false == localbrakeforED && false == dynbrakectrlactive && AnPos < 0.01) || - (edBCP < 0.25 && ShuntModeAllow && false == dynbrakectrlactive && LocalBrakePosA < 0.01)) - DynamicBrakeFlag = false; - else if (BrakePress > 0.25 && edBCP > 0.25 || localbrakeforED || AnPos > 0.02 || dynbrakectrlactive) - DynamicBrakeFlag = true; - edBCP = Hamulec->GetEDBCP() * eimc[eimc_p_abed]; // stala napedu - if (DynamicBrakeFlag) - { - // ustalanie współczynnika blendingu do luzowania hamulca PN - if (eimv[eimv_Fmax] * Sign(V) * DirAbsolute < -1) - { - PosRatio = -Sign(V) * DirAbsolute * eimv[eimv_Fr] / (eimc[eimc_p_Fh] * std::max(edBCP, std::max(0.01, Hamulec->GetEDBCP())) / MaxBrakePress[0]); - PosRatio = std::clamp(PosRatio, 0.0, 1.0); - } - else - { - PosRatio = 0; - } - PosRatio = static_cast(Round(20.0 * PosRatio)) / 20.0; // stopniowanie PN/ED - if (PosRatio < 19.5 / 20.0) - PosRatio *= 0.9; - Hamulec->SetED(std::max(0.0, std::min(PosRatio, 1.0))); // ustalenie stopnia zmniejszenia ciśnienia - // ustalanie siły hamowania ED - if (Hamulec->GetEDBCP() > 0.25 && eimc[eimc_p_abed] < 0.001 || ActiveInverters < InvertersNo) // jeśli PN wyłącza ED - { - PosRatio = 0; - eimv[eimv_Fzad] = 0; - } - else - { - // strefa wylaczenia ED (Vh0..Vh1) - mnoznik 0..1 zaleznie od predkosci - double const vhRamp = std::max(0.0, std::min(1.0, (Vel - eimc[eimc_p_Vh0]) / (eimc[eimc_p_Vh1] - eimc[eimc_p_Vh0]))); - if (SplitEDPneumaticBrake) - { - // w trybie split LocalBrake nie zaleca ED; uzywany jest DynamicBrakeCtrl - // oraz zwykle zapotrzebowanie z hamulca zespolonego (edBCP) - double const edLeverDemand = DynamicBrakeRatio(); - PosRatio = -std::max(std::max(edLeverDemand, std::min(edBCP / MaxBrakePress[0], 1.0)), AnPos) * vhRamp; - eimv[eimv_Fzad] = -std::min(1.0, std::max(edLeverDemand, edBCP / MaxBrakePress[0])); - } - else - { - PosRatio = -std::max(std::min(edBCP * 1.0 / MaxBrakePress[0], 1.0), AnPos) * vhRamp; - eimv[eimv_Fzad] = -std::min(1.0, std::max(LocalBrakeRatio(), edBCP / MaxBrakePress[0])); - } - } - tmp = 5; - } - else - { - PosRatio = std::max(eimic_real, 0.); - eimv[eimv_Fzad] = PosRatio; - if (Flat && eimc[eimc_p_F0] * eimv[eimv_Fful] > 0) - PosRatio = std::min(PosRatio * eimc[eimc_p_F0] / eimv[eimv_Fful], 1.); - /* if (ScndCtrlActualPos > 0) //speed control - if (Vmax < 250) - PosRatio = std::min(PosRatio, std::max(-1, 0.5 * (ScndCtrlActualPos - Vel))); - else - PosRatio = - std::min(PosRatio, std::max(-1, 0.5 * (ScndCtrlActualPos * 2 - Vel))); */ - // PosRatio = 1.0 * (PosRatio * 0 + 1) * PosRatio; // 1 * 1 * PosRatio = PosRatio - Hamulec->SetED(0); - // (Hamulec as TLSt).SetLBP(LocBrakePress); - tmp = 4; // szybkie malenie, powolne wzrastanie - } - // NOTE: the commands to operate the sandbox are likely to conflict with other similar ai decisions - // TODO: gather these in single place so they can be resolved together - if (SlippingWheels) - { - PosRatio = 0; - tmp = 10; - SandboxAuto(true, range_t::unit); - } // przeciwposlizg - else - { - // switch sandbox off - SandboxAuto(false, range_t::unit); - } - if (ActiveInverters == 0.0) - { - PosRatio = 0; - eimv_pr = 0; - } - - eimv_pr += std::max(std::min(PosRatio - eimv_pr, 0.02), -0.02) * 12 * tmp /*2{+4*byte(PosRatio= 0) - Vadd *= 1.0 - 2.0 * dt; - else if (std::abs(EngineVoltage) < EnginePowerSource.CollectorParameters.MaxV) - Vadd *= 1.0 - dt; - else - Vadd = std::max(Vadd * (1.0 - 0.2 * dt), 0.007 * (std::abs(EngineVoltage) - (EnginePowerSource.CollectorParameters.MaxV - 100))); - Itot = eimv[eimv_Ipoj] * (0.01 + std::min(0.99, 0.99 - Vadd)); - - EnginePower = abs(eimv[eimv_Ic] * eimv[eimv_U] * NPoweredAxles) / 1000; - // power inverters - auto const tmpV{std::abs(eimv[eimv_fp])}; - auto const useFFEDList = FFEDListSize > 0 && DynamicBrakeFlag; - auto const list = useFFEDList ? FFEDlist : FFlist; - - if (auto const listSize = useFFEDList ? FFEDListSize : FFListSize; listSize > 0 && std::abs(eimv[eimv_If]) > 1.0 && tmpV > 0.0001) - { - - int i = 0; - while (i < listSize - 1 && list[i + 1].v < tmpV) - { - ++i; - } - InverterFrequency = (tmpV - list[i].v) / std::max(1.0, list[i + 1].v - list[i].v) * (list[i + 1].freq - list[i].freq) + list[i].freq; - } - else - { - InverterFrequency = 0.0; - } - - Mm = eimv[eimv_M] * DirAbsolute; - Mw = Mm * Transmision.Ratio * Transmision.Efficiency; - Fw = Mw * 2.0 / WheelDiameter; - Ft = Fw * NPoweredAxles * InvertersRatio; - eimv[eimv_Fr] = DirAbsolute * Ft / 1000; - } // mains - else - { - for (auto &inv : Inverters) - { - inv.Freal = 0.0; - inv.IsActive = false; - } - Im = 0.0; - Mm = 0.0; - Mw = 0.0; - Fw = 0.0; - Ft = 0.0; - Itot = 0.0; - eimv_pr = 0.0; - EnginePower = 0.0; - { - for (auto &eimvvalue : eimv) - eimvvalue = 0.0; - } - Hamulec->SetED(0.0); - InverterFrequency = 0.0; //(Hamulec as TLSt).SetLBP(LocBrakePress); - } - break; - } // ElectricInductionMotor - - case TEngineType::None: default: - { + DynamicBrakeRes = DynamicBrakeRes1; + TUHEX_Sum = 0; break; } - } // case EngineType - - if (EngineType == TEngineType::DieselElectric) + } + if (Vadd + abs(Im) > TUHEX_Sum + TUHEX_Diff || Hamulec->GetEDBCP() < 0.25 || TUHEX_ResChange || (TUHEX_StageActual == 0 && TUHEX_Stages > 0)) { - // rough approximation of extra effort to overcome friction etc - EnginePower += EngineRPMRatio() * 0.15 * DElist[MainCtrlPosNo].GenPower; + Vadd -= 500.0 * dt; + if (Vadd < TUHEX_MinIw) + { + Vadd = 0; + DynamicBrakeFlag = false; + } + } + else if (DynamicBrakeFlag && Vadd + abs(Im) < TUHEX_Sum - TUHEX_Diff) + { + Vadd += 70.0 * dt; + Vadd = std::min(std::max(Vadd, TUHEX_MinIw), TUHEX_MaxIw); + } + if (Vadd > 0) + Mm = MomentumF(Im, Vadd, 0); +} + +void TMoverParameters::DieselEngineTractionForce(double dt, double const dmoment, double const dtrans) +{ + Mw = dmoment * dtrans * Transmision.Efficiency; // dmoment i dtrans policzone przy okazji enginerotation + if (hydro_R && hydro_R_Placement == 0) + Mw -= dizel_MomentumRetarder(nrot * Transmision.Ratio, dt) * Transmision.Ratio * Transmision.Efficiency; + Fw = Mw * 2.0 / WheelDiameter / NPoweredAxles; + Ft = Fw * NPoweredAxles; // sila trakcyjna + Ft = Ft * DirAbsolute; // DirActive*CabActive; +} + +// tmp: the revolutions the engine aims at [1/s], see UpdateEngineRevolutions() +void TMoverParameters::DieselElectricTractionForce(double tmp) +{ + double PosRatio; + // tmpV:=V*CabActive*DirActive; + auto const tmpV{nrot * Pirazy2 * 0.5 * WheelDiameter * DirAbsolute}; //*CabActive*DirActive; + auto tempUmax = 0.0; + auto tempImax = 0.0; + // jazda manewrowa + if (EIMCtrlType > 0) // sterowanie cyfrowe + { + tmp = DieselElectricDigitalForce(tmpV, tempUmax, tempImax); + PosRatio = tmp / DElist[MainCtrlPosNo].GenPower; + } + else if (true == ShuntMode) + { + DieselElectricShuntForce(tmpV, tmp); + PosRatio = 1; + } + else // jazda ciapongowa + { + auto power = Power; + tempImax = DElist[MainCtrlPos].Imax; + tempUmax = DElist[MainCtrlPos].Umax; + if (true == Heating) + { + power -= HeatingPower; + } + power = std::max(power, 0.0); + // NOTE: very crude way to approximate power generated at current rpm instead of instant top output + // NOTE, TODO: doesn't take into account potentially increased revolutions if heating is on, fix it + auto const currentgenpower{(DElist[MainCtrlPos].RPM > 0 ? DElist[MainCtrlPos].GenPower * (60.0 * enrot / DElist[MainCtrlPos].RPM) : 0.0)}; + + tmp = std::min(power, currentgenpower); + + PosRatio = currentgenpower / DElist[MainCtrlPosNo].GenPower; + // stosunek mocy teraz do mocy max + // NOTE: Mains in this context is working diesel engine + if (true == StLinFlag) + Ft = DieselElectricForce(tmpV, power, PosRatio, tmp); + else + Ft = 0; // jak nastawnik na zero, to sila tez zero + + PosRatio = tmp / DElist[MainCtrlPosNo].GenPower; } - return Ft; + if (FuseFlag) + Ft = 0; + else + Ft = Ft * DirAbsolute; // DirActive * CabActive; //zwrot sily i jej wartosc + Fw = Ft / NPoweredAxles; // sila na obwodzie kola + Mw = Fw * WheelDiameter / 2.0; // moment na osi kola + Mm = Mw / Transmision.Ratio; // moment silnika trakcyjnego + + Im = dieselelectric_motor_current(Mm); + + if (ShuntMode) + { + DieselElectricShuntPower(tmp); + } + else + { + DieselElectricGenerator(tmp, tempUmax, tempImax); + } + + if (Imax > 1 && Im > Imax) + FuseOff(); + if (FuseFlag) + EngineVoltage = 0; + + // przekazniki bocznikowania, kazdy inny dla kazdej pozycji + if (false == StLinFlag || ShuntMode) + { + ScndCtrlPos = 0; + } + else if (AutoRelayFlag) + { + ShuntFieldRelaysCheck(tmpV, PosRatio, tmp); + } +} + +// the tractive force of a diesel-electric shunting, by the generator's table SST and the shunting controller AnPos; +// tmp, the power the generator gives +void TMoverParameters::DieselElectricShuntForce(double const tmpV, double &tmp) +{ + if (true == StLinFlag) + { + EngineVoltage = SST[MainCtrlPos].Umax * AnPos + SST[MainCtrlPos].Umin * (1.0 - AnPos); + // NOTE: very crude way to approximate power generated at current rpm instead of instant top output + // NOTE, TODO: doesn't take into account potentially increased revolutions if heating is on, fix it + tmp = EngineRPMRatio() * (SST[MainCtrlPos].Pmax * AnPos) + SST[MainCtrlPos].Pmin * (1.0 - AnPos); + Ft = tmp * 1000.0 / (abs(tmpV) + 1.6); + } + else + { + EngineVoltage = 0; + Ft = 0; + } +} + +// the tractive force of a diesel-electric set by the integrated controller, at the speed tmpV; the generator's +// voltage and current limits too. returns the power the generator gives +double TMoverParameters::DieselElectricDigitalForce(double const tmpV, double &tempUmax, double &tempImax) +{ + auto eimic_positive = std::max(0.0, eimic_real); + auto const rpmratio{EngineRPMRatio()}; + tempImax = DElist[MainCtrlPosNo].Imax * eimic_positive; + tempUmax = DElist[MainCtrlPosNo].Umax * std::min(eimic_positive, rpmratio); + auto const tempPmax = DElist[MainCtrlPosNo].GenPower * std::min(eimic_positive, rpmratio); + if (true == StLinFlag) + Ft = DieselElectricForce(tmpV, tempPmax, eimic_positive, tempPmax); + else + Ft = 0; // jak nastawnik na zero, to sila tez zero + return tempPmax; +} + +// the tractive force of a diesel-electric at the speed tmpV: on the straight part of its characteristic under the speed +// Vhyp gives at the power LinePower, at the share Ratio of it, on the hyperbola of the power HyperbolaPower over it +double TMoverParameters::DieselElectricForce(double const tmpV, double const LinePower, double const Ratio, double const HyperbolaPower) const +{ + if (tmpV < Vhyp * LinePower / DElist[MainCtrlPosNo].GenPower) + { + // czy na czesci prostej, czy na hiperboli + return (Ftmax - (Ftmax - 1000.0 * DElist[MainCtrlPosNo].GenPower / (Vhyp + Vadd)) * (tmpV / Vhyp) / PowerCorRatio) * Ratio; // posratio - bo sila jakos tam sie rozklada + } + // na hiperboli + // 1.107 - wspolczynnik sredniej nadwyzki Ft w symku nad charakterystyka + return 1000.0 * HyperbolaPower / (tmpV + Vadd) / PowerCorRatio; // tu jest zawarty stosunek mocy +} + +// in the shunting mode, the generator's power limited to tmp, the power the engine gives +void TMoverParameters::DieselElectricShuntPower(double const tmp) +{ + EnginePower = EngineVoltage * Im / 1000.0; + if (EnginePower > tmp) + { + EnginePower = tmp; + EngineVoltage = EnginePower * 1000.0 / Im; + } + if (EnginePower < tmp) + { + Ft *= EnginePower / tmp; + } +} + +// the generator's current limited to tempImax and its voltage by its characteristic, under tempUmax and the power tmp +void TMoverParameters::DieselElectricGenerator(double const tmp, double const tempUmax, double const tempImax) +{ + if (abs(Im) > tempImax) + { // nie ma nadmiarowego, tylko Imax i zwarcie na pradnicy + Ft = Ft / Im * tempImax; + Im = tempImax; + } + + if (Im > 0) + { + // jak pod obciazeniem + if (true == Flat) + { + // ograniczenie napiecia w pradnicy - plaszczak u gory + EngineVoltage = 1000.0 * tmp / std::abs(Im); + } + else + { + auto tempMCP = EIMCtrlType > 0 ? 1 + 99 * std::max(1.0, eimic_real) : MainCtrlPos; + auto tempMCPN = EIMCtrlType > 0 ? 100 : MainCtrlPosNo; + // charakterystyka pradnicy obcowzbudnej (elipsa) - twierdzenie Pitagorasa + EngineVoltage = std::sqrt(std::abs(square(tempUmax) - square(tempUmax * Im / tempImax))) * (tempMCP - 1) + (1.0 - Im / tempImax) * tempUmax * (tempMCPN - tempMCP); + EngineVoltage /= tempMCPN - 1; + EngineVoltage = safe_clamp(EngineVoltage, Im * 0.05, 1000.0 * tmp / std::abs(Im)); + } + } + + if (EngineVoltage > tempUmax || Im == 0) + { + // gdy wychodzi za duze napiecie albo przy biegu jalowym (jest cos takiego?) + EngineVoltage = tempUmax * (ConverterFlag ? 1 : 0); + } + + EnginePower = EngineVoltage * Im / 1000.0; + /* + // power curve drop + // NOTE: disabled for the time being due to side-effects + if( ( tmpV > 1 ) && ( EnginePower < tmp ) ) { + Ft = std::lerp( + Ft, EnginePower / tmp, + std::clamp( tmpV - 1.0, 0.0, 1.0 ) ); + } + */ +} + +// the shunt field relays of a diesel-electric, each kind its own conditions on the current, the speed or the +// power (tmp, the power the engine gives) +void TMoverParameters::ShuntFieldRelaysCheck(double const tmpV, double const PosRatio, double const tmp) +{ + auto const shuntfieldstate{ScndCtrlPos}; + + switch (RelayType) + { + + case 0: + { + + if (ScndCtrlPos < ScndCtrlPosNo && Im <= MPTRelay[ScndCtrlPos].Iup * PosRatio) + { + ++ScndCtrlPos; + } + if (ScndCtrlPos > 0 && Im >= MPTRelay[ScndCtrlPos].Idown * PosRatio) + { + --ScndCtrlPos; + } + break; + } + case 1: + { + + if (ScndCtrlPos < ScndCtrlPosNo && MPTRelay[ScndCtrlPos].Iup < Vel) + { + ++ScndCtrlPos; + } + if (ScndCtrlPos > 0 && MPTRelay[ScndCtrlPos].Idown > Vel) + { + --ScndCtrlPos; + } + break; + } + case 2: + { + + ShuntFieldRelaysType2(tmp); + break; + } + case 41: + { + ShuntFieldRelaysType41(tmpV); + break; + } + case 45: + { + ShuntFieldRelaysType45(); + break; + } + case 46: + { + ShuntFieldRelaysType46(); + break; + } + default: + { + break; + } + } // switch RelayType + + if (ScndCtrlPos != shuntfieldstate) + { + SetFlag(SoundFlag, sound::relay | sound::shuntfield); + } +} + +// the relays of type 2: up by the speed while the engine has power to spare (tmp, the power it gives), down by the current +void TMoverParameters::ShuntFieldRelaysType2(double const tmp) +{ + if (ScndCtrlPos < ScndCtrlPosNo && MPTRelay[ScndCtrlPos].Iup < Vel && EnginePower < tmp * 0.99) + { + ++ScndCtrlPos; + } + if (ScndCtrlPos > 0 && MPTRelay[ScndCtrlPos].Idown < Im) + { + --ScndCtrlPos; + } +} + +// the relays of type 41: up by the speed tmpV at full power, the engine slowed down, down by the current +void TMoverParameters::ShuntFieldRelaysType41(double const tmpV) +{ + if (ScndCtrlPos < ScndCtrlPosNo && MainCtrlPos == MainCtrlPosNo && tmpV * 3.6 > MPTRelay[ScndCtrlPos].Iup) + { + ++ScndCtrlPos; + enrot = enrot * 0.73; + } + if (ScndCtrlPos > 0 && Im > MPTRelay[ScndCtrlPos].Idown) + { + --ScndCtrlPos; + } +} + +// the relays of type 45, by the current and the speed: up from the 11th position, at most two under it, none under the 8th +void TMoverParameters::ShuntFieldRelaysType45() +{ + if (ScndCtrlPos < ScndCtrlPosNo && MainCtrlPos >= 11) + { + + if (Im < MPTRelay[ScndCtrlPos].Iup) + { + ++ScndCtrlPos; + } + // check for cases where the speed drops below threshold for level 2 or 3 + if (ScndCtrlPos > 1 && Vel < MPTRelay[ScndCtrlPos - 1].Idown) + { + --ScndCtrlPos; + } + } + // malenie + if (ScndCtrlPos > 0 && MainCtrlPos < 11) + { + + if (ScndCtrlPos == 1) + { + if (Im > MPTRelay[ScndCtrlPos - 1].Idown) + { + --ScndCtrlPos; + } + } + else + { + if (Vel < MPTRelay[ScndCtrlPos].Idown) + { + --ScndCtrlPos; + } + } + } + // 3rd level drops with master controller at position lower than 10... + if (MainCtrlPos < 11) + { + ScndCtrlPos = std::min(2, ScndCtrlPos); + } + // ...and below position 7 field shunt drops altogether + if (MainCtrlPos < 8) + { + ScndCtrlPos = 0; + } + /* + // crude woodward approximation; difference between rpm for consecutive positions is ~5% + // so we get full throttle until ~half way between desired and previous position, or zero on rpm reduction + auto const woodward { std::clamp( + ( DElist[ MainCtrlPos ].RPM / ( enrot * 60.0 ) - 1.0 ) * 50.0, + 0.0, 1.0 ) }; + */ +} + +// the relays of type 46, by the current and the speed: up from the 12th position, down under it below 50 km/h, at most two +// under the 11th, none under the 8th +void TMoverParameters::ShuntFieldRelaysType46() +{ + // wzrastanie + if (MainCtrlPos >= 12 && ScndCtrlPos < ScndCtrlPosNo) + { + ShuntFieldRelaysType46Up(); + } + // malenie + if (MainCtrlPos < 12 && ScndCtrlPos > 0 && Vel < 50.0) + { + ShuntFieldRelaysType46Down(); + } + if (MainCtrlPos < 11) + { + ScndCtrlPos = std::min(2, ScndCtrlPos); + } + if (MainCtrlPos < 8) + { + ScndCtrlPos = 0; + } +} + +// a relay of type 46 down: an even one by the current, an odd one by the current and the speed +void TMoverParameters::ShuntFieldRelaysType46Down() +{ + // above 50 km/h already active shunt field can be maintained until lower controller setting + if (ScndCtrlPos % 2 == 0) + { + if (MPTRelay[ScndCtrlPos].Idown < Im) + { + --ScndCtrlPos; + } + } + else + { + if (MPTRelay[ScndCtrlPos + 1].Idown < Im && MPTRelay[ScndCtrlPos].Idown > Vel) + { + --ScndCtrlPos; + } + } +} + +// a relay of type 46 up: an even one by the current, an odd one by the current and the speed +void TMoverParameters::ShuntFieldRelaysType46Up() +{ + if (ScndCtrlPos % 2 == 0) + { + if (MPTRelay[ScndCtrlPos].Iup > Im) + { + ++ScndCtrlPos; + } + } + else + { + if (MPTRelay[ScndCtrlPos - 1].Iup > Im && MPTRelay[ScndCtrlPos].Iup < Vel) + { + ++ScndCtrlPos; + } + } +} + +void TMoverParameters::InductionMotorTractionForce(double dt) +{ + if (MainCircuitPowered() && !SecuritySystem.is_engine_blocked()) + { + double PosRatio; + double tmp; + double ActiveInverters = 0.0; + for (auto const &inv : Inverters) + { + if (inv.IsActive) + ActiveInverters += 1.0; + } + InvertersRatio = ActiveInverters / (double)InvertersNo; + if (EIM_Pmax_Table.size() > 1) + { + eimc[eimc_p_Pmax] = TableInterpolation(EIM_Pmax_Table, Vel); + } + InductionMotorSpeedControl(dt); + InductionMotorBrakeBlending(ActiveInverters, PosRatio, tmp); + // NOTE: the commands to operate the sandbox are likely to conflict with other similar ai decisions + // TODO: gather these in single place so they can be resolved together + if (SlippingWheels) + { + PosRatio = 0; + tmp = 10; + SandboxAuto(true, range_t::unit); + } // przeciwposlizg + else + { + // switch sandbox off + SandboxAuto(false, range_t::unit); + } + if (ActiveInverters == 0.0) + { + PosRatio = 0; + eimv_pr = 0; + } + + eimv_pr += std::max(std::min(PosRatio - eimv_pr, 0.02), -0.02) * 12 * tmp /*2{+4*byte(PosRatio 1) + { + SpeedControlByPosition(dt); + } +} + +// the speed control set by the position of the second controller, after it's been held for its delay +void TMoverParameters::SpeedControlByPosition(double dt) +{ + if (ScndCtrlPos != NewSpeed) + { + + SpeedCtrlTimer = 0; + NewSpeed = ScndCtrlPos; + } + else + { + SpeedCtrlTimer += dt; + if (SpeedCtrlTimer > SpeedCtrlDelay) + { + auto NewSCAP = static_cast((float)ScndCtrlPos / (float)ScndCtrlPosNo * Vmax); + if (NewSCAP != SpeedCtrlValue) + { + SpeedCtrlValue = NewSCAP; + // SendCtrlToNext("SpeedCntrl", SpeedCtrlValue, CabActive); + } + } + } + SpeedCtrlUnit.IsActive = SpeedCtrlValue > 0; +} + +// the speed control of a four position second controller, by time: the speed set down or up by 10 km/h a step, held, +// or off and at the top +void TMoverParameters::SpeedControlByTime(double dt) +{ + SpeedCtrlUnit.IsActive = SpeedCtrlValue > 0; + switch (ScndCtrlPos) + { + case 0: + NewSpeed = 0; + SpeedCtrlValue = 0; + SpeedCtrlTimer = 10; + break; + case 1: + if (SpeedCtrlTimer > SpeedCtrlDelay) + { + SpeedCtrlTimer = 0; + NewSpeed -= 10; + if (NewSpeed < 0) + NewSpeed = 0; + } + else + SpeedCtrlTimer += dt; + break; + case 2: + SpeedCtrlTimer = 10; + SpeedCtrlValue = NewSpeed; + break; + case 3: + if (SpeedCtrlTimer > SpeedCtrlDelay) + { + SpeedCtrlTimer = 0; + NewSpeed += 10; + if (NewSpeed > Vmax) + NewSpeed = Vmax; + } + else + SpeedCtrlTimer += dt; + break; + case 4: + NewSpeed = Vmax; + SpeedCtrlValue = Vmax; + SpeedCtrlTimer = 10; + break; + default: + break; + } +} + +// whether the induction motors brake, and the share of the electrodynamic and the pneumatic brake; sets the +// force asked of the motors (PosRatio) and how fast the drive follows it (tmp) +void TMoverParameters::InductionMotorBrakeBlending(double const ActiveInverters, double &PosRatio, double &tmp) +{ + InductionMotorDynamicBrakeFlag(); + auto const edBCP{Hamulec->GetEDBCP() * eimc[eimc_p_abed]}; // stala napedu + if (DynamicBrakeFlag) + { + PosRatio = InductionMotorBrakeRatio(ActiveInverters, edBCP); + tmp = 5; + } + else + { + PosRatio = std::max(eimic_real, 0.); + eimv[eimv_Fzad] = PosRatio; + if (Flat && eimc[eimc_p_F0] * eimv[eimv_Fful] > 0) + PosRatio = std::min(PosRatio * eimc[eimc_p_F0] / eimv[eimv_Fful], 1.); + /* if (ScndCtrlActualPos > 0) //speed control + if (Vmax < 250) + PosRatio = std::min(PosRatio, std::max(-1, 0.5 * (ScndCtrlActualPos - Vel))); + else + PosRatio = + std::min(PosRatio, std::max(-1, 0.5 * (ScndCtrlActualPos * 2 - Vel))); */ + // PosRatio = 1.0 * (PosRatio * 0 + 1) * PosRatio; // 1 * 1 * PosRatio = PosRatio + Hamulec->SetED(0); + // (Hamulec as TLSt).SetLBP(LocBrakePress); + tmp = 4; // szybkie malenie, powolne wzrastanie + } +} + +// the electrodynamic brake of the induction motors on: with the doors open or permitted, by the train brake, the local +// brake or its own controller; off without them +void TMoverParameters::InductionMotorDynamicBrakeFlag() +{ + double const edBCP = Hamulec->GetEDBCP(); + auto const localbrakeactive{CabOccupied != 0 && LocHandle->GetCP() > 0.25}; + // gdy SplitEDPneumaticBrake jest aktywne, hamulec pomocniczy (LocalBrake) NIE wymusza + // zalaczenia hamulca elektrodynamicznego - ED jest sterowany wlasnym nastawnikiem + auto const dynbrakectrlactive{SplitEDPneumaticBrake && DynamicBrakeRatio() > 0.01 && DynamicBrakeAvailable()}; + auto const localbrakeforED{SplitEDPneumaticBrake ? false : localbrakeactive}; + if (false == Doors.instances[side::left].is_closed || false == Doors.instances[side::right].is_closed || + (Doors.permit_needed && (Doors.instances[side::left].open_permit || Doors.instances[side::right].open_permit))) + { + DynamicBrakeFlag = true; + } + else if ((edBCP < 0.25 && false == localbrakeforED && false == dynbrakectrlactive && AnPos < 0.01) || + (edBCP < 0.25 && ShuntModeAllow && false == dynbrakectrlactive && LocalBrakePosA < 0.01)) + DynamicBrakeFlag = false; + else if (BrakePress > 0.25 && edBCP > 0.25 || localbrakeforED || AnPos > 0.02 || dynbrakectrlactive) + DynamicBrakeFlag = true; +} + +// the share of the electrodynamic brake (negative), and the distributor told how much of the air to let out; none +// when the air brake cuts the electrodynamic one off, or an inverter is out +double TMoverParameters::InductionMotorBrakeRatio(double const ActiveInverters, double const edBCP) +{ + double PosRatio; + // ustalanie współczynnika blendingu do luzowania hamulca PN + if (eimv[eimv_Fmax] * Sign(V) * DirAbsolute < -1) + { + PosRatio = -Sign(V) * DirAbsolute * eimv[eimv_Fr] / (eimc[eimc_p_Fh] * std::max(edBCP, std::max(0.01, Hamulec->GetEDBCP())) / MaxBrakePress[0]); + PosRatio = std::clamp(PosRatio, 0.0, 1.0); + } + else + { + PosRatio = 0; + } + PosRatio = static_cast(Round(20.0 * PosRatio)) / 20.0; // stopniowanie PN/ED + if (PosRatio < 19.5 / 20.0) + PosRatio *= 0.9; + Hamulec->SetED(std::max(0.0, std::min(PosRatio, 1.0))); // ustalenie stopnia zmniejszenia ciśnienia + // ustalanie siły hamowania ED + if (Hamulec->GetEDBCP() > 0.25 && eimc[eimc_p_abed] < 0.001 || ActiveInverters < InvertersNo) // jeśli PN wyłącza ED + { + PosRatio = 0; + eimv[eimv_Fzad] = 0; + } + else + { + // strefa wylaczenia ED (Vh0..Vh1) - mnoznik 0..1 zaleznie od predkosci + double const vhRamp = std::max(0.0, std::min(1.0, (Vel - eimc[eimc_p_Vh0]) / (eimc[eimc_p_Vh1] - eimc[eimc_p_Vh0]))); + if (SplitEDPneumaticBrake) + { + // w trybie split LocalBrake nie zaleca ED; uzywany jest DynamicBrakeCtrl + // oraz zwykle zapotrzebowanie z hamulca zespolonego (edBCP) + double const edLeverDemand = DynamicBrakeRatio(); + PosRatio = -std::max(std::max(edLeverDemand, std::min(edBCP / MaxBrakePress[0], 1.0)), AnPos) * vhRamp; + eimv[eimv_Fzad] = -std::min(1.0, std::max(edLeverDemand, edBCP / MaxBrakePress[0])); + } + else + { + PosRatio = -std::max(std::min(edBCP * 1.0 / MaxBrakePress[0], 1.0), AnPos) * vhRamp; + eimv[eimv_Fzad] = -std::min(1.0, std::max(LocalBrakeRatio(), edBCP / MaxBrakePress[0])); + } + } + return PosRatio; +} + +// the model of the induction motors and their inverters: voltage, frequency, currents, moment and force +void TMoverParameters::InductionMotorDrive(double dt) +{ + double tmp; + if (DynamicBrakeFlag) + tmp = eimc[eimc_f_Uzh]; + else + tmp = eimc[eimc_f_Uzmax]; + + auto f_cfu{DynamicBrakeFlag ? eimc[eimc_f_cfuH] : eimc[eimc_f_cfu]}; + + eimv[eimv_Uzsmax] = std::min(EngineVoltage - eimc[eimc_f_DU], tmp); + eimv[eimv_fkr] = eimv[eimv_Uzsmax] / f_cfu; + if (eimv_pr < 0) + { + eimv[eimv_Pmax] = eimc[eimc_p_Ph]; + } + else + { + eimv[eimv_Pmax] = std::min(eimc[eimc_p_Pmax], 0.001 * EngineVoltage * (eimc[eimc_p_Imax] - eimc[eimc_f_I0]) * Pirazy2 * eimc[eimc_s_cim] / eimc[eimc_s_p] / eimc[eimc_s_cfu]); + } + eimv[eimv_FMAXMAX] = 0.001 * + square(std::min(1.0, eimv[eimv_fkr] / std::max(abs(enrot) * eimc[eimc_s_p] + eimc[eimc_s_dfmax] * eimv[eimv_ks], eimc[eimc_s_dfmax])) * f_cfu / eimc[eimc_s_cfu]) * + (eimc[eimc_s_dfmax] * eimc[eimc_s_dfic] * eimc[eimc_s_cim]) * Transmision.Ratio * NPoweredAxles * 2.0 / WheelDiameter; + InductionMotorForceLimits(); + for (auto &inv : Inverters) + { + inv.Request = inv.IsActive ? eimv_pr : 0.0; + inv.Error = inv.Failure_Const || (inv.Failure_Drive && inv.Request != 0); + inv.IsActive = inv.Activate && !inv.Error; + } + eimv[eimv_ks] = eimv[eimv_Fr] / eimv[eimv_FMAXMAX]; + eimv[eimv_df] = eimv[eimv_ks] * eimc[eimc_s_dfmax]; + eimv[eimv_fp] = DirAbsolute * enrot * eimc[eimc_s_p] + eimv[eimv_df]; // do przemyslenia dzialanie pp z tmpV + // eimv[eimv_U]:=std::max(eimv[eimv_Uzsmax],std::min(eimc[eimc_f_cfu]*eimv[eimv_fp],eimv[eimv_Uzsmax])); + // eimv[eimv_pole]:=eimv[eimv_U]/(eimv[eimv_fp]*eimc[eimc_s_cfu]); + if (abs(eimv[eimv_fp]) <= eimv[eimv_fkr]) + eimv[eimv_pole] = f_cfu / eimc[eimc_s_cfu]; + else + eimv[eimv_pole] = eimv[eimv_Uzsmax] / eimc[eimc_s_cfu] / abs(eimv[eimv_fp]); + eimv[eimv_U] = eimv[eimv_pole] * eimv[eimv_fp] * eimc[eimc_s_cfu]; + eimv[eimv_Ic] = (eimv[eimv_fp] - DirAbsolute * enrot * eimc[eimc_s_p]) * eimc[eimc_s_dfic] * eimv[eimv_pole]; + eimv[eimv_If] = eimv[eimv_Ic] * eimc[eimc_s_icif]; + eimv[eimv_M] = eimv[eimv_pole] * eimv[eimv_Ic] * eimc[eimc_s_cim]; + eimv[eimv_Ipoj] = eimv[eimv_Ic] * NPoweredAxles * InvertersRatio * eimv[eimv_U] / (EngineVoltage - eimc[eimc_f_DU]) + eimc[eimc_f_I0]; + eimv[eimv_Pm] = DirActive * eimv[eimv_M] * NPoweredAxles * InvertersRatio * enrot * Pirazy2 / 1000; + eimv[eimv_Pe] = eimv[eimv_Ipoj] * EngineVoltage / 1000; + eimv[eimv_eta] = eimv[eimv_Pm] / eimv[eimv_Pe]; + + Im = eimv[eimv_If]; + if (eimv[eimv_Ipoj] >= 0) + Vadd *= 1.0 - 2.0 * dt; + else if (std::abs(EngineVoltage) < EnginePowerSource.CollectorParameters.MaxV) + Vadd *= 1.0 - dt; + else + Vadd = std::max(Vadd * (1.0 - 0.2 * dt), 0.007 * (std::abs(EngineVoltage) - (EnginePowerSource.CollectorParameters.MaxV - 100))); + Itot = eimv[eimv_Ipoj] * (0.01 + std::min(0.99, 0.99 - Vadd)); + + EnginePower = abs(eimv[eimv_Ic] * eimv[eimv_U] * NPoweredAxles) / 1000; + // power inverters + UpdateInverterFrequency(); + + Mm = eimv[eimv_M] * DirAbsolute; + Mw = Mm * Transmision.Ratio * Transmision.Efficiency; + Fw = Mw * 2.0 / WheelDiameter; + Ft = Fw * NPoweredAxles * InvertersRatio; + eimv[eimv_Fr] = DirAbsolute * Ft / 1000; +} + +// the force the motors give at full and at the setting (eimv_pr), braking within the power and the force of the +// electrodynamic brake, driving within the power and the starting force +void TMoverParameters::InductionMotorForceLimits() +{ + if (eimv_pr < 0) + { + eimv[eimv_Fful] = std::min(eimc[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(eimc[eimc_p_Fh], eimv[eimv_FMAXMAX])); + eimv[eimv_Fmax] = -Sign(V) * DirAbsolute*std::min(eimc[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-eimc[eimc_p_Fh] * eimv_pr, eimv[eimv_FMAXMAX])); + double pr = eimv_pr; + if (EIMCLogForce) + pr = -log(1 - 4 * pr) / log(5); + eimv[eimv_Fr] = -Sign(V) * DirAbsolute*std::min(eimc[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-eimc[eimc_p_Fh] * pr, eimv[eimv_FMAXMAX])); + if (InvertersRatio < 1.0) + eimv[eimv_Fful] = 0; + //*std::min(1,(Vel-eimc[eimc_p_Vh0])/(eimc[eimc_p_Vh1]-eimc[eimc_p_Vh0])) + } + else + { + eimv[eimv_Fful] = std::min(std::min(3.6 * eimv[eimv_Pmax] / std::max(Vel, 1.), eimc[eimc_p_F0] - Vel * eimc[eimc_p_a1]), eimv[eimv_FMAXMAX]); + // if(not Flat)then + eimv[eimv_Fmax] = eimv[eimv_Fful] * eimv_pr; + // else + // eimv[eimv_Fmax]:=std::min(eimc[eimc_p_F0]*eimv_pr,eimv[eimv_Fful]); + double pr = eimv_pr; + if (EIMCLogForce) + pr = log(1 + 4 * pr) / log(5); + eimv[eimv_Fr] = eimv[eimv_Fful] * pr; + } +} + +// the frequency of the inverters at the motors' slip frequency, from the list of the drive or of its brake +void TMoverParameters::UpdateInverterFrequency() +{ + auto const tmpV{std::abs(eimv[eimv_fp])}; + auto const useFFEDList = FFEDListSize > 0 && DynamicBrakeFlag; + auto const list = useFFEDList ? FFEDlist : FFlist; + + if (auto const listSize = useFFEDList ? FFEDListSize : FFListSize; listSize > 0 && std::abs(eimv[eimv_If]) > 1.0 && tmpV > 0.0001) + { + + int i = 0; + while (i < listSize - 1 && list[i + 1].v < tmpV) + { + ++i; + } + InverterFrequency = (tmpV - list[i].v) / std::max(1.0, list[i + 1].v - list[i].v) * (list[i + 1].freq - list[i].freq) + list[i].freq; + } + else + { + InverterFrequency = 0.0; + } +} + +// the induction motor drive without power, or blocked by the security system +void TMoverParameters::InductionMotorOff() +{ + for (auto &inv : Inverters) + { + inv.Freal = 0.0; + inv.IsActive = false; + } + Im = 0.0; + Mm = 0.0; + Mw = 0.0; + Fw = 0.0; + Ft = 0.0; + Itot = 0.0; + eimv_pr = 0.0; + EnginePower = 0.0; + { + for (auto &eimvvalue : eimv) + eimvvalue = 0.0; + } + Hamulec->SetED(0.0); + InverterFrequency = 0.0; //(Hamulec as TLSt).SetLBP(LocBrakePress); } // the current of a diesel-electric vehicle's traction motors giving the moment [N m] of one motor @@ -8170,7 +8517,6 @@ bool TMoverParameters::AutoRelayCheck(void) if (motorconnectorsoff || (HasCamshaft ? IsMainCtrlActualNoPowerPos() : IsMainCtrlNoPowerPos())) { StLinFlag = false; - OK = false; if (false == DynamicBrakeFlag) { Im = 0; @@ -8194,253 +8540,16 @@ bool TMoverParameters::AutoRelayCheck(void) { if (RList[MainCtrlActualPos].R == 0 && (ScndCtrlActualPos > 0 || ScndCtrlPos > 0) && (!CoupledCtrl || RList[MainCtrlActualPos].Relay == MainCtrlPos)) { // zmieniaj scndctrlactualpos - // scnd bez samoczynnego rozruchu - if (ScndCtrlActualPos < ScndCtrlPos) - { - if (LastRelayTime > CtrlDelay && ARFASI2) - { - ++ScndCtrlActualPos; - SetFlag(SoundFlag, sound::shuntfield); - OK = true; - } - } - else if (ScndCtrlActualPos > ScndCtrlPos) - { - if (LastRelayTime > CtrlDownDelay && TrainType != dt_EZT) - { - --ScndCtrlActualPos; - SetFlag(SoundFlag, sound::shuntfield); - OK = true; - } - } - else - OK = false; + OK = AutoRelayShuntStep(ARFASI2); } else { // zmieniaj mainctrlactualpos - // running backwards, the motors don't get joined in more branches than allowed (the series connection - // alone, usually); the camshaft still goes back down from there (eu07/maszyna#393: it stayed where it - // was, the line contactors closed, whatever the driver did with the master controller) - auto const backwardslimit{DirActive < 0 && TrainType != dt_PseudoDiesel && RList[MainCtrlActualPos + 1].Bn > BackwardsBranchesAllowed}; - // main bez samoczynnego rozruchu - if (false == backwardslimit && MainCtrlActualPos < std::size(RList) - 1 // crude guard against running out of current fixed table - && (RList[MainCtrlActualPos].Relay < MainCtrlPos || (RList[MainCtrlActualPos + 1].Relay == MainCtrlPos && MainCtrlActualPos < RlistSize) || - (TrainType == dt_ET22 && DelayCtrlFlag))) - { - - // prevent switch to parallel mode if motor overload relay is set to high threshold mode - if (IsMotorOverloadRelayHighThresholdOn() && RList[MainCtrlActualPos + 1].Bn > 1) - { - return false; - } - - if (RList[MainCtrlPos].R == 0 && MainCtrlPos > 0 && MainCtrlPos != MainCtrlPosNo && FastSerialCircuit == 1) - { - // szybkie wchodzenie na bezoporowa (303E) - // MainCtrlActualPos:=MainCtrlPos; //hunter-111012: - ++MainCtrlActualPos; - if (MainCtrlPos - MainCtrlActualPos == 1) - { - // HACK: ensure we play only single sound of basic relays for entire trasition; return false - // for all but last step despite configuration change, to prevent playback of the basic relay sound - // TBD, TODO: move the basic sound event here and enable it with call parameter - OK = true; - } - if (RList[MainCtrlActualPos].R == 0) - { - SetFlag(SoundFlag, sound::parallel | sound::loud); - OK = true; - } - } - else if (LastRelayTime > CtrlDelay && ARFASI) - { - // WriteLog("LRT = " + FloatToStr(LastRelayTime) + ", " + - // FloatToStr(CtrlDelay)); - if (TrainType == dt_ET22 && MainCtrlPos > 1 && (RList[MainCtrlActualPos].Bn < RList[MainCtrlActualPos + 1].Bn || DelayCtrlFlag)) - { - // et22 z walem grupowym - if (!DelayCtrlFlag) // najpierw przejscie - { - ++MainCtrlActualPos; - DelayCtrlFlag = true; // tryb przejscia - OK = true; - } - else if (LastRelayTime > 4 * CtrlDelay) // przejscie - { - - DelayCtrlFlag = false; - OK = true; - } - /* - else - ; - */ - } - else // nie ET22 z wałem grupowym - { - ++MainCtrlActualPos; - OK = true; - } - //--------- - // hunter-111211: poprawki - if (MainCtrlActualPos > 0) - { - if (RList[MainCtrlActualPos].R == 0 && MainCtrlActualPos != MainCtrlPosNo) - { - // wejscie na bezoporowa - SetFlag(SoundFlag, sound::parallel | sound::loud); - } - else if (RList[MainCtrlActualPos].R > 0 && RList[MainCtrlActualPos - 1].R == 0) - { - // wejscie na drugi uklad - SetFlag(SoundFlag, sound::parallel); - } - } - } - } - else if (RList[MainCtrlActualPos].Relay > MainCtrlPos) - { - if (RList[MainCtrlPos].R == 0 && MainCtrlPos > 0 && !(MainCtrlPos == MainCtrlPosNo) && FastSerialCircuit == 1) - { - // szybkie wchodzenie na bezoporowa (303E) - // MainCtrlActualPos:=MainCtrlPos; //hunter-111012: - --MainCtrlActualPos; - OK = true; - if (RList[MainCtrlActualPos].R == 0) - { - SetFlag(SoundFlag, sound::parallel); - } - } - else if (LastRelayTime > CtrlDownDelay) - { - if (TrainType != dt_EZT) // tutaj powinien być tryb sterowania wałem - { - --MainCtrlActualPos; - OK = true; - } - // hunter-111211: poprawki - if (MainCtrlActualPos > 0 && RList[MainCtrlActualPos].R == 0) - { - // dzwieki schodzenia z bezoporowej} - SetFlag(SoundFlag, sound::parallel); - } - } - } - else if (RList[MainCtrlActualPos].R > 0 && ScndCtrlActualPos > 0) - { - if (LastRelayTime > CtrlDownDelay) - { - --ScndCtrlActualPos; // boczniki nie dzialaja na poz. oporowych - SetFlag(SoundFlag, sound::shuntfield); - OK = true; - } - } - else - OK = false; + OK = AutoRelayMainStep(ARFASI); } } else // not StLinFlag { - OK = false; - // ybARC - zalaczenie stycznikow liniowych - if (false == motorconnectorsoff && MainCtrlActualPos == 0 && (TrainType == dt_EZT || HasCamshaft ? MainCtrlPowerPos() > 0 : MainCtrlPowerPos() == 1)) - { - - DelayCtrlFlag = true; - if (LastRelayTime >= InitialCtrlDelay) - { - StLinFlag = true; - MainCtrlActualPos = 1; - DelayCtrlFlag = false; - SetFlag(SoundFlag, sound::relay | sound::loud); - OK = true; - } - } - else - { - DelayCtrlFlag = false; - } - - if (false == StLinFlag && (MainCtrlActualPos > 0 || ScndCtrlActualPos > 0)) - { - - if (CoupledCtrl) - { - - if (TrainType == dt_EZT) - { - // EN57 wal jednokierunkowy calosciowy - if (MainCtrlActualPos == 1) - { - - MainCtrlActualPos = 0; - OK = true; - } - else - { - - if (LastRelayTime > CtrlDownDelay) - { - - if (MainCtrlActualPos < RlistSize) - { - // dojdz do konca - ++MainCtrlActualPos; - } - else if (ScndCtrlActualPos < ScndCtrlPosNo) - { - // potem boki - ++ScndCtrlActualPos; - SetFlag(SoundFlag, sound::shuntfield); - } - else - { - // i sie przewroc na koniec - MainCtrlActualPos = 0; - ScndCtrlActualPos = 0; - } - OK = true; - } - } - } - else - { - // wal kulakowy dwukierunkowy - if (LastRelayTime > CtrlDownDelay) - { - if (ScndCtrlActualPos > 0) - { - --ScndCtrlActualPos; - SetFlag(SoundFlag, sound::shuntfield); - } - else - { - --MainCtrlActualPos; - } - OK = true; - } - } - } - else if (HasCamshaft) - { - // wal kulakowy dwukierunkowy - if (LastRelayTime > CtrlDownDelay) - { - if (MainCtrlActualPos > 0) - { - --MainCtrlActualPos; - } - ScndCtrlActualPos = 0; - OK = true; - } - } - else - { - MainCtrlActualPos = 0; - ScndCtrlActualPos = 0; - OK = true; - } - } + OK = AutoRelayLineContactorsStep(motorconnectorsoff); } if (OK) LastRelayTime = 0; @@ -8449,6 +8558,304 @@ bool TMoverParameters::AutoRelayCheck(void) } } +// a step of the shunt field on a position without resistors, up or down to the second controller +bool TMoverParameters::AutoRelayShuntStep(bool const ARFASI2) +{ + bool OK = false; + // scnd bez samoczynnego rozruchu + if (ScndCtrlActualPos < ScndCtrlPos) + { + if (LastRelayTime > CtrlDelay && ARFASI2) + { + ++ScndCtrlActualPos; + SetFlag(SoundFlag, sound::shuntfield); + OK = true; + } + } + else if (ScndCtrlActualPos > ScndCtrlPos) + { + if (LastRelayTime > CtrlDownDelay && TrainType != dt_EZT) + { + --ScndCtrlActualPos; + SetFlag(SoundFlag, sound::shuntfield); + OK = true; + } + } + else + OK = false; + return OK; +} + +// a step of the main controller's relays, up or down to its position, or the shunt field off on the resistors +bool TMoverParameters::AutoRelayMainStep(bool const ARFASI) +{ + bool OK = false; + // running backwards, the motors don't get joined in more branches than allowed (the series connection + // alone, usually); the camshaft still goes back down from there (eu07/maszyna#393: it stayed where it + // was, the line contactors closed, whatever the driver did with the master controller) + auto const backwardslimit{DirActive < 0 && TrainType != dt_PseudoDiesel && RList[MainCtrlActualPos + 1].Bn > BackwardsBranchesAllowed}; + // main bez samoczynnego rozruchu + if (false == backwardslimit && MainCtrlActualPos < std::size(RList) - 1 // crude guard against running out of current fixed table + && (RList[MainCtrlActualPos].Relay < MainCtrlPos || (RList[MainCtrlActualPos + 1].Relay == MainCtrlPos && MainCtrlActualPos < RlistSize) || + (TrainType == dt_ET22 && DelayCtrlFlag))) + { + OK = AutoRelayMainUp(ARFASI); + } + else if (RList[MainCtrlActualPos].Relay > MainCtrlPos) + { + OK = AutoRelayMainDown(); + } + else if (RList[MainCtrlActualPos].R > 0 && ScndCtrlActualPos > 0) + { + if (LastRelayTime > CtrlDownDelay) + { + --ScndCtrlActualPos; // boczniki nie dzialaja na poz. oporowych + SetFlag(SoundFlag, sound::shuntfield); + OK = true; + } + } + else + OK = false; + return OK; +} + +// a step of the main relays up to the controller's position, at once to the parallel position without resistors +// on a fast serial circuit (303E); returns whether the relays moved, never into parallel with the overload relay high +bool TMoverParameters::AutoRelayMainUp(bool const ARFASI) +{ + bool OK = false; + // prevent switch to parallel mode if motor overload relay is set to high threshold mode + if (IsMotorOverloadRelayHighThresholdOn() && RList[MainCtrlActualPos + 1].Bn > 1) + { + return false; + } + + if (RList[MainCtrlPos].R == 0 && MainCtrlPos > 0 && MainCtrlPos != MainCtrlPosNo && FastSerialCircuit == 1) + { + // szybkie wchodzenie na bezoporowa (303E) + // MainCtrlActualPos:=MainCtrlPos; //hunter-111012: + ++MainCtrlActualPos; + if (MainCtrlPos - MainCtrlActualPos == 1) + { + // HACK: ensure we play only single sound of basic relays for entire trasition; return false + // for all but last step despite configuration change, to prevent playback of the basic relay sound + // TBD, TODO: move the basic sound event here and enable it with call parameter + OK = true; + } + if (RList[MainCtrlActualPos].R == 0) + { + SetFlag(SoundFlag, sound::parallel | sound::loud); + OK = true; + } + } + else if (LastRelayTime > CtrlDelay && ARFASI) + { + OK = AutoRelayMainNotchUp(); + } + return OK; +} + +// a notch up of the main relays after their delay, through the group switch of the ET22, and the sounds of the +// parallel positions; returns whether they moved +bool TMoverParameters::AutoRelayMainNotchUp() +{ + bool OK = false; + // WriteLog("LRT = " + FloatToStr(LastRelayTime) + ", " + + // FloatToStr(CtrlDelay)); + if (TrainType == dt_ET22 && MainCtrlPos > 1 && (RList[MainCtrlActualPos].Bn < RList[MainCtrlActualPos + 1].Bn || DelayCtrlFlag)) + { + // et22 z walem grupowym + if (!DelayCtrlFlag) // najpierw przejscie + { + ++MainCtrlActualPos; + DelayCtrlFlag = true; // tryb przejscia + OK = true; + } + else if (LastRelayTime > 4 * CtrlDelay) // przejscie + { + + DelayCtrlFlag = false; + OK = true; + } + /* + else + ; + */ + } + else // nie ET22 z wałem grupowym + { + ++MainCtrlActualPos; + OK = true; + } + //--------- + // hunter-111211: poprawki + if (MainCtrlActualPos > 0) + { + if (RList[MainCtrlActualPos].R == 0 && MainCtrlActualPos != MainCtrlPosNo) + { + // wejscie na bezoporowa + SetFlag(SoundFlag, sound::parallel | sound::loud); + } + else if (RList[MainCtrlActualPos].R > 0 && RList[MainCtrlActualPos - 1].R == 0) + { + // wejscie na drugi uklad + SetFlag(SoundFlag, sound::parallel); + } + } + return OK; +} + +// a step of the main relays down to the controller's position; returns whether they moved +bool TMoverParameters::AutoRelayMainDown() +{ + bool OK = false; + if (RList[MainCtrlPos].R == 0 && MainCtrlPos > 0 && !(MainCtrlPos == MainCtrlPosNo) && FastSerialCircuit == 1) + { + // szybkie wchodzenie na bezoporowa (303E) + // MainCtrlActualPos:=MainCtrlPos; //hunter-111012: + --MainCtrlActualPos; + OK = true; + if (RList[MainCtrlActualPos].R == 0) + { + SetFlag(SoundFlag, sound::parallel); + } + } + else if (LastRelayTime > CtrlDownDelay) + { + if (TrainType != dt_EZT) // tutaj powinien być tryb sterowania wałem + { + --MainCtrlActualPos; + OK = true; + } + // hunter-111211: poprawki + if (MainCtrlActualPos > 0 && RList[MainCtrlActualPos].R == 0) + { + // dzwieki schodzenia z bezoporowej} + SetFlag(SoundFlag, sound::parallel); + } + } + return OK; +} + +// the line contactors closed at the first position, or, open, the camshaft run back to zero +bool TMoverParameters::AutoRelayLineContactorsStep(bool const motorconnectorsoff) +{ + bool OK = false; + // ybARC - zalaczenie stycznikow liniowych + if (false == motorconnectorsoff && MainCtrlActualPos == 0 && (TrainType == dt_EZT || HasCamshaft ? MainCtrlPowerPos() > 0 : MainCtrlPowerPos() == 1)) + { + + DelayCtrlFlag = true; + if (LastRelayTime >= InitialCtrlDelay) + { + StLinFlag = true; + MainCtrlActualPos = 1; + DelayCtrlFlag = false; + SetFlag(SoundFlag, sound::relay | sound::loud); + OK = true; + } + } + else + { + DelayCtrlFlag = false; + } + + if (false == StLinFlag && (MainCtrlActualPos > 0 || ScndCtrlActualPos > 0)) + { + OK |= CamshaftRunDown(); + } + return OK; +} + +// the camshaft, the line contactors open, run back to its zero position a step at a time, or at once without one; +// returns whether it moved +bool TMoverParameters::CamshaftRunDown() +{ + bool OK = false; + + if (CoupledCtrl) + { + + if (TrainType == dt_EZT) + { + OK = CamshaftRunDownEMU(); + } + else if (LastRelayTime > CtrlDownDelay) // wal kulakowy dwukierunkowy + { + if (ScndCtrlActualPos > 0) + { + --ScndCtrlActualPos; + SetFlag(SoundFlag, sound::shuntfield); + } + else + { + --MainCtrlActualPos; + } + OK = true; + } + } + else if (HasCamshaft) + { + // wal kulakowy dwukierunkowy + if (LastRelayTime > CtrlDownDelay) + { + if (MainCtrlActualPos > 0) + { + --MainCtrlActualPos; + } + ScndCtrlActualPos = 0; + OK = true; + } + } + else + { + MainCtrlActualPos = 0; + ScndCtrlActualPos = 0; + OK = true; + } + return OK; +} + +// the one way camshaft of the EN57 run on to its end and round to zero; returns whether it moved +bool TMoverParameters::CamshaftRunDownEMU() +{ + bool OK = false; + // EN57 wal jednokierunkowy calosciowy + if (MainCtrlActualPos == 1) + { + + MainCtrlActualPos = 0; + OK = true; + } + else + { + + if (LastRelayTime > CtrlDownDelay) + { + + if (MainCtrlActualPos < RlistSize) + { + // dojdz do konca + ++MainCtrlActualPos; + } + else if (ScndCtrlActualPos < ScndCtrlPosNo) + { + // potem boki + ++ScndCtrlActualPos; + SetFlag(SoundFlag, sound::shuntfield); + } + else + { + // i sie przewroc na koniec + MainCtrlActualPos = 0; + ScndCtrlActualPos = 0; + } + OK = true; + } + } + return OK; +} + bool TMoverParameters::MotorConnectorsCheck() { @@ -8709,160 +9116,205 @@ void TMoverParameters::CheckEIMIC(double dt) switch (EIMCtrlType) { case 0: - eimic = brakeDemand > 0.01 ? -brakeDemand : eimic_analog > 0.01 ? eimic_analog : (double)MainCtrlPos / (double)MainCtrlPosNo; - if (EIMCtrlAdditionalZeros || EIMCtrlEmergency) - { - if (eimic > 0.001) - eimic = std::max(0.002, eimic * (double)MainCtrlPosNo / ((double)MainCtrlPosNo - offset) - offset / ((double)MainCtrlPosNo - offset)); - if (eimic < -0.001 && BrakeHandle != TBrakeHandle::MHZ_EN57) - eimic = std::min(-0.002, eimic * (double)LocalBrakePosNo / ((double)LocalBrakePosNo - multiplier) + offset / ((double)LocalBrakePosNo - multiplier)); - } - if (eimic > 0.001 && SpeedCtrlUnit.IsActive) - eimic = std::max(eimic, SpeedCtrlUnit.MinPower); + EIMICFromController(brakeDemand, offset, multiplier); break; case 1: - switch (MainCtrlPos) + EIMICFromSteps(dt); + break; + case 2: + EIMICFromFourPositions(dt); + break; + case 3: + EIMICFromUniversalController(dt, brakeDemand); + break; + } + if (LocHandleTimeTraxx) + { + EIMICTraxxLocalBrake(dt); + } + + EIMICLimit(); +} + +// the controller (EIMCtrlType 0): the position of the main controller, or the analog one, or the brake asked +void TMoverParameters::EIMICFromController(double const brakeDemand, double const offset, double const multiplier) +{ + eimic = brakeDemand > 0.01 ? -brakeDemand : eimic_analog > 0.01 ? eimic_analog : (double)MainCtrlPos / (double)MainCtrlPosNo; + if (EIMCtrlAdditionalZeros || EIMCtrlEmergency) + { + if (eimic > 0.001) + eimic = std::max(0.002, eimic * (double)MainCtrlPosNo / ((double)MainCtrlPosNo - offset) - offset / ((double)MainCtrlPosNo - offset)); + if (eimic < -0.001 && BrakeHandle != TBrakeHandle::MHZ_EN57) + eimic = std::min(-0.002, eimic * (double)LocalBrakePosNo / ((double)LocalBrakePosNo - multiplier) + offset / ((double)LocalBrakePosNo - multiplier)); + } + if (eimic > 0.001 && SpeedCtrlUnit.IsActive) + eimic = std::max(eimic, SpeedCtrlUnit.MinPower); +} + +// EIMCtrlType 1: the positions B+ to TMax move the value at a steady pace +void TMoverParameters::EIMICFromSteps(double dt) +{ + switch (MainCtrlPos) + { + case 0: // B+ + eimic -= std::clamp(1.0 + eimic, 0.0, dt * 0.14); // odejmuj do -1 + break; + case 1: // B + eimic -= std::clamp(0.0 + eimic, 0.0, dt * 0.14); // odejmuj do 0 + break; + case 2: // B- + case 3: // 0 + case 4: // T- + eimic -= std::clamp(0.0 + eimic, 0.0, dt * 0.14); // odejmuj do 0 + eimic += std::clamp(0.0 - eimic, 0.0, dt * 0.14); // dodawaj do 0 + break; + case 5: // T + eimic += std::clamp(0.0 - eimic, 0.0, dt * 0.14); // dodawaj do 0 + break; + case 6: // T+ + eimic += std::clamp(1.0 - eimic, 0.0, dt * 0.14); // dodawaj do 1 + break; + case 7: // TMax + eimic += std::clamp(1.0 - eimic, 0.0, dt * 0.14); // dodawaj do 1, max + break; + default: + break; + } + if (MainCtrlPos >= 3 && eimic < 0) + eimic = 0; + if (MainCtrlPos <= 3 && eimic > 0) + eimic = 0; +} + +// EIMCtrlType 2: the positions 0 to 4 move the value towards -1, 0 or 1, from the controller's delay on; the +// emergency brake position below them, where the controller has one, brakes in full at once +void TMoverParameters::EIMICFromFourPositions(double dt) +{ + if (IsMainCtrlEmergencyPos()) + { + // hamowanie nagle: pelne hamowanie od razu, przewod glowny oproznia UpdatePipePressure() + eimic = -1.0; + } + else if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) + { + double delta = MainCtrlActualPos == MainCtrlPos ? dt * CtrlDelay : 0.01; + // the positions below are those of the controller without the emergency brake position + switch (MainCtrlPos - EIMCtrlEmergencyPositions()) { - case 0: // B+ - eimic -= std::clamp(1.0 + eimic, 0.0, dt * 0.14); // odejmuj do -1 + case 0: + case 1: + eimic -= std::clamp(1.0 + eimic, 0.0, delta); // odejmuj do -1 + if (eimic > 0) + eimic = 0; break; - case 1: // B - eimic -= std::clamp(0.0 + eimic, 0.0, dt * 0.14); // odejmuj do 0 + case 2: + eimic -= std::clamp(0.0 + eimic, 0.0, delta); // odejmuj do 0 break; - case 2: // B- - case 3: // 0 - case 4: // T- - eimic -= std::clamp(0.0 + eimic, 0.0, dt * 0.14); // odejmuj do 0 - eimic += std::clamp(0.0 - eimic, 0.0, dt * 0.14); // dodawaj do 0 + case 3: + eimic += std::clamp(0.0 - eimic, 0.0, delta); // dodawaj do 0 break; - case 5: // T - eimic += std::clamp(0.0 - eimic, 0.0, dt * 0.14); // dodawaj do 0 - break; - case 6: // T+ - eimic += std::clamp(1.0 - eimic, 0.0, dt * 0.14); // dodawaj do 1 - break; - case 7: // TMax - eimic += std::clamp(1.0 - eimic, 0.0, dt * 0.14); // dodawaj do 1, max + case 4: + eimic += std::clamp(1.0 - eimic, 0.0, delta); // dodawaj do 1 + if (eimic < 0) + eimic = 0; break; default: break; } - if (MainCtrlPos >= 3 && eimic < 0) - eimic = 0; - if (MainCtrlPos <= 3 && eimic > 0) - eimic = 0; - break; - case 2: - if (IsMainCtrlEmergencyPos()) - { - // hamowanie nagle: pelne hamowanie od razu, przewod glowny oproznia UpdatePipePressure() - eimic = -1.0; - } - else if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) - { - double delta = MainCtrlActualPos == MainCtrlPos ? dt * CtrlDelay : 0.01; - // the positions below are those of the controller without the emergency brake position - switch (MainCtrlPos - EIMCtrlEmergencyPositions()) - { - case 0: - case 1: - eimic -= std::clamp(1.0 + eimic, 0.0, delta); // odejmuj do -1 - if (eimic > 0) - eimic = 0; - break; - case 2: - eimic -= std::clamp(0.0 + eimic, 0.0, delta); // odejmuj do 0 - break; - case 3: - eimic += std::clamp(0.0 - eimic, 0.0, delta); // dodawaj do 0 - break; - case 4: - eimic += std::clamp(1.0 - eimic, 0.0, delta); // dodawaj do 1 - if (eimic < 0) - eimic = 0; - break; - default: - break; - } - } - if (MainCtrlActualPos == MainCtrlPos) - LastRelayTime += dt; - else - { - LastRelayTime = 0; - MainCtrlActualPos = MainCtrlPos; - } - break; - case 3: - if (UniCtrlIntegratedBrakePNCtrl) - { - if (UniCtrlList[MainCtrlPos].mode != BrakeCtrlPos && MainCtrlActualPos == MainCtrlPos) // there was no move of controller, but brake only - { - if (BrakeCtrlPos < UniCtrlList[MainCtrlPosNo].mode) - BrakeLevelSet(UniCtrlList[MainCtrlPosNo].mode); // bottom clamping - if (BrakeCtrlPos > UniCtrlList[0].mode) - BrakeLevelSet(UniCtrlList[0].mode); // top clamping - if (IsCabMaster()) - { - while (BrakeCtrlPos > UniCtrlList[MainCtrlPos].mode) - DecMainCtrl(1); // find nearest position - while (BrakeCtrlPos < UniCtrlList[MainCtrlPos].mode) - IncMainCtrl(1); // find nearest position - } - } - else // controller was moved - BrakeLevelSet(UniCtrlList[MainCtrlPos].mode); - } - - if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) - { - auto const &position{UniCtrlList[MainCtrlPos]}; - double ramped{eimic}; - ramped -= safe_clamp(-position.SetCtrlVal + ramped, 0.0, - MainCtrlActualPos == MainCtrlPos ? dt * position.SpeedDown : sign(position.SpeedDown) * 0.01); // odejmuj do X - ramped += safe_clamp(position.SetCtrlVal - ramped, 0.0, - MainCtrlActualPos == MainCtrlPos ? dt * position.SpeedUp : sign(position.SpeedUp) * 0.01); // dodawaj do X - ramped = safe_clamp(ramped, position.MinCtrlVal, position.MaxCtrlVal); - eimic = UniCtrlValStep > 0.0 ? stepped_uc_value(eimic, ramped, position, UniCtrlValStep, MainCtrlActualPos != MainCtrlPos, eimic_step_progress) : ramped; - } - if (MainCtrlActualPos == MainCtrlPos) - LastRelayTime += dt; - else - { - LastRelayTime = 0; - MainCtrlActualPos = MainCtrlPos; - } - if (Hamulec->GetEDBCP() > 0.3 && eimic < 0 && !UniCtrlIntegratedLocalBrakeCtrl) // when braking with pneumatic brake - eimic = 0; // shut off retarder - if (UniCtrlIntegratedBrakeCtrl == false && UniCtrlIntegratedLocalBrakeCtrl == false) - { - // w trybie SplitEDPneumaticBrake hamowanie ED przychodzi z osobnego nastawnika, - // LocalBrake operuje wylacznie pneumatycznym hamulcem lokomotywy - eimic = brakeDemand > 0.01 ? -brakeDemand : eimic; - } } - if (LocHandleTimeTraxx) + if (MainCtrlActualPos == MainCtrlPos) + LastRelayTime += dt; + else { - if (LocalBrakeRatio() < 0.4) // pozycja 0, odhamowywanie - { - eim_localbrake -= dt * 0.17; - } + LastRelayTime = 0; + MainCtrlActualPos = MainCtrlPos; + } +} - if (LocalBrakeRatio() > 0.6) // pozycja 2, zahamowywanie - { - eim_localbrake += dt * 0.17; - eim_localbrake = std::max(eim_localbrake, BrakePress / MaxBrakePress[0]); - } - else // pozycja 1, utrzymanie cisnienia - { - if (eim_localbrake < Hamulec->GetEDBCP() / MaxBrakePress[0]) - eim_localbrake = 0; - } - eim_localbrake = std::clamp(eim_localbrake, 0.0, 1.0); - if (eim_localbrake > 0.04 && eimic > 0) - eimic = 0; +// EIMCtrlType 3: the universal controller of UniCtrlList, with the train brake built in or not +void TMoverParameters::EIMICFromUniversalController(double dt, double const brakeDemand) +{ + if (UniCtrlIntegratedBrakePNCtrl) + { + UniversalControllerTrainBrake(); } + if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) + { + auto const &position{UniCtrlList[MainCtrlPos]}; + double ramped{eimic}; + ramped -= safe_clamp(-position.SetCtrlVal + ramped, 0.0, + MainCtrlActualPos == MainCtrlPos ? dt * position.SpeedDown : sign(position.SpeedDown) * 0.01); // odejmuj do X + ramped += safe_clamp(position.SetCtrlVal - ramped, 0.0, + MainCtrlActualPos == MainCtrlPos ? dt * position.SpeedUp : sign(position.SpeedUp) * 0.01); // dodawaj do X + ramped = safe_clamp(ramped, position.MinCtrlVal, position.MaxCtrlVal); + eimic = UniCtrlValStep > 0.0 ? stepped_uc_value(eimic, ramped, position, UniCtrlValStep, MainCtrlActualPos != MainCtrlPos, eimic_step_progress) : ramped; + } + if (MainCtrlActualPos == MainCtrlPos) + LastRelayTime += dt; + else + { + LastRelayTime = 0; + MainCtrlActualPos = MainCtrlPos; + } + if (Hamulec->GetEDBCP() > 0.3 && eimic < 0 && !UniCtrlIntegratedLocalBrakeCtrl) // when braking with pneumatic brake + eimic = 0; // shut off retarder + if (UniCtrlIntegratedBrakeCtrl == false && UniCtrlIntegratedLocalBrakeCtrl == false) + { + // w trybie SplitEDPneumaticBrake hamowanie ED przychodzi z osobnego nastawnika, + // LocalBrake operuje wylacznie pneumatycznym hamulcem lokomotywy + eimic = brakeDemand > 0.01 ? -brakeDemand : eimic; + } +} + +// the train brake built into the universal controller: the handle set to the controller's position, or the +// controller, at a brake handle moved alone, to the nearest position of the handle's +void TMoverParameters::UniversalControllerTrainBrake() +{ + if (UniCtrlList[MainCtrlPos].mode != BrakeCtrlPos && MainCtrlActualPos == MainCtrlPos) // there was no move of controller, but brake only + { + if (BrakeCtrlPos < UniCtrlList[MainCtrlPosNo].mode) + BrakeLevelSet(UniCtrlList[MainCtrlPosNo].mode); // bottom clamping + if (BrakeCtrlPos > UniCtrlList[0].mode) + BrakeLevelSet(UniCtrlList[0].mode); // top clamping + if (IsCabMaster()) + { + while (BrakeCtrlPos > UniCtrlList[MainCtrlPos].mode) + DecMainCtrl(1); // find nearest position + while (BrakeCtrlPos < UniCtrlList[MainCtrlPos].mode) + IncMainCtrl(1); // find nearest position + } + } + else // controller was moved + BrakeLevelSet(UniCtrlList[MainCtrlPos].mode); +} + +// the local brake of the TRAXX locomotives, by time: released, held or applied, which cuts the drive off +void TMoverParameters::EIMICTraxxLocalBrake(double dt) +{ + if (LocalBrakeRatio() < 0.4) // pozycja 0, odhamowywanie + { + eim_localbrake -= dt * 0.17; + } + + if (LocalBrakeRatio() > 0.6) // pozycja 2, zahamowywanie + { + eim_localbrake += dt * 0.17; + eim_localbrake = std::max(eim_localbrake, BrakePress / MaxBrakePress[0]); + } + else // pozycja 1, utrzymanie cisnienia + { + if (eim_localbrake < Hamulec->GetEDBCP() / MaxBrakePress[0]) + eim_localbrake = 0; + } + eim_localbrake = std::clamp(eim_localbrake, 0.0, 1.0); + if (eim_localbrake > 0.04 && eimic > 0) + eimic = 0; +} + +// the value limited by the power, the spring brake, the pipe lock, the direction and the doors' permits +void TMoverParameters::EIMICLimit() +{ auto const eimicpowerenabled{(MainCircuitPowered() || Power == 0.0) && (!SpringBrake.IsActive || !SpringBrakeCutsOffDrive) && !LockPipe && DirAbsolute != 0}; auto const eimicdoorenabled{(SpringBrake.IsActive && ReleaseParkingBySpringBrakeWhenDoorIsOpen)}; double eimic_max = 0.0; @@ -8931,40 +9383,7 @@ void TMoverParameters::CheckSpeedCtrl(double dt) { if (!SpeedCtrlUnit.Standby) { - if (SpeedCtrlUnit.ManualStateOverride && eimic > 0.0009) - eimic = 1.0; - double error = std::max(SpeedCtrlValue + SpeedCtrlUnit.Offset, 0.0) - Vel; - double factorP = error > 0 ? SpeedCtrlUnit.FactorPpos : SpeedCtrlUnit.FactorPneg; - double eSCP = std::clamp(factorP * error, -1.2, 1.0); // P module - bool retarder_not_work = EngineType != TEngineType::DieselEngine || Vel < SpeedCtrlUnit.BrakeInterventionVel; - if (eSCP < -1.0) - { - SpeedCtrlUnit.BrakeInterventionBraking = eSCP < -1.1 && retarder_not_work && eimicSpeedCtrl < -0.99 * SpeedCtrlUnit.DesiredPower; - eSCP = -1.0; - } - SpeedCtrlUnit.BrakeInterventionUnbraking = eSCP > 0.0 || Vel == 0.0; - if (abs(eSCP) < 0.999) - { - // TODO: check how to disable integral part when braking in smart way - // double factorI = eimicSpeedCtrlIntegral >= 0 ? SpeedCtrlUnit.FactorIpos : SpeedCtrlUnit.FactorIneg; - double factorI = eimicSpeedCtrlIntegral >= 0 ? SpeedCtrlUnit.FactorIpos : SpeedCtrlUnit.FactorIneg; - eimicSpeedCtrlIntegral = safe_clamp(eimicSpeedCtrlIntegral + factorI * eSCP * dt, -1.0 + eSCP, 1.0 - eSCP); - } - else - { - eimicSpeedCtrlIntegral = 0; - } - auto const DesiredeimicSpeedCtrl{safe_clamp(eimicSpeedCtrlIntegral + eSCP, -SpeedCtrlUnit.DesiredPower, accfactor)}; - eimicSpeedCtrl = std::clamp(DesiredeimicSpeedCtrl, eimicSpeedCtrl - SpeedCtrlUnit.PowerDownSpeed * dt, eimicSpeedCtrl + SpeedCtrlUnit.PowerUpSpeed * dt); - if (Vel < SpeedCtrlUnit.FullPowerVelocity) - { - eimicSpeedCtrl = std::min(eimicSpeedCtrl, SpeedCtrlUnit.InitialPower); - } - if (Vel < SpeedCtrlUnit.StartVelocity && MainCtrlPos < MainCtrlPosNo) - { - eimicSpeedCtrl = 0; - eimic = 0; - } + SpeedCtrlRegulator(dt, accfactor); } else { @@ -8996,6 +9415,46 @@ void TMoverParameters::CheckSpeedCtrl(double dt) } } +// the PI regulator of the speed control: the power asked of the drive, or its brake intervention, from the error of +// the speed; accfactor, the most power it may ask +void TMoverParameters::SpeedCtrlRegulator(double dt, double const accfactor) +{ + if (SpeedCtrlUnit.ManualStateOverride && eimic > 0.0009) + eimic = 1.0; + double error = std::max(SpeedCtrlValue + SpeedCtrlUnit.Offset, 0.0) - Vel; + double factorP = error > 0 ? SpeedCtrlUnit.FactorPpos : SpeedCtrlUnit.FactorPneg; + double eSCP = std::clamp(factorP * error, -1.2, 1.0); // P module + bool retarder_not_work = EngineType != TEngineType::DieselEngine || Vel < SpeedCtrlUnit.BrakeInterventionVel; + if (eSCP < -1.0) + { + SpeedCtrlUnit.BrakeInterventionBraking = eSCP < -1.1 && retarder_not_work && eimicSpeedCtrl < -0.99 * SpeedCtrlUnit.DesiredPower; + eSCP = -1.0; + } + SpeedCtrlUnit.BrakeInterventionUnbraking = eSCP > 0.0 || Vel == 0.0; + if (abs(eSCP) < 0.999) + { + // TODO: check how to disable integral part when braking in smart way + // double factorI = eimicSpeedCtrlIntegral >= 0 ? SpeedCtrlUnit.FactorIpos : SpeedCtrlUnit.FactorIneg; + double factorI = eimicSpeedCtrlIntegral >= 0 ? SpeedCtrlUnit.FactorIpos : SpeedCtrlUnit.FactorIneg; + eimicSpeedCtrlIntegral = safe_clamp(eimicSpeedCtrlIntegral + factorI * eSCP * dt, -1.0 + eSCP, 1.0 - eSCP); + } + else + { + eimicSpeedCtrlIntegral = 0; + } + auto const DesiredeimicSpeedCtrl{safe_clamp(eimicSpeedCtrlIntegral + eSCP, -SpeedCtrlUnit.DesiredPower, accfactor)}; + eimicSpeedCtrl = std::clamp(DesiredeimicSpeedCtrl, eimicSpeedCtrl - SpeedCtrlUnit.PowerDownSpeed * dt, eimicSpeedCtrl + SpeedCtrlUnit.PowerUpSpeed * dt); + if (Vel < SpeedCtrlUnit.FullPowerVelocity) + { + eimicSpeedCtrl = std::min(eimicSpeedCtrl, SpeedCtrlUnit.InitialPower); + } + if (Vel < SpeedCtrlUnit.StartVelocity && MainCtrlPos < MainCtrlPosNo) + { + eimicSpeedCtrl = 0; + eimic = 0; + } +} + bool TMoverParameters::IsSpeedCtrlSeparate() const { // no secondary controller, or one of these engines', which shunts the field of the traction motors (eu07/maszyna#69) @@ -9149,108 +9608,142 @@ bool TMoverParameters::dizel_AutoGearCheck(void) if (motor_param(ScndCtrlActualPos).AutoSwitch && Mains) { - if (RList[MainCtrlPos].Mn == 0 && !hydro_TC) - { - if (dizel_engagestate > 0) - dizel_EngageSwitch(0); - if (IsMainCtrlNoPowerPos() && ScndCtrlActualPos > 0) - dizel_automaticgearstatus = -1; - } - else - { - if (motor_param(ScndCtrlActualPos).AutoSwitch && dizel_automaticgearstatus == 0) // sprawdz czy zmienic biegi - { - if (Vel > VelUp) - { - // shift up - if (ScndCtrlActualPos < ScndCtrlPosNo) - { - dizel_automaticgearstatus = 1; - OK = true; - } - } - else if (Vel < VelDown) - { - // shift down - if (ScndCtrlActualPos > 0) - { - dizel_automaticgearstatus = -1; - OK = true; - } - } - } - } - if (dizel_engage < 0.1 && dizel_automaticgearstatus != 0) - { - if (dizel_automaticgearstatus == 1) - ScndCtrlActualPos++; - else - ScndCtrlActualPos--; - dizel_automaticgearstatus = 0; - dizel_EngageSwitch(1.0); - OK = true; - } + OK = dizel_GearShiftCheck(VelUp, VelDown); } if (Mains) { - if (EIMCtrlType > 0) // sterowanie komputerowe - { - if (dizel_automaticgearstatus == 0) - { - if ((hydro_TC && hydro_TC_Fill > 0.01) || eimic_real > 0.005) - dizel_EngageSwitch(1.0); - else if (Vel > hydro_R_EngageVel && hydro_R && hydro_R_Fill > 0.01) - dizel_EngageSwitch(0.5); - else - dizel_EngageSwitch(0.0); - } - else - dizel_EngageSwitch(0.0); - } - else if (dizel_automaticgearstatus == 0) // ustaw cisnienie w silowniku sprzegla} - switch (RList[MainCtrlPos].Mn) - { - case 1: - dizel_EngageSwitch(0.5); - break; - case 2: - dizel_EngageSwitch(1.0); - break; - case 3: - if (Vel > dizel_minVelfullengage) - dizel_EngageSwitch(1.0); - else - dizel_EngageSwitch(0.5); - break; - case 4: - if (Vel > dizel_minVelfullengage) - dizel_EngageSwitch(1.0); - else - dizel_EngageSwitch(0.66); - break; - case 5: - if (Vel > dizel_minVelfullengage) - dizel_EngageSwitch(1.0); - else - dizel_EngageSwitch(0.35 * (1 + RList[MainCtrlPos].R) * RList[MainCtrlPos].R); - break; - default: - if (hydro_TC && hydro_TC_Fill > 0.01) - dizel_EngageSwitch(1.0); - else - dizel_EngageSwitch(0.0); - } - else - dizel_EngageSwitch(0.0); - if (!(motor_param(ScndCtrlActualPos).mIsat > 0)) - dizel_EngageSwitch(0.0); // wylacz sprzeglo na pozycjach neutralnych - if (!AutoRelayFlag) - ScndCtrlActualPos = ScndCtrlPos; + dizel_ClutchCheck(); } return OK; } +// the automatic gearbox: a gear up over VelUp, down under VelDown, changed once the clutch is out; returns whether it acted +bool TMoverParameters::dizel_GearShiftCheck(double const VelUp, double const VelDown) +{ + auto OK{false}; + if (RList[MainCtrlPos].Mn == 0 && !hydro_TC) + { + if (dizel_engagestate > 0) + dizel_EngageSwitch(0); + if (IsMainCtrlNoPowerPos() && ScndCtrlActualPos > 0) + dizel_automaticgearstatus = -1; + } + else + { + OK = dizel_GearShiftRequest(VelUp, VelDown); + } + if (dizel_engage < 0.1 && dizel_automaticgearstatus != 0) + { + if (dizel_automaticgearstatus == 1) + ScndCtrlActualPos++; + else + ScndCtrlActualPos--; + dizel_automaticgearstatus = 0; + dizel_EngageSwitch(1.0); + OK = true; + } + return OK; +} + +// a gear up asked over VelUp, down under VelDown, where the gearbox shifts by itself; returns whether one is +bool TMoverParameters::dizel_GearShiftRequest(double const VelUp, double const VelDown) +{ + auto OK{false}; + if (motor_param(ScndCtrlActualPos).AutoSwitch && dizel_automaticgearstatus == 0) // sprawdz czy zmienic biegi + { + if (Vel > VelUp) + { + // shift up + if (ScndCtrlActualPos < ScndCtrlPosNo) + { + dizel_automaticgearstatus = 1; + OK = true; + } + } + else if (Vel < VelDown) + { + // shift down + if (ScndCtrlActualPos > 0) + { + dizel_automaticgearstatus = -1; + OK = true; + } + } + } + return OK; +} + +// the pressure in the clutch's cylinder, by the controller's position or the integrated controller +void TMoverParameters::dizel_ClutchCheck() +{ + if (EIMCtrlType > 0) // sterowanie komputerowe + { + dizel_ClutchByIntegratedController(); + } + else if (dizel_automaticgearstatus == 0) // ustaw cisnienie w silowniku sprzegla} + dizel_ClutchByController(); + else + dizel_EngageSwitch(0.0); + if (!(motor_param(ScndCtrlActualPos).mIsat > 0)) + dizel_EngageSwitch(0.0); // wylacz sprzeglo na pozycjach neutralnych + if (!AutoRelayFlag) + ScndCtrlActualPos = ScndCtrlPos; +} + +// the clutch by the controller's position: half or fully in, fully over the speed of the full engagement +void TMoverParameters::dizel_ClutchByController() +{ + switch (RList[MainCtrlPos].Mn) + { + case 1: + dizel_EngageSwitch(0.5); + break; + case 2: + dizel_EngageSwitch(1.0); + break; + case 3: + if (Vel > dizel_minVelfullengage) + dizel_EngageSwitch(1.0); + else + dizel_EngageSwitch(0.5); + break; + case 4: + if (Vel > dizel_minVelfullengage) + dizel_EngageSwitch(1.0); + else + dizel_EngageSwitch(0.66); + break; + case 5: + if (Vel > dizel_minVelfullengage) + dizel_EngageSwitch(1.0); + else + dizel_EngageSwitch(0.35 * (1 + RList[MainCtrlPos].R) * RList[MainCtrlPos].R); + break; + default: + if (hydro_TC && hydro_TC_Fill > 0.01) + dizel_EngageSwitch(1.0); + else + dizel_EngageSwitch(0.0); + } +} + +// the clutch of the integrated controller: in with the converter filled or the power asked, half in for the retarder +void TMoverParameters::dizel_ClutchByIntegratedController() +{ + if (dizel_automaticgearstatus == 0) + { + if ((hydro_TC && hydro_TC_Fill > 0.01) || eimic_real > 0.005) + dizel_EngageSwitch(1.0); + else if (Vel > hydro_R_EngageVel && hydro_R && hydro_R_Fill > 0.01) + dizel_EngageSwitch(0.5); + else + dizel_EngageSwitch(0.0); + } + else + dizel_EngageSwitch(0.0); +} + // performs diesel engine startup procedure; potentially clears startup switch; returns: true if the engine can be started, false otherwise bool TMoverParameters::dizel_StartupCheck() { @@ -9370,26 +9863,7 @@ double TMoverParameters::dizel_fillcheck(int mcp, double dt) // napelnienie zalezne od MainCtrlPos if (EIMCtrlType > 0) { - realfill = std::max(0.0, std::min(eimic_real, 1 - motor_param(ScndCtrlActualPos).Isat)); - if (eimic_real > 0.005 && !hydro_TC_Lockup) - { - dizel_nreg_min = std::min(dizel_nreg_min + 2.5 * dt, dizel_nmin_hdrive + eimic_real * dizel_nmin_hdrive_factor); - } - else - { - if (Vel < hydro_R_EngageVel && hydro_R && hydro_R_Fill > 0.01) - dizel_nreg_min = std::min(dizel_nreg_min + 5.0 * dt, dizel_nmin_retarder); - else - dizel_nreg_min = dizel_nmin; - } - if (!dizel_vel2nmax_Table.empty() && !hydro_TC_Lockup) - { - dizel_nreg_max = std::min(std::min(dizel_nreg_max, enrot) + dizel_nreg_acc * dt, TableInterpolation(dizel_vel2nmax_Table, Vel)); - } - else - { - dizel_nreg_max = dizel_nmax; - } + realfill = dizel_DigitalFill(dt); } else { @@ -9399,54 +9873,97 @@ double TMoverParameters::dizel_fillcheck(int mcp, double dt) } if (dizel_nmax_cutoff > 0) { - auto nreg{0.0}; - if (EIMCtrlType > 0) - nreg = eimic_real > 0.005 ? dizel_nreg_max : dizel_nmin; - else - switch (RList[MainCtrlPos].Mn) - { - case 0: - case 1: - nreg = dizel_nmin; - break; - case 2: - if (dizel_automaticgearstatus == 0 && true /*(!hydro_TC) || (dizel_engage>dizel_fill)*/) - nreg = dizel_nreg_max; - else - nreg = dizel_nmin; - break; - case 3: - if (dizel_automaticgearstatus == 0 && Vel > dizel_minVelfullengage) - nreg = dizel_nreg_max; - else - nreg = dizel_nmin; - break; - case 4: - if (dizel_automaticgearstatus == 0 && Vel > dizel_minVelfullengage) - nreg = dizel_nmax; - else - nreg = dizel_nmin * 0.75 + dizel_nreg_max * 0.25; - break; - case 5: - if (Vel > dizel_minVelfullengage) - nreg = dizel_nreg_max; - else - nreg = dizel_nmin + 0.8 * (dizel_nreg_max - dizel_nmin) * RList[mcp].R; - break; - default: - realfill = 0; // sluczaj - break; - } - if (enrot > nreg) // nad predkoscia regulatora zeruj dawke - realfill = 0; - if (enrot < dizel_nreg_min && RList[mcp].R > 0.001) // jesli ponizej biegu jalowego i niezerowa dawka, to dawaj pelna - realfill = 1; + realfill = dizel_GovernorFill(mcp, realfill); } } return std::clamp(realfill, 0.0, 1.0); } +// the fill set by the integrated controller, and the idle and top revolutions the governor keeps to +double TMoverParameters::dizel_DigitalFill(double dt) +{ + double realfill; + realfill = std::max(0.0, std::min(eimic_real, 1 - motor_param(ScndCtrlActualPos).Isat)); + if (eimic_real > 0.005 && !hydro_TC_Lockup) + { + dizel_nreg_min = std::min(dizel_nreg_min + 2.5 * dt, dizel_nmin_hdrive + eimic_real * dizel_nmin_hdrive_factor); + } + else + { + if (Vel < hydro_R_EngageVel && hydro_R && hydro_R_Fill > 0.01) + dizel_nreg_min = std::min(dizel_nreg_min + 5.0 * dt, dizel_nmin_retarder); + else + dizel_nreg_min = dizel_nmin; + } + if (!dizel_vel2nmax_Table.empty() && !hydro_TC_Lockup) + { + dizel_nreg_max = std::min(std::min(dizel_nreg_max, enrot) + dizel_nreg_acc * dt, TableInterpolation(dizel_vel2nmax_Table, Vel)); + } + else + { + dizel_nreg_max = dizel_nmax; + } + return realfill; +} + +// the fill cut off over the revolutions the governor allows at the controller's position, or full under the idle ones +double TMoverParameters::dizel_GovernorFill(int const mcp, double realfill) const +{ + auto nreg{0.0}; + if (EIMCtrlType > 0) + nreg = eimic_real > 0.005 ? dizel_nreg_max : dizel_nmin; + else + nreg = dizel_GovernorRevolutions(mcp, realfill); + if (enrot > nreg) // nad predkoscia regulatora zeruj dawke + realfill = 0; + if (enrot < dizel_nreg_min && RList[mcp].R > 0.001) // jesli ponizej biegu jalowego i niezerowa dawka, to dawaj pelna + realfill = 1; + return realfill; +} + +// the revolutions the governor allows at the controller's position, the gearbox and the speed; the fill cut off at +// a position the governor doesn't know +double TMoverParameters::dizel_GovernorRevolutions(int const mcp, double &realfill) const +{ + auto nreg{0.0}; + switch (RList[MainCtrlPos].Mn) + { + case 0: + case 1: + nreg = dizel_nmin; + break; + case 2: + if (dizel_automaticgearstatus == 0 && true /*(!hydro_TC) || (dizel_engage>dizel_fill)*/) + nreg = dizel_nreg_max; + else + nreg = dizel_nmin; + break; + case 3: + if (dizel_automaticgearstatus == 0 && Vel > dizel_minVelfullengage) + nreg = dizel_nreg_max; + else + nreg = dizel_nmin; + break; + case 4: + if (dizel_automaticgearstatus == 0 && Vel > dizel_minVelfullengage) + nreg = dizel_nmax; + else + nreg = dizel_nmin * 0.75 + dizel_nreg_max * 0.25; + break; + case 5: + if (Vel > dizel_minVelfullengage) + nreg = dizel_nreg_max; + else + nreg = dizel_nmin + 0.8 * (dizel_nreg_max - dizel_nmin) * RList[mcp].R; + break; + default: + realfill = 0; // sluczaj + break; + } + return nreg; +} + // ************************************************************************************************* // Q: 20160715 // Oblicza moment siły wytwarzany przez silnik spalinowy @@ -9499,38 +10016,7 @@ double TMoverParameters::dizel_Momentum(double Fill, double n, double dt) dizel_Torque = Moment; - if (hydro_TC) // jesli przetwornik momentu - { - // napelnianie przetwornika - bool IsPower = EIMCtrlType > 0 ? eimic_real > 0.005 : MainCtrlPowerPos() > 0; - if (IsPower && Mains && enrot > dizel_nmin * 0.9) - hydro_TC_Fill += hydro_TC_FillRateInc * dt; - // oproznianie przetwornika - if ((!IsPower && Vel < dizel_maxVelANS) || !Mains || enrot < dizel_nmin * 0.8) - hydro_TC_Fill -= hydro_TC_FillRateDec * dt; - // obcinanie zakresu - hydro_TC_Fill = std::clamp(hydro_TC_Fill, 0.0, 1.0); - - // blokowanie sprzegla blokującego - if (Vel > hydro_TC_LockupSpeed && Mains && enrot > 0.9 * dizel_nmin && IsPower) - { - hydro_TC_Lockup = true; - hydro_TC_LockupRate += hydro_TC_FillRateInc * dt; - } - // luzowanie sprzegla blokujacego - if (Vel < (IsPower ? hydro_TC_LockupSpeed : hydro_TC_UnlockSpeed) || !Mains || enrot < 0.8 * dizel_nmin) - { - hydro_TC_Lockup = false; - hydro_TC_LockupRate -= hydro_TC_FillRateDec * dt; - } - // obcinanie zakresu - hydro_TC_LockupRate = std::clamp(hydro_TC_LockupRate, 0.0, 1.0); - } - else - { - hydro_TC_Fill = 0.0; - hydro_TC_LockupRate = 0.0; - } + hydro_TCFillCheck(dt); // obliczanie momentow poszczegolnych sprzegiel // sprzeglo glowne (skrzynia biegow) @@ -9538,32 +10024,7 @@ double TMoverParameters::dizel_Momentum(double Fill, double n, double dt) if (hydro_TC) // jesli hydro { - double HydroTorque = 0; - HydroTorque += hydro_TC_nIn * hydro_TC_nIn * hydro_TC_TorqueInIn; - HydroTorque += (hydro_TC_nIn - hydro_TC_nOut) * hydro_TC_TorqueInOut; - HydroTorque += hydro_TC_nOut * hydro_TC_nOut * hydro_TC_TorqueOutOut; - double nOut2In = hydro_TC_nOut / std::max(0.01, hydro_TC_nIn); - if (hydro_TC_Table.size() > 1) - { - hydro_TC_TMRatio = TableInterpolation(hydro_TC_Table, nOut2In); - hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; - hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill * std::min(1.0, hydro_TC_TMRatio); - } - else - { - if (nOut2In < hydro_TC_CouplingPoint) - { - hydro_TC_TMRatio = 1 + (hydro_TC_TMMax - 1) * square(1 - nOut2In / hydro_TC_CouplingPoint); - hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill; - hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; - } - else - { - hydro_TC_TMRatio = (1 - nOut2In) / (1 - hydro_TC_CouplingPoint); - hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; - hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; - } - } + hydro_TCTorque(); TorqueH = hydro_TC_TorqueOut; TorqueL = hydro_TC_LockupTorque * hydro_TC_LockupRate; } @@ -9635,6 +10096,74 @@ double TMoverParameters::dizel_Momentum(double Fill, double n, double dt) return gearMoment; } +// the torque converter filled and emptied, and its lockup clutch engaged and released, by the power and the speed +void TMoverParameters::hydro_TCFillCheck(double dt) +{ + if (hydro_TC) // jesli przetwornik momentu + { + // napelnianie przetwornika + bool IsPower = EIMCtrlType > 0 ? eimic_real > 0.005 : MainCtrlPowerPos() > 0; + if (IsPower && Mains && enrot > dizel_nmin * 0.9) + hydro_TC_Fill += hydro_TC_FillRateInc * dt; + // oproznianie przetwornika + if ((!IsPower && Vel < dizel_maxVelANS) || !Mains || enrot < dizel_nmin * 0.8) + hydro_TC_Fill -= hydro_TC_FillRateDec * dt; + // obcinanie zakresu + hydro_TC_Fill = std::clamp(hydro_TC_Fill, 0.0, 1.0); + + // blokowanie sprzegla blokującego + if (Vel > hydro_TC_LockupSpeed && Mains && enrot > 0.9 * dizel_nmin && IsPower) + { + hydro_TC_Lockup = true; + hydro_TC_LockupRate += hydro_TC_FillRateInc * dt; + } + // luzowanie sprzegla blokujacego + if (Vel < (IsPower ? hydro_TC_LockupSpeed : hydro_TC_UnlockSpeed) || !Mains || enrot < 0.8 * dizel_nmin) + { + hydro_TC_Lockup = false; + hydro_TC_LockupRate -= hydro_TC_FillRateDec * dt; + } + // obcinanie zakresu + hydro_TC_LockupRate = std::clamp(hydro_TC_LockupRate, 0.0, 1.0); + } + else + { + hydro_TC_Fill = 0.0; + hydro_TC_LockupRate = 0.0; + } +} + +// the torque converter's moments on its input and output shafts, by their revolutions and its fill +void TMoverParameters::hydro_TCTorque() +{ + double HydroTorque = 0; + HydroTorque += hydro_TC_nIn * hydro_TC_nIn * hydro_TC_TorqueInIn; + HydroTorque += (hydro_TC_nIn - hydro_TC_nOut) * hydro_TC_TorqueInOut; + HydroTorque += hydro_TC_nOut * hydro_TC_nOut * hydro_TC_TorqueOutOut; + double nOut2In = hydro_TC_nOut / std::max(0.01, hydro_TC_nIn); + if (hydro_TC_Table.size() > 1) + { + hydro_TC_TMRatio = TableInterpolation(hydro_TC_Table, nOut2In); + hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; + hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill * std::min(1.0, hydro_TC_TMRatio); + } + else + { + if (nOut2In < hydro_TC_CouplingPoint) + { + hydro_TC_TMRatio = 1 + (hydro_TC_TMMax - 1) * square(1 - nOut2In / hydro_TC_CouplingPoint); + hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill; + hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; + } + else + { + hydro_TC_TMRatio = (1 - nOut2In) / (1 - hydro_TC_CouplingPoint); + hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; + hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; + } + } +} + double TMoverParameters::dizel_MomentumRetarder(double n, double dt) { double RetarderRequest = Mains ? std::max(0.0, -eimic_real) : 0; @@ -10226,89 +10755,8 @@ void TMoverParameters::update_doors(double const Deltatime) for (auto &door : Doors.instances) { - // revoke permit if... - door.open_permit = true == door.open_permit // ...we already have one... - && (false == Doors.permit_presets.empty() // ...there's no preset switch controlling permit state... - || (false == Doors.is_locked // ...and the door lock is engaged... - && false == door.remote_close)); // ...or the door is about to be closed - - door.is_open = door.position >= Doors.range && (false == Doors.step_enabled || door.step_position >= (Doors.step_range != 0.f ? 1.f : 0.f)); - door.is_closed = door.position <= 0.f && door.step_position <= 0.f; - door.is_door_closed = door.position <= 0.f; - - door.local_open = door.local_open && false == door.is_open && (false == Doors.permit_needed || door.open_permit); - door.remote_open = (door.remote_open || Doors.remote_only) && false == door.is_open && (false == Doors.permit_needed || door.open_permit); - door.local_close = door.local_close && false == door.is_closed && (false == remoteopencontrol || false == door.remote_open); - door.remote_close = door.remote_close && false == door.is_closed && (false == localopencontrol || false == door.local_open); - - auto const autoopenrequest{Doors.open_control == control_t::autonomous && (false == Doors.permit_needed || door.open_permit)}; - auto const openrequest{(localopencontrol && door.local_open) || (remoteopencontrol && door.remote_open) || (autoopenrequest && false == door.is_open)}; - - auto const autocloserequest{(Doors.auto_velocity != -1.f && Vel > Doors.auto_velocity) || (door.auto_timer != -1.f && door.auto_timer <= 0.f) || - (Doors.permit_needed && false == door.open_permit)}; - auto const closerequest{(door.remote_close && remoteclosecontrol) || (door.local_close && localclosecontrol) || (autocloserequest && door.is_open)}; - - auto const ispowered{(Doors.voltage == 0 ? true : Doors.voltage == 24 ? Power24vIsAvailable || Power110vIsAvailable : Doors.voltage == 110 ? Power110vIsAvailable : false)}; - - door.is_opening = false == door.is_open && true == ispowered && false == closerequest && (true == door.is_opening || (true == openrequest && false == Doors.is_locked)); - door.is_closing = false == door.is_closed && true == ispowered && false == openrequest && (door.is_closing || closerequest); - door.step_unfolding = Doors.step_range != 0.f && Doors.step_enabled && false == Doors.is_locked && door.step_position < 1.f && door.is_opening; - door.step_folding = door.step_position > 0.f // is unfolded - && (false == Doors.step_enabled // we lost permission to stay open or our door is calling the shots - || (Doors.permit_needed ? false == door.open_permit : door.is_closing)) && - (door.close_delay > Doors.close_delay || door.position <= 0.f); // door is about to close, or already done - - if (true == door.is_opening) - { - door.auto_timer = localopencontrol && door.local_open ? Doors.auto_duration : remoteopencontrol && door.remote_open && Doors.auto_include_remote ? Doors.auto_duration : -1.f; - } - // doors - if (true == door.is_opening) - { - // open door - if (false == door.step_unfolding // no wait if no doorstep - || Doors.step_type == 2) - { // no wait for rotating doorstep - door.open_delay += static_cast(Deltatime); - if (door.open_delay > Doors.open_delay) - { - door.position = std::min(Doors.range, static_cast(door.position + Doors.open_rate * Deltatime)); - } - } - door.close_delay = 0.f; - } - if (true == door.is_closing) - { - // close door - door.close_delay += static_cast(Deltatime); - if (door.close_delay > Doors.close_delay) - { - door.position = std::max(0.f, static_cast(door.position - Doors.close_rate * Deltatime)); - } - door.open_delay = 0.f; - } - // doorsteps - if (door.step_unfolding) - { - // unfold left doorstep - door.step_position = std::min(1.f, static_cast(door.step_position + Doors.step_rate * Deltatime)); - } - if (door.step_folding) - { - // fold left doorstep - if (TrainType == dt_EZT || TrainType == dt_DMU) - { - // multi-unit vehicles typically fold the doorstep only after closing the door - if (door.position <= 0.f) - { - door.step_position = std::max(0.f, static_cast(door.step_position - Doors.step_rate * Deltatime)); - } - } - else - { - door.step_position = std::max(0.f, static_cast(door.step_position - Doors.step_rate * Deltatime)); - } - } + update_door_requests(door, localopencontrol, remoteopencontrol, localclosecontrol, remoteclosecontrol); + move_door(door, Deltatime); } if (false == Doors.instances[side::right].is_open && false == Doors.instances[side::left].is_open) @@ -10318,25 +10766,7 @@ void TMoverParameters::update_doors(double const Deltatime) if (Doors.auto_duration > 0.f) { - // update door timers if the door close after defined time - for (auto &door : Doors.instances) - { - - if (false == door.is_open) - { - continue; - } - - if (door.auto_timer > 0.f) - { - door.auto_timer -= static_cast(Deltatime); - } - // if there's load exchange in progress, reset the timer(s) for already open doors - if (door.auto_timer != -1.f && (LoadStatus & (2 | 1)) != 0) - { - door.auto_timer = Doors.auto_duration; - } - } + update_door_timers(Deltatime); } /* // the door are closed if their timer goes below 0, or if the vehicle is moving faster than defined threshold @@ -10354,6 +10784,169 @@ void TMoverParameters::update_doors(double const Deltatime) */ } +// the permit, the state and the requests of a door, and whether it and its step open or close +void TMoverParameters::update_door_requests(basic_door &door, bool const localopencontrol, bool const remoteopencontrol, bool const localclosecontrol, bool const remoteclosecontrol) +{ + // revoke permit if... + door.open_permit = true == door.open_permit // ...we already have one... + && (false == Doors.permit_presets.empty() // ...there's no preset switch controlling permit state... + || (false == Doors.is_locked // ...and the door lock is engaged... + && false == door.remote_close)); // ...or the door is about to be closed + + door.is_open = door.position >= Doors.range && (false == Doors.step_enabled || door.step_position >= (Doors.step_range != 0.f ? 1.f : 0.f)); + door.is_closed = door.position <= 0.f && door.step_position <= 0.f; + door.is_door_closed = door.position <= 0.f; + + door.local_open = door.local_open && false == door.is_open && (false == Doors.permit_needed || door.open_permit); + door.remote_open = (door.remote_open || Doors.remote_only) && false == door.is_open && (false == Doors.permit_needed || door.open_permit); + door.local_close = door.local_close && false == door.is_closed && (false == remoteopencontrol || false == door.remote_open); + door.remote_close = door.remote_close && false == door.is_closed && (false == localopencontrol || false == door.local_open); + + auto const openrequest{door_open_request(door, localopencontrol, remoteopencontrol)}; + auto const closerequest{door_close_request(door, localclosecontrol, remoteclosecontrol)}; + auto const ispowered{doors_powered()}; + + door.is_opening = false == door.is_open && true == ispowered && false == closerequest && (true == door.is_opening || (true == openrequest && false == Doors.is_locked)); + door.is_closing = false == door.is_closed && true == ispowered && false == openrequest && (door.is_closing || closerequest); + door.step_unfolding = Doors.step_range != 0.f && Doors.step_enabled && false == Doors.is_locked && door.step_position < 1.f && door.is_opening; + door.step_folding = door_step_folding(door); + + if (true == door.is_opening) + { + door.auto_timer = door_open_duration(door, localopencontrol, remoteopencontrol); + } +} + +// whether the door is asked to open, by the passengers, from afar or by itself +bool TMoverParameters::door_open_request(basic_door const &door, bool const localopencontrol, bool const remoteopencontrol) const +{ + auto const autoopenrequest{Doors.open_control == control_t::autonomous && (false == Doors.permit_needed || door.open_permit)}; + return (localopencontrol && door.local_open) || (remoteopencontrol && door.remote_open) || (autoopenrequest && false == door.is_open); +} + +// whether the door is asked to close, by the passengers, from afar, or by itself: over the speed, after its time or +// with its permit taken back +bool TMoverParameters::door_close_request(basic_door const &door, bool const localclosecontrol, bool const remoteclosecontrol) const +{ + auto const autocloserequest{(Doors.auto_velocity != -1.f && Vel > Doors.auto_velocity) || (door.auto_timer != -1.f && door.auto_timer <= 0.f) || + (Doors.permit_needed && false == door.open_permit)}; + return (door.remote_close && remoteclosecontrol) || (door.local_close && localclosecontrol) || (autocloserequest && door.is_open); +} + +// whether the doors have the voltage they work on +bool TMoverParameters::doors_powered() const +{ + if (Doors.voltage == 0) + { + return true; + } + if (Doors.voltage == 24) + { + return Power24vIsAvailable || Power110vIsAvailable; + } + return Doors.voltage == 110 && Power110vIsAvailable; +} + +// whether the unfolded step folds: without the permission to stay out, or with the door closing, once it's about to +// close or closed +bool TMoverParameters::door_step_folding(basic_door const &door) const +{ + auto const unfolded{door.step_position > 0.f}; + auto const mayfold{false == Doors.step_enabled || (Doors.permit_needed ? false == door.open_permit : door.is_closing)}; + return unfolded && mayfold && (door.close_delay > Doors.close_delay || door.position <= 0.f); +} + +// how long the opening door stays open: the time of the doors, for the passengers' opening and, if it counts, the +// opening from afar; none otherwise +float TMoverParameters::door_open_duration(basic_door const &door, bool const localopencontrol, bool const remoteopencontrol) const +{ + if (localopencontrol && door.local_open) + { + return Doors.auto_duration; + } + if (remoteopencontrol && door.remote_open && Doors.auto_include_remote) + { + return Doors.auto_duration; + } + return -1.f; +} + +// a door and its step moved as they open or close +void TMoverParameters::move_door(basic_door &door, double const Deltatime) +{ + // doors + if (true == door.is_opening) + { + // open door + if (false == door.step_unfolding // no wait if no doorstep + || Doors.step_type == 2) + { // no wait for rotating doorstep + door.open_delay += static_cast(Deltatime); + if (door.open_delay > Doors.open_delay) + { + door.position = std::min(Doors.range, static_cast(door.position + Doors.open_rate * Deltatime)); + } + } + door.close_delay = 0.f; + } + if (true == door.is_closing) + { + // close door + door.close_delay += static_cast(Deltatime); + if (door.close_delay > Doors.close_delay) + { + door.position = std::max(0.f, static_cast(door.position - Doors.close_rate * Deltatime)); + } + door.open_delay = 0.f; + } + // doorsteps + if (door.step_unfolding) + { + // unfold left doorstep + door.step_position = std::min(1.f, static_cast(door.step_position + Doors.step_rate * Deltatime)); + } + if (door.step_folding) + { + // fold left doorstep + if (TrainType == dt_EZT || TrainType == dt_DMU) + { + // multi-unit vehicles typically fold the doorstep only after closing the door + if (door.position <= 0.f) + { + door.step_position = std::max(0.f, static_cast(door.step_position - Doors.step_rate * Deltatime)); + } + } + else + { + door.step_position = std::max(0.f, static_cast(door.step_position - Doors.step_rate * Deltatime)); + } + } +} + +// the timers of the open doors which close after a while, kept running while the load is exchanged +void TMoverParameters::update_door_timers(double const Deltatime) +{ + // update door timers if the door close after defined time + for (auto &door : Doors.instances) + { + + if (false == door.is_open) + { + continue; + } + + if (door.auto_timer > 0.f) + { + door.auto_timer -= static_cast(Deltatime); + } + // if there's load exchange in progress, reset the timer(s) for already open doors + if (door.auto_timer != -1.f && (LoadStatus & (2 | 1)) != 0) + { + door.auto_timer = Doors.auto_duration; + } + } +} + // ************************************************************************************************* // Q: 20160713 // Przesuwa pojazd o podaną wartość w bok względem toru (dla samochodów) @@ -11224,7 +11817,7 @@ bool TMoverParameters::LoadFIZ_Text(std::string const &Text) return LoadFIZ_Parse(fizparser); } -bool TMoverParameters::LoadFIZ_Parse(cParser &fizparser) // NOSONAR the former body of LoadFIZ(), moved as it was; splitting it up is a change of its own +bool TMoverParameters::LoadFIZ_Parse(cParser &fizparser) { LISTLINE = 0; startBPT = false; @@ -11249,7 +11842,7 @@ bool TMoverParameters::LoadFIZ_Parse(cParser &fizparser) // NOSONAR the former b // Zbieranie danych zawartych w pliku FIZ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - std::unordered_map fizlines; + std::map> fizlines; std::string inputline; /* while (std::getline(in, inputline)) @@ -11281,542 +11874,11 @@ bool TMoverParameters::LoadFIZ_Parse(cParser &fizparser) // NOSONAR the former b continue; } - // checking if table parsing should be switched off goes first... - if (issection("END-MPT", inputline)) + if (LoadFIZ_TableEnd(inputline) || LoadFIZ_Section(inputline, fizlines) || LoadFIZ_TableSection(inputline, fizlines)) { - startBPT = false; - startMPT = false; - startMPT0 = false; - continue; - } - if (issection("END-RL", inputline)) - { - startBPT = false; - startRLIST = false; - continue; - } - if (issection("END-UCL", inputline)) - { - startBPT = false; - startUCLIST = false; - continue; - } - if (issection("END-DL", inputline)) - { - startBPT = false; - startDLIST = false; - continue; - } - if (issection("END-DML", inputline)) - { - startBPT = false; - startDIZELMOMENTUMLIST = false; - continue; - } - if (issection("END-V2NL", inputline)) - { - startBPT = false; - startDIZELV2NMAXLIST = false; - continue; - } - if (issection("END-HTCL", inputline)) - { - startBPT = false; - startHYDROTCLIST = false; - continue; - } - if (issection("END-PML", inputline)) - { - startBPT = false; - startPMAXLIST = false; - continue; - } - if (issection("endff", inputline)) - { - startBPT = false; - startFFLIST = false; - startFFEDLIST = false; - continue; - } - if (issection("endwl", inputline)) - { - // skonczylismy czytac liste konfiguracji wycieraczek - startBPT = false; - startWiperList = false; - continue; - } - if (issection("endDimmerList", inputline)) - { - // skonczylismy czytac liste konfiguracji pstryka od przyciemnienia - startBPT = false; - startDimmerList = false; - continue; - } - if (issection("END-WWL", inputline)) - { - startBPT = false; - startWWLIST = false; - continue; - } - if (issection("endL", inputline)) - { - startBPT = false; - startLIGHTSLIST = false; - continue; - } - if (issection("endCL", inputline)) - { - startBPT = false; - startCOMPRESSORLIST = false; - continue; - } - // ...then all recognized sections... - if (issection("Param.", inputline)) - { - startBPT = false; - fizlines.try_emplace("Param", inputline); - LoadFIZ_Param(inputline); - continue; - } - - if (issection("Load:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Load", inputline); - LoadFIZ_Load(inputline); - continue; - } - - if (issection("Dimensions:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Dimensions", inputline); - LoadFIZ_Dimensions(inputline); - continue; - } - - if (issection("Wheels:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Wheels", inputline); - LoadFIZ_Wheels(inputline); - continue; - } - - if (issection("Brake:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Brake", inputline); - LoadFIZ_Brake(inputline); - continue; - } - - if (issection("Doors:", inputline)) - { - - startBPT = false; - fizlines.try_emplace("Doors", inputline); - LoadFIZ_Doors(inputline); - continue; - } - - if (issection("BuffCoupl.", inputline)) - { - - startBPT = false; - fizlines.try_emplace("BuffCoupl", inputline); - LoadFIZ_BuffCoupl(inputline, 0); - continue; - } - - else if (issection("BuffCoupl1.", inputline)) - { - - startBPT = false; - fizlines.try_emplace("BuffCoupl1", inputline); - LoadFIZ_BuffCoupl(inputline, 1); - continue; - } - - else if (issection("BuffCoupl2.", inputline)) - { - - startBPT = false; - fizlines.try_emplace("BuffCoupl2", inputline); - LoadFIZ_BuffCoupl(inputline, 2); - continue; - } - - if (issection("TurboPos:", inputline)) - { - - startBPT = false; - fizlines.try_emplace("TurboPos", inputline); - LoadFIZ_TurboPos(inputline); - continue; - } - - if (issection("Cntrl.", inputline)) - { - - startBPT = true; - LISTLINE = 0; - fizlines.try_emplace("Cntrl", inputline); - LoadFIZ_Cntrl(inputline); - continue; - } - - if (issection("Headlights:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Headlights", inputline); - LoadFIZ_Headlights(inputline); - continue; - } - - if (issection("Blending:", inputline)) - { - - startBPT = false; - LISTLINE = 0; - fizlines.try_emplace("Blending", inputline); - LoadFIZ_Blending(inputline); - continue; - } - - if (issection("DCEMUED:", inputline)) - { - - startBPT = false; - LISTLINE = 0; - fizlines.try_emplace("DCEMUED", inputline); - LoadFIZ_DCEMUED(inputline); - continue; - } - - if (issection("SpringBrake:", inputline)) - { - - startBPT = false; - LISTLINE = 0; - fizlines.try_emplace("SpringBrake", inputline); - LoadFIZ_SpringBrake(inputline); - continue; - } - - if (issection("Light:", inputline)) - { - - startBPT = false; - fizlines.try_emplace("Light", inputline); - LoadFIZ_Light(inputline); - continue; - } - - if (issection("Security:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Security", inputline); - SecuritySystem.load(inputline, Vmax); - extract_value(EmergencyBrakeWarningSignal, "EmergencyBrakeWarningSignal", inputline, ""); - continue; - } - - if (issection("Clima:", inputline)) - { - - startBPT = false; - fizlines.try_emplace("Clima", inputline); - LoadFIZ_Clima(inputline); - continue; - } - - if (issection("Power:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Power", inputline); - LoadFIZ_Power(inputline); - continue; - } - - if (issection("SpeedControl:", inputline)) - { - startBPT = false; - fizlines.try_emplace("SpeedControl", inputline); - LoadFIZ_SpeedControl(inputline); - continue; - } - - if (issection("Engine:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Engine", inputline); - LoadFIZ_Engine(inputline); - continue; - } - - if (issection("Switches:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Switches", inputline); - LoadFIZ_Switches(inputline); - continue; - } - - if (issection("MotorParamTable:", inputline)) - { - startBPT = false; - startMPT = true; - LISTLINE = 0; - fizlines.try_emplace("MotorParamTable", inputline); - LoadFIZ_MotorParamTable(inputline); - continue; - } - - if (issection("MotorParamTable0:", inputline)) - { - startBPT = false; - startMPT0 = true; - LISTLINE = 0; - continue; - } - - if (issection("Circuit:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Circuit", inputline); - LoadFIZ_Circuit(inputline); - continue; - } - - if (issection("AI:", inputline)) - { - startBPT = false; - fizlines.try_emplace("AI", inputline); - LoadFIZ_AI(inputline); - continue; - } - - if (issection("RList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("RList", inputline); - startRLIST = true; - LISTLINE = 0; - LoadFIZ_RList(inputline); - continue; - } - - if (issection("UCList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("UCList", inputline); - startUCLIST = true; - LISTLINE = 0; - LoadFIZ_UCList(inputline); - continue; - } - - if (issection("DList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("DList", inputline); - startDLIST = true; - LISTLINE = 0; - LoadFIZ_DList(inputline); - continue; - } - - if (issection("DMList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("DMList", inputline); - startDIZELMOMENTUMLIST = true; - LISTLINE = 0; - continue; - } - - if (issection("HTCList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("HTCList", inputline); - startHYDROTCLIST = true; - LISTLINE = 0; - continue; - } - - if (issection("PmaxList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("PmaxList", inputline); - startPMAXLIST = true; - LISTLINE = 0; - continue; - } - - if (issection("V2NList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("V2NList", inputline); - startDIZELV2NMAXLIST = true; - LISTLINE = 0; - continue; - } - - if (issection("ffList:", inputline)) - { - startBPT = false; - startFFLIST = true; - LISTLINE = 0; - LoadFIZ_FFList(inputline); - continue; - } - - if (issection("ffBrakeList:", inputline)) - { - startBPT = false; - startFFEDLIST = true; - LISTLINE = 0; - LoadFIZ_FFEDList(inputline); - continue; - } - - if (issection("WWList:", inputline)) - { - startBPT = false; - startWWLIST = true; - LISTLINE = 0; - - continue; - } - - if (issection("WiperList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("WiperList", inputline); - startWiperList = true; - LISTLINE = 0; - LoadFIZ_WiperList(inputline); - - continue; - } - - if (issection("DimmerList:", inputline)) - { - dimPositions.clear(); // uzywamy customowej listy - startBPT = false; - startDimmerList = true; - fizlines.try_emplace("DimmerList", inputline); - LoadFIZ_DimmerList(inputline); - continue; - } - - if (issection("LightsList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("LightsList", inputline); - startLIGHTSLIST = true; - LISTLINE = 0; - LoadFIZ_LightsList(inputline); - continue; - } - - if (issection("CompressorList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("CompressorList", inputline); - startCOMPRESSORLIST = true; - LISTLINE = 0; - LoadFIZ_CompressorList(inputline); - continue; - } - - // ...and finally, table parsers. - // NOTE: once table parsing is enabled it lasts until switched off, when another section is recognized - if (true == startBPT) - { - readBPT(inputline); - continue; - } - if (true == startMPT) - { - readMPT(inputline); - continue; - } - if (true == startMPT0) - { - readMPT0(inputline); - continue; - } - if (true == startRLIST) - { - readRList(inputline); - continue; - } - if (true == startUCLIST) - { - readUCList(inputline); - continue; - } - if (true == startDLIST) - { - readDList(inputline); - continue; - } - if (true == startDIZELMOMENTUMLIST) - { - readDMList(inputline); - continue; - } - if (true == startDIZELV2NMAXLIST) - { - readV2NMAXList(inputline); - continue; - } - if (true == startHYDROTCLIST) - { - readHTCList(inputline); - continue; - } - if (true == startPMAXLIST) - { - readPmaxList(inputline); - continue; - } - if (true == startFFLIST) - { - readFFList(inputline); - continue; - } - if (true == startFFEDLIST) - { - readFFEDList(inputline); - continue; - } - if (true == startWWLIST) - { - readWWList(inputline); - continue; - } - if (true == startWiperList) - { - readWiperList(inputline); - continue; - } - if (true == startDimmerList) - { - readDimmerList(inputline); - } - if (true == startLIGHTSLIST) - { - readLightsList(inputline); - continue; - } - if (true == startCOMPRESSORLIST) - { - readCompressorList(inputline); continue; } + LoadFIZ_TableRow(inputline); } // while line /* in.close(); @@ -11843,6 +11905,564 @@ bool TMoverParameters::LoadFIZ_Parse(cParser &fizparser) // NOSONAR the former b return result; } +// the end of the table being read; returns whether the line is one +bool TMoverParameters::LoadFIZ_TableEnd(std::string const &inputline) const +{ + // checking if table parsing should be switched off goes first... + if (issection("END-MPT", inputline)) + { + startBPT = false; + startMPT = false; + startMPT0 = false; + return true; + } + if (issection("END-RL", inputline)) + { + startBPT = false; + startRLIST = false; + return true; + } + if (issection("END-UCL", inputline)) + { + startBPT = false; + startUCLIST = false; + return true; + } + if (issection("END-DL", inputline)) + { + startBPT = false; + startDLIST = false; + return true; + } + if (issection("END-DML", inputline)) + { + startBPT = false; + startDIZELMOMENTUMLIST = false; + return true; + } + if (issection("END-V2NL", inputline)) + { + startBPT = false; + startDIZELV2NMAXLIST = false; + return true; + } + if (issection("END-HTCL", inputline)) + { + startBPT = false; + startHYDROTCLIST = false; + return true; + } + if (issection("END-PML", inputline)) + { + startBPT = false; + startPMAXLIST = false; + return true; + } + if (issection("endff", inputline)) + { + startBPT = false; + startFFLIST = false; + startFFEDLIST = false; + return true; + } + if (issection("endwl", inputline)) + { + // skonczylismy czytac liste konfiguracji wycieraczek + startBPT = false; + startWiperList = false; + return true; + } + if (issection("endDimmerList", inputline)) + { + // skonczylismy czytac liste konfiguracji pstryka od przyciemnienia + startBPT = false; + startDimmerList = false; + return true; + } + if (issection("END-WWL", inputline)) + { + startBPT = false; + startWWLIST = false; + return true; + } + if (issection("endL", inputline)) + { + startBPT = false; + startLIGHTSLIST = false; + return true; + } + if (issection("endCL", inputline)) + { + startBPT = false; + startCOMPRESSORLIST = false; + return true; + } + return false; +} + +// a section of the definition giving values, kept in fizlines by its name; returns whether the line is one +bool TMoverParameters::LoadFIZ_Section(std::string const &inputline, std::map> &fizlines) +{ + // ...then all recognized sections... + if (issection("Param.", inputline)) + { + startBPT = false; + fizlines.try_emplace("Param", inputline); + LoadFIZ_Param(inputline); + return true; + } + + if (issection("Load:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Load", inputline); + LoadFIZ_Load(inputline); + return true; + } + + if (issection("Dimensions:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Dimensions", inputline); + LoadFIZ_Dimensions(inputline); + return true; + } + + if (issection("Wheels:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Wheels", inputline); + LoadFIZ_Wheels(inputline); + return true; + } + + if (issection("Brake:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Brake", inputline); + LoadFIZ_Brake(inputline); + return true; + } + + if (issection("Doors:", inputline)) + { + + startBPT = false; + fizlines.try_emplace("Doors", inputline); + LoadFIZ_Doors(inputline); + return true; + } + + if (issection("BuffCoupl.", inputline)) + { + + startBPT = false; + fizlines.try_emplace("BuffCoupl", inputline); + LoadFIZ_BuffCoupl(inputline, 0); + return true; + } + + else if (issection("BuffCoupl1.", inputline)) + { + + startBPT = false; + fizlines.try_emplace("BuffCoupl1", inputline); + LoadFIZ_BuffCoupl(inputline, 1); + return true; + } + + else if (issection("BuffCoupl2.", inputline)) + { + + startBPT = false; + fizlines.try_emplace("BuffCoupl2", inputline); + LoadFIZ_BuffCoupl(inputline, 2); + return true; + } + + if (issection("TurboPos:", inputline)) + { + + startBPT = false; + fizlines.try_emplace("TurboPos", inputline); + LoadFIZ_TurboPos(inputline); + return true; + } + + if (issection("Cntrl.", inputline)) + { + + startBPT = true; + LISTLINE = 0; + fizlines.try_emplace("Cntrl", inputline); + LoadFIZ_Cntrl(inputline); + return true; + } + + if (issection("Headlights:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Headlights", inputline); + LoadFIZ_Headlights(inputline); + return true; + } + + if (issection("Blending:", inputline)) + { + + startBPT = false; + LISTLINE = 0; + fizlines.try_emplace("Blending", inputline); + LoadFIZ_Blending(inputline); + return true; + } + + if (issection("DCEMUED:", inputline)) + { + + startBPT = false; + LISTLINE = 0; + fizlines.try_emplace("DCEMUED", inputline); + LoadFIZ_DCEMUED(inputline); + return true; + } + + if (issection("SpringBrake:", inputline)) + { + + startBPT = false; + LISTLINE = 0; + fizlines.try_emplace("SpringBrake", inputline); + LoadFIZ_SpringBrake(inputline); + return true; + } + + if (issection("Light:", inputline)) + { + + startBPT = false; + fizlines.try_emplace("Light", inputline); + LoadFIZ_Light(inputline); + return true; + } + + if (issection("Security:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Security", inputline); + SecuritySystem.load(inputline, Vmax); + extract_value(EmergencyBrakeWarningSignal, "EmergencyBrakeWarningSignal", inputline, ""); + return true; + } + + if (issection("Clima:", inputline)) + { + + startBPT = false; + fizlines.try_emplace("Clima", inputline); + LoadFIZ_Clima(inputline); + return true; + } + + if (issection("Power:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Power", inputline); + LoadFIZ_Power(inputline); + return true; + } + + if (issection("SpeedControl:", inputline)) + { + startBPT = false; + fizlines.try_emplace("SpeedControl", inputline); + LoadFIZ_SpeedControl(inputline); + return true; + } + + if (issection("Engine:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Engine", inputline); + LoadFIZ_Engine(inputline); + return true; + } + + if (issection("Switches:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Switches", inputline); + LoadFIZ_Switches(inputline); + return true; + } + + if (issection("Circuit:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Circuit", inputline); + LoadFIZ_Circuit(inputline); + return true; + } + + if (issection("AI:", inputline)) + { + startBPT = false; + fizlines.try_emplace("AI", inputline); + LoadFIZ_AI(inputline); + return true; + } + + return false; +} + +// a section of the definition opening a table, kept in fizlines by its name; returns whether the line is one +bool TMoverParameters::LoadFIZ_TableSection(std::string const &inputline, std::map> &fizlines) +{ + if (issection("MotorParamTable:", inputline)) + { + startBPT = false; + startMPT = true; + LISTLINE = 0; + fizlines.try_emplace("MotorParamTable", inputline); + LoadFIZ_MotorParamTable(inputline); + return true; + } + + if (issection("MotorParamTable0:", inputline)) + { + startBPT = false; + startMPT0 = true; + LISTLINE = 0; + return true; + } + + if (issection("RList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("RList", inputline); + startRLIST = true; + LISTLINE = 0; + LoadFIZ_RList(inputline); + return true; + } + + if (issection("UCList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("UCList", inputline); + startUCLIST = true; + LISTLINE = 0; + LoadFIZ_UCList(inputline); + return true; + } + + if (issection("DList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("DList", inputline); + startDLIST = true; + LISTLINE = 0; + LoadFIZ_DList(inputline); + return true; + } + + if (issection("DMList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("DMList", inputline); + startDIZELMOMENTUMLIST = true; + LISTLINE = 0; + return true; + } + + if (issection("HTCList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("HTCList", inputline); + startHYDROTCLIST = true; + LISTLINE = 0; + return true; + } + + if (issection("PmaxList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("PmaxList", inputline); + startPMAXLIST = true; + LISTLINE = 0; + return true; + } + + if (issection("V2NList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("V2NList", inputline); + startDIZELV2NMAXLIST = true; + LISTLINE = 0; + return true; + } + + if (issection("ffList:", inputline)) + { + startBPT = false; + startFFLIST = true; + LISTLINE = 0; + LoadFIZ_FFList(inputline); + return true; + } + + if (issection("ffBrakeList:", inputline)) + { + startBPT = false; + startFFEDLIST = true; + LISTLINE = 0; + LoadFIZ_FFEDList(inputline); + return true; + } + + if (issection("WWList:", inputline)) + { + startBPT = false; + startWWLIST = true; + LISTLINE = 0; + + return true; + } + + if (issection("WiperList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("WiperList", inputline); + startWiperList = true; + LISTLINE = 0; + LoadFIZ_WiperList(inputline); + + return true; + } + + if (issection("DimmerList:", inputline)) + { + dimPositions.clear(); // uzywamy customowej listy + startBPT = false; + startDimmerList = true; + fizlines.try_emplace("DimmerList", inputline); + LoadFIZ_DimmerList(inputline); + return true; + } + + if (issection("LightsList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("LightsList", inputline); + startLIGHTSLIST = true; + LISTLINE = 0; + LoadFIZ_LightsList(inputline); + return true; + } + + if (issection("CompressorList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("CompressorList", inputline); + startCOMPRESSORLIST = true; + LISTLINE = 0; + LoadFIZ_CompressorList(inputline); + return true; + } + return false; +} + +// a row of the table being read +void TMoverParameters::LoadFIZ_TableRow(std::string const &inputline) +{ + // ...and finally, table parsers. + // NOTE: once table parsing is enabled it lasts until switched off, when another section is recognized + if (true == startBPT) + { + readBPT(inputline); + return; + } + if (true == startMPT) + { + readMPT(inputline); + return; + } + if (true == startMPT0) + { + readMPT0(inputline); + return; + } + if (true == startRLIST) + { + readRList(inputline); + return; + } + if (true == startUCLIST) + { + readUCList(inputline); + return; + } + if (true == startDLIST) + { + readDList(inputline); + return; + } + if (true == startDIZELMOMENTUMLIST) + { + readDMList(inputline); + return; + } + if (true == startDIZELV2NMAXLIST) + { + readV2NMAXList(inputline); + return; + } + if (true == startHYDROTCLIST) + { + readHTCList(inputline); + return; + } + if (true == startPMAXLIST) + { + readPmaxList(inputline); + return; + } + if (true == startFFLIST) + { + readFFList(inputline); + return; + } + if (true == startFFEDLIST) + { + readFFEDList(inputline); + return; + } + if (true == startWWLIST) + { + readWWList(inputline); + return; + } + if (true == startWiperList) + { + readWiperList(inputline); + return; + } + if (true == startDimmerList) + { + readDimmerList(inputline); + } + if (true == startLIGHTSLIST) + { + readLightsList(inputline); + return; + } + if (true == startCOMPRESSORLIST) + { + readCompressorList(inputline); + return; + } +} + void TMoverParameters::LoadFIZ_Param(std::string const &line) { @@ -12461,6 +13081,14 @@ void TMoverParameters::LoadFIZ_TurboPos(std::string const &Input) void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) { + LoadFIZ_CntrlBrakes(line); + LoadFIZ_CntrlControllers(line); + LoadFIZ_CntrlStarts(line); +} + +// Cntrl.: the brake system, the handles, the brake delays and the local and manual brakes +void TMoverParameters::LoadFIZ_CntrlBrakes(std::string const &line) +{ { using enum TBrakeSystem; std::map> brakesystems{{"Pneumatic", Pneumatic}, {"ElectroPneumatic", ElectroPneumatic}}; @@ -12469,93 +13097,7 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) } if (BrakeSystem != TBrakeSystem::Individual) { - using enum TBrakeHandle; - - extract_value(BrakeCtrlPosNo, "BCPN", line, ""); - for (int idx = 0; idx < 4; ++idx) - { - - extract_value(BrakeDelay[idx], std::format("BDelay{}", idx + 1), line, ""); - } - // brakedelays, brakedelayflag - { - std::map> brakedelays{{"GPR", bdelay_G + bdelay_P + bdelay_R}, - {"PR", bdelay_P + bdelay_R}, - {"GP", bdelay_G + bdelay_P}, - {"R", bdelay_R}, - {"P", bdelay_P}, - {"G", bdelay_G}, - {"GPR+Mg", bdelay_G + bdelay_P + bdelay_R + bdelay_M}, - {"PR+Mg", bdelay_P + bdelay_R + bdelay_M}}; - std::map> brakedelayflags{{"R", bdelay_R}, {"P", bdelay_P}, {"G", bdelay_G}}; - std::string brakedelay; - extract_value(brakedelay, "BrakeDelays", line, ""); - auto lookup = brakedelays.find(brakedelay); - BrakeDelays = lookup != brakedelays.end() ? lookup->second : 0; - lookup = brakedelayflags.find(brakedelay); - BrakeDelayFlag = lookup != brakedelayflags.end() ? lookup->second : 0; - } - // brakeopmode - { - std::map> brakeopmodes{{"PN", bom_PS + bom_PN}, {"PNEP", bom_PS + bom_PN + bom_EP}, {"PNEPMED", bom_PS + bom_PN + bom_EP + bom_MED}}; - auto lookup = brakeopmodes.find(extract_value("BrakeOpModes", line)); - BrakeOpModes = lookup != brakeopmodes.end() ? lookup->second : 0; - } - // brakehandle - { - std::map> brakehandles{ - {"FV4a", FV4a}, {"test", testH}, {"D2", D2}, {"MHZ_EN57", MHZ_EN57}, {"MHZ_K5P", MHZ_K5P}, - {"MHZ_K8P", MHZ_K8P}, {"MHZ_6P", MHZ_6P}, {"M394", M394}, {"Knorr", Knorr}, {"Westinghouse", West}, - {"FVel6", FVel6}, {"FVE408", FVE408}, {"St113", St113}}; - auto lookup = brakehandles.find(extract_value("BrakeHandle", line)); - BrakeHandle = lookup != brakehandles.end() ? lookup->second : NoHandle; - } - extract_value(Handle_AutomaticOverload, "HAO", line, ""); - extract_value(Handle_ManualOverload, "HMO", line, ""); - extract_value(Handle_GenericDoubleParameter1, "HGDP1", line, ""); - extract_value(Handle_GenericDoubleParameter2, "HGDP2", line, ""); - extract_value(Handle_OverloadMaxPressure, "OMP", line, ""); - extract_value(Handle_OverloadPressureDecrease, "OPD", line, ""); - // brakelochandle - { - std::map> locbrakehandles{{"FD1", FD1}, {"Knorr", Knorr}, {"Westinghouse", West}}; - auto lookup = locbrakehandles.find(extract_value("LocBrakeHandle", line)); - BrakeLocHandle = lookup != locbrakehandles.end() ? lookup->second : NoHandle; - } - - // mbpm - if (true == extract_value(MBPM, "MaxBPMass", line, "")) - { - // NOTE: only convert the value from tons to kilograms if the entry is present in the config file - MBPM *= 1000.0; - } - - // asbtype - std::string const asb{ToLower(extract_value("ASB", line))}; - if (BrakeCtrlPosNo > 0) - { - - if (asb == "manual") - { - ASBType = 1; - } - else if (asb == "automatic") - { - ASBType = 2; - } - else if (asb == "yes") - { - ASBType = 128; - } - } - else - { - - if (asb == "yes") - { - ASBType = 128; - } - } + LoadFIZ_CntrlTrainBrake(line); } // brakesystem != individual // localbrake @@ -12567,7 +13109,96 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) } // mbrake extract_value(MBrake, "ManualBrake", line, ""); +} +// Cntrl.: of a vehicle with a train brake, its positions, delays, modes, handles, load weighing and anti-slip brake +void TMoverParameters::LoadFIZ_CntrlTrainBrake(std::string const &line) +{ + using enum TBrakeHandle; + + extract_value(BrakeCtrlPosNo, "BCPN", line, ""); + for (int idx = 0; idx < 4; ++idx) + { + + extract_value(BrakeDelay[idx], std::format("BDelay{}", idx + 1), line, ""); + } + // brakedelays, brakedelayflag + { + std::map> brakedelays{{"GPR", bdelay_G + bdelay_P + bdelay_R}, + {"PR", bdelay_P + bdelay_R}, + {"GP", bdelay_G + bdelay_P}, + {"R", bdelay_R}, + {"P", bdelay_P}, + {"G", bdelay_G}, + {"GPR+Mg", bdelay_G + bdelay_P + bdelay_R + bdelay_M}, + {"PR+Mg", bdelay_P + bdelay_R + bdelay_M}}; + std::map> brakedelayflags{{"R", bdelay_R}, {"P", bdelay_P}, {"G", bdelay_G}}; + std::string brakedelay; + extract_value(brakedelay, "BrakeDelays", line, ""); + auto lookup = brakedelays.find(brakedelay); + BrakeDelays = lookup != brakedelays.end() ? lookup->second : 0; + lookup = brakedelayflags.find(brakedelay); + BrakeDelayFlag = lookup != brakedelayflags.end() ? lookup->second : 0; + } + // brakeopmode + { + std::map> brakeopmodes{{"PN", bom_PS + bom_PN}, {"PNEP", bom_PS + bom_PN + bom_EP}, {"PNEPMED", bom_PS + bom_PN + bom_EP + bom_MED}}; + auto lookup = brakeopmodes.find(extract_value("BrakeOpModes", line)); + BrakeOpModes = lookup != brakeopmodes.end() ? lookup->second : 0; + } + // brakehandle + { + std::map> brakehandles{ + {"FV4a", FV4a}, {"test", testH}, {"D2", D2}, {"MHZ_EN57", MHZ_EN57}, {"MHZ_K5P", MHZ_K5P}, + {"MHZ_K8P", MHZ_K8P}, {"MHZ_6P", MHZ_6P}, {"M394", M394}, {"Knorr", Knorr}, {"Westinghouse", West}, + {"FVel6", FVel6}, {"FVE408", FVE408}, {"St113", St113}}; + auto lookup = brakehandles.find(extract_value("BrakeHandle", line)); + BrakeHandle = lookup != brakehandles.end() ? lookup->second : NoHandle; + } + extract_value(Handle_AutomaticOverload, "HAO", line, ""); + extract_value(Handle_ManualOverload, "HMO", line, ""); + extract_value(Handle_GenericDoubleParameter1, "HGDP1", line, ""); + extract_value(Handle_GenericDoubleParameter2, "HGDP2", line, ""); + extract_value(Handle_OverloadMaxPressure, "OMP", line, ""); + extract_value(Handle_OverloadPressureDecrease, "OPD", line, ""); + // brakelochandle + { + std::map> locbrakehandles{{"FD1", FD1}, {"Knorr", Knorr}, {"Westinghouse", West}}; + auto lookup = locbrakehandles.find(extract_value("LocBrakeHandle", line)); + BrakeLocHandle = lookup != locbrakehandles.end() ? lookup->second : NoHandle; + } + + // mbpm + if (true == extract_value(MBPM, "MaxBPMass", line, "")) + { + // NOTE: only convert the value from tons to kilograms if the entry is present in the config file + MBPM *= 1000.0; + } + + // asbtype + LoadFIZ_CntrlAntiSlipBrake(ToLower(extract_value("ASB", line))); +} + +// Cntrl.: the kind of the anti-slip brake, by hand or automatic only for a vehicle with a brake handle +void TMoverParameters::LoadFIZ_CntrlAntiSlipBrake(std::string_view const asb) +{ + if (asb == "yes") + { + ASBType = 128; + } + else if (BrakeCtrlPosNo > 0 && asb == "manual") + { + ASBType = 1; + } + else if (BrakeCtrlPosNo > 0 && asb == "automatic") + { + ASBType = 2; + } +} + +// Cntrl.: the controllers, their delays, the cab and the switches of the driver's desk +void TMoverParameters::LoadFIZ_CntrlControllers(std::string const &line) +{ // maksymalna predkosc dostepna na tarczce predkosciomierza extract_value(maxTachoSpeed, "MaxTachoSpeed", line, ""); @@ -12667,15 +13298,20 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) extract_value(isBatteryButtonImpulse, "IBTB", line, ""); extract_value(shouldHoldBatteryButton, "SBBBH", line, ""); extract_value(BatteryButtonHoldTime, "BBHT", line, ""); +} - std::map> starts{{"Disabled", start_t::disabled}, {"Manual", start_t::manual}, {"Automatic", start_t::automatic}, {"Mixed", start_t::manualwithautofallback}, - {"Battery", start_t::battery}, {"Converter", start_t::converter}, {"Direction", start_t::direction}}; +// Cntrl.: how the devices start (MainStart, BatteryStart, ...) and their relays +void TMoverParameters::LoadFIZ_CntrlStarts(std::string const &line) +{ + using enum start_t; + std::map> starts{{"Disabled", disabled}, {"Manual", manual}, {"Automatic", automatic}, {"Mixed", manualwithautofallback}, + {"Battery", battery}, {"Converter", converter}, {"Direction", direction}}; // main circuit extract_value(MainsInitTime, "MainInitTime", line, ""); { auto lookup = starts.find(extract_value("MainStart", line)); - MainsStart = lookup != starts.end() ? lookup->second : start_t::manual; + MainsStart = lookup != starts.end() ? lookup->second : manual; } extract_value(PantographsRequireMains, "PantRequiresMain", line, ""); // the brake pipe pressure of an emergency brake application, which opens the line breaker under power @@ -12684,24 +13320,24 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) // battery { auto lookup = starts.find(extract_value("BatteryStart", line)); - BatteryStart = lookup != starts.end() ? lookup->second : start_t::manual; + BatteryStart = lookup != starts.end() ? lookup->second : manual; } // converter { auto lookup = starts.find(extract_value("ConverterStart", line)); - ConverterStart = lookup != starts.end() ? lookup->second : start_t::manual; + ConverterStart = lookup != starts.end() ? lookup->second : manual; } extract_value(ConverterStartDelay, "ConverterStartDelay", line, ""); extract_value(ConverterOverloadRelayOffWhenMainIsOff, "ConverterOverloadWhenMainIsOff", line, TrainType == dt_EZT ? "yes" : "no"); // compressor { auto lookup = starts.find(extract_value("CompressorStart", line)); - CompressorStart = lookup != starts.end() ? lookup->second : start_t::manual; + CompressorStart = lookup != starts.end() ? lookup->second : manual; } // pantograph compressor { auto lookup = starts.find(extract_value("PantCompressorStart", line)); - PantographCompressorStart = lookup != starts.end() ? lookup->second : start_t::manual; + PantographCompressorStart = lookup != starts.end() ? lookup->second : manual; } // pantograph compressor valve PantAutoValve = TrainType == dt_EZT; // legacy code behaviour, automatic valve was initially installed in all EMUs @@ -12709,13 +13345,13 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) // pantographs valve { auto lookup = starts.find(extract_value("PantEPValveStart", line)); - PantsValve.start_type = lookup != starts.end() ? lookup->second : start_t::automatic; // legacy code behaviour, there was no pantographs valve + PantsValve.start_type = lookup != starts.end() ? lookup->second : automatic; // legacy code behaviour, there was no pantographs valve extract_value(PantsValve.spring, "PantEPValveSpring", line, ""); } // pantograph valve configuration { auto lookup = starts.find(extract_value("PantValveStart", line)); - auto valvestarttype = lookup != starts.end() ? lookup->second : start_t::manual; + auto valvestarttype = lookup != starts.end() ? lookup->second : manual; auto valvespring{true}; extract_value(valvespring, "PantValveSpring", line, ""); auto valvesolenoid{true}; @@ -12730,22 +13366,22 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) // fuel pump { auto lookup = starts.find(extract_value("FuelStart", line)); - FuelPump.start_type = lookup != starts.end() ? lookup->second : start_t::manual; + FuelPump.start_type = lookup != starts.end() ? lookup->second : manual; } // oil pump { auto lookup = starts.find(extract_value("OilStart", line)); - OilPump.start_type = lookup != starts.end() ? lookup->second : start_t::manual; + OilPump.start_type = lookup != starts.end() ? lookup->second : manual; } // water pump { auto lookup = starts.find(extract_value("WaterStart", line)); - WaterPump.start_type = lookup != starts.end() ? lookup->second : start_t::manual; + WaterPump.start_type = lookup != starts.end() ? lookup->second : manual; } // traction motor fans { auto lookup = starts.find(extract_value("MotorBlowersStart", line)); - MotorBlowers[end::rear].start_type = lookup != starts.end() ? lookup->second : start_t::manual; + MotorBlowers[end::rear].start_type = lookup != starts.end() ? lookup->second : manual; MotorBlowers[end::front].start_type = MotorBlowers[end::rear].start_type; } // what else the line contactors need to close @@ -12759,19 +13395,19 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) // compartment lights { auto lookup = starts.find(extract_value("CompartmentLightsStart", line)); - CompartmentLights.start_type = lookup != starts.end() ? lookup->second : start_t::automatic; // legacy behaviour + CompartmentLights.start_type = lookup != starts.end() ? lookup->second : automatic; // legacy behaviour } // ground relay { auto lookup = starts.find(extract_value("GroundRelayStart", line)); - auto const defaultstart{TrainType == dt_EZT ? start_t::automatic : start_t::manual}; + auto const defaultstart{TrainType == dt_EZT ? automatic : manual}; GroundRelayStart = lookup != starts.end() ? lookup->second : defaultstart; } // converter overload relay { auto lookup = starts.find(extract_value("ConverterOverloadRelayStart", line)); // the relay of a multiple unit activates when the converter is switched off - auto const defaultstart{TrainType == dt_EZT ? start_t::converter : start_t::manual}; + auto const defaultstart{TrainType == dt_EZT ? converter : manual}; ConverterOverloadRelayStart = lookup != starts.end() ? lookup->second : defaultstart; } } @@ -12960,154 +13596,17 @@ void TMoverParameters::LoadFIZ_Engine(std::string const &Input) } case TEngineType::DieselEngine: { - - extract_value(dizel_nmin, "nmin", Input, ""); - dizel_nmin /= 60.0; - dizel_nreg_min = dizel_nmin * 0.98; - extract_value(dizel_nmin_hdrive, "nmin_hdrive", Input, ""); - dizel_nmin_hdrive /= 60.0; - if (dizel_nmin_hdrive == 0.0) - { - dizel_nmin_hdrive = dizel_nmin; - } - extract_value(dizel_nmin_hdrive_factor, "nmin_hdrive_factor", Input, ""); - dizel_nmin_hdrive_factor /= 60.0; - extract_value(dizel_nmin_retarder, "nmin_retarder", Input, ""); - dizel_nmin_retarder /= 60.0; - if (dizel_nmin_retarder == 0.0) - { - dizel_nmin_retarder = dizel_nmin; - } - // TODO: unify naming scheme and sort out which diesel engine params are used where and how - extract_value(nmax, "nmax", Input, ""); - nmax /= 60.0; - extract_value(dizel_nmax_cutoff, "nmax_cutoff", Input, "0.0"); - dizel_nmax_cutoff /= 60.0; - extract_value(dizel_nreg_acc, "nreg_acc", Input, ""); - dizel_nreg_acc /= 60.0; - extract_value(dizel_AIM, "AIM", Input, "1.0"); - extract_value(dizel_RevolutionsDecreaseRate, "RPMDecRate", Input, ""); - - extract_value(engageupspeed, "EUS", Input, "0.5"); - extract_value(engagedownspeed, "EDS", Input, "0.9"); - - if (true == extract_value(AnPos, "ShuntMode", Input, "")) - { - // dodatkowa przekładnia dla SM03 (2Ls150) - ShuntModeAllow = true; - ShuntMode = false; - if (AnPos < 1.0) - { - //"rozruch wysoki" ma dawać większą siłę - AnPos = 1.0 / AnPos; // im większa liczba, tym wolniej jedzie - } - } - extract_value(hydro_TC, "IsTC", Input, ""); - if (true == hydro_TC) - { - extract_value(hydro_TC_TMMax, "TC_TMMax", Input, ""); - extract_value(hydro_TC_CouplingPoint, "TC_CP", Input, ""); - extract_value(hydro_TC_LockupTorque, "TC_LT", Input, ""); - extract_value(hydro_TC_LockupRate, "TC_LR", Input, ""); - extract_value(hydro_TC_UnlockRate, "TC_ULR", Input, ""); - extract_value(hydro_TC_FillRateInc, "TC_FRI", Input, ""); - extract_value(hydro_TC_FillRateDec, "TC_FRD", Input, ""); - extract_value(hydro_TC_TorqueInIn, "TC_TII", Input, ""); - extract_value(hydro_TC_TorqueInOut, "TC_TIO", Input, ""); - extract_value(hydro_TC_TorqueOutOut, "TC_TOO", Input, ""); - extract_value(hydro_TC_LockupSpeed, "TC_LS", Input, ""); - extract_value(hydro_TC_UnlockSpeed, "TC_ULS", Input, ""); - extract_value(dizel_maxVelANS, "MaxVelANS", Input, ""); - - extract_value(hydro_R, "IsRetarder", Input, ""); - if (true == hydro_R) - { - extract_value(hydro_R_Placement, "R_Place", Input, ""); - extract_value(hydro_R_TorqueInIn, "R_TII", Input, ""); - extract_value(hydro_R_MaxTorque, "R_MT", Input, ""); - extract_value(hydro_R_MaxPower, "R_MP", Input, ""); - extract_value(hydro_R_FillRateInc, "R_FRI", Input, ""); - extract_value(hydro_R_FillRateDec, "R_FRD", Input, ""); - extract_value(hydro_R_MinVel, "R_MinVel", Input, ""); - extract_value(hydro_R_EngageVel, "R_EngageVel", Input, ""); - extract_value(hydro_R_Clutch, "R_IsClutch", Input, ""); - extract_value(hydro_R_ClutchSpeed, "R_ClutchSpeed", Input, ""); - extract_value(hydro_R_WithIndividual, "R_WithIndividual", Input, ""); - } - } + LoadFIZ_EngineDiesel(Input); break; } case TEngineType::DieselElectric: { // youBy - - extract_value(Ftmax, "Ftmax", Input, ""); - Flat = extract_value("Flat", Input) == "1"; - extract_value(Vhyp, "Vhyp", Input, ""); - Vhyp /= 3.6; - extract_value(Vadd, "Vadd", Input, ""); - Vadd /= 3.6; - extract_value(PowerCorRatio, "Cr", Input, ""); - extract_value(RelayType, "RelayType", Input, ""); - if (extract_value("ShuntMode", Input) == "1") - { - - ShuntModeAllow = true; - ShuntMode = false; - AnPos = 0.0; - ImaxHi = 2; - ImaxLo = 1; - } - extract_value(EngineHeatingRPM, "HeatingRPM", Input, ""); - extract_value(dizel_AIM, "AIM", Input, "1.25"); - extract_value(dizel_RevolutionsDecreaseRate, "RPMDecRate", Input, ""); - LoadFIZ_DieselElectricDynamicBrake(Input); + LoadFIZ_EngineDieselElectric(Input); break; } case TEngineType::ElectricInductionMotor: { - - RVentnmax = 1.0; - extract_value(NominalVoltage, "Volt", Input, ""); - - extract_value(eimc[eimc_s_dfic], "dfic", Input, ""); - extract_value(eimc[eimc_s_dfmax], "dfmax", Input, ""); - extract_value(eimc[eimc_s_p], "p", Input, ""); - extract_value(eimc[eimc_s_cfu], "cfu", Input, ""); - extract_value(eimc[eimc_s_cim], "cim", Input, ""); - extract_value(eimc[eimc_s_icif], "icif", Input, ""); - extract_value(eimc[eimc_f_Uzmax], "Uzmax", Input, ""); - extract_value(eimc[eimc_f_Uzh], "Uzh", Input, ""); - extract_value(eimc[eimc_f_DU], "DU", Input, ""); - extract_value(eimc[eimc_f_I0], "I0", Input, ""); - extract_value(eimc[eimc_f_cfu], "fcfu", Input, ""); - extract_value(eimc[eimc_f_cfuH], "fcfuH", Input, std::to_string(eimc[eimc_f_cfu])); - extract_value(eimc[eimc_p_F0], "F0", Input, ""); - extract_value(eimc[eimc_p_a1], "a1", Input, ""); - extract_value(eimc[eimc_p_Pmax], "Pmax", Input, ""); - extract_value(eimc[eimc_p_Fh], "Fh", Input, ""); - extract_value(eimc[eimc_p_Ph], "Ph", Input, ""); - extract_value(eimc[eimc_p_Vh0], "Vh0", Input, ""); - extract_value(eimc[eimc_p_Vh1], "Vh1", Input, ""); - extract_value(eimc[eimc_p_Imax], "Imax", Input, ""); - extract_value(eimc[eimc_p_abed], "abed", Input, ""); - extract_value(eimc[eimc_p_eped], "edep", Input, ""); - extract_value(EIMCLogForce, "eimclf", Input, ""); - extract_value(InvertersNo, "InvNo", Input, ""); - extract_value(InverterControlCouplerFlag, "InvCtrCplFlag", Input, ""); - extract_value(Imaxrpc, "Imaxrpc", Input, ""); - extract_value(BRVto, "BRVto", Input, ""); - extract_value(Flat, "Flat", Input, ""); - - if (eimc[eimc_p_Pmax] > 0 && Power > 0 && InvertersNo == 0) - { - InvertersNo = 1; - } - Inverters.resize(InvertersNo); - /*for (int i = 0; i > InvertersNo; i++) - { - inverter x; - Inverters.emplace_back(x); - }*/ + LoadFIZ_EngineInductionMotor(Input); break; } default: @@ -13119,40 +13618,7 @@ void TMoverParameters::LoadFIZ_Engine(std::string const &Input) // NOTE: elements shared by both diesel engine variants; crude but, eh if (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) { - // oil pump - extract_value(OilPump.pressure_minimum, "OilMinPressure", Input, ""); - extract_value(OilPump.pressure_maximum, "OilMaxPressure", Input, ""); - // the time the starter turns the engine before it fires and smokes (eu07/maszyna#523) - extract_value(dizel_SmokeDelay, "SmokeDelay", Input, "0"); - dizel_SmokeDelay = std::max(0.0, dizel_SmokeDelay); - // engine cooling factore - extract_value(dizel_heat.kw, "HeatKW", Input, ""); - extract_value(dizel_heat.kv, "HeatKV", Input, ""); - extract_value(dizel_heat.kfe, "HeatKFE", Input, ""); - extract_value(dizel_heat.kfs, "HeatKFS", Input, ""); - extract_value(dizel_heat.kfo, "HeatKFO", Input, ""); - extract_value(dizel_heat.kfo2, "HeatKFO2", Input, ""); - // engine cooling systems - extract_value(dizel_heat.water.config.temp_min, "WaterMinTemperature", Input, ""); - extract_value(dizel_heat.water.config.temp_max, "WaterMaxTemperature", Input, ""); - extract_value(dizel_heat.water.config.temp_flow, "WaterFlowTemperature", Input, ""); - extract_value(dizel_heat.water.config.temp_cooling, "WaterCoolingTemperature", Input, ""); - extract_value(dizel_heat.water.config.shutters, "WaterShutters", Input, ""); - extract_value(dizel_heat.auxiliary_water_circuit, "WaterAuxCircuit", Input, ""); - extract_value(dizel_heat.water_aux.config.temp_min, "WaterAuxMinTemperature", Input, ""); - extract_value(dizel_heat.water_aux.config.temp_max, "WaterAuxMaxTemperature", Input, ""); - extract_value(dizel_heat.water_aux.config.temp_cooling, "WaterAuxCoolingTemperature", Input, ""); - extract_value(dizel_heat.water_aux.config.shutters, "WaterAuxShutters", Input, ""); - extract_value(dizel_heat.oil.config.temp_min, "OilMinTemperature", Input, ""); - extract_value(dizel_heat.oil.config.temp_max, "OilMaxTemperature", Input, ""); - extract_value(dizel_heat.engine_max_temp, "EngineMaxTemperature", Input, ""); - extract_value(dizel_heat.fan_speed, "WaterCoolingFanSpeed", Input, ""); - // water heater - extract_value(WaterHeater.config.temp_min, "HeaterMinTemperature", Input, ""); - extract_value(WaterHeater.config.temp_max, "HeaterMaxTemperature", Input, ""); - float pf{ 1235.f }; - extract_value(pf, "NominalCoolingPower", Input, "1235"); - dizel_heat.powerfactor = 1235 / pf; + LoadFIZ_EngineDieselShared(Input); } // traction motors @@ -13166,6 +13632,200 @@ void TMoverParameters::LoadFIZ_Engine(std::string const &Input) extract_value(PressureSwitchBrakeCylinder, "PressureSwitchBrakeCylinder", Input, ""); } +// Engine: of a diesel engine, its revolutions, gears, hydraulic transmission and retarder +void TMoverParameters::LoadFIZ_EngineDiesel(std::string const &Input) +{ + + extract_value(dizel_nmin, "nmin", Input, ""); + dizel_nmin /= 60.0; + dizel_nreg_min = dizel_nmin * 0.98; + extract_value(dizel_nmin_hdrive, "nmin_hdrive", Input, ""); + dizel_nmin_hdrive /= 60.0; + if (dizel_nmin_hdrive == 0.0) + { + dizel_nmin_hdrive = dizel_nmin; + } + extract_value(dizel_nmin_hdrive_factor, "nmin_hdrive_factor", Input, ""); + dizel_nmin_hdrive_factor /= 60.0; + extract_value(dizel_nmin_retarder, "nmin_retarder", Input, ""); + dizel_nmin_retarder /= 60.0; + if (dizel_nmin_retarder == 0.0) + { + dizel_nmin_retarder = dizel_nmin; + } + // TODO: unify naming scheme and sort out which diesel engine params are used where and how + extract_value(nmax, "nmax", Input, ""); + nmax /= 60.0; + extract_value(dizel_nmax_cutoff, "nmax_cutoff", Input, "0.0"); + dizel_nmax_cutoff /= 60.0; + extract_value(dizel_nreg_acc, "nreg_acc", Input, ""); + dizel_nreg_acc /= 60.0; + extract_value(dizel_AIM, "AIM", Input, "1.0"); + extract_value(dizel_RevolutionsDecreaseRate, "RPMDecRate", Input, ""); + + extract_value(engageupspeed, "EUS", Input, "0.5"); + extract_value(engagedownspeed, "EDS", Input, "0.9"); + + if (true == extract_value(AnPos, "ShuntMode", Input, "")) + { + // dodatkowa przekładnia dla SM03 (2Ls150) + ShuntModeAllow = true; + ShuntMode = false; + if (AnPos < 1.0) + { + //"rozruch wysoki" ma dawać większą siłę + AnPos = 1.0 / AnPos; // im większa liczba, tym wolniej jedzie + } + } + extract_value(hydro_TC, "IsTC", Input, ""); + if (true == hydro_TC) + { + extract_value(hydro_TC_TMMax, "TC_TMMax", Input, ""); + extract_value(hydro_TC_CouplingPoint, "TC_CP", Input, ""); + extract_value(hydro_TC_LockupTorque, "TC_LT", Input, ""); + extract_value(hydro_TC_LockupRate, "TC_LR", Input, ""); + extract_value(hydro_TC_UnlockRate, "TC_ULR", Input, ""); + extract_value(hydro_TC_FillRateInc, "TC_FRI", Input, ""); + extract_value(hydro_TC_FillRateDec, "TC_FRD", Input, ""); + extract_value(hydro_TC_TorqueInIn, "TC_TII", Input, ""); + extract_value(hydro_TC_TorqueInOut, "TC_TIO", Input, ""); + extract_value(hydro_TC_TorqueOutOut, "TC_TOO", Input, ""); + extract_value(hydro_TC_LockupSpeed, "TC_LS", Input, ""); + extract_value(hydro_TC_UnlockSpeed, "TC_ULS", Input, ""); + extract_value(dizel_maxVelANS, "MaxVelANS", Input, ""); + + extract_value(hydro_R, "IsRetarder", Input, ""); + if (true == hydro_R) + { + extract_value(hydro_R_Placement, "R_Place", Input, ""); + extract_value(hydro_R_TorqueInIn, "R_TII", Input, ""); + extract_value(hydro_R_MaxTorque, "R_MT", Input, ""); + extract_value(hydro_R_MaxPower, "R_MP", Input, ""); + extract_value(hydro_R_FillRateInc, "R_FRI", Input, ""); + extract_value(hydro_R_FillRateDec, "R_FRD", Input, ""); + extract_value(hydro_R_MinVel, "R_MinVel", Input, ""); + extract_value(hydro_R_EngageVel, "R_EngageVel", Input, ""); + extract_value(hydro_R_Clutch, "R_IsClutch", Input, ""); + extract_value(hydro_R_ClutchSpeed, "R_ClutchSpeed", Input, ""); + extract_value(hydro_R_WithIndividual, "R_WithIndividual", Input, ""); + } + } +} + +// Engine: of a diesel-electric +void TMoverParameters::LoadFIZ_EngineDieselElectric(std::string const &Input) +{ + + extract_value(Ftmax, "Ftmax", Input, ""); + Flat = extract_value("Flat", Input) == "1"; + extract_value(Vhyp, "Vhyp", Input, ""); + Vhyp /= 3.6; + extract_value(Vadd, "Vadd", Input, ""); + Vadd /= 3.6; + extract_value(PowerCorRatio, "Cr", Input, ""); + extract_value(RelayType, "RelayType", Input, ""); + if (extract_value("ShuntMode", Input) == "1") + { + + ShuntModeAllow = true; + ShuntMode = false; + AnPos = 0.0; + ImaxHi = 2; + ImaxLo = 1; + } + extract_value(EngineHeatingRPM, "HeatingRPM", Input, ""); + extract_value(dizel_AIM, "AIM", Input, "1.25"); + extract_value(dizel_RevolutionsDecreaseRate, "RPMDecRate", Input, ""); + LoadFIZ_DieselElectricDynamicBrake(Input); +} + +// Engine: of an induction motor drive +void TMoverParameters::LoadFIZ_EngineInductionMotor(std::string const &Input) +{ + + RVentnmax = 1.0; + extract_value(NominalVoltage, "Volt", Input, ""); + + extract_value(eimc[eimc_s_dfic], "dfic", Input, ""); + extract_value(eimc[eimc_s_dfmax], "dfmax", Input, ""); + extract_value(eimc[eimc_s_p], "p", Input, ""); + extract_value(eimc[eimc_s_cfu], "cfu", Input, ""); + extract_value(eimc[eimc_s_cim], "cim", Input, ""); + extract_value(eimc[eimc_s_icif], "icif", Input, ""); + extract_value(eimc[eimc_f_Uzmax], "Uzmax", Input, ""); + extract_value(eimc[eimc_f_Uzh], "Uzh", Input, ""); + extract_value(eimc[eimc_f_DU], "DU", Input, ""); + extract_value(eimc[eimc_f_I0], "I0", Input, ""); + extract_value(eimc[eimc_f_cfu], "fcfu", Input, ""); + extract_value(eimc[eimc_f_cfuH], "fcfuH", Input, std::to_string(eimc[eimc_f_cfu])); + extract_value(eimc[eimc_p_F0], "F0", Input, ""); + extract_value(eimc[eimc_p_a1], "a1", Input, ""); + extract_value(eimc[eimc_p_Pmax], "Pmax", Input, ""); + extract_value(eimc[eimc_p_Fh], "Fh", Input, ""); + extract_value(eimc[eimc_p_Ph], "Ph", Input, ""); + extract_value(eimc[eimc_p_Vh0], "Vh0", Input, ""); + extract_value(eimc[eimc_p_Vh1], "Vh1", Input, ""); + extract_value(eimc[eimc_p_Imax], "Imax", Input, ""); + extract_value(eimc[eimc_p_abed], "abed", Input, ""); + extract_value(eimc[eimc_p_eped], "edep", Input, ""); + extract_value(EIMCLogForce, "eimclf", Input, ""); + extract_value(InvertersNo, "InvNo", Input, ""); + extract_value(InverterControlCouplerFlag, "InvCtrCplFlag", Input, ""); + extract_value(Imaxrpc, "Imaxrpc", Input, ""); + extract_value(BRVto, "BRVto", Input, ""); + extract_value(Flat, "Flat", Input, ""); + + if (eimc[eimc_p_Pmax] > 0 && Power > 0 && InvertersNo == 0) + { + InvertersNo = 1; + } + Inverters.resize(InvertersNo); + /*for (int i = 0; i > InvertersNo; i++) + { + inverter x; + Inverters.emplace_back(x); + }*/ +} + +// Engine: what both kinds of diesels have, their heat among it +void TMoverParameters::LoadFIZ_EngineDieselShared(std::string const &Input) +{ + // oil pump + extract_value(OilPump.pressure_minimum, "OilMinPressure", Input, ""); + extract_value(OilPump.pressure_maximum, "OilMaxPressure", Input, ""); + // the time the starter turns the engine before it fires and smokes (eu07/maszyna#523) + extract_value(dizel_SmokeDelay, "SmokeDelay", Input, "0"); + dizel_SmokeDelay = std::max(0.0, dizel_SmokeDelay); + // engine cooling factore + extract_value(dizel_heat.kw, "HeatKW", Input, ""); + extract_value(dizel_heat.kv, "HeatKV", Input, ""); + extract_value(dizel_heat.kfe, "HeatKFE", Input, ""); + extract_value(dizel_heat.kfs, "HeatKFS", Input, ""); + extract_value(dizel_heat.kfo, "HeatKFO", Input, ""); + extract_value(dizel_heat.kfo2, "HeatKFO2", Input, ""); + // engine cooling systems + extract_value(dizel_heat.water.config.temp_min, "WaterMinTemperature", Input, ""); + extract_value(dizel_heat.water.config.temp_max, "WaterMaxTemperature", Input, ""); + extract_value(dizel_heat.water.config.temp_flow, "WaterFlowTemperature", Input, ""); + extract_value(dizel_heat.water.config.temp_cooling, "WaterCoolingTemperature", Input, ""); + extract_value(dizel_heat.water.config.shutters, "WaterShutters", Input, ""); + extract_value(dizel_heat.auxiliary_water_circuit, "WaterAuxCircuit", Input, ""); + extract_value(dizel_heat.water_aux.config.temp_min, "WaterAuxMinTemperature", Input, ""); + extract_value(dizel_heat.water_aux.config.temp_max, "WaterAuxMaxTemperature", Input, ""); + extract_value(dizel_heat.water_aux.config.temp_cooling, "WaterAuxCoolingTemperature", Input, ""); + extract_value(dizel_heat.water_aux.config.shutters, "WaterAuxShutters", Input, ""); + extract_value(dizel_heat.oil.config.temp_min, "OilMinTemperature", Input, ""); + extract_value(dizel_heat.oil.config.temp_max, "OilMaxTemperature", Input, ""); + extract_value(dizel_heat.engine_max_temp, "EngineMaxTemperature", Input, ""); + extract_value(dizel_heat.fan_speed, "WaterCoolingFanSpeed", Input, ""); + // water heater + extract_value(WaterHeater.config.temp_min, "HeaterMinTemperature", Input, ""); + extract_value(WaterHeater.config.temp_max, "HeaterMaxTemperature", Input, ""); + float pf{1235.f}; + extract_value(pf, "NominalCoolingPower", Input, "1235"); + dizel_heat.powerfactor = 1235 / pf; +} + void TMoverParameters::LoadFIZ_Switches(std::string const &Input) { @@ -13588,6 +14248,136 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) } // WriteLog("BVV = " + FloatToStr(BrakeVVolume)); + CreateBrakeValve(); + + CreateBrakeHandles(); + + CreateBrakePipes(); + + if (LightsPosNo > 0) + LightsPos = LightsDefPos; + + // set default wiper switch position + wiperSwitchPos = WiperDefaultPos; + + if (CompressorListPosNo > 0) + CompressorListPos = CompressorListDefPos; + + // NOTE: legacy compatibility behaviour for vehicles without defined heating power source + if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector && HeatingPowerSource.SourceType == TPowerSource::NotDefined) + { + HeatingPowerSource.SourceType = TPowerSource::Main; + } + if (HeatingPowerSource.SourceType == TPowerSource::NotDefined && HeatingPower > 0) + { + HeatingPowerSource.SourceType = TPowerSource::PowerCable; + HeatingPowerSource.PowerType = TPowerType::ElectricPower; + } + + // checking ready flag + // to dac potem do init + if (ReadyFlag) // gotowy do drogi + { + SetReadyToDepart(); + } + else + { // zahamowany} + SetBraked(); + } + + ActFlowSpeed = 0.0; + BrakeCtrlPosR = BrakeCtrlPos; + + if (BrakeLocHandle == TBrakeHandle::Knorr) + LocalBrakePosA = 0.5; + + Pipe->CreatePress(PipePress); + Pipe2->CreatePress(ScndPipePress); + Pipe->Act(); + Pipe2->Act(); + + EqvtPipePress = PipePress; + + Handle->Init(PipePress); + + ComputeConstans(); + + if (LoadFlag > 0) + { + + if (LoadAmount < MaxLoad * 0.45) + { + IncBrakeMult(); + IncBrakeMult(); + DecBrakeMult(); // TODO: przeinesiono do mover.cpp + if (LoadAmount < MaxLoad * 0.35) + DecBrakeMult(); + } + else + { + IncBrakeMult(); // TODO: przeinesiono do mover.cpp + if (LoadAmount >= MaxLoad * 0.55) + IncBrakeMult(); + } + } + + // taki mini automat - powinno byc ladnie dobrze :) + BrakeDelayFlag = bdelay_P; + if (TestFlag(BrakeDelays, bdelay_G) && !TestFlag(BrakeDelays, bdelay_R)) + BrakeDelayFlag = bdelay_G; + if (TestFlag(BrakeDelays, bdelay_R) && !TestFlag(BrakeDelays, bdelay_G)) + BrakeDelayFlag = bdelay_R; + /* + // disabled, as test mode is used in specific situations and not really a default + if (BrakeOpModes & bom_PS) + BrakeOpModeFlag = bom_PS; + else + */ + BrakeOpModeFlag = bom_PN; + + // yB: jesli pojazdy nie maja zadeklarowanych czasow, to wsadz z przepisow +-16,(6)% + std::array const DefBrakeTable{15, 4, 25, 25, 13, 3, 12, 2}; + + for (int b = 1; b < 4; b++) + { + if (BrakeDelay[b] == 0) + BrakeDelay[b] = DefBrakeTable[b]; + BrakeDelay[b] = BrakeDelay[b] * (2.5 + Random(0.0, 0.2)) / 3.0; + } + + Hamulec->Init(PipePress, HighPipePress, LowPipePress, BrakePress, BrakeDelayFlag); + /* + ScndPipePress = Compressor; + */ + // WriteLogSS("OK=", BoolTo10(OK)); + // WriteLog(""); + + if (EIMCtrlType == 3) + { + for (auto idx = 0; idx < MainCtrlPosNo; ++idx) + { + if (UniCtrlList[idx].MaxCtrlVal > 0.0) + { + UniCtrlNoPowerPos = std::max(0, idx - 1); + break; + } + } + } + + // security system + // by default place the magnet in the vehicle centre + if (SecuritySystem.MagnetLocation == 0) + { + SecuritySystem.MagnetLocation = Dim.L / 2 - 0.5; + } + SecuritySystem.MagnetLocation = std::clamp(SecuritySystem.MagnetLocation, 0.0, Dim.L); + + return OK; +} + +// the distributor valve of the vehicle's kind +void TMoverParameters::CreateBrakeValve() +{ switch (BrakeValve) { case TBrakeValve::W: @@ -13682,7 +14472,11 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) Hamulec->SetASBP(MaxBrakePress[4]); Hamulec->SetRV(RapidVel); +} +// the driver's handle and the local brake handle of the vehicle's kinds +void TMoverParameters::CreateBrakeHandles() +{ switch (BrakeHandle) { using enum TBrakeHandle; @@ -13744,7 +14538,11 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) default: LocHandle = std::make_shared(); } +} +// the brake pipe, the main pipe and the spring brake's cylinder +void TMoverParameters::CreateBrakePipes() +{ if (true == TestFlag(BrakeDelays, bdelay_G) && (false == TestFlag(BrakeDelays, bdelay_R) || Power > 1.0)) // ustalanie srednicy przewodu glownego (lokomotywa lub napędowy Spg = 0.792; else @@ -13760,173 +14558,73 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) SpringBrake.Cylinder = std::make_shared(); SpringBrake.Cylinder->CreateCap(1); } +} - if (LightsPosNo > 0) - LightsPos = LightsDefPos; - - // set default wiper switch position - wiperSwitchPos = WiperDefaultPos; - - if (CompressorListPosNo > 0) - CompressorListPos = CompressorListDefPos; - - // NOTE: legacy compatibility behaviour for vehicles without defined heating power source - if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector && HeatingPowerSource.SourceType == TPowerSource::NotDefined) +// the pressure of the main pipe at the start: the main reservoir's, or HosePressure fed through a main hose, or none +double TMoverParameters::InitialScndPipePress(double const HosePressure) const +{ + if (VeselVolume > 0.0) { - HeatingPowerSource.SourceType = TPowerSource::Main; + return CompressedVolume / VeselVolume; } - if (HeatingPowerSource.SourceType == TPowerSource::NotDefined && HeatingPower > 0) + if ((Couplers[end::front].AllowedFlag & coupling::mainhose) != 0 || (Couplers[end::rear].AllowedFlag & coupling::mainhose) != 0) { - HeatingPowerSource.SourceType = TPowerSource::PowerCable; - HeatingPowerSource.PowerType = TPowerType::ElectricPower; + return HosePressure; } + return 0.0; +} - // checking ready flag - // to dac potem do init - if (ReadyFlag) // gotowy do drogi - { - WriteLog("Ready to depart"); - CompressedVolume = VeselVolume * MinCompressor * 9.8 / 10.0; - ScndPipePress = VeselVolume > 0.0 ? CompressedVolume / VeselVolume : - (Couplers[end::front].AllowedFlag & coupling::mainhose) != 0 ? 5.0 : - (Couplers[end::rear].AllowedFlag & coupling::mainhose) != 0 ? 5.0 : - 0.0; - PipePress = CntrlPipePress; - BrakePress = 0.0; - LocalBrakePosA = 0.0; - if (CabActive == 0) - BrakeCtrlPos = static_cast(Handle->GetPos(bh_NP)); - else - BrakeCtrlPos = static_cast(Handle->GetPos(bh_RP)); - /* - // NOTE: disabled and left up to the driver, if there's any - MainSwitch( false ); - PantFront( true ); - PantRear( true ); - MainSwitch( true ); - */ - DirActive = 0; // Dir; //nastawnik kierunkowy - musi być ustawiane osobno! - DirAbsolute = DirActive * CabActive; // kierunek jazdy względem sprzęgów - LimPipePress = CntrlPipePress; - - Battery = BatteryStart != start_t::disabled; - } - else - { // zahamowany} - WriteLog("Braked"); - Volume = BrakeVVolume * MaxBrakePress[3]; - CompressedVolume = VeselVolume * MinCompressor * 0.55; - /* - ScndPipePress = 5.1; - */ - ScndPipePress = VeselVolume > 0.0 ? CompressedVolume / VeselVolume : - (Couplers[end::front].AllowedFlag & coupling::mainhose) != 0 ? 5.1 : - (Couplers[end::rear].AllowedFlag & coupling::mainhose) != 0 ? 5.1 : - 0.0; - PipePress = LowPipePress; - PipeBrakePress = MaxBrakePress[3] * 0.5; - BrakePress = MaxBrakePress[3] * 0.5; - LocalBrakePosA = 0.0; +// the air and the controls of a vehicle ready to depart +void TMoverParameters::SetReadyToDepart() +{ + WriteLog("Ready to depart"); + CompressedVolume = VeselVolume * MinCompressor * 9.8 / 10.0; + ScndPipePress = InitialScndPipePress(5.0); + PipePress = CntrlPipePress; + BrakePress = 0.0; + LocalBrakePosA = 0.0; + if (CabActive == 0) BrakeCtrlPos = static_cast(Handle->GetPos(bh_NP)); - LimPipePress = LowPipePress; - if (LocalBrake == TLocalBrake::ManualBrake || MBrake == true) - { - IncManualBrakeLevel(ManualBrakePosNo); - } - if (SpringBrake.MaxBrakeForce > 0.0) - { - SpringBrake.Activate = true; - } - } - - ActFlowSpeed = 0.0; - BrakeCtrlPosR = BrakeCtrlPos; - - if (BrakeLocHandle == TBrakeHandle::Knorr) - LocalBrakePosA = 0.5; - - Pipe->CreatePress(PipePress); - Pipe2->CreatePress(ScndPipePress); - Pipe->Act(); - Pipe2->Act(); - - EqvtPipePress = PipePress; - - Handle->Init(PipePress); - - ComputeConstans(); - - if (LoadFlag > 0) - { - - if (LoadAmount < MaxLoad * 0.45) - { - IncBrakeMult(); - IncBrakeMult(); - DecBrakeMult(); // TODO: przeinesiono do mover.cpp - if (LoadAmount < MaxLoad * 0.35) - DecBrakeMult(); - } - else - { - IncBrakeMult(); // TODO: przeinesiono do mover.cpp - if (LoadAmount >= MaxLoad * 0.55) - IncBrakeMult(); - } - } - - // taki mini automat - powinno byc ladnie dobrze :) - BrakeDelayFlag = bdelay_P; - if (TestFlag(BrakeDelays, bdelay_G) && !TestFlag(BrakeDelays, bdelay_R)) - BrakeDelayFlag = bdelay_G; - if (TestFlag(BrakeDelays, bdelay_R) && !TestFlag(BrakeDelays, bdelay_G)) - BrakeDelayFlag = bdelay_R; + else + BrakeCtrlPos = static_cast(Handle->GetPos(bh_RP)); /* - // disabled, as test mode is used in specific situations and not really a default - if (BrakeOpModes & bom_PS) - BrakeOpModeFlag = bom_PS; - else + // NOTE: disabled and left up to the driver, if there's any + MainSwitch( false ); + PantFront( true ); + PantRear( true ); + MainSwitch( true ); */ - BrakeOpModeFlag = bom_PN; + DirActive = 0; // Dir; //nastawnik kierunkowy - musi być ustawiane osobno! + DirAbsolute = DirActive * CabActive; // kierunek jazdy względem sprzęgów + LimPipePress = CntrlPipePress; - // yB: jesli pojazdy nie maja zadeklarowanych czasow, to wsadz z przepisow +-16,(6)% - std::array const DefBrakeTable{15, 4, 25, 25, 13, 3, 12, 2}; + Battery = BatteryStart != start_t::disabled; +} - for (int b = 1; b < 4; b++) - { - if (BrakeDelay[b] == 0) - BrakeDelay[b] = DefBrakeTable[b]; - BrakeDelay[b] = BrakeDelay[b] * (2.5 + Random(0.0, 0.2)) / 3.0; - } - - Hamulec->Init(PipePress, HighPipePress, LowPipePress, BrakePress, BrakeDelayFlag); +// the air and the brakes of a vehicle standing braked +void TMoverParameters::SetBraked() +{ + WriteLog("Braked"); + Volume = BrakeVVolume * MaxBrakePress[3]; + CompressedVolume = VeselVolume * MinCompressor * 0.55; /* - ScndPipePress = Compressor; + ScndPipePress = 5.1; */ - // WriteLogSS("OK=", BoolTo10(OK)); - // WriteLog(""); - - if (EIMCtrlType == 3) + ScndPipePress = InitialScndPipePress(5.1); + PipePress = LowPipePress; + PipeBrakePress = MaxBrakePress[3] * 0.5; + BrakePress = MaxBrakePress[3] * 0.5; + LocalBrakePosA = 0.0; + BrakeCtrlPos = static_cast(Handle->GetPos(bh_NP)); + LimPipePress = LowPipePress; + if (LocalBrake == TLocalBrake::ManualBrake || MBrake == true) { - for (auto idx = 0; idx < MainCtrlPosNo; ++idx) - { - if (UniCtrlList[idx].MaxCtrlVal > 0.0) - { - UniCtrlNoPowerPos = std::max(0, idx - 1); - break; - } - } + IncManualBrakeLevel(ManualBrakePosNo); } - - // security system - // by default place the magnet in the vehicle centre - if (SecuritySystem.MagnetLocation == 0) + if (SpringBrake.MaxBrakeForce > 0.0) { - SecuritySystem.MagnetLocation = Dim.L / 2 - 0.5; + SpringBrake.Activate = true; } - SecuritySystem.MagnetLocation = std::clamp(SecuritySystem.MagnetLocation, 0.0, Dim.L); - - return OK; } // ************************************************************************************************* @@ -14022,8 +14720,26 @@ bool TMoverParameters::SendCtrlToNext(std::string const &CtrlCommand, double con // jakiejś zmiany (np. IncMainCtrl) lepiej wywołać funkcję, czy od razu wysłać komendę. bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype) { - bool OK{false}; + // the group of the command sets OK; a command none of them knows isn't done + if (bool OK{false}; RunControllerCommand(Command, CValue1, CValue2, Couplertype, OK) || RunRelaysCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunCabCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunBrakeCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunBrakeEquipmentCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunAuxiliariesCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunPumpsCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunBlowersCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunPowerCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunDoorsCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunLoadCommand(Command, CValue1, CValue2, Couplertype, OK)) + { + return OK; // dla true komenda będzie usunięta, dla false wykonana ponownie + } + return false; +} +// RunCommand() for the controllers; returns whether the command is one of them +bool TMoverParameters::RunControllerCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ if (Command == "MainCtrl") { // sent as MainCtrlPosForCoupled(), passed on unchanged @@ -14063,7 +14779,102 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do eimic_real = CValue1; OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "Brake") // youBy - jak sie EP hamuje, to trza sygnal wyslac... + else + { + return false; + } + return true; +} + +// RunCommand() for the direction, the automatic start and the current relays; returns whether the command is one of them +bool TMoverParameters::RunRelaysCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "Direction") + { + DirActive = static_cast(floor(CValue1)); + DirAbsolute = DirActive * CabActive; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "AutoRelaySwitch") + { + if (CValue1 == 1 && AutoRelayType == 2) + AutoRelayFlag = true; + else + AutoRelayFlag = false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "MaxCurrentSwitch") + { + MaxCurrentSwitch(CValue1 == 1, range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "MinCurrentSwitch") + { + OK = MinCurrentSwitch(CValue1 == 1); + } + /*test komend oddzialywujacych na tabor*/ + else + { + return false; + } + return true; +} + +// RunCommand() for the cab and the speed control; returns whether the command is one of them +bool TMoverParameters::RunCabCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "CabActivisation") + { + // OK:=Power>0.01; + switch (static_cast(CValue1 * CValue2)) + { // CValue2 ma zmieniany znak przy niezgodności sprzęgów + case 1: + { + CabActive = 1; + break; + } + case -1: + { + CabActive = -1; + break; + } + default: + { + CabActive = 0; // gdy CValue1==0 + break; + } + } + if (PulleeMode) + { + // a vehicle prepared for hauling takes no cab, the command only passes through it + CabActive = 0; + } + DirAbsolute = DirActive * CabActive; + CabMaster = false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "SpeedCntrl") + { + if (EngineType == TEngineType::ElectricInductionMotor || SpeedCtrl) + SpeedCtrlValue = static_cast(round(CValue1)); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "SpeedCtrlUnit.Parking") + { + SpeedCtrlUnit.Parking = static_cast(CValue1); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + { + return false; + } + return true; +} + +// RunCommand() for the train brake, the releaser and the emergency brake; returns whether the command is one of them +bool TMoverParameters::RunBrakeCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "Brake") // youBy - jak sie EP hamuje, to trza sygnal wyslac... { if (CValue1 < 0.001) DynamicBrakeEMUStatus = true; @@ -14086,7 +14897,119 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do OK = BrakeReleaser(static_cast(Round(CValue1))); // samo się przesyła dalej // OK:=SendCtrlToNext(command,CValue1,CValue2); //to robiło kaskadę 2^n } - else if (Command == "WaterPumpBreakerSwitch") + else if (Command == "Emergency_brake") + { + if (RadiostopSwitch(floor(CValue1) == 1)) // YB: czy to jest potrzebne? + OK = true; + else + OK = false; + } + else + { + return false; + } + return true; +} + +// RunCommand() for the brake delays, the spring brake, the sand and the cab signalling; returns whether the command is one of them +bool TMoverParameters::RunBrakeEquipmentCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "BrakeDelay") + { + if (auto const brakesetting = static_cast(std::floor(CValue1)); true == Hamulec->SetBDF(brakesetting)) + { + BrakeDelayFlag = brakesetting; + OK = true; + } + else + { + OK = false; + } + SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "SpringBrakeActivate") + { + if (Power24vIsAvailable || Power110vIsAvailable) + { + SpringBrake.Activate = CValue1 > 0; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + OK = true; + } + + else if (Command == "Sandbox") + { + OK = Sandbox(CValue1 == 1, range_t::local); + } + else if (Command == "CabSignal") /*SHP,Indusi*/ + { // Ra: to powinno działać tylko w członie obsadzonym + SecuritySystem.set_cabsignal(); + // else OK:=false; + OK = true; // true, gdy można usunąć komendę + } + /*naladunek/rozladunek*/ + // TODO: have these commands leverage load exchange system instead + // TODO: CValue1 defines amount to load/unload + else + { + return false; + } + return true; +} + +// RunCommand() for the heating, the converter, the battery and the compressor; returns whether the command is one of them +bool TMoverParameters::RunAuxiliariesCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "HeatingSwitch") + { + HeatingSwitch_(CValue1 > 0.0); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "ConverterSwitch") /*NBMX*/ + { + if (ConverterStart == start_t::manual) + { + ConverterAllow = CValue1 > 0.0; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "BatterySwitch") /*NBMX*/ + { + // the battery of a vehicle prepared for hauling (PulleeMode) stays off + if (BatteryStart == start_t::manual && (false == PulleeMode || CValue1 <= 0.0)) + { + Battery = CValue1 > 0.0; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + // else if command='EpFuseSwitch' then {NBMX} + // begin + // if (CValue1=1) then EpFuse:=true + // else if (CValue1=0) then EpFuse:=false; + // OK:=SendCtrlToNext(command,CValue1,CValue2); + // end + else if (Command == "CompressorSwitch") /*NBMX*/ + { + CompressorSwitch(CValue1 == 1, range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "CompressorPreset") + { + CompressorListPos = std::clamp(static_cast(CValue1), 0, CompressorListPosNo); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + { + return false; + } + return true; +} + +// RunCommand() for the water, fuel and oil pumps and the water heater; returns whether the command is one of them +bool TMoverParameters::RunPumpsCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "WaterPumpBreakerSwitch") { /* if( FuelPump.start_type != start::automatic ) { @@ -14187,7 +15110,17 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "MotorBlowersFrontSwitch") + else + { + return false; + } + return true; +} + +// RunCommand() for the motor blowers and the compartment lights; returns whether the command is one of them +bool TMoverParameters::RunBlowersCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "MotorBlowersFrontSwitch") { if (MotorBlowers[end::front].start_type != start_t::manual && MotorBlowers[end::front].start_type != start_t::manualwithautofallback) { @@ -14243,176 +15176,26 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "MainSwitch") + else + { + return false; + } + return true; +} + +// RunCommand() for the line breaker, the relays and the pantographs; returns whether the command is one of them +bool TMoverParameters::RunPowerCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "MainSwitch") { MainSwitch_(CValue1 > 0.0); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "HeatingSwitch") - { - HeatingSwitch_(CValue1 > 0.0); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "Direction") - { - DirActive = static_cast(floor(CValue1)); - DirAbsolute = DirActive * CabActive; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "CabActivisation") - { - // OK:=Power>0.01; - switch (static_cast(CValue1 * CValue2)) - { // CValue2 ma zmieniany znak przy niezgodności sprzęgów - case 1: - { - CabActive = 1; - break; - } - case -1: - { - CabActive = -1; - break; - } - default: - { - CabActive = 0; // gdy CValue1==0 - break; - } - } - if (PulleeMode) - { - // a vehicle prepared for hauling takes no cab, the command only passes through it - CabActive = 0; - } - DirAbsolute = DirActive * CabActive; - CabMaster = false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "AutoRelaySwitch") - { - if (CValue1 == 1 && AutoRelayType == 2) - AutoRelayFlag = true; - else - AutoRelayFlag = false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } else if (Command == "RelayReset") { RelayReset(static_cast(CValue1), range_t::local); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "ConverterSwitch") /*NBMX*/ - { - if (ConverterStart == start_t::manual) - { - ConverterAllow = CValue1 > 0.0; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "BatterySwitch") /*NBMX*/ - { - // the battery of a vehicle prepared for hauling (PulleeMode) stays off - if (BatteryStart == start_t::manual && (false == PulleeMode || CValue1 <= 0.0)) - { - Battery = CValue1 > 0.0; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - // else if command='EpFuseSwitch' then {NBMX} - // begin - // if (CValue1=1) then EpFuse:=true - // else if (CValue1=0) then EpFuse:=false; - // OK:=SendCtrlToNext(command,CValue1,CValue2); - // end - else if (Command == "CompressorSwitch") /*NBMX*/ - { - CompressorSwitch(CValue1 == 1, range_t::local); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "CompressorPreset") - { - CompressorListPos = std::clamp(static_cast(CValue1), 0, CompressorListPosNo); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorPermit") - { - - auto const leftside{CValue2 > 0 ? 1 : 2}; - - if (auto const rightside{3 - leftside}; std::abs(static_cast(CValue1)) & rightside) - { - PermitDoors_(side::right, CValue1 > 0); - } - if (std::abs(static_cast(CValue1)) & leftside) - { - PermitDoors_(side::left, CValue1 > 0); - } - - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorOpen") /*NBMX*/ - { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów - // ignore remote command if the door is only operated locally - if ((Doors.open_control == control_t::conductor || Doors.open_control == control_t::driver || Doors.open_control == control_t::mixed) && (Power24vIsAvailable || Power110vIsAvailable)) - { - - auto const leftside{CValue2 > 0 ? 1 : 2}; - - if (auto const rightside{3 - leftside}; static_cast(CValue1) & rightside) - { - Doors.instances[side::right].remote_open = true; - Doors.instances[side::right].remote_close = false; - } - if (static_cast(CValue1) & leftside) - { - Doors.instances[side::left].remote_open = true; - Doors.instances[side::left].remote_close = false; - } - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorClose") /*NBMX*/ - { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów - // ignore remote command if the door is only operated locally - if ((Doors.close_control == control_t::conductor || Doors.close_control == control_t::driver || Doors.close_control == control_t::mixed) && (Power24vIsAvailable || Power110vIsAvailable)) - { - - auto const leftside{CValue2 > 0 ? 1 : 2}; - - if (auto const rightside{3 - leftside}; static_cast(CValue1) & rightside) - { - Doors.instances[side::right].remote_close = true; - Doors.instances[side::right].remote_open = false; - } - if (static_cast(CValue1) & leftside) - { - Doors.instances[side::left].remote_close = true; - Doors.instances[side::left].remote_open = false; - } - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorLock") - { - Doors.lock_enabled = CValue1 == 1 ? true : false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorStep") - { - Doors.step_enabled = CValue1 == 1 ? true : false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorMode") - { - Doors.remote_only = CValue1 == 1 ? true : false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DepartureSignal") - { - DepartureSignal = CValue1 == 1 ? true : false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } else if (Command == "PantValve") // Winger 160204 { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów auto const inputend{(static_cast(CValue1) & 0x80) != 0 ? 1 : 0}; @@ -14437,63 +15220,94 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do DropAllPantographs(CValue1 == 1, range_t::local); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "MaxCurrentSwitch") + else { - MaxCurrentSwitch(CValue1 == 1, range_t::local); + return false; + } + return true; +} + +// RunCommand() for the doors and the departure signal; returns whether the command is one of them +bool TMoverParameters::RunDoorsCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "DoorPermit") + { + DoorPermitCommand(CValue1, CValue2); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "MinCurrentSwitch") + else if (Command == "DoorOpen" || Command == "DoorClose") /*NBMX*/ + { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów + DoorRemoteCommand(Command == "DoorOpen", CValue1, CValue2); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "DoorLock") { - OK = MinCurrentSwitch(CValue1 == 1); + Doors.lock_enabled = CValue1 == 1 ? true : false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - /*test komend oddzialywujacych na tabor*/ - else if (Command == "SetDamage") + else if (Command == "DoorStep") { - if (CValue2 == 1) - OK = SetFlag(DamageFlag, static_cast(floor(CValue1))); - if (CValue2 == -1) - { - auto const derailed{TestFlag(DamageFlag, dtrain_out)}; - OK = SetFlag(DamageFlag, static_cast(-floor(CValue1))); - // taking the derailment off puts the vehicle back on the rails, with what the criteria of derailment held - if (derailed && false == TestFlag(DamageFlag, dtrain_out)) - rerail(); - } + Doors.step_enabled = CValue1 == 1 ? true : false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "Emergency_brake") + else if (Command == "DoorMode") { - if (RadiostopSwitch(floor(CValue1) == 1)) // YB: czy to jest potrzebne? - OK = true; - else - OK = false; + Doors.remote_only = CValue1 == 1 ? true : false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "BrakeDelay") + else if (Command == "DepartureSignal") { - if (auto const brakesetting = static_cast(std::floor(CValue1)); true == Hamulec->SetBDF(brakesetting)) - { - BrakeDelayFlag = brakesetting; - OK = true; - } - else - { - OK = false; - } - SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + DepartureSignal = CValue1 == 1 ? true : false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "Sandbox") + else { - OK = Sandbox(CValue1 == 1, range_t::local); + return false; } - else if (Command == "CabSignal") /*SHP,Indusi*/ - { // Ra: to powinno działać tylko w członie obsadzonym - SecuritySystem.set_cabsignal(); - // else OK:=false; - OK = true; // true, gdy można usunąć komendę + return true; +} + +// the doors' permits, on the sides the command names: CValue1 the sides, negative to take the permit back, CValue2 the +// direction the command comes from +void TMoverParameters::DoorPermitCommand(double const CValue1, double const CValue2) +{ + auto const leftside{CValue2 > 0 ? 1 : 2}; + if (auto const rightside{3 - leftside}; std::abs(static_cast(CValue1)) & rightside) + { + PermitDoors_(side::right, CValue1 > 0); } - /*naladunek/rozladunek*/ - // TODO: have these commands leverage load exchange system instead - // TODO: CValue1 defines amount to load/unload - else if (issection("Load=", Command)) + if (std::abs(static_cast(CValue1)) & leftside) + { + PermitDoors_(side::left, CValue1 > 0); + } +} + +// the doors opened or closed from afar on the sides the command names, unless they're only worked locally +void TMoverParameters::DoorRemoteCommand(bool const Open, double const CValue1, double const CValue2) +{ + using enum control_t; + if (auto const doorcontrol{Open ? Doors.open_control : Doors.close_control}; + (doorcontrol != conductor && doorcontrol != driver && doorcontrol != mixed) || (false == Power24vIsAvailable && false == Power110vIsAvailable)) + { + return; + } + auto const leftside{CValue2 > 0 ? 1 : 2}; + if (auto const rightside{3 - leftside}; static_cast(CValue1) & rightside) + { + Doors.instances[side::right].remote_open = Open; + Doors.instances[side::right].remote_close = false == Open; + } + if (static_cast(CValue1) & leftside) + { + Doors.instances[side::left].remote_open = Open; + Doors.instances[side::left].remote_close = false == Open; + } +} + +// RunCommand() for the load and the damage; returns whether the command is one of them +bool TMoverParameters::RunLoadCommand(std::string const &Command, double CValue1, double CValue2, int const /*Couplertype*/, bool &OK) +{ + if (issection("Load=", Command)) { OK = false; // będzie powtarzane aż się załaduje if (Vel < 0.1 // tolerance margin for small vehicle movements in the consist @@ -14530,29 +15344,24 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do LastLoadChangeTime = 0.0; } } - else if (Command == "SpeedCntrl") + else if (Command == "SetDamage") { - if (EngineType == TEngineType::ElectricInductionMotor || SpeedCtrl) - SpeedCtrlValue = static_cast(round(CValue1)); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "SpeedCtrlUnit.Parking") - { - SpeedCtrlUnit.Parking = static_cast(CValue1); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "SpringBrakeActivate") - { - if (Power24vIsAvailable || Power110vIsAvailable) + if (CValue2 == 1) + OK = SetFlag(DamageFlag, static_cast(floor(CValue1))); + if (CValue2 == -1) { - SpringBrake.Activate = CValue1 > 0; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + auto const derailed{TestFlag(DamageFlag, dtrain_out)}; + OK = SetFlag(DamageFlag, static_cast(-floor(CValue1))); + // taking the derailment off puts the vehicle back on the rails, with what the criteria of derailment held + if (derailed && false == TestFlag(DamageFlag, dtrain_out)) + rerail(); } - else - OK = true; } - - return OK; // dla true komenda będzie usunięta, dla false wykonana ponownie + else + { + return false; + } + return true; } // ************************************************************************************************* diff --git a/McZapkie/hamulce.cpp b/McZapkie/hamulce.cpp index b30372e5e..4a2029af5 100644 --- a/McZapkie/hamulce.cpp +++ b/McZapkie/hamulce.cpp @@ -855,25 +855,7 @@ void TESt::CheckState(double const BCP, double & /*dV1*/) if ((BrakeStatus & b_hld) == b_hld) { - - if (VVP + 0.003 + BCP / BVM < CVP) - { - // hamowanie stopniowe - BrakeStatus |= b_on; - } - else - { - if (VVP + BCP / BVM > CVP) - { - // zatrzymanie napelaniania - BrakeStatus &= ~b_on; - } - if (VVP - 0.003 + (BCP - 0.1) / BVM > CVP) - { - // luzowanie - BrakeStatus &= ~(b_on | b_hld); - } - } + CheckStateHeld(BCP, VVP, CVP); } else { @@ -908,6 +890,29 @@ void TESt::CheckState(double const BCP, double & /*dV1*/) } } +// the state of a valve holding: braking on in steps, the filling stopped, or released +void TESt::CheckStateHeld(double const BCP, double const VVP, double const CVP) +{ + if (VVP + 0.003 + BCP / BVM < CVP) + { + // hamowanie stopniowe + BrakeStatus |= b_on; + } + else + { + if (VVP + BCP / BVM > CVP) + { + // zatrzymanie napelaniania + BrakeStatus &= ~b_on; + } + if (VVP - 0.003 + (BCP - 0.1) / BVM > CVP) + { + // luzowanie + BrakeStatus &= ~(b_on | b_hld); + } + } +} + /// /// Returns the dimensionless opening factor of the ZS-filling slide valve /// (control reservoir <-> brake pipe) for the current pre-chamber/auxiliary @@ -1164,33 +1169,7 @@ double TEStEP2::GetPF(double const PP, double const dt, double const Vel) // odluzniacz CheckReleaser(dt); - // sprawdzanie stanu - if ((BrakeStatus & b_hld) == b_hld && BCP > 0.25) - { - if (VVP + 0.003 + BCP / BVM < CVP - 0.12) - BrakeStatus |= b_on; // hamowanie stopniowe; - else if (VVP - 0.003 + BCP / BVM > CVP - 0.12) - BrakeStatus &= ~(b_on | b_hld); // luzowanie; - else if (VVP + BCP / BVM > CVP - 0.12) - BrakeStatus &= ~b_on; // zatrzymanie napelaniania; - } - else if (VVP + 0.10 < CVP - 0.12 && BCP < 0.25) // poczatek hamowania - { - // if ((BrakeStatus & 1) == 0) - //{ - // // ValveRes.CreatePress(0.5*VVP); //110115 - konsultacje warszawa1 - // // SoundFlag:=SoundFlag or sf_Acc; - // // ValveRes.Act; - //} - BrakeStatus |= b_on | b_hld; - } - else if (VVP + BCP / BVM < CVP - 0.12 && BCP > 0.25) // zatrzymanie luzowanie - BrakeStatus |= b_hld; - - if ((BrakeStatus & b_hld) == 0) - { - SoundFlag |= sf_CylU; - } + UpdateStatusEP2(BCP, VVP, CVP); // przeplyw ZS <-> PG if (BVP < CVP - 0.2 || BrakeStatus != b_off || BCP > 0.25) @@ -1258,6 +1237,38 @@ double TEStEP2::GetPF(double const PP, double const dt, double const Vel) return result; } +// the state of the valve: braking in steps, holding or releasing, the start of braking +void TEStEP2::UpdateStatusEP2(double const BCP, double const VVP, double const CVP) +{ + // sprawdzanie stanu + if ((BrakeStatus & b_hld) == b_hld && BCP > 0.25) + { + if (VVP + 0.003 + BCP / BVM < CVP - 0.12) + BrakeStatus |= b_on; // hamowanie stopniowe; + else if (VVP - 0.003 + BCP / BVM > CVP - 0.12) + BrakeStatus &= ~(b_on | b_hld); // luzowanie; + else if (VVP + BCP / BVM > CVP - 0.12) + BrakeStatus &= ~b_on; // zatrzymanie napelaniania; + } + else if (VVP + 0.10 < CVP - 0.12 && BCP < 0.25) // poczatek hamowania + { + // if ((BrakeStatus & 1) == 0) + //{ + // // ValveRes.CreatePress(0.5*VVP); //110115 - konsultacje warszawa1 + // // SoundFlag:=SoundFlag or sf_Acc; + // // ValveRes.Act; + //} + BrakeStatus |= b_on | b_hld; + } + else if (VVP + BCP / BVM < CVP - 0.12 && BCP > 0.25) // zatrzymanie luzowanie + BrakeStatus |= b_hld; + + if ((BrakeStatus & b_hld) == 0) + { + SoundFlag |= sf_CylU; + } +} + /// /// Recomputes the load-weighing coefficient LoadC for the current vehicle /// mass (linear between TareBP/MaxBP for TareM..LoadM, capped at 1.0). @@ -1672,58 +1683,8 @@ double TLSt::GetPF(double const PP, double const dt, double const Vel) double dV{0.0}; double dV1{0.0}; - // sprawdzanie stanu - // NOTE: partial copypaste from checkstate() of base class - // TODO: clean inheritance for checkstate() and checkreleaser() and reuse these instead of manual copypaste - if ((BrakeStatus & b_hld) == b_hld && BCP > 0.25) - { - if (VVP + 0.003 + BCP / BVM < CVP) - { - // hamowanie stopniowe - BrakeStatus |= b_on; - } - else if (VVP - 0.003 + (BCP - 0.1) / BVM > CVP) - { - // luzowanie - BrakeStatus &= ~(b_on | b_hld); - } - else if (VVP + BCP / BVM > CVP) - { - // zatrzymanie napelaniania - BrakeStatus &= ~b_on; - } - } - else if (VVP + 0.10 < CVP && BCP < 0.25) - { - // poczatek hamowania - if ((BrakeStatus & b_hld) == b_off) - { - SoundFlag |= sf_Acc; - } - BrakeStatus |= b_on | b_hld; - } - else if (VVP + (BCP - 0.1) / BVM < CVP && (CVP - VVP) * BVM > 0.25 && BCP > 0.25) - { - // zatrzymanie luzowanie - BrakeStatus |= b_hld; - } - if ((BrakeStatus & b_hld) == 0) - { - SoundFlag |= sf_CylU; - } - // equivalent of checkreleaser() in the base class? - if (bool is_releasing = BrakeStatus & b_rls || UniversalFlag & TUniversalBrake::ub_Release; is_releasing) - { - if (CVP < 0.0) - { - BrakeStatus &= ~b_rls; - } - else - { // 008 - dV = PF1(CVP, BCP, 0.024) * dt; - CntrlRes->Flow(dV); - } - } + UpdateStatusLSt(BCP, VVP, CVP); + ReleaserLSt(BCP, CVP, dt); // przeplyw ZS <-> PG double temp; @@ -1770,6 +1731,87 @@ double TLSt::GetPF(double const PP, double const dt, double const Vel) // if Vel>55 then temp:=0.72 else // temp:=1;{R} // cisnienie PP + CylinderFlowLSt(BCP, BVP, CVP, dt, Vel); + + ImplsRes->Act(); + ValveRes->Act(); + BrakeCyl->Act(); + BrakeRes->Act(); + CntrlRes->Act(); + // LBP:=ValveRes->P(); + // ValveRes.CreatePress(ImplsRes->P()); + return result; +} + +// the state of the valve: braking in steps, holding or releasing, the start of braking +void TLSt::UpdateStatusLSt(double const BCP, double const VVP, double const CVP) +{ + // sprawdzanie stanu + // NOTE: partial copypaste from checkstate() of base class + // TODO: clean inheritance for checkstate() and checkreleaser() and reuse these instead of manual copypaste + if ((BrakeStatus & b_hld) == b_hld && BCP > 0.25) + { + if (VVP + 0.003 + BCP / BVM < CVP) + { + // hamowanie stopniowe + BrakeStatus |= b_on; + } + else if (VVP - 0.003 + (BCP - 0.1) / BVM > CVP) + { + // luzowanie + BrakeStatus &= ~(b_on | b_hld); + } + else if (VVP + BCP / BVM > CVP) + { + // zatrzymanie napelaniania + BrakeStatus &= ~b_on; + } + } + else if (VVP + 0.10 < CVP && BCP < 0.25) + { + // poczatek hamowania + if ((BrakeStatus & b_hld) == b_off) + { + SoundFlag |= sf_Acc; + } + BrakeStatus |= b_on | b_hld; + } + else if (VVP + (BCP - 0.1) / BVM < CVP && (CVP - VVP) * BVM > 0.25 && BCP > 0.25) + { + // zatrzymanie luzowanie + BrakeStatus |= b_hld; + } + if ((BrakeStatus & b_hld) == 0) + { + SoundFlag |= sf_CylU; + } +} + +// the releaser, or the universal button set to release, letting the control reservoir out into the impulse chamber +void TLSt::ReleaserLSt(double const BCP, double const CVP, double const dt) +{ + double dV; + // equivalent of checkreleaser() in the base class? + if (bool is_releasing = BrakeStatus & b_rls || UniversalFlag & TUniversalBrake::ub_Release; is_releasing) + { + if (CVP < 0.0) + { + BrakeStatus &= ~b_rls; + } + else + { // 008 + dV = PF1(CVP, BCP, 0.024) * dt; + CntrlRes->Flow(dV); + } + } +} + +// the cylinders filled from the auxiliary reservoir or let out to the pressure the relay is set to: by the pilot +// pressure, the anti-slip brake and the rapid setting, at least the local brake's +void TLSt::CylinderFlowLSt(double const BCP, double const BVP, double const CVP, double const dt, double const Vel) +{ + double dV; + double temp; RapidTemp = RapidTemp + (RM * int(Vel > 55 && (BrakeDelayFlag & bdelay_R) == bdelay_R) - RapidTemp) * dt / 2; temp = 1 - RapidTemp; if (EDFlag > 0.2) @@ -1795,15 +1837,6 @@ double TLSt::GetPF(double const PP, double const dt, double const Vel) dV = 0; BrakeRes->Flow(dV); BrakeCyl->Flow(-dV); - - ImplsRes->Act(); - ValveRes->Act(); - BrakeCyl->Act(); - BrakeRes->Act(); - CntrlRes->Act(); - // LBP:=ValveRes->P(); - // ValveRes.CreatePress(ImplsRes->P()); - return result; } /// @@ -1916,33 +1949,7 @@ double TEStED::GetPF(double const PP, double const dt, double const Vel) nastG = BrakeDelayFlag & bdelay_G; - // sprawdzanie stanu - if (BCP < 0.25 && VVP + 0.08 > CVP) - Przys_blok = false; - - // sprawdzanie stanu - if (VVP + 0.002 + BCP / BVM < CVP - 0.05 && Przys_blok) - BrakeStatus |= b_on | b_hld; // hamowanie stopniowe; - else if (VVP - 0.002 + (BCP - 0.1) / BVM > CVP - 0.05) - BrakeStatus &= ~(b_on | b_hld); // luzowanie; - else if (VVP + BCP / BVM > CVP - 0.05) - BrakeStatus &= ~b_on; // zatrzymanie napelaniania; - else if (VVP + (BCP - 0.1) / BVM < CVP - 0.05 && BCP > 0.25) // zatrzymanie luzowania - BrakeStatus |= b_hld; - - // poczatek hamowania - if (VVP + 0.10 < CVP && BCP < 0.25 && !Przys_blok) - { - ValveRes->CreatePress(0.75 * VVP); - SoundFlag |= sf_Acc; - ValveRes->Act(); - Przys_blok = true; - } - - if (BCP > 0.5) - Zamykajacy = true; - else if (VVP - 0.6 < MPP) - Zamykajacy = false; + UpdateStatus(BCP, VVP, CVP, MPP); if ((BrakeStatus & b_rls) == b_rls) { @@ -1963,60 +1970,9 @@ double TEStED::GetPF(double const PP, double const dt, double const Vel) ImplsRes->Flow(-dv); BrakeRes->Flow(dv); - // przeplyw testowy miedzypojemnosci - if (MPP < CVP - 0.3) - temp = Nozzles[4]; - else if (BCP < 0.5) - if (Zamykajacy) - temp = Nozzles[8]; // 1.25; - else - temp = Nozzles[7]; - else - temp = 0; - dv = PF(MPP, VVP, temp); + Miedzypoj->Flow(IntermediateFlow(BCP, VVP, CVP, MPP, BVP, nastG) * dt * 0.15); - if (MPP < CVP - 0.17) - temp = 0; - else if (MPP > CVP - 0.08) - temp = Nozzles[5]; - else - temp = Nozzles[6]; - dv = dv + PF(MPP, CVP, temp); - - if (MPP - 0.05 > BVP) - dv = dv + PF(MPP - 0.05, BVP, Nozzles[10] * nastG + (1 - nastG) * Nozzles[9]); - if (MPP > VVP) - dv = dv + PF(MPP, VVP, 0.02); - Miedzypoj->Flow(dv * dt * 0.15); - - RapidTemp = RapidTemp + (RM * int(Vel > RV && (BrakeDelayFlag & bdelay_R) == bdelay_R) - RapidTemp) * dt / 2; - temp = std::max(1 - RapidTemp, 0.001); - // if EDFlag then temp:=1000; - // temp:=temp/(1-); - - // powtarzacz — podwojny zawor zwrotny - temp = std::max(LoadC * BCP / temp * std::clamp(1 - EDFlag, 0., 1.), LBP); - - if ((UniversalFlag & TUniversalBrake::ub_AntiSlipBrake) > 0) - temp = std::max(temp, ASBP); - - double speed = 1; - if (ASBP < 0.1 && (BrakeStatus & b_asb_unbrake) == b_asb_unbrake) - { - temp = 0; - speed = 3; - } - - if (BrakeCyl->P() > temp) - dv = -PFVd(BrakeCyl->P(), 0, 0.05 * SizeBC * speed, temp) * dt; - else if (BrakeCyl->P() < temp && (BrakeStatus & b_asb) == 0) - dv = PFVa(BVP, BrakeCyl->P(), 0.05 * SizeBC, temp) * dt; - else - dv = 0; - - BrakeCyl->Flow(dv); - if (dv > 0) - BrakeRes->Flow(-dv); + CylinderFlow(BCP, BVP, dt, Vel); // przeplyw ZS <-> PG if (MPP < CVP - 0.17) @@ -2051,6 +2007,107 @@ double TEStED::GetPF(double const PP, double const dt, double const Vel) return dv - dV1; } +// the state of the valve: braking in steps, holding or releasing, the accelerator at the start of braking, and the +// closing valve +void TEStED::UpdateStatus(double const BCP, double const VVP, double const CVP, double const MPP) +{ + // sprawdzanie stanu + if (BCP < 0.25 && VVP + 0.08 > CVP) + Przys_blok = false; + + // sprawdzanie stanu + if (VVP + 0.002 + BCP / BVM < CVP - 0.05 && Przys_blok) + BrakeStatus |= b_on | b_hld; // hamowanie stopniowe; + else if (VVP - 0.002 + (BCP - 0.1) / BVM > CVP - 0.05) + BrakeStatus &= ~(b_on | b_hld); // luzowanie; + else if (VVP + BCP / BVM > CVP - 0.05) + BrakeStatus &= ~b_on; // zatrzymanie napelaniania; + else if (VVP + (BCP - 0.1) / BVM < CVP - 0.05 && BCP > 0.25) // zatrzymanie luzowania + BrakeStatus |= b_hld; + + // poczatek hamowania + if (VVP + 0.10 < CVP && BCP < 0.25 && !Przys_blok) + { + ValveRes->CreatePress(0.75 * VVP); + SoundFlag |= sf_Acc; + ValveRes->Act(); + Przys_blok = true; + } + + if (BCP > 0.5) + Zamykajacy = true; + else if (VVP - 0.6 < MPP) + Zamykajacy = false; +} + +// the flow into the intermediate reservoir from the pipe and the control reservoir, less the flow filling the auxiliary one +double TEStED::IntermediateFlow(double const BCP, double const VVP, double const CVP, double const MPP, double const BVP, double const nastG) const +{ + double dv; + double temp; + // przeplyw testowy miedzypojemnosci + if (MPP < CVP - 0.3) + temp = Nozzles[4]; + else if (BCP < 0.5) + if (Zamykajacy) + temp = Nozzles[8]; // 1.25; + else + temp = Nozzles[7]; + else + temp = 0; + dv = PF(MPP, VVP, temp); + + if (MPP < CVP - 0.17) + temp = 0; + else if (MPP > CVP - 0.08) + temp = Nozzles[5]; + else + temp = Nozzles[6]; + dv = dv + PF(MPP, CVP, temp); + + if (MPP - 0.05 > BVP) + dv = dv + PF(MPP - 0.05, BVP, Nozzles[10] * nastG + (1 - nastG) * Nozzles[9]); + if (MPP > VVP) + dv = dv + PF(MPP, VVP, 0.02); + return dv; +} + +// the cylinders filled or let out to the pressure the relay is set to: by the pilot pressure and the load, at least the +// local brake's, the anti-slip brake's, faster at the rapid setting +void TEStED::CylinderFlow(double const BCP, double const BVP, double const dt, double const Vel) +{ + double dv; + double temp; + RapidTemp = RapidTemp + (RM * int(Vel > RV && (BrakeDelayFlag & bdelay_R) == bdelay_R) - RapidTemp) * dt / 2; + temp = std::max(1 - RapidTemp, 0.001); + // if EDFlag then temp:=1000; + // temp:=temp/(1-); + + // powtarzacz — podwojny zawor zwrotny + temp = std::max(LoadC * BCP / temp * std::clamp(1 - EDFlag, 0., 1.), LBP); + + if ((UniversalFlag & TUniversalBrake::ub_AntiSlipBrake) > 0) + temp = std::max(temp, ASBP); + + double speed = 1; + if (ASBP < 0.1 && (BrakeStatus & b_asb_unbrake) == b_asb_unbrake) + { + temp = 0; + speed = 3; + } + + if (BrakeCyl->P() > temp) + dv = -PFVd(BrakeCyl->P(), 0, 0.05 * SizeBC * speed, temp) * dt; + else if (BrakeCyl->P() < temp && (BrakeStatus & b_asb) == 0) + dv = PFVa(BVP, BrakeCyl->P(), 0.05 * SizeBC, temp) * dt; + else + dv = 0; + + BrakeCyl->Flow(dv); + if (dv > 0) + BrakeRes->Flow(-dv); +} + /// /// Initialises the EStED: chains TLSt::Init, sizes Miedzypoj (5 l), pre-charges /// pressures, computes BVM with a 0.05 bar offset on HPP, configures the @@ -2509,25 +2566,7 @@ void TKE::CheckState(double const BCP, double & /*dV1*/) if ((BrakeStatus & b_hld) == b_hld) { - - if (VVP + 0.003 + BCP / BVM < CVP) - { - // hamowanie stopniowe; - BrakeStatus |= b_on; - } - else - { - if (VVP + BCP / BVM > CVP) - { - // zatrzymanie napelaniania; - BrakeStatus &= ~b_on; - } - if (VVP - 0.003 + BCP / BVM > CVP) - { - // luzowanie; - BrakeStatus &= ~(b_on | b_hld); - } - } + CheckStateHeld(BCP, VVP, CVP); } else { @@ -2562,6 +2601,29 @@ void TKE::CheckState(double const BCP, double & /*dV1*/) } } +// the state of a valve holding: braking on in steps, the filling stopped, or released +void TKE::CheckStateHeld(double const BCP, double const VVP, double const CVP) +{ + if (VVP + 0.003 + BCP / BVM < CVP) + { + // hamowanie stopniowe; + BrakeStatus |= b_on; + } + else + { + if (VVP + BCP / BVM > CVP) + { + // zatrzymanie napelaniania; + BrakeStatus &= ~b_on; + } + if (VVP - 0.003 + BCP / BVM > CVP) + { + // luzowanie; + BrakeStatus &= ~(b_on | b_hld); + } + } +} + /// /// Returns the KE ZS-filling slide valve opening factor: closed once /// any pneumatic braking is requested, slightly attenuated when the @@ -2681,6 +2743,36 @@ double TKE::GetPF(double const PP, double const dt, double const Vel) BrakeRes->Flow(dv); ImplsRes->Flow(-dv); + IMP = CylinderFlowKE(IMP, BCP, BVP, Vel, dt); + + // przeplyw ZP <-> rozdzielacz + temp = BVs(IMP); + // if(BrakeStatus and b_hld)=b_off then + if (IMP < 0.25 || VVP + 0.05 > BVP) + dv = PF(BVP, VVP, 0.02 * SizeBR * temp / 1.87) * dt; + else + dv = 0; + BrakeRes->Flow(dv); + dV1 = dV1 + dv * 0.96; + ValveRes->Flow(-0.04 * dv); + // przeplyw PG <-> rozdzielacz + dv = PF(PP, VVP, 0.01) * dt; + ValveRes->Flow(-dv); + + ValveRes->Act(); + BrakeCyl->Act(); + BrakeRes->Act(); + CntrlRes->Act(); + ImplsRes->Act(); + return dv - dV1; +} + +// the cylinders filled from the auxiliary reservoir or let out to the pressure of the impulse chamber IMP, by the load +// and the rapid setting, at least the local brake's and the anti-slip brake's; returns that pressure +double TKE::CylinderFlowKE(double IMP, double const BCP, double const BVP, double const Vel, double const dt) +{ + double dv; + double temp; // rapid auto const &frictionmaterial{*FM}; if (auto const &frictionmaterialtype{typeid(frictionmaterial)}; !(frictionmaterialtype == typeid(TDisk1) || frictionmaterialtype == typeid(TDisk2))) // jesli zeliwo to schodz @@ -2715,27 +2807,7 @@ double TKE::GetPF(double const PP, double const dt, double const Vel) dv = 0; BrakeRes->Flow(-dv); BrakeCyl->Flow(+dv); - - // przeplyw ZP <-> rozdzielacz - temp = BVs(IMP); - // if(BrakeStatus and b_hld)=b_off then - if (IMP < 0.25 || VVP + 0.05 > BVP) - dv = PF(BVP, VVP, 0.02 * SizeBR * temp / 1.87) * dt; - else - dv = 0; - BrakeRes->Flow(dv); - dV1 = dV1 + dv * 0.96; - ValveRes->Flow(-0.04 * dv); - // przeplyw PG <-> rozdzielacz - dv = PF(PP, VVP, 0.01) * dt; - ValveRes->Flow(-dv); - - ValveRes->Act(); - BrakeCyl->Act(); - BrakeRes->Act(); - CntrlRes->Act(); - ImplsRes->Act(); - return dv - dV1; + return IMP; } /// @@ -3034,32 +3106,7 @@ double TFV4aM::GetPF(double i_bcp, double PP, double HP, double dt, double ep) // na wszelki wypadek, zeby nie wyszlo poza zakres i_bcp = std::clamp(i_bcp, -1.999, 5.999); - double DP{0.0}; - if (TP > 0.0) - { - // jesli czasowy jest niepusty - DP = 0.045; // 2.5 w 55 sekund (5,35->5,15 w PG) - TP -= DP * dt; - Sounds[s_fv4a_t] = DP; - } - else - { - //.08 - TP = 0.0; - } - - if (XP > 0) - { - // jesli komora pod niepusta jest niepusty - DP = 2.5; - Sounds[s_fv4a_x] = DP * XP; - XP -= dt * DP * 2.0; // od cisnienia 5 do 0 w 10 sekund ((5-0)*dt/10) - } - else - { - // jak pusty, to pusty - XP = 0.0; - } + DischargeChambers(dt); double pom; if (EQ(i_bcp, -1.0)) @@ -3071,21 +3118,7 @@ double TFV4aM::GetPF(double i_bcp, double PP, double HP, double dt, double ep) pom = std::min(CP, HP); } - if (pom > RP + 0.25) - { - Fala = true; - } - if (Fala) - { - if (pom > RP + 0.3) - { - XP = XP - 20.0 * PR(pom, XP) * dt; - } - else - { - Fala = false; - } - } + UpdateWave(pom, dt); double LimPP = std::min(LPP_RP(i_bcp) + TP * 0.08 + RedAdj, HP); // pozycja + czasowy lub zasilanie @@ -3127,28 +3160,12 @@ double TFV4aM::GetPF(double i_bcp, double PP, double HP, double dt, double ep) } ep = dpPipe; - if (EQ(i_bcp, 0) || RP > ep) - { - // powolne wzrastanie, ale szybsze na jezdzie; - RP += PF(RP, ep, 0.0007) * dt; - } - else - { - // powolne wzrastanie i to bardzo - RP += PF(RP, ep, 0.000093 / 2 * 2) * dt; - } - // jednak trzeba wydluzyc, bo obecnie zle dziala - if (RP < ep && RP < BPT[std::lround(i_bcpno) + 2][1]) - { - // jesli jestesmy ponizej cisnienia w sterujacym (2.9 bar) - // przypisz cisnienie w PG - wydluzanie napelniania o czas potrzebny do napelnienia PG - RP += PF(RP, CP, 0.005) * dt; - } + UpdateReductor(i_bcp, ep, dt); if (EQ(i_bcp, i_bcpno) || EQ(i_bcp, -2)) { - DP = PF(0.0, PP, ActFlowSpeed / LBDelay); + auto const DP{PF(0.0, PP, ActFlowSpeed / LBDelay)}; dpMainValve = DP; Sounds[s_fv4a_e] = DP; Sounds[s_fv4a_u] = 0.0; @@ -3171,6 +3188,80 @@ double TFV4aM::GetPF(double i_bcp, double PP, double HP, double dt, double ep) return dpMainValve * dt; } +// the time reservoir and the reductor's air chamber let out, and their sounds +void TFV4aM::DischargeChambers(double const dt) +{ + double DP{0.0}; + if (TP > 0.0) + { + // jesli czasowy jest niepusty + DP = 0.045; // 2.5 w 55 sekund (5,35->5,15 w PG) + TP -= DP * dt; + Sounds[s_fv4a_t] = DP; + } + else + { + //.08 + TP = 0.0; + } + + if (XP > 0) + { + // jesli komora pod niepusta jest niepusty + DP = 2.5; + Sounds[s_fv4a_x] = DP * XP; + XP -= dt * DP * 2.0; // od cisnienia 5 do 0 w 10 sekund ((5-0)*dt/10) + } + else + { + // jak pusty, to pusty + XP = 0.0; + } +} + +// the release pressure wave: on while the supply is well over the reductor's pressure, its chamber filled meanwhile +void TFV4aM::UpdateWave(double const pom, double const dt) +{ + if (pom > RP + 0.25) + { + Fala = true; + } + if (Fala) + { + if (pom > RP + 0.3) + { + XP = XP - 20.0 * PR(pom, XP) * dt; + } + else + { + Fala = false; + } + } +} + +// the reductor reservoir following the pressure ep the pipe is driven to, slowly, faster at running, and filled from +// the control reservoir under the lowest pressure of the handle +void TFV4aM::UpdateReductor(double const i_bcp, double const ep, double const dt) +{ + if (EQ(i_bcp, 0) || RP > ep) + { + // powolne wzrastanie, ale szybsze na jezdzie; + RP += PF(RP, ep, 0.0007) * dt; + } + else + { + // powolne wzrastanie i to bardzo + RP += PF(RP, ep, 0.000093 / 2 * 2) * dt; + } + // jednak trzeba wydluzyc, bo obecnie zle dziala + if (RP < ep && RP < BPT[std::lround(i_bcpno) + 2][1]) + { + // jesli jestesmy ponizej cisnienia w sterujacym (2.9 bar) + // przypisz cisnienie w PG - wydluzanie napelniania o czas potrzebny do napelnienia PG + RP += PF(RP, CP, 0.005) * dt; + } +} + /// Initialises CP and RP to the supplied pressure. /// Initial pressure [bar]. void TFV4aM::Init(double Press) @@ -3259,7 +3350,6 @@ double TMHZ_EN57::GetPF(double i_bcp, double PP, double HP, double dt, double ep double dpPipe; double dpMainValve; double ActFlowSpeed; - double DP; double pom; for (auto &soundvalue : Sounds) @@ -3270,30 +3360,12 @@ double TMHZ_EN57::GetPF(double i_bcp, double PP, double HP, double dt, double ep i_bcp = std::clamp(i_bcp, -0.999, 9.999); // na wszelki wypadek, zeby nie wyszlo poza zakres - if (TP > 0 && CP > 4.9) - { - DP = OverloadPressureDecrease; - if (EQ(i_bcp, 0)) - TP = TP - DP * dt; - Sounds[s_fv4a_t] = DP; - } - else - { - TP = 0; - } + DischargeTimedReservoir(i_bcp, dt); LimPP = std::min(LPP_RP(i_bcp) + TP * 0.08 + RedAdj, HP); // pozycja + czasowy lub zasilanie ActFlowSpeed = 4; - double uop = UnbrakeOverPressure; // unbrake over pressure in actual state - ManualOvrldActive = UniversalFlag & TUniversalBrake::ub_HighPressure; // button is pressed - if (ManualOvrld && !ManualOvrldActive) // no overpressure for not pressed button if it does not exists - uop = 0; - - if (EQ(i_bcp, -1) && uop > 0) - pom = std::min(HP, 5.4 + RedAdj + uop); - else - pom = std::min(CP, HP); + pom = SupplyPressure(i_bcp, HP); if (LimPP > CP) // podwyzszanie szybkie CP = CP + 60 * std::min(abs(LimPP - CP), 0.05) * PR(CP, LimPP) * dt; // zbiornik sterujacy; @@ -3313,15 +3385,12 @@ double TMHZ_EN57::GetPF(double i_bcp, double PP, double HP, double dt, double ep if ((EQ(i_bcp, -1) && AutoOvrld) || (i_bcp < 0.5 && UniversalFlag & TUniversalBrake::ub_Overload)) { - if (TP < 5) - TP = TP + dt; // 5/10 - if (TP < OverloadMaxPressure) - TP = TP - 0.5 * dt; // 5/10 + ChargeTimedReservoir(dt); } if (EQ(i_bcp, 10) || EQ(i_bcp, -2)) { - DP = PF(0, PP, 2 * ActFlowSpeed / LBDelay); + auto const DP{PF(0, PP, 2 * ActFlowSpeed / LBDelay)}; dpMainValve = DP; Sounds[s_fv4a_e] = DP; Sounds[s_fv4a_u] = 0; @@ -3344,6 +3413,45 @@ double TMHZ_EN57::GetPF(double i_bcp, double PP, double HP, double dt, double ep return dpMainValve * dt; } +// the time reservoir let out of the overload, at the running position, while the control reservoir is charged +void TMHZ_EN57::DischargeTimedReservoir(double const i_bcp, double const dt) +{ + if (TP > 0 && CP > 4.9) + { + auto const DP{OverloadPressureDecrease}; + if (EQ(i_bcp, 0)) + TP = TP - DP * dt; + Sounds[s_fv4a_t] = DP; + } + else + { + TP = 0; + } +} + +// the time reservoir charged by the overload, up to its highest pressure +void TMHZ_EN57::ChargeTimedReservoir(double const dt) +{ + if (TP < 5) + TP = TP + dt; // 5/10 + if (TP < OverloadMaxPressure) + TP = TP - 0.5 * dt; // 5/10 +} + +// the pressure the handle feeds the pipe from: the supply's over the running pressure at the filling stroke, where the +// handle has the overpressure (with its button pressed, for a button worked one), the control reservoir's otherwise +double TMHZ_EN57::SupplyPressure(double const i_bcp, double const HP) +{ + double uop = UnbrakeOverPressure; // unbrake over pressure in actual state + ManualOvrldActive = UniversalFlag & TUniversalBrake::ub_HighPressure; // button is pressed + if (ManualOvrld && !ManualOvrldActive) // no overpressure for not pressed button if it does not exists + uop = 0; + + if (EQ(i_bcp, -1) && uop > 0) + return std::min(HP, 5.4 + RedAdj + uop); + return std::min(CP, HP); +} + /// Initialises CP to the supplied pressure. /// Initial pressure [bar]. void TMHZ_EN57::Init(double Press) diff --git a/McZapkie/hamulce.h b/McZapkie/hamulce.h index 097a164d7..1e4572dfe 100644 --- a/McZapkie/hamulce.h +++ b/McZapkie/hamulce.h @@ -605,6 +605,8 @@ class TESt : public TBrake /// Brake cylinder (or impulse) pressure. /// In/out accumulator for the brake pipe flow correction. void CheckState(double BCP, double &dV1); // glowny przyrzad rozrzadczy + /// The state of a valve holding: braking on in steps, the filling stopped, or released. + void CheckStateHeld(double BCP, double VVP, double CVP); /// Drives the releaser logic — bleeds the control reservoir while the releaser is engaged. /// Time step [s]. void CheckReleaser(double dt); // odluzniacz @@ -763,6 +765,12 @@ class TLSt : public TESt4R /// Constructs the LSt distributor. using TESt4R::TESt4R; + + private: + // the parts of GetPF() + void UpdateStatusLSt(double BCP, double VVP, double CVP); + void ReleaserLSt(double BCP, double CVP, double dt); + void CylinderFlowLSt(double BCP, double BVP, double CVP, double dt, double Vel); }; /// @@ -803,6 +811,13 @@ class TEStED : public TLSt /// Stores the load-weighing parameters. void SetLP(double const TM, double const LM, double const TBP) override; // parametry przystawki wazacej + private: + // the parts of GetPF() + void UpdateStatus(double BCP, double VVP, double CVP, double MPP); + double IntermediateFlow(double BCP, double VVP, double CVP, double MPP, double BVP, double nastG) const; + void CylinderFlow(double BCP, double BVP, double dt, double Vel); + + public: /// Constructs the distributor and creates the intermediate reservoir. inline TEStED(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TLSt(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) { @@ -829,6 +844,10 @@ class TEStEP2 : public TLSt /// EP intensity (-1..1). double EPS = 0.0; + private: + // the part of GetPF() + void UpdateStatusEP2(double BCP, double VVP, double CVP); + public: /// Initialises the EP2-equipped distributor (impulse chamber, P delay). void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; // inicjalizacja @@ -986,6 +1005,10 @@ class TKE : public TBrake /// Auxiliary (local) brake pressure feeding the DCV. double LBP = 0.0; // cisnienie hamulca pomocniczego + // the parts of GetPF() and CheckState() + double CylinderFlowKE(double IMP, double BCP, double BVP, double Vel, double dt); + void CheckStateHeld(double BCP, double VVP, double CVP); + public: /// Initialises the KE distributor (control / impulse / auxiliary reservoirs and BVM). void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; @@ -1164,6 +1187,10 @@ class TFV4aM : public TDriverHandle double LPP_RP(double pos) const; /// Returns true if pos is within ±0.5 of i_pos (detent comparison). bool EQ(double pos, double i_pos) const; + // the parts of GetPF() + void DischargeChambers(double dt); + void UpdateWave(double pom, double dt); + void UpdateReductor(double i_bcp, double ep, double dt); public: /// Computes brake pipe flow for the FV4a/M handle (interpolated BPT, wave modelling, accelerator). @@ -1214,6 +1241,10 @@ class TMHZ_EN57 : public TDriverHandle double LPP_RP(double pos) const; /// Returns true if pos is within ±0.5 of i_pos. bool EQ(double pos, double i_pos) const; + // the parts of GetPF() + void DischargeTimedReservoir(double i_bcp, double dt); + void ChargeTimedReservoir(double dt); + double SupplyPressure(double i_bcp, double HP); public: /// Computes brake pipe flow for MHZ_EN57 (covers handle positions -1..10 with EP/pneumatic mix). From 3cbb529d16e3b06216414fa0c55e773715a3a358 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 16:32:32 +0100 Subject: [PATCH 089/136] fix(scene): write the region cache through a temporary file, reject a damaged one (#351) * fix(scene): write the region cache through a temporary file, reject a damaged one The static geometry cache of a scenery (.sbt) was written in place, and only its 8-byte header was checked before it was used. A write cut short (a crash, the process killed, the test mode's real time watchdog) left a truncated file which every later start loaded as it was: the sections up to the cut, then whatever the reads past the end produced, with the section index used unchecked and the section size read and ignored. - basic_region::serialize() writes .sbt.tmp and renames it over the final name only when complete; a failed write is logged and the temporary file removed, the previous file stays. - basic_region::is_scene() checks the whole layout: header, section count, every section index within the region and present once, and the section sizes adding up to the length of the file. A cut-short file is turned down there ("Bad file: ... ignored"), so the scenery loads from the text and the cache is written anew at the end of the load. - basic_region::deserialize() checks the layout again, reads each section out of its own data (sectionsize bytes) and requires the section to use exactly that; sections are restored apart from the region and taken over only when the whole file was read, so a damaged file leaves nothing of itself behind. If the content is damaged although the layout holds, the default .sbt (the game's own copy of the text) is removed so the next start rebuilds it. - A vertex count the rest of the data can't hold, a shape count running past the data, and a string cut short by the end of the data (sn_utils::d_str() looped forever there) now stop the read instead of allocating or looping on. - The layout check and the write through a temporary file are in scene/regionfile.{h,cpp}, in the core library with sn_utils, and have unit tests (test_region_file.cpp). - run.py also removes a .sbt.tmp left by a run cut short. The file format is unchanged. * refactor(scene): the region file code without Sonar issues write_through_temporary takes the writer as a template parameter, the messages are built with std::format, the reading of one section moves into a helper (one break per loop), and the test drops chained assignments and implicit lambda captures. No change in behaviour. --- CMakeLists.txt | 3 +- scene/regionfile.cpp | 130 ++++++++++++ scene/regionfile.h | 77 ++++++++ scene/scene.cpp | 240 ++++++++++++++++------- scene/scene.h | 9 + scene/scenenode.cpp | 16 +- scene/sn_utils.cpp | 16 +- scene/sn_utils.h | 2 + simulation/simulationstateserializer.cpp | 8 +- tests/scenarios/run.py | 9 +- tests/unit/test_region_file.cpp | 207 +++++++++++++++++++ 11 files changed, 634 insertions(+), 83 deletions(-) create mode 100644 scene/regionfile.cpp create mode 100644 scene/regionfile.h create mode 100644 tests/unit/test_region_file.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 4bb63e935..2f4f8227d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -146,7 +146,6 @@ set(SOURCES "rendering/nullrenderer.cpp" "rendering/renderer.cpp" "model/ResourceManager.cpp" -"scene/sn_utils.cpp" "world/Segment.cpp" "environment/sky.cpp" "environment/sun.cpp" @@ -552,6 +551,8 @@ set(CORE_SOURCES "McZapkie/Oerlikon_ESt.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" +"scene/sn_utils.cpp" +"scene/regionfile.cpp" "utilities/inionlysettings.cpp" "scripting/ladderlogic.cpp" "scripting/scriptscreenrules.cpp" diff --git a/scene/regionfile.cpp b/scene/regionfile.cpp new file mode 100644 index 000000000..593e07e82 --- /dev/null +++ b/scene/regionfile.cpp @@ -0,0 +1,130 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "scene/regionfile.h" +#include "scene/sn_utils.h" + +#include +#include +#include +#include + +namespace scene::region_file { + +std::string +check_layout( std::istream &Input, std::uint32_t const Header, std::uint32_t const Version, std::uint32_t const Sectionlimit ) { + + Input.clear(); + Input.seekg( 0, std::ios::end ); + auto const end { Input.tellg() }; + Input.seekg( 0, std::ios::beg ); + if( ( end < 0 ) || ( false == Input.good() ) ) { + return "can't be read"; + } + auto const filesize { static_cast( end ) }; + + auto const headermain { sn_utils::ld_uint32( Input ) }; + if( auto const headertype { sn_utils::ld_uint32( Input ) }; ( false == Input.good() ) || ( headermain != Header ) || ( headertype != Version ) ) { + return "is of either unrecognized type or version"; + } + auto sectioncount { sn_utils::ld_uint32( Input ) }; + if( false == Input.good() ) { + return "ends before the section count"; + } + if( sectioncount > Sectionlimit ) { + return std::format( "holds {} sections, more than the {} a region has", sectioncount, Sectionlimit ); + } + std::vector present( Sectionlimit, false ); + std::uint64_t position { 3 * sizeof( std::uint32_t ) }; + std::uint32_t sectionnumber { 0 }; + while( sectionnumber < sectioncount ) { + if( filesize - position < section_header_size ) { + return std::format( "ends after {} of its {} sections", sectionnumber, sectioncount ); + } + std::uint32_t index; + std::uint32_t size; + if( auto const error { read_section_header( Input, Sectionlimit, index, size ) }; false == error.empty() ) { + return error; + } + if( true == present[ index ] ) { + return std::format( "holds section {} more than once", index ); + } + present[ index ] = true; + if( filesize - position < size ) { + return std::format( + "ends inside section {} ({} of {}), {} of its {} bytes are there", index, sectionnumber + 1, sectioncount, filesize - position, size ); + } + position += size; + Input.seekg( static_cast( position ), std::ios::beg ); + if( false == Input.good() ) { + return std::format( "can't be read past section {}", index ); + } + ++sectionnumber; + } + if( position != filesize ) { + return std::format( "has {} bytes past its last section", filesize - position ); + } + return {}; +} + +std::string +read_section_header( std::istream &Input, std::uint32_t const Sectionlimit, std::uint32_t &Index, std::uint32_t &Size ) { + + Index = sn_utils::ld_uint32( Input ); + Size = sn_utils::ld_uint32( Input ); + if( false == Input.good() ) { + return "ends inside a section header"; + } + if( Index >= Sectionlimit ) { + return std::format( "holds section {}, out of the {} a region has", Index, Sectionlimit ); + } + if( Size < section_header_size ) { + return std::format( "gives section {} the size of {} bytes, less than its header takes", Index, Size ); + } + return {}; +} + +std::string +open_temporary( std::string const &Filename, std::ofstream &Output ) { + + Output.open( Filename + ".tmp", std::ios::binary | std::ios::trunc ); + if( Output.fail() ) { + return "can't write to file \"" + Filename + ".tmp\""; + } + return {}; +} + +std::string +finish_temporary( std::string const &Filename, std::ofstream &Output, std::string Error ) { + + if( ( true == Error.empty() ) && ( Output.fail() ) ) { + Error = "can't write to file \"" + Filename + ".tmp\""; + } + Output.close(); + if( ( true == Error.empty() ) && ( Output.fail() ) ) { + Error = "can't write to file \"" + Filename + ".tmp\""; + } + std::filesystem::path const temporaryfile { Filename + ".tmp" }; + std::error_code result; + if( false == Error.empty() ) { + std::filesystem::remove( temporaryfile, result ); + return Error; + } + // the finished file replaces the previous version in one go, so an interrupted write doesn't leave a broken one behind + std::filesystem::rename( temporaryfile, Filename, result ); + if( result ) { + Error = "can't replace file \"" + Filename + "\": " + result.message(); + std::filesystem::remove( temporaryfile, result ); + return Error; + } + return {}; +} + +} // scene::region_file diff --git a/scene/regionfile.h b/scene/regionfile.h new file mode 100644 index 000000000..dd497a487 --- /dev/null +++ b/scene/regionfile.h @@ -0,0 +1,77 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include +#include +#include + +// the parts of the region file (.sbt, the static geometry of a scenery cached by basic_region) which need +// nothing of the scene: checking how a file is laid out, and writing it so that an interrupted write leaves no +// cut-short file behind. kept apart so the unit tests can check them +namespace scene::region_file { + +// layout of the file: the header (two uint32: the file type and its version), the section count (uint32), then for +// each section its index (uint32), its size (uint32, counted from the start of the index, so it covers the index, +// the size itself and the section data) and the section data. all numbers little endian + +// size of the index and the size of a section, the least a section can take +std::uint32_t constexpr section_header_size { 2 * sizeof( std::uint32_t ) }; + +// checks the layout of the file held by the stream, read from its start: the header has to match the provided type +// and version, the sections have to have indices below Sectionlimit, each one no more than once, and their sizes have +// to add up to the length of the file. the section data itself isn't read. returns: the empty string if the layout +// holds, the reason why not otherwise +std::string + check_layout( std::istream &Input, std::uint32_t const Header, std::uint32_t const Version, std::uint32_t const Sectionlimit ); + +// reads the index and the size of the next section, and checks them: the index has to be below Sectionlimit, and the +// section no smaller than its own index and size. returns: the empty string if both were read and are sound, the +// reason why not otherwise +std::string + read_section_header( std::istream &Input, std::uint32_t const Sectionlimit, std::uint32_t &Index, std::uint32_t &Size ); + +// opens the temporary file write_through_temporary() writes into. returns: the empty string on success, the reason of +// the failure otherwise +std::string + open_temporary( std::string const &Filename, std::ofstream &Output ); + +// closes the temporary file write_through_temporary() wrote into, and puts it in place of the file, unless Error holds +// the reason why the writing failed. the temporary file is removed on a failure. returns: the empty string on success, +// the reason of the failure otherwise +std::string + finish_temporary( std::string const &Filename, std::ofstream &Output, std::string Error ); + +// writes a file with the provided function (taking the std::ostream to write into) into a temporary file next to it +// (the name with .tmp added), which then replaces the file in one go. if the writing fails or is cut short, the +// previous file (or none) stays in place, rather than a partial one; the temporary file is removed when the failure is +// noticed. returns: the empty string on success, the reason of the failure otherwise +template +std::string + write_through_temporary( std::string const &Filename, Writer_ const &Write ) { + + std::ofstream output; + if( auto const openerror { open_temporary( Filename, output ) }; false == openerror.empty() ) { + return openerror; + } + std::string error; + try { + Write( output ); + output.flush(); + } + catch( std::exception const &Exception ) { + error = "can't write to file \"" + Filename + ".tmp\": " + Exception.what(); + } + return finish_temporary( Filename, output, std::move( error ) ); +} + +} // scene::region_file diff --git a/scene/scene.cpp b/scene/scene.cpp index eed3f6438..666cd43c0 100644 --- a/scene/scene.cpp +++ b/scene/scene.cpp @@ -19,17 +19,71 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "utilities/Logs.h" #include "scene/sn_utils.h" +#include "scene/regionfile.h" #include "scene/sceneterrain.h" #include "rendering/renderer.h" #include "widgets/map_objects.h" #include "vehicle/aiwire.h" +#include + namespace scene { std::string const EU07_FILEEXTENSION_REGION { ".sbt" }; std::uint32_t const EU07_FILEHEADER { MAKE_ID4( 'E','U','0','7' ) }; std::uint32_t const EU07_FILEVERSION_REGION { MAKE_ID4( 'S', 'B', 'T', '2' ) }; std::map Hierarchy; + +namespace { + +// name of the region file kept for specified scenario file +std::string +region_file_name( std::string const &Scenariofile ) { + + auto filename { Scenariofile }; + while( filename[ 0 ] == '$' ) { + // trim leading $ char rainsted utility may add to the base name for modified .scn files + filename.erase( 0, 1 ); + } + erase_extension( filename ); + filename = Global.asCurrentSceneryPath + filename; + filename += EU07_FILEEXTENSION_REGION; + + return filename; +} + +// reads the next section of a region file into the provided list. returns: the empty string on success, the reason +// of the failure otherwise +std::string +read_region_section( std::istream &Input, std::uint32_t const Sectionlimit, std::vector>> &Sections ) { + + // section index, followed by section data size (counted from the start of the index), followed by section data + std::uint32_t sectionindex; + std::uint32_t sectionsize; + if( auto const error { region_file::read_section_header( Input, Sectionlimit, sectionindex, sectionsize ) }; false == error.empty() ) { + return error; + } + // the section is read out of its own data, it can't reach into the next one + std::string data( sectionsize - region_file::section_header_size, '\0' ); + Input.read( data.data(), static_cast( data.size() ) ); + if( false == Input.good() ) { + return std::format( "ends inside section {}", sectionindex ); + } + std::istringstream sectioninput { std::move( data ) }; + auto section { std::make_unique() }; + section->deserialize( sectioninput ); + std::string error; + if( true == sectioninput.fail() ) { + error = std::format( "has section {} shorter than its content", sectionindex ); + } + else if( sectioninput.peek() != std::char_traits::eof() ) { + error = std::format( "has section {} longer than its content", sectionindex ); + } + Sections.emplace_back( sectionindex, std::move( section ) ); + return error; +} + +} // namespace // potentially activates event handler with the same name as provided node, and within handler activation range void @@ -241,22 +295,38 @@ basic_cell::deserialize( std::istream &Input ) { m_area.deserialize( Input ); // cell shapes // shape count followed by opaque shape data + // NOTE: a damaged count is cut short by the end of the data rather than followed auto itemcount { sn_utils::ld_uint32( Input ) }; - while( itemcount-- ) { + while( ( itemcount-- ) && ( true == Input.good() ) ) { m_shapesopaque.emplace_back( shape_node().deserialize( Input ) ); } itemcount = sn_utils::ld_uint32( Input ); - while( itemcount-- ) { + while( ( itemcount-- ) && ( true == Input.good() ) ) { m_shapestranslucent.emplace_back( shape_node().deserialize( Input ) ); } itemcount = sn_utils::ld_uint32( Input ); - while( itemcount-- ) { + while( ( itemcount-- ) && ( true == Input.good() ) ) { m_lines.emplace_back( lines_node().deserialize( Input ) ); } // cell activation flag m_active = true == m_active || false == m_shapesopaque.empty() || false == m_shapestranslucent.empty() || false == m_lines.empty(); } +// takes over the content restored from a file into another cell, as deserialize() would have added it to this one +void +basic_cell::merge( basic_cell &&Other ) { + + m_area.center = Other.m_area.center; + m_area.radius = std::max( m_area.radius, Other.m_area.radius ); + m_shapesopaque.insert( m_shapesopaque.end(), std::make_move_iterator( Other.m_shapesopaque.begin() ), std::make_move_iterator( Other.m_shapesopaque.end() ) ); + m_shapestranslucent.insert( m_shapestranslucent.end(), std::make_move_iterator( Other.m_shapestranslucent.begin() ), std::make_move_iterator( Other.m_shapestranslucent.end() ) ); + m_lines.insert( m_lines.end(), std::make_move_iterator( Other.m_lines.begin() ), std::make_move_iterator( Other.m_lines.end() ) ); + m_active = true == m_active || true == Other.m_active; + Other.m_shapesopaque.clear(); + Other.m_shapestranslucent.clear(); + Other.m_lines.clear(); +} + // sends content of the class in legacy (text) format to provided stream void basic_cell::export_as_text( std::ostream &Output ) const { @@ -885,7 +955,7 @@ basic_section::deserialize( std::istream &Input ) { m_area.deserialize( Input ); // section shapes: shape count followed by shape data auto shapecount { sn_utils::ld_uint32( Input ) }; - while( shapecount-- ) { + while( ( shapecount-- ) && ( true == Input.good() ) ) { m_shapes.emplace_back( shape_node().deserialize( Input ) ); } // partitioned data @@ -894,6 +964,19 @@ basic_section::deserialize( std::istream &Input ) { } } +// takes over the content restored from a file into another section, as deserialize() would have added it to this one +void +basic_section::merge( basic_section &&Other ) { + + m_area.center = Other.m_area.center; + m_area.radius = std::max( m_area.radius, Other.m_area.radius ); + m_shapes.insert( m_shapes.end(), std::make_move_iterator( Other.m_shapes.begin() ), std::make_move_iterator( Other.m_shapes.end() ) ); + Other.m_shapes.clear(); + for( std::size_t index { 0 }; index < m_cells.size(); ++index ) { + m_cells[ index ].merge( std::move( Other.m_cells[ index ] ) ); + } +} + // sends content of the class in legacy (text) format to provided stream void basic_section::export_as_text( std::ostream &Output ) const { @@ -1220,26 +1303,17 @@ basic_region::wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, doubl bool basic_region::is_scene( std::string const &Scenariofile ) const { - auto filename { Scenariofile }; - while( filename[ 0 ] == '$' ) { - // trim leading $ char rainsted utility may add to the base name for modified .scn files - filename.erase( 0, 1 ); - } - erase_extension( filename ); - filename = Global.asCurrentSceneryPath + filename; - filename += EU07_FILEEXTENSION_REGION; + auto const filename { region_file_name( Scenariofile ) }; if( false == FileExists( filename ) ) { return false; } - // file type and version check + // file type and version check, and whether the sections add up to the whole file. a file cut short (by a write + // interrupted with an older version, or a copy) is caught here, while the scenery can still be loaded from the text std::ifstream input( filename, std::ios::binary ); - - uint32_t headermain{ sn_utils::ld_uint32( input ) }; - uint32_t headertype{ sn_utils::ld_uint32( input ) }; - - if( headermain != EU07_FILEHEADER || headertype != EU07_FILEVERSION_REGION ) { - // wrong file type + if( auto const layout { region_file::check_layout( input, EU07_FILEHEADER, EU07_FILEVERSION_REGION, static_cast( m_sections.size() ) ) }; + false == layout.empty() ) { + WriteLog( "Bad file: \"" + filename + "\" " + layout + ", ignored" ); return false; } @@ -1250,38 +1324,35 @@ basic_region::is_scene( std::string const &Scenariofile ) const { void basic_region::serialize( std::string const &Scenariofile ) const { - auto filename { Scenariofile }; - while( filename[ 0 ] == '$' ) { - // trim leading $ char rainsted utility may add to the base name for modified .scn files - filename.erase( 0, 1 ); - } - erase_extension( filename ); - filename = Global.asCurrentSceneryPath + filename; - filename += EU07_FILEEXTENSION_REGION; + auto const filename { region_file_name( Scenariofile ) }; - std::ofstream output { filename, std::ios::binary }; - - // region file version 1 - // header: EU07SBT + version (0-255) - sn_utils::ls_uint32( output, EU07_FILEHEADER ); - sn_utils::ls_uint32( output, EU07_FILEVERSION_REGION ); - // sections - // TBD, TODO: build table of sections and file offsets, if we postpone section loading until they're within range - std::uint32_t sectioncount { 0 }; - for( auto *section : m_sections ) { - if( section != nullptr ) { - ++sectioncount; + // the file is written under a temporary name and takes the final one only when complete, so a write cut short + // (a crash, the process killed) leaves no partial file to be read on the next start + auto const error { region_file::write_through_temporary( filename, [ this ]( std::ostream &output ) { + // region file version 1 + // header: EU07SBT + version (0-255) + sn_utils::ls_uint32( output, EU07_FILEHEADER ); + sn_utils::ls_uint32( output, EU07_FILEVERSION_REGION ); + // sections + // TBD, TODO: build table of sections and file offsets, if we postpone section loading until they're within range + std::uint32_t sectioncount { 0 }; + for( auto *section : m_sections ) { + if( section != nullptr ) { + ++sectioncount; + } } - } - // section count, followed by section data - sn_utils::ls_uint32( output, sectioncount ); - std::uint32_t sectionindex { 0 }; - for( auto *section : m_sections ) { - // section data: section index, followed by length of section data, followed by section data - if( section != nullptr ) { - sn_utils::ls_uint32( output, sectionindex ); - section->serialize( output ); } - ++sectionindex; + // section count, followed by section data + sn_utils::ls_uint32( output, sectioncount ); + std::uint32_t sectionindex { 0 }; + for( auto *section : m_sections ) { + // section data: section index, followed by length of section data, followed by section data + if( section != nullptr ) { + sn_utils::ls_uint32( output, sectionindex ); + section->serialize( output ); } + ++sectionindex; + } } ) }; + if( false == error.empty() ) { + ErrorLog( "Bad file: binary version of the scenery wasn't written, " + error ); } } @@ -1289,48 +1360,69 @@ basic_region::serialize( std::string const &Scenariofile ) const { bool basic_region::deserialize( std::string const &Scenariofile ) { - auto filename { Scenariofile }; - while( filename[ 0 ] == '$' ) { - // trim leading $ char rainsted utility may add to the base name for modified .scn files - filename.erase( 0, 1 ); - } - erase_extension( filename ); - filename = Global.asCurrentSceneryPath + filename; - filename += EU07_FILEEXTENSION_REGION; + auto const filename { region_file_name( Scenariofile ) }; if( false == FileExists( filename ) ) { Global.file_binary_terrain_state = false; return false; } // region file version 1 - // file type and version check + // file type and version check, and whether the sections add up to the whole file std::ifstream input( filename, std::ios::binary ); - - uint32_t headermain { sn_utils::ld_uint32( input ) }; - uint32_t headertype { sn_utils::ld_uint32( input ) }; - - if( headermain != EU07_FILEHEADER || headertype != EU07_FILEVERSION_REGION ) { - // wrong file type - WriteLog( "Bad file: \"" + filename + "\" is of either unrecognized type or version" ); + auto const sectionlimit { static_cast( m_sections.size() ) }; + auto error { region_file::check_layout( input, EU07_FILEHEADER, EU07_FILEVERSION_REGION, sectionlimit ) }; + if( false == error.empty() ) { + ErrorLog( "Bad file: \"" + filename + "\" " + error + ", the geometry it holds is missing" ); return false; } // sections // TBD, TODO: build table of sections and file offsets, if we postpone section loading until they're within range - // section count - auto sectioncount { sn_utils::ld_uint32( input ) }; - while( sectioncount-- ) { - // section index, followed by section data size, followed by section data - auto const sectionindex { sn_utils::ld_uint32( input ) }; - auto const sectionsize { sn_utils::ld_uint32( input ) }; - if( m_sections[ sectionindex ] == nullptr ) { - m_sections[ sectionindex ] = new basic_section(); + // the sections are restored apart from the region, which takes them over only once the whole file was read + // without a fault: a damaged file leaves nothing of itself behind + std::vector>> sections; + try { + input.clear(); + input.seekg( 2 * sizeof( std::uint32_t ), std::ios::beg ); + // section count + auto sectioncount { sn_utils::ld_uint32( input ) }; + sections.reserve( sectioncount ); + while( ( sectioncount-- ) && ( true == error.empty() ) ) { + error = read_region_section( input, sectionlimit, sections ); + } + } + catch( std::exception const &Exception ) { + error = std::string( "can't be read, " ) + Exception.what(); + } + if( false == error.empty() ) { + ErrorLog( "Bad file: \"" + filename + "\" " + error + ", the geometry it holds is missing" ); + return false; + } + for( auto &[ sectionindex, section ] : sections ) { + if( m_sections[ sectionindex ] == nullptr ) { + m_sections[ sectionindex ] = section.release(); + } + else { + m_sections[ sectionindex ]->merge( std::move( *section ) ); } - m_sections[ sectionindex ]->deserialize( input ); } return true; } +// removes the region file of specified scenario file, which turned out to be damaged, so the next start writes it anew +void +basic_region::discard_scene( std::string const &Scenariofile ) const { + + auto const filename { region_file_name( Scenariofile ) }; + std::error_code error; + if( true == std::filesystem::remove( filename, error ) ) { + WriteLog( "Bad file: \"" + filename + "\" removed, it will be made anew from the scenery on the next start" ); + } + else if( error ) { + ErrorLog( "Bad file: \"" + filename + "\" can't be removed, " + error.message() + ". Remove it to have it made anew from the scenery" ); + } +} + // sends content of the class in legacy (text) format to provided stream void basic_region::export_as_text( std::ostream &Output ) const { diff --git a/scene/scene.h b/scene/scene.h index b8256e257..bde88bc87 100644 --- a/scene/scene.h +++ b/scene/scene.h @@ -134,6 +134,9 @@ public: // restores content of the class from provided stream void deserialize( std::istream &Input ); + // takes over the content restored from a file into another cell, as deserialize() would have added it to this one + void + merge( basic_cell &&Other ); // sends content of the class in legacy (text) format to provided stream void export_as_text( std::ostream &Output ) const; @@ -343,6 +346,9 @@ public: // restores content of the class from provided stream void deserialize( std::istream &Input ); + // takes over the content restored from a file into another section, as deserialize() would have added it to this one + void + merge( basic_section &&Other ); // sends content of the class in legacy (text) format to provided stream void export_as_text( std::ostream &Output ) const; @@ -474,6 +480,9 @@ public: // restores content of the class from file with specified name. returns: true on success, false otherwise bool deserialize( std::string const &Scenariofile ); + // removes the region file of specified scenario file, which turned out to be damaged, so the next start writes it anew + void + discard_scene( std::string const &Scenariofile ) const; // sends content of the class in legacy (text) format to provided stream void export_as_text( std::ostream &Output ) const; diff --git a/scene/scenenode.cpp b/scene/scenenode.cpp index 18b1905a4..afe87cf83 100644 --- a/scene/scenenode.cpp +++ b/scene/scenenode.cpp @@ -108,7 +108,13 @@ shape_node::shapenode_data::deserialize( std::istream &Input ) { origin = sn_utils::d_dvec3( Input ); // NOTE: geometry handle is acquired during geometry creation // vertex data - vertices.resize( sn_utils::ld_uint32( Input ) ); + auto const vertexcount { sn_utils::ld_uint32( Input ) }; + if( vertexcount > sn_utils::remaining( Input ) / ( 8 * sizeof( float ) ) ) { + // each vertex takes 8 floats of the data at least: a count the rest of it can't hold comes from a damaged file + Input.setstate( std::ios::failbit ); + return; + } + vertices.resize( vertexcount ); if(has_userdata) userdata.resize(vertices.size()); gfx::basic_vertex localvertex; @@ -527,7 +533,13 @@ lines_node::linesnode_data::deserialize( std::istream &Input ) { origin = sn_utils::d_dvec3( Input ); // NOTE: geometry handle is acquired during geometry creation // vertex data - vertices.resize( sn_utils::ld_uint32( Input ) ); + auto const vertexcount { sn_utils::ld_uint32( Input ) }; + if( vertexcount > sn_utils::remaining( Input ) / ( 8 * sizeof( float ) ) ) { + // each vertex takes 8 floats of the data at least: a count the rest of it can't hold comes from a damaged file + Input.setstate( std::ios::failbit ); + return; + } + vertices.resize( vertexcount ); gfx::basic_vertex localvertex; for( auto &vertex : vertices ) { localvertex.deserialize( Input ); diff --git a/scene/sn_utils.cpp b/scene/sn_utils.cpp index b6a3f7c32..fbdbcb7f0 100644 --- a/scene/sn_utils.cpp +++ b/scene/sn_utils.cpp @@ -93,14 +93,26 @@ std::string sn_utils::d_str(std::istream &s) char c{}; while (true) { - s.read(&c, 1); - if (c == 0) + // a string cut short by the end of the data ends there too + if (!s.read(&c, 1) || c == 0) break; r.push_back(c); } return r; } +// number of bytes left to read in the stream, 0 if it failed or can't tell +std::uint64_t sn_utils::remaining(std::istream &s) +{ + auto const position{s.tellg()}; + if (position < 0) + return 0; + s.seekg(0, std::ios::end); + auto const end{s.tellg()}; + s.seekg(position); + return end > position ? static_cast(end - position) : 0; +} + bool sn_utils::d_bool(std::istream& s) { return ld_uint16(s) == 1; diff --git a/scene/sn_utils.h b/scene/sn_utils.h index 4212ac29a..87da22d93 100644 --- a/scene/sn_utils.h +++ b/scene/sn_utils.h @@ -20,6 +20,8 @@ public: static glm::dvec3 d_dvec3(std::istream&); static glm::vec3 d_vec3(std::istream&); static glm::vec4 d_vec4(std::istream&); + // number of bytes left to read in the stream, 0 if it failed or can't tell + static std::uint64_t remaining(std::istream&); static void ls_uint16(std::ostream&, uint16_t); static void ls_uint32(std::ostream&, uint32_t); diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index da3e075ef..0b114f837 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -426,7 +426,13 @@ state_serializer::deserialize_firstinit( cParser &Input, scene::scratch_data &Sc // TBD: postpone loading furter and only load required blocks during the simulation? if (false == Scratchpad.binary.terrain_included) { - Region->deserialize(Scratchpad.name); + if (false == Region->deserialize(Scratchpad.name)) + { + // the file looked whole to is_scene() but its content is damaged. the geometry it holds is missing from this + // session, as the text definitions were skipped already. the file is the game's own copy of the text, so it + // goes, and the next start loads the text and writes it anew + Region->discard_scene(Scratchpad.name); + } } else { diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py index 52ff6cf2a..438b68aa4 100644 --- a/tests/scenarios/run.py +++ b/tests/scenarios/run.py @@ -883,10 +883,13 @@ def _run_case(name: str, case: dict, exe: Path, game_dir: Path, timespeed: float say(f" {'PASS' if passed else 'FAIL'} exit code {describe_exit(result.exit_code)}{watchdog}, expected {expect}") ok &= passed # a run cut short (the real time watchdog, an error, a crash, or closed by us) could have been writing - # the scenery's geometry cache; the simulator checks only the header of it, so the next runs would read - # a truncated one. it is written again on the next run + # the scenery's geometry cache. the simulator writes it through .sbt.tmp and turns down a cut-short + # one, but older builds wrote it in place and checked only its header, so the next runs would read a + # truncated one. either is written again on the next run if result.failure or (not watch and got in (None, "error", WALL_TIMEOUT)): - scenery_cache(game_dir, name).unlink(missing_ok=True) + cache = scenery_cache(game_dir, name) + cache.unlink(missing_ok=True) + cache.with_name(cache.name + ".tmp").unlink(missing_ok=True) if result.failure: say(f" FAIL {result.failure}") ok = False diff --git a/tests/unit/test_region_file.cpp b/tests/unit/test_region_file.cpp new file mode 100644 index 000000000..346823ae3 --- /dev/null +++ b/tests/unit/test_region_file.cpp @@ -0,0 +1,207 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scratch.h" +#include "scene/regionfile.h" +#include "scene/sn_utils.h" + +#include +#include +#include +#include + +// the region file (.sbt), the static geometry of a scenery the game caches beside it: a file cut short or +// damaged is turned down before any of it is used, and the game writes it so that it is never left cut short + +namespace { + +std::uint32_t constexpr header{0x37305545}; // EU07 +std::uint32_t constexpr version{0x32544253}; // SBT2 +std::uint32_t constexpr sectionlimit{500 * 500}; + +struct section { + std::uint32_t index; + std::string data; +}; + +// the file as basic_region::serialize() lays it out: the section size covers the index, the size and the data +std::string region(std::vector
const &Sections, std::uint32_t const Header = header, std::uint32_t const Version = version) { + std::ostringstream output; + sn_utils::ls_uint32(output, Header); + sn_utils::ls_uint32(output, Version); + sn_utils::ls_uint32(output, static_cast(Sections.size())); + for (auto const §ion : Sections) { + sn_utils::ls_uint32(output, section.index); + sn_utils::ls_uint32(output, static_cast(scene::region_file::section_header_size + section.data.size())); + output << section.data; + } + return output.str(); +} + +std::string check(std::string const &File) { + std::istringstream input{File}; + return scene::region_file::check_layout(input, header, version, sectionlimit); +} + +// what a writer throws when it gives up +class writer_failure : public std::runtime_error { + public: + using std::runtime_error::runtime_error; +}; + +std::string read(std::filesystem::path const &Path) { + std::ifstream input{Path, std::ios::binary}; + return {std::istreambuf_iterator{input}, std::istreambuf_iterator{}}; +} + +} // namespace + +TEST_CASE("region file: a file laid out whole is accepted, with no sections or with many") { + CHECK(check(region({})) == ""); + CHECK(check(region({{0, ""}, {7, std::string(100, 'x')}, {sectionlimit - 1, std::string(3, '\0')}})) == ""); +} + +TEST_CASE("region file: a file cut short anywhere is turned down") { + auto const file{region({{12, std::string(40, 'a')}, {13, std::string(7, 'b')}, {250, std::string(64, 'c')}})}; + REQUIRE(check(file) == ""); + for (std::size_t length{0}; length < file.size(); ++length) { + CAPTURE(length); + CHECK(check(file.substr(0, length)) != ""); + } + // the count of the sections is checked against those present, and the length against where the last one ends + CHECK(check(file.substr(0, file.size() - 64 - 8)).find("ends after 2 of its 3 sections") != std::string::npos); + CHECK(check(file.substr(0, file.size() / 2)).find("ends inside section") != std::string::npos); +} + +TEST_CASE("region file: a file of another type or version is turned down") { + CHECK(check(region({{1, "x"}}, header, version + 1)).find("unrecognized type or version") != std::string::npos); + CHECK(check(region({{1, "x"}}, header + 1, version)).find("unrecognized type or version") != std::string::npos); + CHECK(check("EU0").find("unrecognized type or version") != std::string::npos); +} + +TEST_CASE("region file: sections the region can't hold, held twice, or of impossible sizes are turned down") { + CHECK(check(region({{sectionlimit, "x"}})).find("out of the 250000") != std::string::npos); + CHECK(check(region({{0xffffffffu, "x"}})).find("out of the 250000") != std::string::npos); + CHECK(check(region({{5, "x"}, {5, "y"}})).find("more than once") != std::string::npos); + + // a size smaller than the header of the section + auto file{region({{5, "abcd"}})}; + file[16] = 7; + file[17] = 0; + file[18] = 0; + file[19] = 0; + CHECK(check(file).find("less than its header takes") != std::string::npos); + // a size reaching past the end of the file + file[16] = 13; + CHECK(check(file).find("ends inside section 5") != std::string::npos); + // a size falling short of it + file[16] = 11; + CHECK(check(file).find("bytes past its last section") != std::string::npos); + // more sections than a region has + auto many{region({})}; + for (std::size_t byte{8}; byte < 12; ++byte) { + many[byte] = static_cast(0xff); + } + CHECK(check(many).find("more than the 250000") != std::string::npos); +} + +TEST_CASE("region file: the header of a section is read and checked") { + std::uint32_t index{0}; + std::uint32_t size{0}; + { + std::istringstream input{region({{42, "abc"}}).substr(12)}; + CHECK(scene::region_file::read_section_header(input, sectionlimit, index, size) == ""); + CHECK(index == 42); + CHECK(size == 11); + } + { + std::istringstream input{region({{42, "abc"}}).substr(12, 6)}; + CHECK(scene::region_file::read_section_header(input, sectionlimit, index, size).find("ends inside a section header") != std::string::npos); + } + { + std::istringstream input{region({{42, "abc"}}).substr(12)}; + CHECK(scene::region_file::read_section_header(input, 42, index, size).find("out of the 42") != std::string::npos); + } +} + +TEST_CASE("region file: a string cut short by the end of the data ends there, rather than being read on forever") { + std::istringstream input{std::string{"abc"}}; + CHECK(sn_utils::d_str(input) == "abc"); + CHECK(input.fail()); + CHECK(sn_utils::d_str(input) == ""); + + std::istringstream whole{std::string{"abc\0def", 7}}; + CHECK(sn_utils::d_str(whole) == "abc"); + CHECK(whole.good()); +} + +TEST_CASE("region file: the bytes left in the data are known, so a count it can't hold is turned down before anything is made for it") { + std::istringstream input{std::string(100, 'x')}; + CHECK(sn_utils::remaining(input) == 100); + sn_utils::ld_uint32(input); + CHECK(sn_utils::remaining(input) == 96); + // asking doesn't move the reading on + CHECK(sn_utils::ld_uint32(input) == 0x78787878); + input.seekg(0, std::ios::end); + CHECK(sn_utils::remaining(input) == 0); + sn_utils::ld_uint32(input); + CHECK(input.fail()); + CHECK(sn_utils::remaining(input) == 0); +} + +TEST_CASE("region file: the file is written through a temporary one, which replaces the previous file when complete") { + test::scratch_folder folder{"region_file"}; + auto const file{folder.root() / "scenery.sbt"}; + auto const temporary{folder.root() / "scenery.sbt.tmp"}; + auto const write = [&file](std::string const &Content) { + return scene::region_file::write_through_temporary(file.string(), [&Content](std::ostream &Output) { Output << Content; }); + }; + + SUBCASE("a new file") { + CHECK(write("first") == ""); + CHECK(read(file) == "first"); + CHECK_FALSE(std::filesystem::exists(temporary)); + } + SUBCASE("a previous file is replaced, a longer one entirely") { + REQUIRE(write("a much longer first version") == ""); + CHECK(write("second") == ""); + CHECK(read(file) == "second"); + CHECK_FALSE(std::filesystem::exists(temporary)); + } + SUBCASE("a temporary file left by a write cut short earlier is written over") { + folder.write("scenery.sbt.tmp", "left over from a crash, longer than what follows"); + CHECK(write("third") == ""); + CHECK(read(file) == "third"); + CHECK_FALSE(std::filesystem::exists(temporary)); + } +} + +TEST_CASE("region file: a write which fails leaves the previous file, or none, and no temporary file") { + test::scratch_folder folder{"region_file_failed"}; + auto const file{folder.root() / "scenery.sbt"}; + auto const temporary{folder.root() / "scenery.sbt.tmp"}; + folder.write("scenery.sbt", "previous"); + + SUBCASE("the writer gives up half way") { + auto const error{scene::region_file::write_through_temporary(file.string(), [](std::ostream &Output) { + Output << "half of the"; + throw writer_failure("out of memory"); + })}; + CHECK(error.find("out of memory") != std::string::npos); + } + SUBCASE("the stream fails") { + auto const error{scene::region_file::write_through_temporary(file.string(), [](std::ostream &Output) { + Output << "half of the"; + Output.setstate(std::ios::badbit); + })}; + CHECK(error.find("can't write to file") != std::string::npos); + } + CHECK(read(file) == "previous"); + CHECK_FALSE(std::filesystem::exists(temporary)); + + SUBCASE("the temporary file can't be made") { + auto const missing{folder.root() / "no such folder" / "scenery.sbt"}; + auto const error{scene::region_file::write_through_temporary(missing.string(), [](std::ostream &Output) { Output << "x"; })}; + CHECK(error.find("can't write to file") != std::string::npos); + CHECK_FALSE(std::filesystem::exists(missing)); + } +} From b24e87dc6394c56855b9735ccb9191ceac961925 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 16:32:55 +0100 Subject: [PATCH 090/136] Cab: the light preset selector turns on past its end, with sound (#345) * fix: the light preset selector turns on past its end with sound (eu07/maszyna#464) A selector with Wrap=Yes turned past its last position to the first one (or back) was set with PutValue(): no animation and no sound. On the EN57AKM these are the positions 0 and A1. A knob whose positions make a full turn now turns on the same way it was turned, sounding the position it reaches; other switches still jump, but sound the position too. * refactor(cab): the wrapping rotary switch without Sonar issues The full turn and the way on are declared in the ifs that use them, and the optional is tested with has_value(). No change in behaviour. --- CMakeLists.txt | 1 + tests/unit/test_gauge_wrap.cpp | 55 ++++++++++++++++++++++++++++++++++ vehicle/Gauge.cpp | 21 +++++++++++++ vehicle/Gauge.h | 4 +++ vehicle/Train.cpp | 9 +++--- vehicle/gaugewrap.cpp | 48 +++++++++++++++++++++++++++++ vehicle/gaugewrap.h | 29 ++++++++++++++++++ 7 files changed, 163 insertions(+), 4 deletions(-) create mode 100644 tests/unit/test_gauge_wrap.cpp create mode 100644 vehicle/gaugewrap.cpp create mode 100644 vehicle/gaugewrap.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 2f4f8227d..a047f11ad 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -564,6 +564,7 @@ set(CORE_SOURCES "utilities/physicslog.cpp" "vehicle/enginestart.cpp" "vehicle/brakesetting.cpp" +"vehicle/gaugewrap.cpp" "vehicle/drivingaid.cpp" "vehicle/handover.cpp" "vehicle/crew.cpp" diff --git a/tests/unit/test_gauge_wrap.cpp b/tests/unit/test_gauge_wrap.cpp new file mode 100644 index 000000000..629183369 --- /dev/null +++ b/tests/unit/test_gauge_wrap.cpp @@ -0,0 +1,55 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/gaugewrap.h" +#include "vehicle/gaugepositions.h" + +#include +#include + +// a light preset selector with Wrap=Yes turned on past its last position to the first one, or back past the first one +// to the last (eu07/maszyna#464): the EN57AKM selector has 0 as its first position and A1 as its last one, and the +// knob, rather than jump between them with no sound, turns on to the next position as it does between any two others + +TEST_CASE("gauge wrap: a knob whose positions make a full turn turns on past its end") { + CHECK(gauge_wrap::full_turn(-0.08333f, 12) == 12); // E186, BR285: 12 positions, 30 degrees each + CHECK(gauge_wrap::full_turn(-0.0625f, 16) == 16); // E189: 16 positions + CHECK(gauge_wrap::full_turn(-0.167f, 6) == 6); // EN57AL Zachodniopomorskie: a sixth given as 0.167 +} + +TEST_CASE("gauge wrap: a knob with a free position in its turn turns on across it (eu07/maszyna#464)") { + // EN57AKM: 7 positions, 45 degrees each, A1 at 270 degrees, 0 at 0 degrees: 90 degrees on from A1 to 0 + CHECK(gauge_wrap::full_turn(0.125f, 7) == 8); + // the way on is half a turn at most + CHECK(gauge_wrap::full_turn(0.25f, 3) == 4); + CHECK_FALSE(gauge_wrap::full_turn(0.125f, 4).has_value()); +} + +TEST_CASE("gauge wrap: a switch whose positions don't make a full turn doesn't turn on past its end") { + CHECK_FALSE(gauge_wrap::full_turn(0.1f, 12).has_value()); // the positions would overlap in a turn + CHECK_FALSE(gauge_wrap::full_turn(0.15f, 6).has_value()); // 6.67 positions in a turn + CHECK_FALSE(gauge_wrap::full_turn(0.f, 6).has_value()); // no motion + CHECK_FALSE(gauge_wrap::full_turn(0.5f, 1).has_value()); // nothing to turn to +} + +TEST_CASE("gauge wrap: turned round, the knob stands the same one turn earlier or later") { + // EN57AKM, from A1 (value 6) on to 0: from -2 up to 0, 90 degrees the way it was turned + CHECK(gauge_wrap::turned_round(6.f, 8, true) == doctest::Approx(-2.f)); + // from 0 back to A1 (value 6): from 8 down to 6 + CHECK(gauge_wrap::turned_round(0.f, 8, false) == doctest::Approx(8.f)); + // the angle stays: value * scale differs by one full turn + CHECK((6.f - gauge_wrap::turned_round(6.f, 8, true)) * 0.125f == doctest::Approx(1.f)); +} + +TEST_CASE("gauge wrap: turned round, the knob sounds the position it reaches (eu07/maszyna#464)") { + // the EN57AKM selector has a sound for each position 0-7, as values of the gauge + std::map sounds{{0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}, {7, 7}}; + auto const reached{[&sounds](float const From, float const To) { + auto const position{gauge_positions::last_reached(sounds, static_cast(std::round(100.f * From)), static_cast(std::round(100.f * To)))}; + return position != sounds.end() ? position->second : -1; + }}; + // A1 (6) on to 0 + CHECK(reached(gauge_wrap::turned_round(6.f, 8, true), 0.f) == 0); + // 0 back to A1 (6) + CHECK(reached(gauge_wrap::turned_round(0.f, 8, false), 6.f) == 6); +} diff --git a/vehicle/Gauge.cpp b/vehicle/Gauge.cpp index c99448eed..0944fe83b 100644 --- a/vehicle/Gauge.cpp +++ b/vehicle/Gauge.cpp @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Gauge.h" #include "vehicle/gaugepositions.h" #include "vehicle/gaugeduplicates.h" +#include "vehicle/gaugewrap.h" #include "utilities/parser.h" #include "model/Model3d.h" #include "vehicle/DynObj.h" @@ -401,6 +402,26 @@ TGauge::UpdateValue( float fNewDesired ) { return false; // no suitable sound was found } +void +TGauge::UpdateValueWrapped( float const fNewDesired, bool const Forward, int const Positions, std::optional &Fallbacksound ) { + + if( auto const turn { ( + m_animation == TGaugeAnimation::gt_Rotate && false == m_interpolatescale && m_scaletable.empty() ? + gauge_wrap::full_turn( m_scale, Positions ) : + std::nullopt ) }; + turn.has_value() ) { + // the knob stands the same one turn earlier (later), from there it turns on to the new position + // rather than all the way back, sounding the position it reaches + m_value = gauge_wrap::turned_round( m_value, *turn, Forward ); + m_targetvalue = gauge_wrap::turned_round( m_targetvalue, *turn, Forward ); + UpdateValue( fNewDesired, Fallbacksound ); + return; + } + // a switch that doesn't turn all the way round jumps to the new position, which still sounds + UpdateValue( fNewDesired, Fallbacksound ); + m_value = m_targetvalue; +} + void TGauge::PutValue(float fNewDesired) { // McZapkie-281102: natychmiastowe wpisanie wartosci m_targetvalue = fNewDesired; diff --git a/vehicle/Gauge.h b/vehicle/Gauge.h index 18ddf373a..9c93057c1 100644 --- a/vehicle/Gauge.h +++ b/vehicle/Gauge.h @@ -47,6 +47,10 @@ public: void Load(cParser &Parser, TDynamicObject const *Owner, double const mul = 1.0); bool UpdateValue( float fNewDesired ); bool UpdateValue( float fNewDesired, std::optional &Fallbacksound ); + // sets a multi-position switch of Positions positions, turned on past its last position to the first one (Forward) + // or back past the first one to the last, to the position at fNewDesired. A knob which turns all the way round + // turns on the same way, others jump there; either way the position reached sounds + void UpdateValueWrapped( float fNewDesired, bool Forward, int Positions, std::optional &Fallbacksound ); void PutValue(float fNewDesired); float GetValue() const; float GetDesiredValue() const; diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 4ed2a6b67..080e697c4 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -5455,14 +5455,15 @@ void TTrain::OnCommand_lightspresetactivatenext(TTrain *Train, command_data cons // visual feedback if (Train->ggLightsButton.SubModel != nullptr) { - // HACK: skip submodel animation when restarting cycle, since it plays in the 'wrong' direction if (false == restartcycle) { Train->ggLightsButton.UpdateValue(static_cast(Train->mvOccupied->LightsPos - 1), Train->dsbSwitch); } else { - Train->ggLightsButton.PutValue(static_cast(Train->mvOccupied->LightsPos - 1)); + // past the last position to the first one: a knob turning all the way round turns on rather than + // back across all the positions, and the position reached sounds (eu07/maszyna#464) + Train->ggLightsButton.UpdateValueWrapped(static_cast(Train->mvOccupied->LightsPos - 1), true, Train->mvOccupied->LightsPosNo, Train->dsbSwitch); } } } @@ -5493,14 +5494,14 @@ void TTrain::OnCommand_lightspresetactivateprevious(TTrain *Train, command_data // visual feedback if (Train->ggLightsButton.SubModel != nullptr) { - // HACK: skip submodel animation when restarting cycle, since it plays in the 'wrong' direction if (false == restartcycle) { Train->ggLightsButton.UpdateValue(static_cast(Train->mvOccupied->LightsPos - 1), Train->dsbSwitch); } else { - Train->ggLightsButton.PutValue(static_cast(Train->mvOccupied->LightsPos - 1)); + // back past the first position to the last one, the same way (eu07/maszyna#464) + Train->ggLightsButton.UpdateValueWrapped(static_cast(Train->mvOccupied->LightsPos - 1), false, Train->mvOccupied->LightsPosNo, Train->dsbSwitch); } } } diff --git a/vehicle/gaugewrap.cpp b/vehicle/gaugewrap.cpp new file mode 100644 index 000000000..f16b6e857 --- /dev/null +++ b/vehicle/gaugewrap.cpp @@ -0,0 +1,48 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/gaugewrap.h" + +#include + +namespace gauge_wrap { + +namespace { + +// how far the positions in a full turn worked out from the scale may be off a whole number: the scales in the cab +// definitions are given to three decimals or so, 0.167 for a sixth gives 5.988 +constexpr double turn_tolerance{0.05}; + +} // namespace + +std::optional full_turn(float const Scale, int const Positions) { + if (Positions < 2 || Scale == 0.f) { + return std::nullopt; + } + auto const perturn{1.0 / std::abs(static_cast(Scale))}; + auto const turn{std::round(perturn)}; + if (std::abs(perturn - turn) > turn_tolerance) { + // the positions don't make a full turn: a lever, or a knob that stops at its ends + return std::nullopt; + } + auto const positions{static_cast(turn)}; + // the way on from the last position to the first one, in positions + if (auto const wayon{positions - (Positions - 1)}; wayon < 1 || 2 * wayon > positions) { + // the positions overlap in a turn, or the knob would turn on more than half a turn + return std::nullopt; + } + return positions; +} + +float turned_round(float const Value, int const Turn, bool const Forward) { + return Forward ? Value - static_cast(Turn) : Value + static_cast(Turn); +} + +} // namespace gauge_wrap diff --git a/vehicle/gaugewrap.h b/vehicle/gaugewrap.h new file mode 100644 index 000000000..126652922 --- /dev/null +++ b/vehicle/gaugewrap.h @@ -0,0 +1,29 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include + +// a multi-position rotary switch of the cab turned past its last position to the first one, or back past the first +// one to the last (a selector with Wrap=Yes, such as the light preset selector) +namespace gauge_wrap { + +// the number of positions in one full turn of a rotary switch of Positions positions that turns by Scale of a full turn +// per position, if the switch can turn on past its end the short way round: the full turn is a whole number of positions +// (within the rounding of the scale in the cab definition, e.g. 0.167 for a sixth), all the positions fit in it, and the +// way on from the last position to the first one is at most half a turn. None otherwise +std::optional full_turn(float Scale, int Positions); + +// the value of the switch at Value seen one full turn of Turn positions earlier (Forward: it turns on past its last +// position to the first one) or later (back past the first position to the last one). The knob stands the same there, +// and turning from that value to the new position turns it on the way it was turned rather than all the way back +float turned_round(float Value, int Turn, bool Forward); + +} // namespace gauge_wrap From 97a6218094e9556c9b24cd2ee1b331a240842515 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 16:33:34 +0100 Subject: [PATCH 091/136] fix(audio): measure the start offset on the buffer queued last, not on AL_BUFFER (AL_INVALID_NAME) (#350) * fix(audio): measure the start offset on the buffer queued last, not on AL_BUFFER (AL_INVALID_NAME) openal_source::update() looked up the buffer left playing after a multipart sound's opening bookend with alGetSourcei(AL_BUFFER). For a source with queued buffers that is 0 in OpenAL Soft 1.18 (the version the game ships), and in newer versions once the source has stopped, so alGetBufferi(0) raised AL_INVALID_NAME ("sound: al error: AL_INVALID_NAME" in errors.txt) and the sample offset came from an uninitialised size. It happened every time a sound with a start offset (the motor blowers of the EN76/EN96 family, with start/stop bookends) went from its start sample to the loop. The source now remembers the buffer it queued last and measures that one. The offset itself is computed by audio::start_sample(), in the core library with unit tests; it also keeps the offset inside the buffer. * refactor(audio): the start sample without Sonar issues The sample count is cast to float explicitly, as it was converted implicitly. No change in behaviour. --- CMakeLists.txt | 1 + audio/audiorenderer.cpp | 16 +++++++-------- audio/audiorenderer.h | 2 ++ audio/audiorenderer_extra.h | 5 +++-- audio/startsample.cpp | 28 ++++++++++++++++++++++++++ audio/startsample.h | 19 ++++++++++++++++++ tests/unit/test_start_sample.cpp | 34 ++++++++++++++++++++++++++++++++ 7 files changed, 94 insertions(+), 11 deletions(-) create mode 100644 audio/startsample.cpp create mode 100644 audio/startsample.h create mode 100644 tests/unit/test_start_sample.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index a047f11ad..3e80acbf7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -541,6 +541,7 @@ add_library(eu07_settings INTERFACE) # the parts of the simulation the game shares with the unit tests: the vehicle physics, the vehicle # definition parser, the helpers they use and the rules of the test mode. built once, and tested as the game uses them set(CORE_SOURCES +"audio/startsample.cpp" "McZapkie/friction.cpp" "McZapkie/hamulce.cpp" "McZapkie/Mover.cpp" diff --git a/audio/audiorenderer.cpp b/audio/audiorenderer.cpp index 7950fca56..7d5285def 100644 --- a/audio/audiorenderer.cpp +++ b/audio/audiorenderer.cpp @@ -182,18 +182,16 @@ openal_source::update( double const Deltatime, glm::vec3 const &Listenervelocity --sound_index; sound_change = true; // potentially adjust starting point of the last buffer (to reduce chance of reverb effect with multiple, looping copies playing) - if( controller->start() > 0.f && sounds.size() == 1 ) { - ALint bufferid; - ::alGetSourcei( - id, - AL_BUFFER, - &bufferid ); - ALint buffersize; - ::alGetBufferi( bufferid, AL_SIZE, &buffersize ); + if( controller->start() > 0.f && sounds.size() == 1 && last_buffer != audio::null_resource ) { + // NOTE: the buffer is the one queued last, not the one the source reports: for a source with queued + // buffers AL_BUFFER is 0 in OpenAL Soft 1.18 (the one the game comes with), and in the newer ones + // once the source has stopped. alGetBufferi() on buffer 0 fails with AL_INVALID_NAME + ALint buffersize { 0 }; + ::alGetBufferi( last_buffer, AL_SIZE, &buffersize ); ::alSourcei( id, AL_SAMPLE_OFFSET, - static_cast( controller->start() * ( buffersize / sizeof( std::int16_t ) ) ) ); + audio::start_sample( controller->start(), buffersize ) ); } } diff --git a/audio/audiorenderer.h b/audio/audiorenderer.h index 86ea89cd8..afa819c1b 100644 --- a/audio/audiorenderer.h +++ b/audio/audiorenderer.h @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #pragma once #include "audio/audio.h" +#include "audio/startsample.h" #include "model/ResourceManager.h" #include "application/uitranscripts.h" @@ -69,6 +70,7 @@ struct openal_source { using buffer_sequence = std::vector; ALuint id { audio::null_resource }; + ALuint last_buffer { audio::null_resource }; // the buffer queued last, the one left playing once those before it are done sound_source *controller { nullptr }; uint32_sequence sounds; int sound_index { 0 }; diff --git a/audio/audiorenderer_extra.h b/audio/audiorenderer_extra.h index 430f594b3..fb38816fc 100644 --- a/audio/audiorenderer_extra.h +++ b/audio/audiorenderer_extra.h @@ -19,6 +19,7 @@ openal_source::bind( sound_source *Controller, uint32_sequence Sounds, Iterator_ if( id != audio::null_resource && !buffers.empty()) { ::alSourceQueueBuffers( id, static_cast( buffers.size() ), buffers.data() ); + last_buffer = buffers.back(); ::alSourceRewind( id ); // sound controller can potentially request playback to start from certain buffer point // for multipart sounds the offset is applied only to last piece during playback @@ -29,12 +30,12 @@ openal_source::bind( sound_source *Controller, uint32_sequence Sounds, Iterator_ } else { // move playback start to specified point in 0-1 range - ALint buffersize; + ALint buffersize { 0 }; ::alGetBufferi( buffers.front(), AL_SIZE, &buffersize ); ::alSourcei( id, AL_SAMPLE_OFFSET, - static_cast( controller->start() * ( buffersize / sizeof( std::int16_t ) ) ) ); + audio::start_sample( controller->start(), buffersize ) ); } } diff --git a/audio/startsample.cpp b/audio/startsample.cpp new file mode 100644 index 000000000..673dda151 --- /dev/null +++ b/audio/startsample.cpp @@ -0,0 +1,28 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "audio/startsample.h" + +#include +#include + +namespace audio { + +int start_sample( float const Start, int const Buffersize ) { + + auto const samples { Buffersize / static_cast( sizeof( std::int16_t ) ) }; + if( samples <= 0 + || false == ( Start > 0.f ) ) { // also a NaN + return 0; + } + return std::min( static_cast( std::min( Start, 1.f ) * static_cast( samples ) ), samples - 1 ); +} + +} // audio diff --git a/audio/startsample.h b/audio/startsample.h new file mode 100644 index 000000000..e9837a3a9 --- /dev/null +++ b/audio/startsample.h @@ -0,0 +1,19 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +namespace audio { + +// the sample a sound set to start at Start (a fraction of its length, 0-1) begins to play from, in a buffer of +// Buffersize bytes of 16 bit mono samples (the sound buffers are all made so, see upload_sound()). always a sample +// the buffer has: OpenAL rejects an offset at or past the end with AL_INVALID_VALUE. 0 for an empty buffer +int start_sample( float const Start, int const Buffersize ); + +} // audio diff --git a/tests/unit/test_start_sample.cpp b/tests/unit/test_start_sample.cpp new file mode 100644 index 000000000..00e7fc781 --- /dev/null +++ b/tests/unit/test_start_sample.cpp @@ -0,0 +1,34 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "audio/startsample.h" + +#include + +// the sample a sound with a start offset (startoffset:, or the random one of motors, motor blowers and +// the running noise) begins to play from, in the 16 bit mono buffers the sound files are loaded into + +TEST_CASE("start_sample: a fraction of the samples of the buffer, two bytes each") { + CHECK(audio::start_sample(0.5f, 1000) == 250); + CHECK(audio::start_sample(0.25f, 88200) == 11025); + CHECK(audio::start_sample(0.999f, 1000) == 499); +} + +TEST_CASE("start_sample: no offset starts at the first sample") { + CHECK(audio::start_sample(0.f, 1000) == 0); + CHECK(audio::start_sample(-0.5f, 1000) == 0); + CHECK(audio::start_sample(std::numeric_limits::quiet_NaN(), 1000) == 0); +} + +TEST_CASE("start_sample: the end of the buffer is its last sample, not past it") { + // OpenAL takes an offset at or past the end of the buffer for AL_INVALID_VALUE + CHECK(audio::start_sample(1.f, 1000) == 499); + CHECK(audio::start_sample(1.5f, 1000) == 499); + CHECK(audio::start_sample(1.f, 2) == 0); +} + +TEST_CASE("start_sample: a buffer of unknown or no size starts at 0") { + CHECK(audio::start_sample(0.5f, 0) == 0); + CHECK(audio::start_sample(0.5f, 1) == 0); + CHECK(audio::start_sample(0.5f, -4) == 0); +} From 96bc3e686358fdd47d12bc5785f7f0d08689d2f3 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 16:33:42 +0100 Subject: [PATCH 092/136] fix(cab): the compartment lights keyboard toggle works more than once in a cab without the switch (#353) * fix(cab): the compartment lights keyboard toggle works more than once in a cab without the switch The compartment lights get two requests, on (CompartmentLights.is_enabled) and off (is_disabled), and the off one wins in LightsCheck(). The enable and disable commands withdrew the other request only when the cab had a toggle type compartmentlights_sw:. A push type switch and the separate compartmentlightson_sw:/compartmentlightsoff_sw: push buttons withdraw their own request when released, but a cab with none of these controls (the CD 810 cab A, where only the engine compartment has the switch) never withdrew anything: after one on/off both requests stayed set, the lights stayed off and ctrl+; kept choosing "turn off". Now a command withdraws the other request when the cab has the toggle type switch (as before), or when it has no compartmentlights_sw: and no push button for the other request, so the keyboard toggle acts as a two-state switch there. Cabs with a push type switch or with the on/off push buttons keep their behaviour. The decision is in vehicle/compartmentlightsswitch.h, unit tested together with the vehicle's LightsCheck() on the Elf definition. * fix(cab): the compartment lights keyboard toggle latches in a cab with the on and off push buttons (#355) In a cab with the compartmentlightson_sw: / compartmentlightsoff_sw: push buttons and no compartmentlights_sw: (the EN57-2000, the SA134, the 214M, the EN57AKL/AL/KM and EN71) ctrl+; turned the compartment lights off only while the key was held. OnCommand_compartmentlightstoggle picked the command from the lights' state again on the key release, after the press had changed that state, so the release went to the other command: the push button that was pressed never withdrew its request. After the first press the on request stayed set, and from then on every release withdrew the off request and the lights came back on. The toggle now sends the release to both commands, as a release of the push buttons would: each returns its own push type control to the neutral position and withdraws its request. The press is picked from the state as before. Mouse clicks on the push buttons go to the enable and disable commands directly and are unchanged; with a compartmentlights_sw: both commands release it the same way, and a cab without the controls has nothing to release. In the Elf cab (an impulse compartmentlights_sw: and the on/off return buttons) the lights worked, but the button the key had pressed stayed pressed; now it returns too. * test(cab): the compartment lights switch test without Sonar issues using enum for range_t in the release helpers, and the lights declared in the if that reads them. No change in what is tested. --- tests/unit/test_compartment_lights_switch.cpp | 227 ++++++++++++++++++ vehicle/Train.cpp | 31 ++- vehicle/compartmentlightsswitch.h | 27 +++ 3 files changed, 273 insertions(+), 12 deletions(-) create mode 100644 tests/unit/test_compartment_lights_switch.cpp create mode 100644 vehicle/compartmentlightsswitch.h diff --git a/tests/unit/test_compartment_lights_switch.cpp b/tests/unit/test_compartment_lights_switch.cpp new file mode 100644 index 000000000..b9ba78398 --- /dev/null +++ b/tests/unit/test_compartment_lights_switch.cpp @@ -0,0 +1,227 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +#include "vehicle/compartmentlightsswitch.h" + +using test::definition; +using test::vehicle; + +// the compartment lights commands of the cab (TTrain::OnCommand_compartmentlightsenable/disable/toggle): whether the +// command for one request (on: CompartmentLights.is_enabled, off: is_disabled) also withdraws the other one. In a cab +// without compartmentlights_sw: and without the push buttons (the CD 810 cab A) the keyboard toggle, ctrl+;, turned +// the lights on and off once, then never again: the off request stayed set alongside the on one. In a cab with the +// compartmentlightson_sw: / compartmentlightsoff_sw: push buttons (the EN57-2000) the toggle sent the key release to the +// other command than the press, picked again from the state the press had changed: the pressed button never withdrew +// its request and the lights were off only while ctrl+; was held. + +TEST_CASE("compartment lights switch: which command withdraws the other request") { + // a two-state compartmentlights_sw: holds one request at a time + CHECK(compartment_lights_switch::withdraws_other_request(true, true, false)); + CHECK(compartment_lights_switch::withdraws_other_request(true, true, true)); + // a push type compartmentlights_sw: withdraws both requests itself, when it's released + CHECK_FALSE(compartment_lights_switch::withdraws_other_request(true, false, false)); + CHECK_FALSE(compartment_lights_switch::withdraws_other_request(true, false, true)); + // no compartmentlights_sw:, the push button of the other request withdraws it when it's released + CHECK_FALSE(compartment_lights_switch::withdraws_other_request(false, false, true)); + CHECK_FALSE(compartment_lights_switch::withdraws_other_request(false, true, true)); + // no compartmentlights_sw: and no push button: nothing else would withdraw it + CHECK(compartment_lights_switch::withdraws_other_request(false, false, false)); + CHECK(compartment_lights_switch::withdraws_other_request(false, true, false)); +} + +namespace { + +// the compartment lights controls a cab's .mmd may have +struct cab_controls { + bool has_switch{false}; // compartmentlights_sw: + bool switch_is_toggle{true}; // its type (a gauge is a toggle type unless declared otherwise) + bool has_on_button{false}; // compartmentlightson_sw: + bool has_off_button{false}; // compartmentlightsoff_sw: +}; + +// the effect of the cab's commands on the vehicle, as TTrain::OnCommand_compartmentlightsenable/disable/toggle do it +// NOTE: LightsCheck() runs between the press and the release, as the vehicle update does between two frames +void lights_check(vehicle &Car) { + Car->LightsCheck(0.01); +} + +void enable_press(vehicle &Car, cab_controls const &Cab) { + Car->CompartmentLightsSwitch(true, range_t::local); + if (compartment_lights_switch::withdraws_other_request(Cab.has_switch, Cab.switch_is_toggle, Cab.has_off_button)) { + Car->CompartmentLightsSwitchOff(false, range_t::local); + } +} + +void enable_release(vehicle &Car, cab_controls const &Cab) { + using enum range_t; + if (Cab.has_switch && false == Cab.switch_is_toggle) { + Car->CompartmentLightsSwitch(false, local); + Car->CompartmentLightsSwitchOff(false, local); + } + if (Cab.has_on_button) { + Car->CompartmentLightsSwitch(false, local); + } +} + +void disable_press(vehicle &Car, cab_controls const &Cab) { + Car->CompartmentLightsSwitchOff(true, range_t::local); + if (compartment_lights_switch::withdraws_other_request(Cab.has_switch, Cab.switch_is_toggle, Cab.has_on_button)) { + Car->CompartmentLightsSwitch(false, range_t::local); + } +} + +void disable_release(vehicle &Car, cab_controls const &Cab) { + using enum range_t; + if (Cab.has_switch && false == Cab.switch_is_toggle) { + Car->CompartmentLightsSwitch(false, local); + Car->CompartmentLightsSwitchOff(false, local); + } + if (Cab.has_off_button) { + Car->CompartmentLightsSwitchOff(false, local); + } +} + +// a click on the control of the command (or its own key): the press, then the release +void enable(vehicle &Car, cab_controls const &Cab) { + enable_press(Car, Cab); + lights_check(Car); + enable_release(Car, Cab); + lights_check(Car); +} + +void disable(vehicle &Car, cab_controls const &Cab) { + disable_press(Car, Cab); + lights_check(Car); + disable_release(Car, Cab); + lights_check(Car); +} + +// the keyboard toggle picks the command from the state on the press, the key held down for a few frames; the release +// goes to both commands, the press changed the state it would be picked from +void toggle(vehicle &Car, cab_controls const &Cab) { + if (auto const &lights{Car->CompartmentLights}; false == lights.is_active && false == lights.is_enabled) { + enable_press(Car, Cab); + } + else { + disable_press(Car, Cab); + } + for (auto frame = 0; frame < 3; ++frame) { + lights_check(Car); + } + enable_release(Car, Cab); + disable_release(Car, Cab); + lights_check(Car); +} + +// the Elf (21WE-a), its compartment lights started by hand, with the converter running +void power_up(vehicle &Car) { + REQUIRE(Car->CompartmentLights.start_type == start_t::manual); + Car->Power110vIsAvailable = true; + lights_check(Car); + REQUIRE_FALSE(Car->CompartmentLights.is_active); +} + +} // namespace + +TEST_CASE("compartment lights switch: the keyboard toggle works every time in a cab without the switch") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + power_up(car); + cab_controls const cab{}; // no compartmentlights_sw:, no push buttons, like the CD 810 cab A + + for (auto press = 1; press <= 6; ++press) { + CAPTURE(press); + toggle(car, cab); + // odd presses turn the lights on, even ones off + CHECK(car->CompartmentLights.is_active == (press % 2 == 1)); + // one request at a time + CHECK_FALSE((car->CompartmentLights.is_enabled && car->CompartmentLights.is_disabled)); + } +} + +TEST_CASE("compartment lights switch: the keyboard toggle in a cab with the two-state switch, as before") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + power_up(car); + cab_controls const cab{.has_switch = true, .switch_is_toggle = true}; + + for (auto press = 1; press <= 4; ++press) { + CAPTURE(press); + toggle(car, cab); + CHECK(car->CompartmentLights.is_active == (press % 2 == 1)); + // the switch holds the request of its position + CHECK(car->CompartmentLights.is_enabled == (press % 2 == 1)); + CHECK(car->CompartmentLights.is_disabled == (press % 2 == 0)); + } +} + +TEST_CASE("compartment lights switch: the push type switch withdraws both requests when released, as before") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + power_up(car); + cab_controls const cab{.has_switch = true, .switch_is_toggle = false}; + + for (auto press = 1; press <= 4; ++press) { + CAPTURE(press); + toggle(car, cab); + CHECK(car->CompartmentLights.is_active == (press % 2 == 1)); + CHECK_FALSE(car->CompartmentLights.is_enabled); + CHECK_FALSE(car->CompartmentLights.is_disabled); + } +} + +TEST_CASE("compartment lights switch: the on and off push buttons latch the lights, as before") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + power_up(car); + cab_controls const cab{.has_on_button = true, .has_off_button = true}; + + for (auto round = 1; round <= 2; ++round) { + CAPTURE(round); + // each button withdraws its own request when it's released, the lights stay as they were put + enable(car, cab); + CHECK(car->CompartmentLights.is_active); + CHECK_FALSE(car->CompartmentLights.is_enabled); + CHECK_FALSE(car->CompartmentLights.is_disabled); + disable(car, cab); + CHECK_FALSE(car->CompartmentLights.is_active); + CHECK_FALSE(car->CompartmentLights.is_enabled); + CHECK_FALSE(car->CompartmentLights.is_disabled); + } +} + +TEST_CASE("compartment lights switch: the keyboard toggle latches the lights in a cab with the on and off push buttons") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + power_up(car); + cab_controls const cab{.has_on_button = true, .has_off_button = true}; // no compartmentlights_sw:, like the EN57-2000 + + for (auto press = 1; press <= 6; ++press) { + CAPTURE(press); + toggle(car, cab); + // odd presses turn the lights on, even ones off, and they stay so after the key is released + CHECK(car->CompartmentLights.is_active == (press % 2 == 1)); + // both push buttons are back in the neutral position, neither request is left behind + CHECK_FALSE(car->CompartmentLights.is_enabled); + CHECK_FALSE(car->CompartmentLights.is_disabled); + } +} + +TEST_CASE("compartment lights switch: the keyboard toggle and the on and off push buttons work together") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + power_up(car); + cab_controls const cab{.has_on_button = true, .has_off_button = true}; + + toggle(car, cab); + REQUIRE(car->CompartmentLights.is_active); + // the off button turns off what the key turned on... + disable(car, cab); + CHECK_FALSE(car->CompartmentLights.is_active); + // ...and the key turns on what the off button turned off + toggle(car, cab); + CHECK(car->CompartmentLights.is_active); + toggle(car, cab); + CHECK_FALSE(car->CompartmentLights.is_active); + enable(car, cab); + CHECK(car->CompartmentLights.is_active); + toggle(car, cab); + CHECK_FALSE(car->CompartmentLights.is_active); + CHECK_FALSE(car->CompartmentLights.is_enabled); + CHECK_FALSE(car->CompartmentLights.is_disabled); +} diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 080e697c4..24d3132f6 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/horn.h" #include "vehicle/linebreaker.h" #include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" #include "vehicle/odometer.h" #include "vehicle/mainctrlact.h" @@ -6636,6 +6637,16 @@ void TTrain::OnCommand_compartmentlightstoggle(TTrain *Train, command_data const return; } + if (Command.action == GLFW_RELEASE) + { + // the press changed the state the command is picked from below, so a release picked from it went to the other + // command and the push button that was pressed never withdrew its request. The release goes to both commands: + // each returns its own push type control to the neutral position and withdraws its request + OnCommand_compartmentlightsenable(Train, Command); + OnCommand_compartmentlightsdisable(Train, Command); + return; + } + // keep the switch from flipping back and forth if key is held down if (false == Train->mvOccupied->CompartmentLights.is_active && false == Train->mvOccupied->CompartmentLights.is_enabled) { @@ -6655,13 +6666,11 @@ void TTrain::OnCommand_compartmentlightsenable(TTrain *Train, command_data const if (Command.action == GLFW_PRESS) { Train->mvOccupied->CompartmentLightsSwitch(true); - if (Train->m_controlmapper.contains("compartmentlights_sw:")) + // withdraw the off request, unless a push type control in the cab withdraws it when released + if (compartment_lights_switch::withdraws_other_request(Train->m_controlmapper.contains("compartmentlights_sw:"), Train->ggCompartmentLightsButton.is_toggle(), + Train->m_controlmapper.contains("compartmentlightsoff_sw:"))) { - auto const istoggle{(static_cast(Train->ggCompartmentLightsButton.type()) & static_cast(TGaugeType::toggle)) != 0}; - if (istoggle) - { - Train->mvOccupied->CompartmentLightsSwitchOff(false); - } + Train->mvOccupied->CompartmentLightsSwitchOff(false); } // visual feedback if (Train->m_controlmapper.contains("compartmentlights_sw:")) @@ -6696,13 +6705,11 @@ void TTrain::OnCommand_compartmentlightsdisable(TTrain *Train, command_data cons if (Command.action == GLFW_PRESS) { Train->mvOccupied->CompartmentLightsSwitchOff(true); - if (Train->m_controlmapper.contains("compartmentlights_sw:")) + // withdraw the on request, unless a push type control in the cab withdraws it when released + if (compartment_lights_switch::withdraws_other_request(Train->m_controlmapper.contains("compartmentlights_sw:"), Train->ggCompartmentLightsButton.is_toggle(), + Train->m_controlmapper.contains("compartmentlightson_sw:"))) { - auto const istoggle{(static_cast(Train->ggCompartmentLightsButton.type()) & static_cast(TGaugeType::toggle)) != 0}; - if (istoggle) - { - Train->mvOccupied->CompartmentLightsSwitch(false); - } + Train->mvOccupied->CompartmentLightsSwitch(false); } // visual feedback if (Train->m_controlmapper.contains("compartmentlights_sw:")) diff --git a/vehicle/compartmentlightsswitch.h b/vehicle/compartmentlightsswitch.h new file mode 100644 index 000000000..0ef6684c0 --- /dev/null +++ b/vehicle/compartmentlightsswitch.h @@ -0,0 +1,27 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +// the compartment lights get two requests: on (CompartmentLights.is_enabled) and off (is_disabled), and the off one +// wins. A two-state compartmentlights_sw: holds one of them, so turning it to one position withdraws the other request. +// A push type compartmentlights_sw: and the separate compartmentlightson_sw: / compartmentlightsoff_sw: push buttons +// withdraw their own request when they're released, so the other command leaves it alone. A cab with none of these +// controls (the keyboard toggle, ctrl+;, is all there is) acts as if it had the two-state switch, otherwise nothing +// would ever withdraw the off request and the lights couldn't be turned on again. +namespace compartment_lights_switch { + +// whether the command for one of the requests also withdraws the other one, from the cab's compartmentlights_sw: +// (whether it's there and whether it's a toggle type switch) and whether the cab has the push button of the other +// request (compartmentlightsoff_sw: for the on command, compartmentlightson_sw: for the off command) +inline bool withdraws_other_request(bool const Hasswitch, bool const Switchistoggle, bool const Hasotherbutton) { + return Hasswitch ? Switchistoggle : false == Hasotherbutton; +} + +} // namespace compartment_lights_switch From 8bff78588634d41769255a777c21f41173810668 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 16:34:04 +0100 Subject: [PATCH 093/136] build: optionally use the system nlohmann_json (USE_SYSTEM_JSON) (#360) USE_SYSTEM_JSON (default OFF) takes an installed nlohmann_json 3.9 or newer (ordered_json, used by the unit tests) with find_package instead of the ref/json submodule. Both give the nlohmann_json::nlohmann_json target linked to eu07_settings. Drop the include directory from the never defined NLOHMANN_JSON_INCLUDE_INSTALL_DIR. Fixes #54. --- CMakeLists.txt | 11 ++++++++--- README.md | 1 + 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 3e80acbf7..cf1b137f7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -86,6 +86,7 @@ option(ENABLE_MCC "Enable multicore compilation" ON) option(WITHDUMPGEN "Enable generating DMP files on crash" ON) option(ENABLE_AVX2 "Enable AVX2 instruction set (requires AVX2-capable CPU, Haswell/2013 or newer)" ON) option(ADD_VERSION_SUFFIX "Add date and commit hash to the executable name" ON) +option(USE_SYSTEM_JSON "Use an installed nlohmann_json (3.9 or newer) instead of the ref/json submodule" OFF) set(BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) # vcpkg init @@ -698,10 +699,14 @@ target_link_libraries(eu07_settings INTERFACE Threads::Threads) find_package(GLM REQUIRED) target_include_directories(eu07_settings INTERFACE ${GLM_INCLUDE_DIR}) -# JSON lib -add_subdirectory(ref/json) +# JSON lib: the ref/json submodule by default, or an installed package (e.g. nlohmann-json3-dev, vcpkg nlohmann-json). +# Both give the nlohmann_json::nlohmann_json target; 3.9 is the first release with ordered_json, used by the unit tests. +if (USE_SYSTEM_JSON) + find_package(nlohmann_json 3.9 REQUIRED) +else() + add_subdirectory(ref/json) +endif() target_link_libraries(eu07_settings INTERFACE nlohmann_json::nlohmann_json) -target_include_directories(eu07_settings INTERFACE ${NLOHMANN_JSON_INCLUDE_INSTALL_DIR}) diff --git a/README.md b/README.md index 675026ccf..f0c7ac3cd 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,7 @@ MaSzyna compiles and runs natively on **Linux** and **Windows**. Other platforms | `-DCMAKE_BUILD_TYPE=Release` | Release build | | `-DCMAKE_BUILD_TYPE=RelWithDebInfo` | Release build with debug symbols | | `-DWITH_BETTER_RENDERER=ON/OFF` | Enable/disable NVRHI-based renderer | +| `-DUSE_SYSTEM_JSON=ON/OFF` | Use an installed **nlohmann_json** 3.9 or newer (e.g. `nlohmann-json3-dev`, vcpkg `nlohmann-json`) instead of the `ref/json` submodule (default `OFF`) | | `-DPython3_ROOT_DIR=` | Root of the **Python 3.14** install on Windows (`python.exe`, `Lib`, `DLLs`) for embed/copy steps; on Linux, optional if CMake picks the wrong interpreter | > **Linux note:** `WITH_BETTER_RENDERER` uses DirectX 12 through NVRHI and is **not supported on Linux**. From 2f12768815c3258e08aa036ad5823eb557084e54 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 16:35:59 +0100 Subject: [PATCH 094/136] fix(timetable): the station of departure written in capitals is still a stop (#343) The first row of a timetable, which usually gives only the departure time, became a stop only when its name matched the relation's first station case-sensitively. Os33733 of linia_107_poludnie.scn writes ZAGORZ in the rows and Zagorz in the relation, so its driver counted Zagorz as passed at the start, left before its departure time and the train manager never gave the departure signal. The names are now compared regardless of case (timetable::starts_at in the core library). Tests: unit test of the rule; td.scn scenario cases with a timetable of the case's own (first row STACJA1, and Stacja1 as control) and the td.scn train started with its head 80 m past the W4 of Stacja1; the scenario runner can copy a timetable of the case into the game for the run. --- CMakeLists.txt | 1 + tests/scenarios/README.md | 15 ++++++- .../cases/eu07_td_departure_station.json | 35 +++++++++++++++++ .../eu07_td_departure_station_capitals.json | 35 +++++++++++++++++ .../cases/eu07_td_timetable_past_w4.json | 28 +++++++++++++ .../scenarios/cases/td_departure_station.scn | 9 +++++ .../scenarios/cases/td_departure_station.txt | 20 ++++++++++ .../cases/td_departure_station_capitals.txt | 20 ++++++++++ .../scenarios/cases/td_timetable_past_w4.scn | 9 +++++ tests/scenarios/run.py | 19 +++++++-- tests/unit/test_timetable_start.cpp | 39 +++++++++++++++++++ world/mtable.cpp | 5 ++- world/timetablestart.cpp | 25 ++++++++++++ world/timetablestart.h | 23 +++++++++++ 14 files changed, 277 insertions(+), 6 deletions(-) create mode 100644 tests/scenarios/cases/eu07_td_departure_station.json create mode 100644 tests/scenarios/cases/eu07_td_departure_station_capitals.json create mode 100644 tests/scenarios/cases/eu07_td_timetable_past_w4.json create mode 100644 tests/scenarios/cases/td_departure_station.scn create mode 100644 tests/scenarios/cases/td_departure_station.txt create mode 100644 tests/scenarios/cases/td_departure_station_capitals.txt create mode 100644 tests/scenarios/cases/td_timetable_past_w4.scn create mode 100644 tests/unit/test_timetable_start.cpp create mode 100644 world/timetablestart.cpp create mode 100644 world/timetablestart.h diff --git a/CMakeLists.txt b/CMakeLists.txt index cf1b137f7..75dbc5df5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -575,6 +575,7 @@ set(CORE_SOURCES "vehicle/linebreaker.cpp" "vehicle/smoke.cpp" "vehicle/odometer.cpp" +"world/timetablestart.cpp" "vehicle/timetableservice.cpp" "world/timetableflags.cpp" "world/timetablereader.cpp" diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index d8bdd160b..7e9ceef7c 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -135,7 +135,7 @@ Python 3.10+, no extra packages. Options: `cmake-build-*/bin/Release/eu07*.exe`. The build needs the `--test` and `-ini` command line options. - name one or more cases to run only those, e.g. `run.py ... eu07_td_timetable`. -- `-j N` runs N cases at once. Each case prints its results when it is done. The 19 cases +- `-j N` runs N cases at once. Each case prints its results when it is done. The 22 cases that aren't `slow` take about 30 s with `-j 4` and 2 minutes one at a time, loading included. - `--watch` runs a case the old way, in a visible window in real time (or faster with `--timespeed N`), closed after the case's `duration`; the exit code isn't checked then. For @@ -214,6 +214,7 @@ to `logs/`. | `ini` | extra `eu07.ini` lines for the run, after the common ones of the runner's `-ini` file, e.g. `["crashdamage yes"]` | | `fragment` | `.scn` file in `cases/` added to the scenery: trainsets after `FirstInit` (before it they derail on unlinked track), the rest before it (launchers read after it never fire). Optional when the case keeps the scenery's trainsets | | `vars` | values for `{{name}}` in the fragment; a list becomes one line per item | +| `timetable` | a timetable file in `cases/` for a trainset of the fragment, for a train whose timetable no scenery of the game has: copied to the game's `scenery/` dir as `autotest_.txt` for the run and removed after it; the fragment names it `{{timetable}}` | | `expect` | the result the test mode should end with: `pass`, `fail`, `signal_passed_at_danger`, `timeout`, `standstill` or `error`, or `wall_timeout` for the timeout of the real time watchdog (the timeout code with a verdict saying it was the real time; a case expecting `timeout` fails on it). Default `timeout` for a case with `duration`, else `pass` | | `duration` | seconds of simulation to record: the test timeout of the run (`--test-timeout`) | | `timeout` | wall-clock seconds before giving up, loading included: the simulator's `--test-wall-timeout` (default 600) | @@ -236,6 +237,18 @@ and slides past the signal, so those cases set `test.fail_if_stop_overran no`. `td_red_signal_pass.scn` adds the `test_pass` event, which `test_mode_pass` puts as `event0` on `tor1k`, the track in front of the signal. +`eu07_td_departure_station_capitals` runs an EU07 from where `td_timetable.scn` puts it, with the W4 of Stacja1 about +35 m ahead, on a timetable of its own (`td_departure_station_capitals.txt`, fragment `td_departure_station.scn`): +its first row, the station of departure, gives no arrival time and is written in capitals (`STACJA1`), the relation +says `Stacja1`, as in some timetables of the game (`Os33733` of linia_107_poludnie.scn starts at `ZAGORZ`). The +train has to stop there and leave at its departure time, 10:35, which the log shows as `as TEST24: at 10:35 next +Przystanek`; taking Stacja1 for a station it passes through, the driver logs `passed STACJA1` at once and leaves as +soon as the route is set at 10:34, and the train manager gives no departure signal. `eu07_td_departure_station` is the +same with the row written as in the relation. `eu07_td_timetable_past_w4` (fragment `td_timetable_past_w4.scn`) puts +the td/rozklad train, an EU07 with three coaches, with its head 80 m past the W4 of Stacja1, on `tor1k`: the W4 stays +under the consist, behind the head, and the driver still counts Stacja1 and leaves at 10:35, since the scan of the +route begins at the last vehicle and keeps a W4 behind the head. + The `test_mode_*` cases show the ends of the test mode: `test_mode_pass` (exit 0, the pass event), `test_mode_signal_passed_at_danger` (exit 11), `test_mode_timeout` (exit 12, from `test.timeout`), `test_mode_standstill` (exit 13, from `test.standstill`) and diff --git a/tests/scenarios/cases/eu07_td_departure_station.json b/tests/scenarios/cases/eu07_td_departure_station.json new file mode 100644 index 000000000..eb97b708c --- /dev/null +++ b/tests/scenarios/cases/eu07_td_departure_station.json @@ -0,0 +1,35 @@ +{ + "description": "Control for eu07_td_departure_station_capitals: the same timetable with the first row written as in the relation (Stacja1). The train stops at Stacja1 and leaves at 10:35.", + "base_scenery": "td.scn", + "time": "10:33", + "fragment": "td_departure_station.scn", + "timetable": "td_departure_station.txt", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 360, + "timeout": 600, + "checks": [ + { + "type": "log_lacks", + "pattern": "as TEST25: at \\d+:\\d+ passed Stacja1" + }, + { + "type": "log_contains", + "pattern": "as TEST25: at 10:35 next Przystanek" + }, + { + "type": "starts", + "min_speed": 20, + "within": 240 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 0, + "min_distance": 1380, + "max_distance": 1420 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_departure_station_capitals.json b/tests/scenarios/cases/eu07_td_departure_station_capitals.json new file mode 100644 index 000000000..cf1cbe2bd --- /dev/null +++ b/tests/scenarios/cases/eu07_td_departure_station_capitals.json @@ -0,0 +1,35 @@ +{ + "description": "EU07 on td.scn on a timetable whose first row, the station of departure, is written in capitals (STACJA1) and gives no arrival time, while the relation says Stacja1. The train is to stop there and wait for its departure at 10:35, not take Stacja1 for a station it passes through and leave as soon as the route is set at 10:34 (linia_107_poludnie.scn, Os33733 at ZAGORZ).", + "base_scenery": "td.scn", + "time": "10:33", + "fragment": "td_departure_station.scn", + "timetable": "td_departure_station_capitals.txt", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 360, + "timeout": 600, + "checks": [ + { + "type": "log_lacks", + "pattern": "as TEST24: at \\d+:\\d+ passed STACJA1" + }, + { + "type": "log_contains", + "pattern": "as TEST24: at 10:35 next Przystanek" + }, + { + "type": "starts", + "min_speed": 20, + "within": 240 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 0, + "min_distance": 1380, + "max_distance": 1420 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_timetable_past_w4.json b/tests/scenarios/cases/eu07_td_timetable_past_w4.json new file mode 100644 index 000000000..c60effbed --- /dev/null +++ b/tests/scenarios/cases/eu07_td_timetable_past_w4.json @@ -0,0 +1,28 @@ +{ + "description": "EU07 with three coaches on td.scn on the td/rozklad timetable, placed with its head 80 m past the W4 of Stacja1, the first station of the timetable, which stays under the consist. The driver counts Stacja1 as the stop it stands at and leaves at 10:35.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable_past_w4.scn", + "vars": { + "offset": 15, + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic" + ] + }, + "duration": 300, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "as ROJ65113: at 10:35 next Przystanek" + }, + { + "type": "starts", + "min_speed": 20, + "within": 240 + } + ] +} diff --git a/tests/scenarios/cases/td_departure_station.scn b/tests/scenarios/cases/td_departure_station.scn new file mode 100644 index 000000000..b005516c4 --- /dev/null +++ b/tests/scenarios/cases/td_departure_station.scn @@ -0,0 +1,9 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// the same start as td_timetable.scn, the W4 of Stacja1 about 35 m ahead of the train, but on the case's own +// timetable: {{timetable}}, a copy of the case's "timetable" file, Stacja1 10:35 -> Przystanek -> Stacja2 whose +// first row gives no arrival time, only the departure. the route out of track 1 is set at 10:34 +trainset {{timetable}} tdo_n1734 0.0 0.1 +{{consist}} +endtrainset + +node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end diff --git a/tests/scenarios/cases/td_departure_station.txt b/tests/scenarios/cases/td_departure_station.txt new file mode 100644 index 000000000..cd4851228 --- /dev/null +++ b/tests/scenarios/cases/td_departure_station.txt @@ -0,0 +1,20 @@ +________________________________________________________________ +[ Rodzaj i numer pociagu | TEST25 ] +[ Kategoria | RO ] +[________________________________________________|______________] +[ | Stacja1 ] +[ Relacja pociagu | Stacja2 ] +[________________________________________________|______________] +[ Wymagany % ciezaru hamujacego | 88% ] +[________________________________________________|______________] +[ Seria i obciazenie lokomotywy | EU07 210 ] +[________________________________________________|______________] +[ | | Stacja1 2 | | ] +[ | 60 | R1,L,H,RT,PP 2 10.35 | ] +[ | |----------------------------------1----------|---] +[ | | Przystanek 1 10.37 | 4 ] +[ |_____| R1,+,L,H,PP,pt 1 10.37.3 | ] +[ | 90 |----------------------------------1----------|---] +[ | | Stacja2 1 10.39 | 1 ] +[ | | R1 1 10.40 | ] +[_______|_____|__________________________________1__________|___] diff --git a/tests/scenarios/cases/td_departure_station_capitals.txt b/tests/scenarios/cases/td_departure_station_capitals.txt new file mode 100644 index 000000000..8d727d5d0 --- /dev/null +++ b/tests/scenarios/cases/td_departure_station_capitals.txt @@ -0,0 +1,20 @@ +________________________________________________________________ +[ Rodzaj i numer pociagu | TEST24 ] +[ Kategoria | RO ] +[________________________________________________|______________] +[ | Stacja1 ] +[ Relacja pociagu | Stacja2 ] +[________________________________________________|______________] +[ Wymagany % ciezaru hamujacego | 88% ] +[________________________________________________|______________] +[ Seria i obciazenie lokomotywy | EU07 210 ] +[________________________________________________|______________] +[ | | STACJA1 2 | | ] +[ | 60 | R1,L,H,RT,PP 2 10.35 | ] +[ | |----------------------------------1----------|---] +[ | | Przystanek 1 10.37 | 4 ] +[ |_____| R1,+,L,H,PP,pt 1 10.37.3 | ] +[ | 90 |----------------------------------1----------|---] +[ | | Stacja2 1 10.39 | 1 ] +[ | | R1 1 10.40 | ] +[_______|_____|__________________________________1__________|___] diff --git a/tests/scenarios/cases/td_timetable_past_w4.scn b/tests/scenarios/cases/td_timetable_past_w4.scn new file mode 100644 index 000000000..e7e83d51b --- /dev/null +++ b/tests/scenarios/cases/td_timetable_past_w4.scn @@ -0,0 +1,9 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// the timetable train of td.scn (td/rozklad, Stacja1 10:35 -> Przystanek -> Stacja2) placed past the W4 of +// Stacja1 instead of before it: the head {{offset}} m into tor1k, the track after the one with the W4, which is +// left under the consist, behind the head. the route out of track 1 is set at 10:34 +trainset td/rozklad tor1k {{offset}} 0.1 +{{consist}} +endtrainset + +node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py index 438b68aa4..fd1941577 100644 --- a/tests/scenarios/run.py +++ b/tests/scenarios/run.py @@ -146,6 +146,15 @@ def scenery_cache(game_dir: Path, case_name: str) -> Path: return game_dir / "scenery" / f"autotest_{case_name}.sbt" +def timetable_name(case_name: str) -> str: + """The case's own timetable as a trainset names it: {{timetable}} in the fragment.""" + return f"autotest_{case_name}" + + +def timetable_path(game_dir: Path, case_name: str) -> Path: + return game_dir / "scenery" / f"{timetable_name(case_name)}.txt" + + def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> str: """Writes the case scenery into the game's scenery dir and returns its file name.""" scenery_dir = game_dir / "scenery" @@ -165,9 +174,9 @@ def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> s text = text.replace(old, new) # a case on a mission of the base scenery may have nothing to add but its test_config fragment = (CASES_DIR / case["fragment"]).read_bytes().decode("latin-1") if "fragment" in case else "" - # vars first: {{vehicle}} inside a var's value gets filled in the second pass - fragment = fill_vars(fragment, case.get("vars", {}), keep={"vehicle"}) - fragment = fill_vars(fragment, {"vehicle": vehicle}) + # vars first: {{vehicle}} and {{timetable}} inside a var's value get filled in the second pass + fragment = fill_vars(fragment, case.get("vars", {}), keep={"vehicle", "timetable"}) + fragment = fill_vars(fragment, {"vehicle": vehicle, "timetable": timetable_name(case_name)}) # FirstInit binds event launchers to their events and links the tracks. so launchers and # events of the case go in before it (read after it they never fire), trainsets after it # (placed before it they stand on unlinked track and derail at once) @@ -185,6 +194,9 @@ def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> s text += header + trainsets + "\n" name = f"autotest_{case_name}.scn" (scenery_dir / name).write_bytes(text.encode("latin-1")) + # a timetable of the case's own, for a train whose timetable the sceneries of the game have none like + if "timetable" in case: + shutil.copyfile(CASES_DIR / case["timetable"], timetable_path(game_dir, case_name)) # the simulator caches the scenery's static geometry in .sbt and reads it instead of # the terrain in the .scn (tracks, events and trainsets always come from the .scn), so # drop the cache once the base scenery has changed @@ -838,6 +850,7 @@ def _run_case(name: str, case: dict, exe: Path, game_dir: Path, timespeed: float result = run_simulator(exe, game_dir, scenery, ini, physicslog, duration, float(case.get("timeout", 600)), watch, say, expect_rows=with_physicslog and not own_vehicle) + timetable_path(game_dir, name).unlink(missing_ok=True) # a case that asked for no geometry cache (file.binary.terrain no) leaves none of an earlier run behind if any(line.split()[:2] == ["file.binary.terrain", "no"] for line in case.get("ini", [])): scenery_cache(game_dir, name).unlink(missing_ok=True) diff --git a/tests/unit/test_timetable_start.cpp b/tests/unit/test_timetable_start.cpp new file mode 100644 index 000000000..de00eba52 --- /dev/null +++ b/tests/unit/test_timetable_start.cpp @@ -0,0 +1,39 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "world/timetablestart.h" + +// the first row of a timetable is the station of departure, a stop the train waits at for its departure time, +// when it names the station the relation starts at. the loader then takes the departure time for the arrival +// one, which the row usually leaves out; a row without an arrival time is otherwise a station passed through + +TEST_CASE("timetable: the first row naming the station of the relation is the station of departure") { + CHECK(timetable::starts_at("Stacja1", "Stacja1")); + CHECK(timetable::starts_at("Zagorz", "Zagorz")); +} + +TEST_CASE("timetable: the station of departure written in capitals in the rows is still the one of the relation") { + // linia_107_poludnie.scn, Os33733: ZAGORZ in the rows, Zagorz in the relation (both with the polish letters + // stripped by the loader). taken for a station passed through, the AI left before its departure time and the + // train manager never gave the departure signal + CHECK(timetable::starts_at("ZAGORZ", "Zagorz")); + CHECK(timetable::starts_at("LEOSIN", "Leosin")); + CHECK(timetable::starts_at("Warszawa_Wschodnia", "WARSZAWA_WSCHODNIA")); +} + +TEST_CASE("timetable: a first row naming another station is not the station of departure") { + // a timetable which starts on the way, at a station the train passes through + CHECK_FALSE(timetable::starts_at("Tarnawa_Dolna", "Zagorz")); + CHECK_FALSE(timetable::starts_at("Nowy_Zagorz", "Zagorz")); + CHECK_FALSE(timetable::starts_at("Zagorz", "Nowy_Zagorz")); + // a name which only begins like the other one + CHECK_FALSE(timetable::starts_at("Zagorz_Towarowy", "Zagorz")); + CHECK_FALSE(timetable::starts_at("Zagorz", "Zagorz_Towarowy")); +} + +TEST_CASE("timetable: the station names are compared as a whole, letters and the rest") { + CHECK_FALSE(timetable::starts_at("Stacja1", "Stacja2")); + CHECK_FALSE(timetable::starts_at("Stacja_1", "Stacja-1")); + CHECK_FALSE(timetable::starts_at("Stacja1", "")); + CHECK_FALSE(timetable::starts_at("", "Stacja1")); +} diff --git a/world/mtable.cpp b/world/mtable.cpp index 23a48e3a7..bef0e20d8 100644 --- a/world/mtable.cpp +++ b/world/mtable.cpp @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "world/mtable.h" +#include "world/timetablestart.h" #include "utilities/Globals.h" #include "simulation/simulationtime.h" #include "utilities/dictionary.h" @@ -355,8 +356,8 @@ bool TTrainParameters::LoadTTfile(std::string const &scnpath, int iPlus, double } } } - // jeśli nazwa pierwszego zgodna z relacją - if (conversionerror == 0 && TimeTable[1].StationName == Relation1 && TimeTable[1].Ah < 0) // a nie podany czas przyjazdu + // jeśli nazwa pierwszego zgodna z relacją (bez względu na wielkość liter) + if (conversionerror == 0 && timetable::starts_at( TimeTable[1].StationName, Relation1 ) && TimeTable[1].Ah < 0) // a nie podany czas przyjazdu { // to mamy zatrzymanie na pierwszym, a nie przelot TimeTable[1].Ah = TimeTable[1].Dh; TimeTable[1].Am = TimeTable[1].Dm; diff --git a/world/timetablestart.cpp b/world/timetablestart.cpp new file mode 100644 index 000000000..2ece9a71c --- /dev/null +++ b/world/timetablestart.cpp @@ -0,0 +1,25 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "world/timetablestart.h" + +#include +#include + +namespace timetable { + +bool starts_at(std::string_view const Firststation, std::string_view const Relationfrom) { + // the station names are plain ascii by now, the timetable loader strips the polish letters + return std::ranges::equal(Firststation, Relationfrom, [](char const Left, char const Right) { + return std::tolower(static_cast(Left)) == std::tolower(static_cast(Right)); + }); +} + +} // namespace timetable diff --git a/world/timetablestart.h b/world/timetablestart.h new file mode 100644 index 000000000..78e6f2c36 --- /dev/null +++ b/world/timetablestart.h @@ -0,0 +1,23 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include + +// the first row of a timetable +namespace timetable { + +// whether the first row of a timetable is the station the train sets off from: it names the station +// the relation starts at. such a row is a stop even with no arrival time given, the train waits there +// for its departure time. the names are compared regardless of case, as the timetables write the +// station of departure in capitals as often as not (ZAGORZ in the rows, Zagorz in the relation) +bool starts_at(std::string_view Firststation, std::string_view Relationfrom); + +} // namespace timetable From e76ab8b5b37c9a36ceecbe243994f816f76bdb8c Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 22 Nov 2026 09:55:09 +0100 Subject: [PATCH 095/136] Revert #408 and merge master into staging (unblocks #442) (#443) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Enhance Windows build matrix with AVX2 variants * fix(lang): the two Polish lines of the download area written with \n, so they match the tooltip and the hint * fix(files): data named in another case is found on Linux, folders included The parser and the loaders lowercase every name they read, while the data made on Windows has files and folders named in any case (scenery/Braniewo, textures/siec_trakcyjna_ph/.../STS_*.tga, sounds/sip/Gorki.wav). FileCased matched the file name only, so a folder in another case wasn't found. - FileCased walks every part of the path on Linux, the folder listings kept by their lowercase and read again once the folder changed; Windows as it was - FileExists finds the file in any case on Linux, and the variant with names and extensions gives back the name as it's on the disk, so textures, materials, sounds, station announcements and scripts open that name - models, sound captions, timetables and nodebank previews open the file as it's named on the disk; the texture format is told by the extension in any case * fix(files): the banks keep the names asked for, only the opening takes the case of the disk The textures, materials and sounds are kept by the names they're asked for. Given back as named on the disk, a file in another case missed the bank and was loaded again on every request. - FileExists with names and extensions finds the file in any case but gives back the name asked for; FileOnDisk gives the file to open, used where textures, sounds and scripts are opened - FileExists of a single name is a plain check again, the places checking it and opening the same name stay as they were - the texture format is told by the extension asked for again - a folder changed shortly before it was read is read again for a name missing from it, the time of a change being as coarse as the clock of the file system; a listing cut short isn't kept * fix(files): a folder changed in the future isn't read again on every name missing from it * perf(files): a file missing costs a single check, as before Measured in a case sensitive folder (3000 textures, every 20th in mixed case, looked up the way Texture.cpp does), the walk over every part of the path made a texture lookup 4-5 times slower than master: each name tried and missing checked every folder of its path. - the folders found are kept by the name they're given with, the missing ones for a second, so a missing file checks its folder alone - a folder named as it is on the disk is taken without its listing - the time a folder was changed is looked at once a second at most The lookup is now as fast as master's (about 180 us per texture on NTFS in both) while finding the files named in another case too. * fix(files): terrain files named in another case are found on Linux The terrain directive names .txtf/.btf files in lowercase, as the parser gives every token. The name is now taken as it is on disk, from the text file first, so the binary file is made next to the text and the editor's references and layers keep one name. * fix(files): models named in another case are found on Linux The manager of the models looked for the file with FileExists of a single name, a plain check again since the banks keep the names asked for, so a model named in another case (models/przejazdy/plyty3_L, dynamic/pkp/st44_v2/main/2M62-0685-A) was reported missing before TModel3d::LoadFromFile() could open it as it's named on the disk. find_on_disk() finds the file in any case and gives back the name asked for, the key of the bank. * refactor(files): named functions instead of the lambdas of the folder cache (Sonar S2259, S3608, S6004) Sonar took the folder captured by the lambda reading it for a reference to null, failing the quality gate on reliability. The folder is read and the path kept by functions in the anonymous namespace, the age of the listing declared in its if. * fix: the simulator opens more than 512 files at once, and a shader it can't open says why With "physicslog yes" every driver keeps its .dat open, and a large scenery (Tomaszewo: some 500 vehicles, cars of the roads included) took all 512 streams the MSVC runtime gives: the next fopen failed and the simulator stopped at "cannot read shader: shaders/map.vert" on opening the map. The limit is raised to 8192 at the start (the soft limit of open files up to the hard one on Linux), and a shader file that doesn't open is told as such, with the system's reason, rather than as one that can't be read. * feat(blackbox): the black box on its own, writing the tapes of the user's vehicles at the end "blackbox yes" in eu07.ini records the black box with the physics logs on or off, "blackbox no" never; with no entry it goes with "physicslog yes" as before. With the physics logs off, the recorder keeps the line of the physics log of the driver the user is with, every 0.05 s, and writes it to physicslog/.dat when the recording closes: the speed recorder's tape of the vehicles the user was in, without every vehicle keeping a log open and written twenty times a second. The line and the header of the log are made by one function of the driver, which its own log writes too, and the file is opened the same way, so the two are the same to the byte: the readers of these logs (the old Hasler tape viewer, the starter) read them as before. * feat(physicslog): the logs written every two seconds by a thread of their own, no file kept open; the black box's tapes as it goes "physicslog yes" kept the .dat of every vehicle with a driver open for the whole run and flushed it twenty times a second from the simulation's thread: some 580 open files on Tomaszewo. The lines are kept now and a thread of their own writes them every two seconds, each file opened only for the moment it is written to. The files, their lines and their text mode stay as they were. - The black box, with the physics logs off, writes the tapes of the user's vehicles through the same writer as it goes, not at the end. A log begins when the user is first in the vehicle and goes on while the user looks around outside, until another vehicle is taken; back in it, the log goes on after the gap. The vehicle's own driver keeps the log only if it is the primary one, as a passive one's clock stands still; otherwise the driver of its train does. - What is kept is written when the simulator closes, after the black box, at the end of a test run, and when the test watchdog ends a run. A crash loses the last two seconds. - On Tomaszewo with the black box alone, the one tape grows every two seconds. With "physicslog yes", the 581 logs grow and the simulator holds as many handles as without them; writing them takes the thread about 1.9 s, which the closing waits for once. * feat(blackbox): the cab record holds the speed of the wheels, apart from the vehicle's when they slip The speed of the cab record is the vehicle's. The speedometer, and a speed recorder's tape with it, shows the speed of the wheels as they turn, which runs away from it while they slip and drops to 0 while they are locked in a skid. It is added at the end of the record (194 bytes), where the readers skip what they don't know; the .dat tapes have it already, in their second column. * fix(ci): build OpenAL Soft with the PipeWire, PulseAudio and ALSA backends, so the Linux game has sound The Linux job builds OpenAL Soft 1.24.2 from source, but the runner had none of the headers of its audio backends, and OpenAL Soft's CMake leaves out every backend it can't find. The bundled libopenal.so.1 had only OSS, Null, Wave and Loopback. Modern distributions and the Steam Linux Runtime have no /dev/dsp, so the game logged "Failed to obtain audio device" and played nothing, with any Steam Linux Runtime and without one. - install libasound2-dev, libpulse-dev and libpipewire-0.3-dev before building OpenAL Soft - configure it with ALSOFT_REQUIRE_PIPEWIRE/PULSEAUDIO/ALSA, so a missing header fails the build instead of shipping a library without sound The backends are loaded with dlopen at run time (ALSOFT_DLOPEN is on by default), so the bundled library gains no new dependency. Tested by putting an OpenAL Soft 1.24.2 with these backends next to the game from the Steam depot: under Steam Linux Runtime 4.0 the sound works. Co-Authored-By: Claude Opus 5.5 * fix(editor): the certificates of https looked for where the distribution keeps them The Linux game bundles the libcurl of Ubuntu, which knows only Ubuntu's /etc/ssl/certs/ca-certificates.crt. Fedora, RHEL and openSUSE keep the certificates elsewhere, so every download of the editor (orthophoto, terrain model, topo map) failed there with a certificate error. The file is taken from SSL_CERT_FILE or CURL_CA_BUNDLE when set, else the first of the files the distributions keep, and passed as CURLOPT_CAINFO. With none found libcurl keeps its own. * fix(editor): an https proxy checked with the same certificates CURLOPT_PROXY_CAINFO gets the file found for CURLOPT_CAINFO, so a download through an https:// proxy on Fedora or RHEL doesn't fail on the proxy's certificate. * fix(ci): the no-AVX2 Windows build has its own concurrency group and its own public download After master was merged the two Windows variants shared one concurrency group with cancel-in-progress, so one cancelled the other, and the publish job looked for an artifact name the matrix no longer produces. Each variant now has its own group, the publish job downloads both, and the release carries maszyna-windows-x64.zip (AVX2, the old name, so the links already handed out still work) and maszyna-windows-x64-noavx2.zip. The AVX2 variant passes -DENABLE_AVX2=ON explicitly instead of an empty flag. * build: a build without AVX2 has _noavx2 at the end of its executable name With ENABLE_AVX2=OFF the executable is eu07-x64___noavx2.exe (eu07-x64_noavx2.exe without ADD_VERSION_SUFFIX), so a starter can tell the two builds apart by the name alone and pick this one on a CPU without AVX2. The AVX2 build keeps its name. * ci: Linux is built without AVX2 too, published as maszyna-linux-x64-noavx2.tar.gz The Linux job becomes the same two-variant matrix as Windows (ENABLE_AVX2=ON/OFF), each variant with a concurrency group of its own. The publish job downloads both Linux artifacts, restores the executable bits in both and releases maszyna-linux-x64.tar.gz (AVX2, the old name) next to maszyna-linux-x64-noavx2.tar.gz. The no-AVX2 executable is eu07___noavx2. * fix(renderer): the legacy renderer clears the arrays the scene left before it draws the ui The legacy renderer drew the ui with the client arrays of the last scene draw still enabled: the texture coordinates of the normal map unit and the normals, pointing into the vertex buffer of whatever was drawn last, 48 bytes a vertex. The ImGui backend sets up the vertex, colour and texture coordinates of the active unit only, so the driver read the stale arrays with the indices of the ui. Once the ui had more vertices than that buffer, the NVIDIA driver read past its end and the game crashed; a crash dump of the editor (an area selected, a track being laid) shows the read of vertex 15113 at a 48-byte stride in ImGui_ImplOpenGL2_RenderDrawData. The arrays are now disabled on every texture unit the geometry uses, with the normal and colour arrays, inside the glPushClientAttrib already there, so the scene gets its state back after the ui. The default and the experimental renderers don't go through this code. * fix(app): a renderer this build doesn't have starts the full one, not the legacy one The starter writes "gfxrenderer vulkan" for the Vulkan renderer of the builds that have it. This exe doesn't know the word, and every word other than default/experimental fell to the legacy renderer: a player who picked Vulkan got the slowest renderer, the one whose ui crashes on NVIDIA (the arrays left by the scene). "experimental" in a build without the NVRHI renderer ended with "no renderer found!" and no game at all. After the settings are read, a gfxrenderer word this build has no renderer for becomes "default", with a line in the log saying so. The words it knows stay as they were: full/default, legacy, simple, null, the older starters' simpleshader and off (legacy as before), and experimental where it is built. * fix(settings): the gfxrenderer word read in any case, as the starter reads it A hand-written "gfxrenderer Legacy" started the legacy renderer only because every unknown word did; with unknown words going to the full renderer it would have changed. The word is lowercased when read, as StarterNG's RenderEngineOf does, so Legacy, Simple or Full mean what they say. * fix(physicslog): a log whose file can't be written keeps its lines and header, and the writer is stopped once on every way out A failed write put its lines back, ahead of those since, so a file held by another program for a while gets its header and every line once it can be written; up to 4 MB kept per log. Stopping is joined once, and not from the writer's own thread. main stops the logs after an error it caught too, and the test watchdog flushes with a time limit, so a disk that doesn't answer doesn't keep the run from ending. * fix(blackbox): the wheels of the powered vehicle, as the speedometer has them, and the logs described as the drivers' they are In a unit driven from an unpowered car, the speed of the wheels was of the car the user is in, whose wheels never slip; now of the motor car, signed as the occupied vehicle's speed. The doc tells of a log per driver, and of the two seconds of real time a crash loses. * fix(physicslog): failed logs kept within 64 MB in all, cut outside the lock, never written twice; the writer knows itself when stopped The lines kept while files can't be written are cut to their share of 64 MB before the lock the simulation waits on. A log written in part is cut back to its length, so the next try doesn't write its start twice. A stop from the writer itself is told by its id even after another thread took it to join, and the watchdog's flush waits at most its time, the writing on a thread of its own. * feat(physicslog): the logs of the trains only, physicslog.trains "physicslog.trains yes" in eu07.ini writes the .dat log of each driver who drives rail vehicles, not of the passengers nor of the road vehicles that make "physicslog yes" hundreds of files on a big scenery: the tape of every train. A driver made primary later begins its log then, and isn't counted while it doesn't log. The black box goes with it when the ini says nothing of its own, and doesn't write a second log of a driver writing its own. The doc tells the doors' sides are the vehicle's, the driver's swapped in the rear cab. * fix(physicslog): a train's log begun at its first line, so passive crews get no file Every crew is primary in the constructor and the drivers but one of a train with crews in more vehicles are made passive only before it starts, so a log begun there left files with only the header. With physicslog on all logs begin at once as before; one of a train waits for update_logs. * fix(editor): the texture pickers let go of the images scrolled past, the memory no longer runs out The picker of the textures of a track offers every texture of the textures folder, and each tile that came into sight read its texture full size, into the graphics card and the memory, and kept it there for good. Scrolling through the list for a trackbed texture took about 2.5 MB a tile: some 900 tiles made 3.5 GB, the whole folder 28 GB, and the game went down once the memory ran out. An image out of sight for 3 seconds is now taken out of both again (texture_manager::unload, Unload_Texture of the renderers) and read anew when it's shown once more, a few a frame as before. Only a texture the scene has never drawn is let go; those of the scene stay to the resource sweep. The texture browser lets go of its images on Refresh too. The picker no longer lists textures/previews: the 4100 previews of the node bank are images of models, not textures of anything. Checked on td.scn by a scripted run: 8000 images of the picker read one batch a few frames after another held the game at 2-3 GB, where it went to 28 GB and fell before; images shown again after they were let go come back; a trackbed texture picked from the folder is drawn on the track after its image was let go. * fix(physicslog): the writer's destructor throws nothing, its wait a plain condition variable woken to stop; a driver of no vehicle controls nothing * fix(editor): the images of the materials let go of with all their textures, the browser's Refresh a frame later An image of a material read the material with all its textures, the normal and specular maps and the variants, and only the first one was let go of: those stayed in the memory for every material scrolled past. They are let go of together now (Unload_Material). texture_manager::unload also takes the textures read and not made yet, waiting for a worker still reading one, and deletes the gl texture itself: release() would read it back from the card with gfx.resource.move only for it to be dropped. The Refresh of the texture browser let go of the images in the middle of the frame, while panels drawn before it could still refer to them; it now marks them, and they go at the start of the next frame. Checked on td.scn by a scripted run: 8040 images of the picker read a batch every few frames end at 2.0 GB, against 2.3-2.6 GB before this and 1.1 GB at the start; a trackbed material picked from the folder is drawn on the track after its image was let go. * fix(physicslog): every stop asked wakes the writer, the one from itself too; no psyche for a driver of no vehicle * fix(editor): the image of a material with no texture in its first slot is let go of too Its normal and specular maps were read with it and stayed in the memory: the trim passed over every image with no texture of its own, the material along with it. * fix(physicslog): nothing that goes wrong in the writing ends the simulator; a name in 1250 makes a path on a Windows set to UTF-8 The writer's thread called flush() with nothing around it, so an exception leaving write() ended the process with std::terminate, with no message. One that happens: the file of a log was made a std::filesystem::path of the vehicle's name, which MSVC converts in the code page of the system and throws for bytes not of it; on a Windows with "Use Unicode UTF-8 for worldwide language support" a vehicle named in 1250, as the sceneries have them (0xB3 for ł), isn't UTF-8. - the file of a log is made of the name with MultiByteToWideChar without MB_ERR_INVALID_CHARS: the same file as before for every name of the code page, U+FFFD for the bytes not of it instead of a throw. Elsewhere the bytes are the name of the file as they were - a log whose writing throws for any other reason (memory) is kept for the next try as one whose file can't be written, and the other logs are written still - the thread, flush_for() and stop() write through flush_safely(), which lets nothing out: what was taken for a writing failing as a whole is lost and told in the log, the next writing goes on - the messages name the file by the bytes of the name, not by path::string(), which converts back Tests: a log which can't be written doesn't keep the others from theirs; a vehicle named in 1250 has its log, read back by physicslog_writer::file(). Reported in the review of #385. Co-Authored-By: Claude Opus 5.5 * fix(blackbox): the tapes go on after the editor, with the physics logs off The tapes of the user's vehicles were written by update() after the check for the writer of the recording, which close() drops on entering the editor (F11). With "physicslog no", the speed recorder's tape ended at F11 while the drivers' own logs of "physicslog yes" went on. The tapes are files of their own: they are kept from the moment the recording was to be made, the file made or not, closed or not, until the simulator closes, after the gap of the time in the editor. Only the recording itself stops at F11, as before. Reported in the review of #385. Co-Authored-By: Claude Opus 5.5 * fix(physicslog): what no file name may have on Windows is replaced in the name of a log, on every system A spawned vehicle is named :, and its log went to physicslog/:.dat. On NTFS that isn't even an error: it is the stream .dat of the file , which nothing lists, so the log was written and no one could find it. On Linux the file was there, under a name Windows can't open. The name of the file of a log has < > : " / \ | ? * and the control characters replaced by _, on every system, so the logs are named alike everywhere (spawn_ezt:12 is spawn_ezt_12.dat), and a _ before a name Windows keeps for a device (con, nul, com1..., with an extension too). The bytes of 1250 stay. The black box tells the log it begins by the same name. Co-Authored-By: Claude Opus 5.5 * refactor(renderer): a material's textures let go of in one place, for every backend Unload_Material walked the textures of a material and of its variants the same way in both opengl renderers, and Sonar counted its declarations, set into the long run of overrides the two headers share, as duplicated: 5.2% of the new code, 3% allowed. The walk is gfx_renderer's now, over IMaterial::GetAllTextures and the backend's Unload_Texture. Materials that don't tell their textures, the Vulkan renderer's, give none, and are left alone as before. Co-Authored-By: Claude Opus 5.5 * AI: shunting brakes for a stop point again; test mode: no false SPAD for a train set across a signal (#409) * fix(ai): shunting AI brakes for a stop point again, the braking curve doesn't plan from a brake table left at zero The braking curve outside the final approach plans from the consist brake table since ce87aa0e (#187, merged with #264) whenever the brake is pneumatic. That table is worked out only for train running (Obey_train, Bank); in shunting it stays at zero, the planned full braking falls to its floor of 0.01 m/s2, and the demand comes out at a few hundredths of a m/s2, above the shunting brake threshold of -0.2. A shunting engine then rolled on without braking until the final approach, too late, and ran through the signal it was to stop at (seed 480873929 of l053_poranek: ep07p-2003 at sandomierz_g4_sem_info, sm42-1096, et22-654). With no worked out table the curve is again the constant deceleration over the distance left, as it was before ce87aa0e and as #187 meant to keep it for shunting. Train running is unchanged. The curve moves out of TController into vehicle/brakingcurve.{h,cpp} so that it is unit tested: tests/unit/test_braking_curve.cpp checks a shunting engine braking to a stop point with the zeroed table, and that a train with a worked out table gets the same demand as before. * test(ai): pin the train braking-curve demand to the results of the code before the move A brake table that grips harder as the train slows and a gradient, so that a wrong gravity sign, table index or a dropped term in the shaped demand shows; the expected values were worked out with the code removed from TController::adjust_desired_speed_for_braking_curve. * fix(test): a train set across a signal doesn't pass it at danger the moment the AI first looks at it The speed table takes in events up to a train length behind the head, so a signal the train stands across at the start of a scenario is found already behind the head, becomes elapsed on its first update, and the test mode reported it as passed at danger (calkowo_lotos: st43-189 at mac_daleko3_sem_info, manewrowo3: st43-100 at suw_szopa_a02_sem_info, both at 13.6 s with the train at a stand, the signal 20 m behind the head). A point now counts as passed only when the head of the train had it ahead once; the blackbox record of passed signals follows the same rule. * fix(test): a signal found up to 5 m behind the head still counts as seen ahead The distance to an event is found in steps of a metre from the position of its memory cell, so a signal just ahead of the head (a train stopped short of it when the autopilot takes over, or set right at it at the start) could come out slightly behind it, and passing it would not be reported. The trains set across a signal that the previous commit is about stood 20 m past it. Still not reported: a signal crossed while the speed table is being traced anew in motion (a Timetable: command to a running train, the autopilot taking over in motion), as it is found behind the head when the trace is made. * docs(test): say what the seen-ahead tolerance gives up A train set less than 5 m past a signal at stop is still reported to pass it at danger: standing that close it can't be told from a train stopped just short of the signal, which the tolerance is there for. --------- Co-authored-by: maj00r * fix(camera): the roll of the cab shake tilts the view about the line of sight again (#414) 623c4f82 (#97, in 26.05.1) changed the order of the camera rotations from Z, X, Y to X, Y, Z. The order matters only with a roll, which the cab shake gives (Angle.z, set in drivermode.cpp), or a camera entry of the scenery with a roll. Applied last, in the space of the cab, the roll nodded the view up and down when looking out of a side window instead of tilting it. The roll is multiplied in first again, as in 26.05. Co-authored-by: maj00r * fix(particles): the smoke of a cold diesel keeps the colour of its template (#413) bcb9e644 (#109) turned a comparison into an assignment: the smoke of a vehicle in air at 5 degrees or less, or with its engine under 45 degrees, got the colour 128,128,128. The emitter colour is on a 0-1 scale, so the smoke turned pure white, glowing at night, and stayed so once the engine warmed up. Up to 26.05 the line compared and did nothing; the smoke keeps the colour of its template again, as it did then. Co-authored-by: maj00r * Fix stutter with fpslimit on Windows and a texture unit cache race with threaded Python screens (#399) * fix(render): the python upload thread only marks the texture unit cache stale, the drawing thread clears it update_from_memory() runs on the python upload thread with python.threadedupload (the default), and since e230d7b9 it cleared opengl_texture::units there outright. That raced Bind_Material filling the same array for its multi-bind: a unit reset between the fill and glBindTextures() made the bind of that unit fail, and the object was drawn with the texture of the one drawn before it, for a frame, at the rate of the screens. The thread now sets an atomic flag, and the drawing thread clears the cache when it next binds textures (bind() and the multi-bind of Bind_Material), so a screen texture given a new gl name is still rebound. * fix(app): fpslimit asks Windows for the 1 ms timer, the frames no longer come in turns long and short The wait of fpslimit sleeps, and Windows wakes a process which didn't ask for a finer timer in steps of up to ~15.6 ms. A 10 ms slot of fpslimit 100 ended ~15.6 ms later, the pacer made it up with no wait in the next frame, and with vsync on the frames were shown for one or two refreshes in turn: visible stutter at a steady FPS. timeBeginPeriod(1) is held from the settings to the exit, only when fpslimit is set. * fix: the 1 ms timer also for an fpslimit set by the scenery, the stale unit cache checked with a plain load first A config block of the scenery is parsed after the settings and can set fpslimit, so the timer period is asked for at the first wait of the pacer too, once. bind() checks the stale flag of the unit cache with a relaxed load before the exchange, which it does for every texture. * fix(textures): the stale flag of the unit cache uses the default memory order (Sonar S8417) On x86 a sequentially consistent load and exchange cost the same as the relaxed and acq_rel ones; only the store in invalidate_unit_cache() becomes an xchg, and it runs rarely. --------- Co-authored-by: maj00r * fix(camera): the cab shake taken at the frame's moment between its fixed steps, it no longer moves in steps (#403) The shake of the cab camera (ShakeState) is stepped by update_shake at a fixed 1/50 s, while the camera read the raw state every frame. At any frame rate other than 50 the shake moved in steps: some frames showed the same state as the one before, others jumped one or two steps at once. Players with 144/165 Hz screens saw the cab jump around the camera. The vehicle now keeps the state from before the last step (ShakeStateBefore), and the camera takes the state between the two at the share of the step the simulation time has reached (shake_between). The offset and the velocity are blended, the angles worked out from the blended velocity. The shake itself is computed as before, with the same fixed step and the same springs; only what the camera shows of it changes. It lags the vehicle by a constant 1/50 s instead of 0 to 1/50 s. Measured with the same build and the blending switched off by a temporary environment variable (not in this commit), the EU07 on td.scn driven by the AI, frames over 30 km/h, two runs of each: - 60 fps: frames with the shake standing still 25% -> 0%, the change in its speed frame to frame 4-5 times smaller for the offset, a third smaller for the angles - ~144 fps: 65% -> 0%, 10-18 times smaller for the offset, 4 times for the angles - no fps limit (~520 fps): 90% -> 0% Co-authored-by: maj00r * fix: inverted clamp bounds give the upper bound again, as the old clamp did (#412) * fix: inverted clamp bounds give the upper bound again, as the old clamp did The project's own clamp() of 26.05 applied the lower bound first and the upper one last, so bounds given the wrong way round always gave the upper one. Its calls became std::clamp (undefined for such bounds) and, where the bounds can cross, safe_clamp, which swapped them instead. Neither gives the old result. - safe_clamp is the old clamp again, min(max(value, lo), hi). This restores 26.05 at every place it is used, among them the AI's dynamic brake test (its demand was fAccThreshold x1.21, the swap made it x1.01), the generator voltage, the heavy cargo acceleration of the AI and the EP correction of the brake. - The cab camera is kept inside the cab with safe_clamp. The bounds come from the .mmd as written and some cabs have them reversed (the B cars of SA134 and 21xM, ET40, 754); with std::clamp the camera jumped between the two bounds every frame on MSVC, as its result is fed back. * fix: every call of the old clamp gives what it gave up to 26.05.1 d1f16411 (#99) made every call of the project's clamp() std::clamp. Where the bounds come from the data or are computed at runtime they can cross, and then std::clamp gives another result (undefined behaviour; MSVC gives the lower bound unless the value is above the upper one) where the old clamp gave the upper bound. These calls use safe_clamp, the old clamp, too: - Mover: the pantograph pressure (MaxPress), the compressor switch (CompressorListPosNo), the coupler distance (DmaxB, DmaxC), the engine revolutions, the eimic ramp (CtrlDelay), the eimic limit (eimic_max), the speed control ramp (PowerUpSpeed, PowerDownSpeed), the load (MaxLoad), the magnet of the security system (Dim.L); - DynObj: the coupler distance of the buffers (DmaxB), the axle distance (Dim.L); - Train: the brake handle positions (BrakeCtrlPosNo, the range of the handle); - the legacy renderer: the mouse pick (the window size). With the bounds in order nothing changes. Calls whose bounds the code keeps in order (constants, SplineFidelity 1-4, the season table, the guarded output calibration) give the same result with std::clamp and stay as they are. The load offset takes its arguments in the 26.05.1 order again; fa2ed089 swapped them, which with the old clamp differs only for a negative load. The bump at a rail joint gives the old result again. Up to 26.05.1 its clamps had 0 in place of the value (since 96f43e11 and 4d72d352), and the old clamp made that the headroom Vmax - (Vel + 0.32 Vmax), negative above 68% of the top speed, capped from above only; d464628a and 03bfbb13 kept it at 0 or above. Only damaged track has the bump: a damage flag in the .scn, a derailer set by an event, a track made on a derailment. The interior light of the cab in the 3.3 renderer is computed in double again, as before d1f16411. The call added since (stepped_uc_value, 00955513) keeps what master does: bounds given the other way round are put in order. * fix: the alpha of a particle in the legacy renderer as up to 26.05.1, the NaN cases of the clamp tested Up to 26.05.1 the alpha was clamp( particle.opacity * 255, 0, 255 ): the float was made a byte first, so the clamp did nothing and an opacity over 1 (a smoke max_opacity over 1) wrapped round, 1.2 giving 50. The move to std::clamp made it 255. It's made a byte as then again, through int: the byte the x86-64 compilers gave, without the undefined behaviour of that conversion (MSVC makes the same two instructions of both). openglparticles.cpp goes with feat/gl46-migration; its opengl33 counterpart, std::clamp( opacity, 0, 1 ), already gives what 26.05.1 gave. The tests pin what the old clamp gave with NaN: a NaN value stays NaN, a NaN bound doesn't clamp. The checks named after the AI braking test and the bump at a rail joint say they test the helper with the arguments of those calls, not the calls. * test: the includes of the clamp tests before the project's headers and go up, after the test headers, so the change no longer touches the lines #416 adds its includes after. With both merged is included twice, which is harmless. --------- Co-authored-by: maj00r * Python screens: the worker's image goes in place only after its fence, not a bare glFlush (#411) * fix(python): a screen uploaded by the worker goes into a texture of its own, put in place after a fence With python.threadedupload (the default) the worker wrote the image into the texture the drawing thread draws from, with glTexImage2D and glGenerateMipmap from its own context, and only a glFlush after. Nothing ordered the two contexts: the drawing one could sample the texture while its storage was being made anew, its level 0 half written or its mipmaps not made yet, and on a change of size the worker deleted the texture and wrote a new name into `id` with no synchronisation. The worker now uploads each image into a new texture, sets a fence after it and flushes. The drawing thread, once per frame in python_taskqueue::update(), waits for that fence on the gpu (glWaitSync, the cpu goes on), deletes the old texture and puts the new one in place. The worker no longer touches the texture drawn from, nor `id`. An image the drawing thread didn't take yet is dropped by the next one. Without sync objects the worker waits for the upload with glFinish. The windows of python.displaywindows with python.sharectx bound the texture once; they now bind the name of the last image put in place, which python_rt keeps for them. Uploads on the drawing thread (python.threadedupload no, the Lua and WebAssembly screens, the editor) are as they were. * fix(python): the image of the worker goes in place once its fence is signalled, the viewer binds it each frame From the review of 8811ee5a: - glWaitSync ordered only the context of the main window. The extra viewports and the windows of python.displaywindows draw in contexts of their own and could bind the new texture before the upload was done. commit_thread_upload() now asks the fence without waiting (glClientWaitSync, timeout 0) and puts the image in place only once it is signalled, so every context binding it afterwards has it whole. Until then the task stays in the upload queue and is asked again the next frame. - The drawing thread chose between upload and commit by python.threadedupload, the worker by whether it got a context. With python.threadedupload on and no context made for the worker, the screens were no longer updated. The task now records that a worker uploaded it. - The viewer of python.displaywindows told a new image by its texture name, but a deleted name comes back for a later texture. It binds the name of the last image each frame, read under the lock of the render target, and the name it starts with is read on the drawing thread when it is made. * fix(python): the old texture deleted under the lock the viewers bind under, a fence not made waited for with glFinish From the review of #411: - finish_upload() deleted the old texture before it took the lock of the render target, and the windows of python.displaywindows read the name under that lock but bound it after letting go of it. A window could bind a name already deleted, or already given to the next upload. In a compatibility context (the legacy renderer) that makes a new empty texture: a black frame and a texture never deleted. The commit and the publishing of the new name now go under the lock, and the viewer binds under it too. A name bound before the deletion stays alive in that window's context while bound. - A glFenceSync that returns no fence was taken for a signalled one: the image went in place at once, with nothing ordering the contexts. The worker now waits for its upload with glFinish then, as without sync objects. * fix(python): the worker waits for the lock of the screen without the gil, no flush after a finish From the review of 939514ea: - The drawing thread now holds the lock of the render target for a whole upload with python.threadedupload off. The worker, copying the next image under that lock, waited for it holding the gil. It now lets the gil go around the lock and the copy: the bytes it copies stay valid, the object is immutable and held by the reference the worker has. - glFlush after glFinish did nothing; the worker flushes only when it made a fence. --------- Co-authored-by: maj00r * fix(models): a scenery light that is off no longer shows lit for a moment the first time it comes into view (#407) * fix(models): a scenery light that is off no longer shows lit for a moment the first time it comes into view Since d13c27a7 (the light blinking rework) the opacity of a light changes step by step from its last value, and the opacities start at 1. RaAnimate runs only for the instances that are drawn, so a model with "lights 0" (a W24 LED indicator, for one) was drawn lit when it first came into range and faded out over 0.45 s. Before d13c27a7 the opacity of a plain on/off light was worked out anew from a timer starting at 0, so a light that is off was off from the first frame. Now the first time an instance is animated its lights take their current state at once, whether it came from the definition or from an event since. Every later change fades as before. The light threshold modes (ls_Dark, ls_Home) are untouched. The only other difference from before d13c27a7: a light that is on no longer fades in the first time it is drawn. * fix(models): the light opacity step written without an implicit double to float conversion (Sonar S5276) The sum is still worked out in double and rounded to float once, as the compound assignment did, so the result is the same to the bit. --------- Co-authored-by: maj00r * Editor: switch drives with no switch listed and marked; a deleted switch takes its drives and ballast along (#330) * feat(track): the rail code split by concern, the blades of the switches with the key frogs shaped from their templates The rails are laid by code of their own instead of inside Track.cpp: gauge lines (GaugeLine), knot lines (Knots.h), crossings and check rails (RailCrossings), rail materials (RailMaterials), measuring the rail profile (RailProfile), planning the cuts (RailPlan), the carving scan (RailCarve) and laying the geometry (RailLayer). A switch with the key frogs draws its blades from the tip where their planed nose ends to the heel, bent as they're thrown, and the rail behind them from the heel on, where they were laid from the start of the switch before; on a switch of the catalogue they start at the cut tip of the tables, 1.248 m from the joint at R 190, 1.5 m at R 300 (track_features::blades). The frogs cut from the rails, the wing and the check rails are built but switched off (track_features::crossings), the rails laid whole as before. The switches without the key keep the blades they had. A switch path can be a chain of pieces: pieces1 and pieces2 keep the parts of each path after the classic bezier, which stays as the approximation older versions read. A path with its radius given is a curve however gently it bends, a plain track a straight only where both of its control vectors lie along it. A vehicle trailing through a switch with a movable nose set the other way runs off the rails at it (TRAILED_SWITCH). * feat(render): the shared treads of the rails and their cut faces drawn, the cut faces in the matte variants of the rail materials Both renderers draw the treads a track shares with the rails it crosses, in the pick pass too, and a pass of their own for the faces where the rails are cut, the ends of the blades among them, in the matte variants of the rail materials, so the cut faces don't shine like the head the wheels polish. * feat(vehicle): an axle on a switch keeps to the path it came on, and coming from the frog end trails the switch through where the wheels reach the blades The switch thrown under an axle no longer moves it over onto the other path; it runs on along the one it entered. Coming from the frog end, where the blades are shaped or the frog has a movable nose, the switch set the other way is trailed through (rozprucie) only where the wheels get to the blades or to the nose, not as the axle enters the track; the other switches are trailed through as it enters, as before. * fix(track): the tracks drawn straight before, which their second control vector bends now, written to the log The simulator told a straight by the first control vector of a path alone, so a track whose second control vector bent it was drawn straight; now it's a curve. Such a track is named in the log as it loads, so a scenery made counting on the straight can be found: 25 tracks of lk357. Paths with both control vectors along them bend a centimetre or so at most and aren't named. * feat(track): 3D sleepers and switch timbers laid where the simulator makes the ballast, switched off in the build The sleepers of a track running alone are laid square to it, the timbers of the switches and crossings across the tracks running over them, shared by them, of the models set with sleepers3d and sleepers3dplain in eu07.ini; sleepers3dbed tells whether the ballast is laid under them too, lowered so they stick out of it. The layout of a cluster of tracks is worked out once and kept till a track of it changes, in a thread of its own while the simulation runs. timbermodel of a track, read and written back before, takes the place of the model of sleepers3d there. All of it is off whatever eu07.ini sets (track_features::sleepers), the tracks keeping their ballast and their sleeper models. * feat(render): the 3D sleepers and switch timbers drawn in instanced batches Render_Timbers lays the beams of the tracks in range where they're out of date and draws those of a run of tracks of a cell gathered by the model and its part or its level of detail, in as few instanced batches as they fit in; in the shadow pass only those near the camera. A track with them leaves its old sleeper model out. OpenGL 3.3 renderer only. * fix(track): the counts of what's wrong with the sleepers kept safe from the thread laying them, and that thread stopped before what it works with goes The counts of the beams clipped, dropped and off the plane, of the slowest and the biggest cluster, are counted by the thread working out the layouts in the background as well as by the simulation laying a cluster itself, and were plain values written by both; they're atomic now. What the thread keeps the clusters in, their version and the counts were made after the worker, as it first asked for them, and so destroyed before it at the exit while its thread could still be laying a cluster; they're made first now, the worker stopping and joining its thread before they go. The tracks go with the paths of the simulation, made before the worker. * revert(track): a tributary and a track of an unknown type load as before They came in with the rail code from the guards of the editor against crashing, and don't belong with the blades: a track of an unknown type loaded as a normal track of the railway could be joined to it and run on, and a tributary loaded as a river with its first path lost the second one when the editor saved the scenery. Both load as on master again; the place where the editor crashed on them is to be guarded where it is. * fix(track): the tracks drawn straight before named in the log once, as they load, and the paths of the switches with no radius told a straight as before in one term The log of the tracks the second control vector bends now was written each time the segments of a track were made again, as a track with its unevenness loads and as the editor changes or drags a track; it's written only the first time, as the track loads. The paths of a switch or a crossing with no radius keep the rule of master, a straight told by the first control vector alone, its two terms being the same length; they're one term now, with the comment saying so. * fix(track): the thread laying the sleepers stopped as the application exits, and loading no models itself The thread reads the scenery, which the application deletes as it exits well before the statics go: it's stopped and joined first thing in exit() now, the worker destroyed with the statics only where the application exits some other way, and not started again after. The models the beams are made of were loaded by the thread where it didn't find them, through the renderer, out of the thread of the renderer, into a map read by the simulation meanwhile: they're found under a lock now and loaded only by the threads other than it, again for all the tracks whenever a track changed since, before a layout is asked of it. With the 3D sleepers off in the build their settings aren't exported, and a track changed doesn't look for the tracks around to lay their beams again. * feat(track): the 3D sleepers turned on with sleepers3d in eu07.ini, no longer switched off in the build track_features::sleepers is gone: sleepers3d in eu07.ini lays them, none (the default) lays nothing and the tracks keep their ballast, as before. The sleepers3d settings are written back with the others. The editor changes the tracks, so while it's open their sleepers are worked out on the main thread as they're needed, not in the background. * fix(render): only the part of a timber model drawn, not what else the model holds A timber model of parts may hold more than its begin, main and end, as the kits with the fastenings of the rails do. Those were drawn with each part of each timber, in the middle of the track; they aren't laid, so they're skipped now. * fix(track): the 3D sleepers laid only for a renderer which draws them Only the OpenGL 3.3 renderer draws the beams. With another one a track set to them lost its ballast to them, lowered or not laid at all with sleepers3dbed no, and nothing was drawn in its place. Draws_Timbers() of the renderer tells now, and where it's false the tracks keep their ballast, as with sleepers3d none. * fix(render): the submodels of a timber model left as they were after its parts are drawn They were all made visible after a part was drawn, the ones the model hides itself too, like Light_On, while the same model may stand in the scenery. The submodels of the top level besides the parts are listed as the model is loaded, hidden while a part is drawn and given back their own visibility after. The parts have to be at the top level of the model for that; a model with them deeper is logged and drawn whole. Render_Timbers no longer looks the model up under the lock for every run of tracks, the name set is enough there. * fix(render): a vertex whose faces give its texture no direction gets a tangent across its normal, not a NaN one The cut ends of the rails have one spot of the texture on all their corners, so their tangent came out of normalize() as NaN. The normal-mapped shaders then shaded them with a NaN normal: about half of the vertices of the cuts and frogs, and the end faces of the rails. * feat(track): the frogs cut from the rails turned on with frogs in eu07.ini, no longer switched off in the build frogs yes cuts the rails of the plain tracks and of the switches with the key frogs where they cross other rails, into frogs, wing rails and check rails. It's off by default: the rails are laid whole as before, the blades of the switches with the key are shaped still. * refactor(editor): the track mode file split into the files of its tools, the code as it was A pure move, so that the commits after it show what changes in each tool rather than a 4800-line file rewritten. The member functions of editor_mode go to the file the editor of this branch has them in: route, straights, lay, switchplace, switchdrive, switchtool, trackgizmo, and the rest stays in editormodetrack.cpp. The helpers of its anonymous namespace go to editormodetrackshared.h, as they were but inline, in namespace track_mode, which the files use. No line of code changes; the files add only their license, includes and the using line. * feat(editor): the groundwork the tools of the editor share - The tool interface (editortool.h), the gestures of the mouse (editorgestures.h) and what the modes share (editormodeshared.h); the projection, viewport, selection and texture picking taking them up. - Scripted input (scriptedinput): the input of a selftest script fed to the editor as if typed and clicked, the real mouse and keyboard ignored meanwhile; EU07_EDITOR_SELFTEST_HIDDEN draws into a window never shown nor focused. - The ui layers and panels of the editor, its settings, icons and the info of the includes; the layers of the scenery and their saving; the launcher mode. - utilities: user_cache_path (the cache folder of the system for the user) and the helpers of the translations. - stb_image: the gif loader takes the frame two back from the frames it decoded, not from before its buffer. - tools/editor: the scripts making the headers of the drives, the turntables, the editor and its usage. - Unit tests: test_area and the stubs of the editor the tests link. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the tracks laid along an alignment, to the PKP PLK norms, with their grade line and the ground - The alignment of the laying (editorAlignment, editorAlignmentStore): straights, transition curves and arcs with the cant of the norms for the speed, the radius below the minimum for it a warning; the lay, route and straights tools build on it, the route plan reading the curves going on from the tracks adjoining. - The grade line (editorProfile, the profile and gradeline tools): fitted to the terrain model or edited by hand, the tracks fitted marked in the scenery (//$f), the shared grade lines of nearly parallel tracks (//$n). - The ground under the tracks (editorGroundFollow, trackbed): the terrain drawn to the tracks and restored, the tracks put onto the terrain. - Connections between tracks (editorConnections, the connection and connection curve tools), the track presets, the shape of a track (editorTrackShape), digitizing tracks from the orthophoto, the properties sheet of the tracks (trackprops) and the track ux. - Unit tests: alignment, ground fit, heights, with the data of two fits. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the switches placed, slid and designed from their templates - The switch templates (editorSwitchStore, the template tool): the catalogue switches and the user's own, kept with the settings; the designer (editorSwitchDesign) with a drawing of the dimensions, a and b typed in with the shape making up the rest, a switch clicked off the orthophoto. - The curve of a switch laid into a curve (editorSwitchCurve), placement on a straight or into a curve, slide along it, crossovers and double slips (switchplace, switchslide), the drives of the switches (switchdrive) and the records of the switches placed (records). - Unit tests: test_switch_curve. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the tools of the infrastructure beside the tracks The gauge, speed, joints, lineside, parallel tracks, vehicles, signals, turntables, sweep and road tools with headers of their own; the kilometrage of the lines (editorKilometrage, the km tool); the infrastructure, roads and speeds behind them (editorInfra, editorRoad, editorSpeed). Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the terrain model of geoportal.gov.pl and the orthophoto downloaded for the editor - editorNmt: the squares of the terrain model at 1 m (NMT GRID1, the WCS service of geoportal.gov.pl) fetched by two workers, kept in editor/cache/nmt/grid1 of the game folder, the heights of the scenery taken from them; the nmt mode loads it along the tracks or around the camera. - editorHttp: the HTTP client of both, WinHTTP on Windows, libcurl elsewhere where it's built with it; without it the caches only. - The orthophoto: its cache moved to the cache folder of the system for the user, the download area a polygon on the topo map (//$a) filled in the background, the 4K imagery, the tiles waiting outlined on the ground. - editorGeoMap: the topo map of the top view; heightmapterrain and the terrain streamer grow the terrain made from the model around the camera. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(launcher): the scenery wizard picks the place of a new scenery on the topo map the editor shares The wizard drops its own map download and decoding for the topo map widget of the editor (editorGeoMap). The place clicked becomes the geographic reference of the new scenery (//$g PUWG1992), and the scenery starts with the orthophoto of the editor on (//$o), lying under it in place. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the tools wired into the editor mode and the build editor_mode takes the tools of the commits before: its header declares them, editormode.cpp and the track mode drive them, and the renderers draw their overlays (opengl33 and legacy). CMakeLists lists the new sources and adds WITH_EDITOR_SELFTESTS (off by default); the unit tests build the new test files. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the selftests of the editor split by what they test The scripts of EU07_EDITOR_SELFTEST run the commands of editormodeselftest*.cpp: scene, track, rails, join, switch, signal, sleepers, sweep, terrain, monkey. The code is in every build; only with WITH_EDITOR_SELFTESTS=ON does the editor read the variables and run a script. The selftests of master now need the option too. The tree builds again with this commit. * feat(editor): the Polish texts of the editor, all of them in one update of editor_pl.po * fix(editor): the marks of the editor moved off the letters the starters read, and its lines told by their words The starters read some letters in a scenery file: the Starter the title //$n, the attachments //$f and the old scenery //$a, StarterNG and the launcher of the game the attachments //$f and the title //$n. The editor wrote its download area, shared grade lines and fitted tracks under them, and took every line of those marks as its own: saved, a scenery lost its title and attachments, and the starters showed the lines of the editor as them. - The download area is //$z, the shared grade lines //$w, the fitted tracks //$t. - Their lines and those of //$o are told by their first words, as //$h, //$r and //$k were: //$o only as "on 0" or "on 1", the origin or the settings of older builds after it, so a trainset described as "on ..." isn't taken. - The lines older builds wrote under //$a, //$n and //$f are read only by the words the editor wrote in them, or by its own comment line before them, under the new mark. Each save writes them again with it, also when the editor didn't change them; the lines of the starters stay. * fix(editor): a square of the terrain model cut short isn't read, and the squares are kept in the user's cache The service puts the directory of its GeoTIFF before the pixels, so a file cut short by a write or a fetch broken off was read whole, the pixels missing coming out as heights of 0 m, for good. - The reader (editorGeoTiff.hpp, with unit tests) wants all the strips the rows need, each within the file. - A square is written under a name of its own and renamed. - The squares are kept in the user's cache folder (nmt/grid1), as the orthophoto, since the game folder may not be writable; without one, in the game folder as before. The ones older builds kept there are moved over as each is asked for, a damaged one deleted. - Capabilities that didn't come aren't kept as the fallback name for the session: the next square asks again. * chore(editor): the http client said to serve the terrain model and the topo map too, the gif fix of stb_image marked local - CMake names the orthophoto, the terrain model and the topo map as what goes without libcurl. - The fix of the gif frame two back in stb_image is ours, not upstream's (v2.30 still has the old line): a comment at the line says so, for an update of stb_image to keep it. * fix(editor): the lines moved off the letters of the starters in a merged layer written once, not again with each save A merged layer's text goes into the file of its target on save, and the target is read again; the marked lines of the merged layer were dropped only for the marks the editor had changed. The lines moved to the new letters stayed with their old places, and the next save of the session wrote them into the target once more. - After a save, the marked lines of every merged layer are dropped; those of its target are read again from its file. - The lines of a dead layer aren't written again. - The selftest layermerge merges the layer of one file into another's, as the layers panel does. * feat(editor): the station as the signalling sees it, found from a switch of it, and its schematic editorStation: the switches joined by plain track no longer than 1.5 km, the tracks between them and the lines leading out, 400 m of each beyond the outermost switch; laid out as a schematic along the main track through the station. The track circuits, the signals and their lights, the lengths of the station tracks and the lines to the next stations are worked out from it for the signalling tool. Nothing uses it yet: the signalling tool, wired in the next commit, does. It builds on its own. * feat(editor): the signalling of a station in the Signalling tab, laid out from a switch of it as on the lines of PKP PLK LMB on a switch in the Signalling tab opens its station: the schematic in a window of its own, the name, the code, the line and the km of the station, and the steps of its signalling, each one step of undo: - the switches numbered along the station after its code, bpd_1, the parts of a slip bpd_15a..d; the drives and the objects naming a switch follow it, events written by hand keep the old names; - the tracks cut at the joints of the track circuits, Ie-4, and the circuits named, bpd_iz1, bpd_it1; - the entry, exit and shunting signals placed and named, A, F1, Tm1, from the templates chosen; - the signals of the lines out: the automatic block of three or four aspects, the block sections no shorter than the braking distance, or the semi-automatic one with a warning disc; block boundaries drawn by hand; - the lights each signal needs for its routes, Ie-1 and Ie-4 § 8, its template fitted to them; - the SHP track resonators the signals lack, rezonator.inc; - the lengths of the station tracks as a table, and what the station and its lines still lack, with Repair. The stations described are kept as //$s lines in the files of their layers. * fix(editor): the signals of a station and of its lines not placed with no template for a kind, no track cut for them first - Set the signals and Set the line signals cut the tracks first, and only then found no template for a kind. They stopped there, but the cuts stayed as a step of undo. Now they ask for the templates first, by the lookup signal_batch() uses (signal_template_for(), behind editor_signals::signal_templates_missing()). Without one nothing is cut. - Set the signals and Set the track circuits again under Track lengths had the ids of the buttons of the steps above them. ImGui flagged them when hovered. Each now has an id of its own. * fix(utilities): win1250_to_utf8 turns the polish letters into utf-8, not into themselves utilities.cpp starts with a byte order mark, so the compiler reads it as utf-8. The game's targets don't get /utf-8, though: set_target_properties(... COMPILE_OPTIONS ...) in the MSVC block of CMakeLists.txt replaces the options add_compile_options gave them. So the string literals went into the program in the code page of the system, windows-1250 on a polish one, and the map of win1250_to_utf8 turned each letter into itself. What read windows-1250 through it got no utf-8: the names, descriptions and categories of the sceneries and the names of the textures in the launcher, and the descriptions of the templates in the editor. The editor writes such a description back through utf8_to_win1250, which makes a question mark of each byte that doesn't start a utf-8 sequence, so the letters it had read unchanged didn't come back. The utf-8 sequences are written as bytes now, the way utf8_to_win1250 has them, so they don't depend on the options. The options stay as they are: with /utf-8 other literals of the files with a byte order mark would change, the "±" of the table of Bezogonkow would take two bytes and move the letters after it. The unit tests check the letters and that the text given is valid utf-8. (cherry picked from commit 9ffed96ec1af6cdafd918ab1ca4c0d75bbd334f5) * fix(editor): the switches renamed only after the events by their old names are shown, the station records in windows-1250 and in the file the scenery had Number the switches renames the switches and what the editor writes along with them, but not the events written by hand: a switch event aiming at a switch, or :event0 and the others named after it, would keep the old name and lose its switch. Now the first click lists them in the status, up to six and how many more, and renames nothing. A second click with the same renames goes ahead. The name of a station is written in windows-1250, like the rest of the scenery file. A name read that isn't valid utf-8 is taken for windows-1250; the utf-8 the earlier builds wrote is read as it is. utf8_to_win1250 moves from editorIncludeInfo.cpp to the utilities, beside win1250_to_utf8, and the unit tests check both ways. The record of a station that had none goes beside the records of the other stations, in the file marked with them, so a scenery saved under another name keeps them in one file. output_layer takes, after _.scm, an included file of the part of another name, the one of the scenery it was copied from, before it makes a new one. The comments: the joints of the track circuits stand 4.2 m beyond the fouling points, where the axes are 3.5 m apart, as joints() counts them; the regulation of the lengths is cited with its date and title. * fix(editor): a scenery saved under another name keeps one file of the keys by the movable noses, not the old one beside its own The editor writes the keys by the movable noses on each save to _dzioby.scm and includes it. A copy of a scenery, saved under another name, still included the file of the scenery it came from, and its save wrote a file of its own and included it too, so each key stood twice. Now the save leaves out of the scenery the other files of such keys it includes, told by the line the editor writes at their start. Their files stay on the disk, for the scenery they were made for. A file made by hand, without that line, stays included. The turntable controls had the same, fixed the same way on their own. * fix(editor): a file of the scenery named like a part of a tool isn't taken for the one the tool made output_layer took, after _.scm, any included file named *_.scm, so that a scenery saved under another name goes on with the file of the scenery it was copied from. A file of the scenery named alike, written by hand, such as rejon_teren.scm, got the terrain directive, the hectometre posts or the new signals too. The files output_layer makes start with a line of their own now, "// scenery layer created in the editor for its part", and a file of another name is taken only with that line. A layer gets it through the new parameter of scene::node_layers::create(); the others start with the general line as before. _.scm of the scenery itself is taken without the line, as it was. A file made for a part by an earlier build has only the general line, so a copy saved from it gets a file of its own. * feat(editor): a player of GIF clips for the windows of the editor editor_clips::clip plays a GIF in an ImGui window, looped, from the time given. stb_image decodes the whole file on a thread of its own, so the window isn't held up; until then the clip says it's loading. The frames are kept as stb_image decoded them, and the one shown is a texture of the ImGui renderer (Create_Image), made again only when the frame changes. A file that isn't there is told missing at once, with no thread started. Nothing uses it yet; the tutorial of the next commit shows its clips with it. * feat(editor): Help > Tutorial, fifteen short lessons of the editor The lessons: looking around, laying track, curves, the radius of the curves at the bends, correcting a curve, joining tracks, switches, switch templates, signals and posts, selecting and fixing, editing with the gizmo, the grade line, terrain from the terrain model, sceneries made before, saving and driving. Each lesson has: - in eight lessons, a looping clip from lang/editor_tutorial/.gif, played from the start on a click; in six others, a moving drawing (the radius at a bend, a switch template clicked, the signals, the grade line, the terrain, a trainset); - the mouse buttons and keys drawn as pictures beside what they do; - ticks that fill in as the user does it, told by the tools through editor_guide::first_step_done(); - a button that turns the tool of the lesson on; - Back / Next and a dot per lesson, green when the lesson is done. The window follows the work: when the tool in use changes, it turns to the first lesson of that tool not done yet, and a page turned by hand stays until then. In a lesson of laying it warns when there's no ground under the cursor. Where it opens: - by itself when an editor session starts, until "Show when the editor opens" is unticked (first_steps in the editor's settings); - from the Help menu; - from a Tutorial button beside Lay a track in the hint of an empty scenery, which isn't drawn while the tutorial is open; - at its lesson, from a "?" by the radius at the bends in the lay panel. A lesson whose clip isn't there is shown without it; the clips aren't in this commit. editor_guide is a new role of the editor, given to the hekto-post and trainset tools. Selftest command tutorial : opens the tutorial at a lesson, from 0; -1 closes it. * fix(editor): the lessons of the tutorial say what the editor does The lesson texts checked one by one against the tools; the ones that told otherwise: - Switches: a connection isn't chosen at the top of the panel, its kind comes from where the drag is let go (a crossover onto the other track, over a crossover the other way a double one, or scissors where they overlap). - Switches: a ladder leads onto the parallel tracks it's dragged across, let go on the farthest, with the straights up to where they start; it lays no missing tracks. - Terrain: there is no step 3. Step 1 is Location, step 2 is Load around the camera while there are no tracks and Tracks and terrain with its three ways once there are. The rows had the step numbers in the keys column, and 1, 2 and 3 switch the edit modes in the Terrain field. Now the steps show the mouse, the terrain under some tracks only is a row of F3 (the line the terrain panel shows), and the rows that only tell what the fit does have no key. - Sceneries made before: a plain include can be changed; the row lists what can't: an include template (.inc), the binary terrain cache, a file included twice or with parameters, a locked or hidden layer. - Laying: the second Esc drops the points only within 3 s. - The radius at the bends: two transition curves from 6000 m down to 2000 m while they're long enough for the speed, then an arc; a label turns orange where the curve breaks the norms, not because it came out smaller; two transitions meeting read 2xL and R; the labels of each transition curve are on laid tracks, close up. - Signals and posts: the W17 markers go by the selected switch, around the camera or the whole scenery, not along a line. - Selecting and fixing: E lengthens the track, the control vectors bend it. - The gizmo: at a point Q moves the point alone, W turns the whole track about it. The tooltip of Help > Tutorial no longer speaks of clips: the tutorial goes without them. lang/editor_pl.po has the new texts. * fix(editor): the lessons of the tutorial in plain words Every row, goal and warning of the tutorial is said again for someone who has never laid a track, in English and in Polish: - the words of the railway and of the editor are said in everyday ones, or explained where they come: the radius (how big the curve is), the transition curve (the easing into it), the cant (the outer rail raised), the gizmo (handles on the track), the control vectors (points that bend it), the grade line (how the line goes up and down), the terrain model (the real ground), the orthophoto (the aerial photo), the hectometre posts (every 100 m), W17 (how far a wagon may stand); - what only a designer needs is left out: the 6000 and 2000 m of the radius ladder, the compound curve, the hump, the kinds of include that can't be changed; - the buttons are named as the panels name them: Apply to the scenery, Template editor..., the tiles of the switch tool; - the Polish names of three lessons say what they are about ("Uchwyty na torze (gizmo)", "Wzniesienia i spadki", "Prawdziwy teren"). Their English titles stay, the lessons are found by them; - the warning of no ground under the cursor tells what happens to the track; - two captions of the drawings say what they show (the tracks inside a box, posts every 100 m), and in Polish the button of the top view is "Widok z góry (O)", without "ortogonalny". What each row tells of is the same as before. The msgid of the length typed while laying stays, the window of the keys (F1) uses it. * feat(editor): the semaphores and the warning discs chosen by what their descriptions say they show The descriptions of the signal templates can now say what a semaphore shows and what a disc repeats, and the editor reads it: - signal: {arms: 2, aspects: {Sr1: ..., Sr2: ..., Sr3: ..., Sz: ...}, repeats: {stop: ..., vmax: ..., "40": ...}} is kept with the template, the events named for each aspect - the palette shows a template with arms as a semaphore of its arms, with 1 arm / 2 arms and Sz picking the template of the same tile that has them - the signals of SRK take a semaphore whose aspects cover what the signal needs (Sr3 where a speed is reduced, Sz on the main signals), the fewest arms that do it, and say which one does when the placed one hasn't them or has more than it needs - the warning disc before a semaphore is one whose repeats cover stop, the highest speed and 40 km/h when the semaphore shows Sr3; SRK writes no events of the routes, so this only chooses and checks the disc - the linked signal (parameter 7) is read for the role link as well as text - signal_headers.py keeps the keys written by hand in a description (arms, aspects, repeats, the description and the parameters from 6 on) when it writes the guessed ones again - signaltemplates of the self test lists what the templates say and the heads made of them * feat(editor): the shaped discs swapped and set by hand, the warning discs checked by what they repeat The shaped shunting and stop discs (mk1, tzm, z1) are known to the signalling, but it doesn't place them by itself: - a shaped disc chosen in the palette for the shunting or the stop signals is placed by hand only; the signalling of a station takes the light template of the kind there, and says so when there is none - the template of a shunting or a stop signal standing can be swapped for a light or a shaped one of another mount as well (dwarf and mast, not gantry) - a signal whose description lists its aspects shows a button for each under its card: it sets the signal to that aspect in the editor, by the animations, the lights and the submodels its event sets off, the time standing still; nothing of it is saved. TAnimContainer::Finish takes an animation to its end at once, giving the submodel its angles, multi_event::branches tells the events set off when the condition isn't met From the review of the descriptions: - a shaped warning disc standing before a semaphore described is checked by the events it repeats: stop, the highest speed and 40 km/h of a second arm told apart; one which doesn't is offered the disc which does, and Fit swaps it - the disc offered is of the mount of the disc chosen, taken from the template even when it isn't described - 1 arm / 2 arms / Sz of the palette pick the template leaning as the chosen one and most like it by its name - a semaphore described with its arms but not its aspects has Sr1, Sr2 and with a second arm Sr3 - Fit leaves a semaphore having what it needs with its arms, for the events written by hand to the aspects of a second one; the messages of the fitting speak of what the signals need, not of their lights - signal_headers.py warns of a signal map written as a block, whose keys it can't keep * fix(editor): an aspect shown by hand doesn't name a vehicle that may be gone The Show button runs the events of the aspect outside the queue. run() writes the vehicle that set the event off last into the log, and nothing clears that pointer, so a train deleted since would have been read after it was freed. The queue sets the activator anew each time, so it is cleared before the run. * fix(editor): a disc not described is only offered the one that tells, a light stand-in of the mount of the shaped one - A shaped warning disc whose template doesn't say what it repeats may tell all its semaphore shows as well. It is no longer marked as not fitting: the disc described is offered as a hint, and Fit leaves it be. A disc whose template isn't among the scanned, its mount not known, is offered nothing rather than discs of any mount. - A shaped disc chosen for shunting or stop is stood in for by a light template of its own mount first, a dwarf for a dwarf. - The tooltip of the aspect buttons says the trains read the signal as its events set it last, in a run started from the editor too. - The Polish texts of the fitting speak of signals, not semaphores, since it takes the discs too. * refactor: the Sonar remarks on the switch blades taken care of - the big functions of the rails split into helpers with one job each: the carving, the laying and the planning of the rails, their crossings, the blades, the lofted spans of a segment, the profile of a rail measured piece by piece, the joining of the switches - the floating-point loop counters are while loops doing the same additions, so the samples come out where they did - C arrays are std::array, the two sides of the paths path_sides; the ends of a cut are two parts of one struct, ending and starting - the rail laid by a course of its own, not eleven parameters - the globals kept in functions, the nested ternaries taken apart, one declaration per statement, explicit captures, ranges algorithms, std::format, std::numbers, emplace_back, structured bindings - the region finds the sections around a point into a list the caller gives, so the search for the rails around a track shares no list with another thread - check_rails and create_track_rail_profile are const, the pool of the reused chunks can't be copied The geometry of every chunk of lk357 and td_fog, with the frogs on and off, comes out the same as before. * refactor: the Sonar remarks on the 3D sleepers taken care of - the big functions of the sleepers split into helpers with one job each: the clusters and the lines of timbers, the gaps under the rails, the models and their parts, the check of the layout, the drawing of the timbers in instanced batches - the tracks near a track found into a list of their own, the region searched into a list the caller keeps, not the one the region shares with the main thread; the callbacks are templates, not std::function - the layout of a cluster takes a span of its tracks - the globals kept in functions, the parts of a beam int constants, beam_overhang no longer hidden by a field of the same name - scoped_lock, jthread, contains, ranges algorithms, std::format, emplace_back, structured bindings, explicit captures, upper-case literal suffixes, one declaration per statement - the uniform buffer takes a span of bytes * fix(editor): the editor core builds with GCC again - kCrossoverStraights is constexpr, so the connection curve can take it into a constant expression; GCC refused a double that was only const there. - the track_hover alias inside editor_mode dropped: declared after hovered_track had already used the name, it changed what the name meant in the class (-Wchanges-meaning); the definitions name the shared track_hover. - included where the rail self-test uses std::memcpy, which MSVC reached through other headers. * refactor: the second round of Sonar remarks on the switch blades - the carve of a throwable part takes the cut before it only where there is one, as only that cut makes it throwable - the splitting of a grooved profile by the floor of its groove moved out of the rail layer into a class of its own, which is given the profile, the size of the rail, the texture of the plates and the side - the rail drawing is made by a const function - the triangles of an ear-clipped outline go in as the arrays they are, the search for a corner within an ear is an any_of, the loop pruning thin corners keeps the count it started with, as it stops at the first - the bytes of the blocks of a texture are taken off the file through its buffer, with no cast of their storage - the log of a carved part takes the tracks around it as a span - the joint length of a switch, a constant, isn't captured, and the directions at the ends of a crossroads are tested in one condition each * refactor: the Sonar remarks on the tutorial - the window of the tutorial in smaller pieces: the steps reached, the lesson followed and its clip, the clip or the sketch of a lesson, its keys and steps, the button under it and the buttons of the pages; the lessons are a table of their own, the button of each kind of lesson picked from a switch - a clip whose delays add up to nothing shows no frame instead of dividing by them - the frames of a clip are decoded by a function of their own, on a thread kept with them and joined once it's done, or as the editor closes, instead of a detached one - the sleepers of the signal sketch counted by a whole number, the texts of the sketches made by std::format, their points kept in std::array, the whole numbers turned into floats where it's meant * fix: the bugs and vulnerabilities Sonar found in the editor core - the loops stepping along a track, a curve or the view count their steps by a whole number and take the station as so many steps from the first, instead of adding a fraction up, which drifts - the self-test of the guard rails keeps the plan of the rails of the track against while it goes through them: the range of the loop was in a plan made for it and gone before the loop began - the generators of the self-tests and of a unit test are seeded on purpose, so a run can be repeated: marked for Sonar as such - the tool writing the descriptions of the templates takes the names out of its tables only where they stay in the data folder * fix: the loops of the signalling stepping by a whole number the places of the block signals along a line and the marks of the chainage under the plan of a station are counted by a whole number and taken as so many steps from the first, instead of adding a fraction up, which drifts; Sonar took the counters of floats for bugs * refactor: the checks of the signal heads and the signal sheet in smaller pieces the remarks Sonar made on the signal descriptions: the warning about a disc on the mount of a signal is worked out by a function of its own, the fit and the aspects of a head, the swap of a template and its aspects in the sheet of a signal are drawn by members of their own, the walk over the events of a signal is a free function instead of a std::function held by a lambda, and the description of an include is read a part at a time; the names of the kinds are kept in a std::array and looked up by the algorithms of ranges, a name is taken as a std::string_view where it is only compared, and the locals named event, which hid the enumerator, are renamed * style: a space after a comma in the join self-test * style: a space after the question mark in the terrain sketch * style: a space after the question mark in the status of the fitting * refactor: the last Sonar remarks on the small fixes the opening of a scenario catches the exception the scenery throws when it can't be read, not any runtime error; the vehicle moved between trainsets keeps its source by a reference to const; the messages of a track of an unknown type and of a tributary are raw string literals; the parser opens a file by a std::filesystem::path, and the log of a file it can't open still names its folder and its name * refactor: the crossings of a track found without casting its const away the radius of a node can be read off a const one: radius_() is const across the nodes, the ones of the tracks and the models marked override, and a const radius() gives the radius worked out already, or works it out anew without keeping it; the helpers finding the crossings of a track only read it and take it const, its own run of rails typed apart from the ones of the tracks it crosses, which the crossings found name; the triangles of a filled outline are pushed as named corners * refactor: the paths around a track sampled without casting its const away the sampling of the paths and the clusters of tracks laid together only read the tracks, so they take and keep them const: the path sampled points at a const track, the tracks near one are found from a const one by its const radius, and a cluster holds const tracks; the shared zones of the timbers no longer cast the const of their track away * fix(editor): the Sonar blocker remarks on the stack, no side effects in the operands of && and ||, no local named final (S912, S1669) Counting the leftover signals, the pieces of a station walk, the places with nothing beside a run and the joints and fouling points logged by the self-tests no longer counts inside a condition; the last span of a straight is named tail. The counts and what they log are the same. * revert(vehicle): an axle on a switch follows the switch as it is set, as before the stack The axle kept to the path it came on, so a switch thrown under a moving train no longer sent the rest of it onto the other branch, and coming from the frog end it trailed shaped blades only where the wheels reached them. That changed the running of every switch in every scenery, and the AI still scans its route by the switch as set. TrkFoll is as on master again, and the trailing point of the blades it used is gone. * revert(track): a path is told a straight by its first control vector alone again, as the sceneries are made for A plain track was drawn bent where its second control vector was off the chord though the first lay along it, and a path with a radius given was never straightened. Tracks of existing sceneries drawn straight before would have been drawn bent, with their length, cant and the models along them. TTrack::straightened is the rule of master, for plain tracks and the paths of switches. The editor keeps a bend dragged with the second control vector, or set by joining the tangents, by moving the first one 2.5 cm off the chord to the side of the bend, past the tolerance, so the track is drawn, saved and read back bent, by older builds too; the second one dragged back along the chord takes the first one back onto it. * feat(track): the switches joined directly to other switches at load told in the log A switch right after another one is joined to it as the sceneries load, where its end was left open before and vehicles came off the track there. Each switch joined so is logged with its place and the number of ends, and the whole number once, so a scenery can be checked for places that run differently now. * fix(editor): a bend kept by lengthening the first control vector, not turning it keep_bent moved the first control vector 2.5 cm sideways, which turned the start tangent: a kink of 0.29 deg on a 15 m track, flagged by the joints check, and against the fixed direction at a switch or a locked track. Now the vector keeps its direction and gets 2.5 cm longer than a third of the chord, which the simulator no longer takes for a straight. It is also applied after an end is moved or snapped, since a new chord or a snap onto a neighbour could bring the vector back within the tolerance. With the second vector back on the chord, the first goes back to a third of it. * fix(track): each switch joined directly to another one logged with both names join_switches counted ends, while one join links both switches, and only the first switch of a pair was named. It now returns the switches joined to, and the log names both of each joint and gives the number of joints. * fix(editor): a path drawn bent is kept bent through every edit, one drawn straight is left as it is The first control vector is made longer past the 2 cm tolerance only where the path was drawn bent before the edit, or where the edit itself sets the second vector: the end of the path moved, its first vector, its second one, a neighbour followed or its grade taken, the controls aligned at a joint, an end snapped. A path drawn straight keeps being straight when its ends move, and the paths of a track that the edit doesn't bend aren't changed. Moving the second vector back along the chord takes the first one back to a third of the chord where it was made longer here. * fix(app): a scenery that can't be opened takes the game back to the launcher whatever the file system throws Catches std::runtime_error again, as master did: invalid_scenery_exception is one of them, and so is what the file system throws while the scenery is opened. * fix(track): the beams worked out in the background don't read the ends a switch is set to The ballast a switch trackbed takes is asked of the tracks joined to its main path, as the trackbed is made at the load, not of the ends the switch is set to now, which change as it's thrown while the thread runs. What the thread reads with no lock against the main thread is written down where it runs, with the two things driving can change: a switch thrown and a turntable turned. * perf(render): the cut faces of a track drawn with nothing put on the heap, a track with none passed over at once * chore(track): the switch drawing the cut faces in the unrolled material read only in the builds with the self-tests * docs(track): the blades flag said to be switched on, and what frogs in eu07.ini changes of it * fix(editor): a response over 64 MB is refused, curl kept to http and https, the address read as UTF-8 The body of a map or of a service the user typed is read into memory up to 64 MB and fails above that, with WinHTTP and with curl. curl follows at most 10 redirects and only to http or https. WinHTTP gets the address widened from UTF-8, so a pasted one with letters past ASCII isn't turned into garbage. * fix(editor): only the orthophoto an older editor kept is deleted from the settings folder, not all its cache The geoportal folder of the old cache is removed, and the cache folder itself only where nothing else is left in it. * fix(editor): the square metre of the outlined area written as its UTF-8 bytes, shown right where /utf-8 doesn't reach * docs(track): why the velocity read for a switch is put back after its segments are made * fix(track): the blade tips and the open ends of a track take the dark of the rail, not the colour of a worn tread No wheel runs over them, so their cut faces aren't drawn as worn: the beige the matte material gives a worn face is left to the cut faces of the frogs. * fix(editor): a neighbour followed or given its grade is bent only where its second vector really changed follow() and follow_grade() write the second vector of a track joined at its end back as it was when the joint didn't turn or keep its grade; a track the simulator draws straight with that vector off the chord was made bent then, though the edit never touched it. Its first vector is lengthened now only where the path was drawn bent or the second vector took another direction or grade. * fix(track): the open ends of a track laid with cuts take the dark of the rail too The rails a frog or a crossing cuts are laid piece by piece; the caps of their pieces at the open ends of the track were drawn worn with the cuts of the frogs. They aren't worn now, as the open ends of the other tracks. * fix(editor): a neighbour drawn straight is bent only where the edit took its second vector off the chord follow_grade() sets the height of the second vector anew on every graded joint, a fraction of a millimetre off the height the scenery has, so a change of the vector bent a track whose second vector stood off the chord sideways already, though the simulator draws it straight. follow() and follow_grade() keep a path drawn straight bent now only where its second vector lay along the chord before the edit and stands off it after; a path drawn bent is kept bent as before. How far the vector stands off the chord is measured in one place, keep_bent() uses it too. * docs(editor): the comment of keep_bent above keep_bent again, not above the measure of the chord * Editor: signal reads kept by the signal, level crossing discs, signals out of the gauge, indicators, the signalling tools split (#307) * fix(editor): the read of a signal stays by it as its track is split, on a switch and when it is moved, and a level crossing disc is placed The trains find a signal by its read, a passive event in a list of the track, and measure the way to the cell it reads along three tracks further at most. The editor let the read drift away from the signal, or put it where trains of another path read it. - A track split in two: a read the trains scan for (a passive event) goes to the piece by the point it reads, whatever its list; before, those of the runs towards the end stayed on the first piece. Five splits left the reads of A, B, C and J on the first piece while the signals stood on the sixth, out of the reach of the trains. The reads of signals placed since the scenery was opened, not bound to an event yet, go to the piece by their signal the same way. - A signal moved off its track jumped back to that track's end once the track was changed: the track had taken it up as its object and measured it again along itself. A moved signal is let go by the track it stood by, and an object of a single point moved off the side of its track no longer follows it. - A switch reads its events to the trains of both its paths. A signal past the frog of a path, where the axes are a gauge apart, is passed by the trains of that path only, so its read goes to the track joined to the far end of the path, in the list of the trains running from the switch onto it or the other way. Before the frog it stays on the switch. Moving the signal across the frog takes the read between the two. - A signal by a switch on the side of its other path stood on that path, in the way of its trains (0.45 m from its axis); it is refused there, placed or moved, with the reason. - The kind crossing of the descriptions (tsosp, tsospn) is known: the level crossing disc is listed in the palette and placed with its read. Checked in the editor on a hidden desktop: five splits of a track with bound and fresh reads, a signal moved to another track and the old one raised, signals placed before and past the frog of a switch on both paths, turned and moved across the frog, saved and opened again with the reads bound, the tracks raised, shifted and bent with the signals following. Unit tests pass. * fix(editor): a split keeps reads far off the path and bound objects up to 30 m by their pieces A read the trains scan for moves to the piece by the point it reads only from event1 and event2, only when it isn't ignored and only when that point is within 50 m of one of the pieces; a read at the station building stays in its list. An object bound by hand keeps its binding as its path moves up to 30 m from it, an adopted one up to 12 m as before. * feat(editor): the tracks that read a signal are drawn and can be picked, flipped or dropped The selected signal shows each read of its _sem_info as a thick band over the reading track, arrows in the way the read is scanned, a line from the foot of the signal and a plate with the list and the track; the hovered one shows them thinner and placing or moving a signal shows where it will be read. The panel lists the reads: each can be turned the other way or removed, "Pick the path" takes a click on a track (with Shift one read more or less) and "By the path it stands by" puts back the read the signal gets when it is placed. Each change is one step of the undo. The self-test gets signalread, signalreadflip, signalreaddrop and signalreaddefault, and the probe lists every read of a signal. * fix(editor): a moved or turned signal keeps the reads picked by hand, and a read set again isn't an undo step Moving a signal, taking it across the track or turning it put back only the read by the track it stands by and dropped the others: those stay on their tracks now, on the other list when the signal is turned. Setting the reads the signal has already says so and adds no step to the undo. Picking a reading track disarms the template, so a click after Esc doesn't place a signal, and the signals are listed again after any change of the history, also once it is full. * feat(editor): a signal is placed out of the gauge of the tracks around it As a signal is placed, moved, taken across or turned, its models are measured against the gauge chosen in the Gauge window along every path near it. One that enters it is taken sideways, away from the axis of the track whose gauge it enters, as deep as it went in and 3 cm more, in the same step of the undo; between two tracks too close for it, it stays where it was put and the status tells which gauge it enters and how deep. A gantry is only measured. The panel of the selected signal tells when it stands in the gauge, with a button to move it out, and the view marks the deepest place. The gauge tool measures any models against the paths around them for it. The self-test places a signal at a given offset and its probe tells the gauge. * fix(editor): a moved signal leaves only the read of the track it stood by, and the gauge is checked on its level The reads a moved signal keeps were all but the first one listed, which is the first track of the scenery having it, not the one the signal stood by: a read picked by hand could go and the track it left could keep it. It is the read of the track it stood by that goes with it now, and turned, eventall1 and eventall2 swap as well. A track more than 2 m above or below the foot doesn't push the signal aside, the status tells the real distance it went, the gauge is measured again when the signal follows a dragged track, and the marker in the view shows only what is up to date. * feat(editor): indicators put on a signal from the panel, they move and go with it The indicators of scenery/pkp/wskazniki described as "category: indicator" are offered under the selected signal, grouped by their sign. One is put in as an include named after the signal, on the srk layer: - a lit one (place: head) under the lowest lamp of the signal, 0.73 m below it and 5 cm ahead of the mast, each next one 0.45 m lower; a dwarf signal is refused, it has no mast for one; - a plate (place: foot) at the foot of the signal, its model has its place by the mast built in. The panel lists the indicators standing by the signal with a Remove button. They are found as the includes whose first parameter is the signal's name, within 1 m of it in plan. When the signal is flipped, turned or moved, they keep their place in its frame, in the same undo step; deleting the signal deletes them too. If the signal and the indicator both define an event, the status says so, since the scenery keeps only one of them. The self-test gets signalindicator and signalindicatordrop, and its signalprobe gives each indicator's height and the height of the lowest lamp. * feat(tools): indicator descriptions and the indicators taken out of the signal templates indicator_headers.py writes //$e descriptions into the LED indicators of scenery/pkp/wskazniki (W19, W20, W21, W24, W26) with the events each shows. It also makes the indicators that were so far only built into the signal templates: - W1 of the warning discs, new, old and with the light strip; - W1 and W18 (new and old) of the block signals; - the I, II and III plates of the repeaters. The plates fixed flat to the mast are moved 4 cm ahead. Their back is 5 cm from the mast's axis, while the mast is 6.1 cm thick and its clamp under them 8.3 cm, so the mast went through the plate, in the templates too. * fix(editor): a signal turned or moved by the gizmo is read and kept out of the gauge, its indicators go with it everywhere The gizmo of an include only rewrote the numbers of a signal. Its read stayed on the event it had, even when the signal was turned to the trains of the other direction. Its indicators stayed behind, its height could be dragged off the ground, and the gauge wasn't checked. Now: - the gizmo moves a signal in the plan only, at the height it has; - while it is dragged, its indicators keep their place by it; - once it is let go, the drag is made again as a move of the signal tool, one step of the history: the read goes to the event of the trains it faces on the path it stands by, and it is taken out of the gauge; - dropped away from every track, it goes back where it stood. The indicators of a signal are found in the scenery now, not in the list the signal tool keeps up only while it is open: - deleted from another tab, the signal takes them with it; - a signal renamed in the node properties gives its new name to them in the same step of the history; - in the station and line batches, a renamed signal renames them, and a removed one removes them; - the binding of objects to tracks puts them on the path reading their signal, not on the one nearest to them, and a signal moved by hand lets go of them too. Also: - a signal on a gantry takes no indicator from the list; - an indicator a signal has already isn't put on it twice; - the signals and their indicators are found in one pass over the includes, the indicators by the name of their signal; - a step of the history with tracks is always one of their edit, so they are taken back with the includes. The self-test gets signalgizmo, which turns and moves a signal as the gizmo does. * fix(tools): indicator_headers.py keeps the files it replaces, writes beside the data on request - An indicator it made, found changed, is put into a tar in editor_backup before it's written again. - --sidecar writes the descriptions of the lit indicators into editor/templates, as the other header scripts do, the files of the game left alone. - The indicators it makes are copies: the signal templates keep their own, and the docstring and the files say so. * fix(editor): a signal moved by the gizmo by another track is read by it, the templates known without the signal tool - At the end of a gizmo move the nearest track takes the signal when it is nearer than its own by more than 0.5 m; a track it was dropped onto, within 1.2 m of its axis, doesn't, so a signal only turned between two tracks or dropped onto one in a switch keeps its own. - The signal templates and indicators are looked for when a signal is renamed or its gizmo shown, so its indicators follow without the signal tool opened first. - A drop refused puts the gizmo and the node properties back where the signal stands. - The indicators follow only once the gizmo made its step, and the ones not changed are left alone: grabbed and let go it changes nothing. * fix(editor): a signal dropped by the gizmo onto a track keeps its own, the gizmo doesn't wait for the template scan - When the nearest path to the drop is within 1.2 m of its axis, the signal keeps its own track, instead of only that path being left out: dropped onto a middle track it no longer goes to the track beyond it. - The gizmo starts the signal template scan without waiting for it, so a rescan with a signal selected doesn't stop the editor; renaming a signal still waits. * feat(editor): the signalling split into Signals, Station, Station signals and Line block The one Signalling tool held the signals placed by hand, the whole wizard of a station and its checks; each is now a tool of its own in the toolbar: - Signals (I): the palette, a signal placed by a track, dragged along it, selected; a click on a switch no longer opens a station. - Station: LMB on a switch lays the station out; its name, code, line, km, speed and braking distance, the numbers of the switches, the track circuits, the number of the selected track, the list of the switches. - Station signals: the signals of the whole station placed at once, the template of each of their kinds (main, shunt) chosen in a table, and below what the signalling lacks: the repairs, the SHP resonators, the track lengths, the signal heads. - Line block: the block of each line, the block boundaries drawn by hand, the line signals, the templates of the block signals and warning discs. The station tools share the open station and its schematic; Station signals and Line block show what the Station tool set for it, the line and the km in red where the line block needs them. The template table replaces the palette in the station tools, so choosing a template there no longer arms placing. Two icons drawn for the new tools, in editor_icons.py too; the png is drawn by the same shapes, Pillow wasn't at hand. The tracktab self-test takes a tool by its name, and srkopen shows the Station tool. * feat(editor): a signal shows its distance from the track axis and to the switch ahead, and goes to 50, 100 m... from it - editor/editorTrackTrace: the track followed the way a train runs, shared by the W17 markers and the signals. The fouling point of a switch (where the axes of its tracks are 3.5 m apart) moved here… * fix: a failed start says why and ends with an error code; a small crash dump by default (#425) * fix: a failed start says why in the log and ends with an error code When the window could not be made, the log only said "Bad init: failed to create glfw window", without the reason glfw knows (no OpenGL driver, no pixel format that fits, no EGL). Sometimes it did not even say that: the log thread writes every 50 ms, and main() ended the process with std::_Exit(0) without stopping it, so a start that failed within that time left a log that ends at "// startup". - glfw's errors go to the log and errors.txt through glfwSetErrorCallback, set before glfwInit(); each distinct message once. - after a failed start (or an exception caught in main) the log thread is stopped and waited for, as the test runs already do, so nothing logged last is lost. - a failed start ends with exit code 1 instead of 0, so the starter can tell it from a closing. A start that worked ends as before. * fix: glfw's errors told during the start only, a closed crash dialog is no failed start After review of the previous commit: - the glfw error callback is taken off at the end of init(). Once the simulator runs, glfw would only repeat what the platform can't do (glfwSetCursorPos on Wayland, on every mouse-look) or what a scenery asks for in vain (launcher key codes below GLFW_KEY_SPACE, checked on every update), which would put new lines in errors.txt of existing sceneries and cost a format and a lock per call. - closing the crash-report window ends the simulator as before, but init() now returns 1 for it (above 0: closed by the player), and only a result below 0 gives exit code 1. - a start that throws from init() (bad_alloc, or a runtime_error on Windows) ends with exit code 1 too; an exception after a start that worked ends with 0 as before. * feat: a small crash dump by default, the full one with "crashdump.full yes" The dump written by the crash handler (Windows, WITHDUMPGEN) held all the memory of the simulator (MiniDumpWithFullMemory), so it was as large as the memory the simulator took: gigabytes on a large scenery, written to the game folder at the moment of the crash, on machines with 8 GB of RAM too. By default it now holds the stacks with the memory they point to, the threads, the modules, the handles, the memory map and the modules' data segments (MiniDumpWithDataSegs in place of MiniDumpWithFullMemory, the rest of the flags as before). The globals, Global among them, stay readable. "crashdump.full yes" in eu07.ini writes the full dump as before. Measured on td.scn with a ghostview camera (1.2 GB committed): the small dump 44 MB in 2 s, the full one 1.6 GB in 19 s. The key is new and optional: eu07.ini files without it read as before, and the setting is listed in the log at start. * fix: the small crash dump keeps the process and thread blocks MiniDumpWithProcessThreadData adds the PEB and the TEBs, a few KB: the command line (the scenery and the vehicle), the environment and the last error of each thread, which the small dump otherwise lacks, since the heap behind Global's longer strings is not in it. * fix: an exception that ends the simulator says what it was in the log After review of #425: - the exceptions main() catches are logged ("Critical error: ..."): on Windows the runtime_error that only showed a message box, and on the other systems any std::exception, which used to end the simulator through std::terminate with no word in the log. On Windows the others are still left to CrashHandler, whose dump shows where they were thrown. - every exception caught there ends with exit code 1, in the start or later, as a crash; it used to be 0 when caught, the abort code when not. - closing the crash-report window logs "Crash report window closed, closing" instead of the error "Failed to run crash gui!", which stays for a result below 0. * feat: the stack of a crash on Linux in the log and on the standard error On Linux no dump is written (the crash handler is Windows only, crashpad is off), so a crash left a log that just stopped. A handler of SIGSEGV, SIGBUS, SIGFPE, SIGILL and SIGABRT (installed at the start of main) now writes, with write() only: Crash: signal 11 (SIGSEGV) at address 0x... Version: EU07 (cmake), (...) Stack (addr2line -f -C -e ): to the end of the log file (its whole path, set when the log opens it) and to the standard error, which StarterNG shows first. The Linux builds carry their symbols (GENERATE_PDB adds -g, nothing strips them), so addr2line on the eu07 file of the same version gives the files and lines. Then the signal ends the process as before (SA_RESETHAND, raise): the same exit status, and a core dump where the system makes one. The handler runs on an alternate stack, so an overflow of the main thread's stack is reported too; backtrace() is warmed up at install so it doesn't allocate in the handler, and alarm(5) ends a handler that hangs (a crash in the allocator or the loader). WAMR is built without its hardware bound checks, so it installs no SIGSEGV handler of its own. Elsewhere crash_signals does nothing. A unit test (Linux only) crashes a child process and checks the report on its standard error and in the log, and that the child still ended by SIGSEGV. * fix: the crash report can't be cut by a second crash signal or end with SIGALRM After review: - the five crash signals are blocked while a report is written, so a second one waits rather than starting a second report in its middle (a fault that comes while blocked still ends the process). - a report that hangs past alarm(5) ends the process by the signal of the crash, not by SIGALRM: a SIGALRM handler, set only in the crash handler, raises the crash signal and unblocks it. - the child of the unit test calls alarm(10) first, so a child stuck before the crash can't hang the build. --------- Co-authored-by: maj00r * feat(track): unevenness waves shaped by the track spectra of FRA and ORE B176 (#426) * feat(track): unevenness waves shaped by the track spectra of FRA and ORE B176 The waves were 5-42 m sideways and 8-83 m vertically, with the long ones cut down, so a short wavelength carried a large share and the ride and the rails looked busy. They are now 7-90 m sideways and 8-110 m vertically, about the bands D1-D3 of EN 13848, each wave standing for a band of the spectrum S ~ Wc^2 / (W^2 (W^2 + Wc^2)), Wc = 0.8245 rad/m, the shape the FRA and the ORE B176 (German) spectra share: the longer a wave, the higher it is. The "uneven" value keeps its meaning, the peak deviation of a rail on a 10 m chord as PLK Id-14 measures it, so the values in sceneries stay as they are. Since the chord sees the long waves less, the amplitudes are calibrated again, and apart for the vertical and the sideways waves: stray_per_mm becomes stray_up_per_mm 0.00229 and stray_side_per_mm 0.0031, and cross_share 0.35. A track at "uneven 18" measures 18 mm vertically, 17 sideways, 15 of twist, +-10 of gauge, 21 of cross level and J 5.7 against the Id-14 limits for 80 km/h. A rail now goes up to about 5 cm off its design over the long waves, so the bound of the test goes from 40 to 60 mm; the short waves the cab shakes on are smaller, the sideways bend under the axles about 30% less. Every scenery with unevenness looks and rides differently after this. No release has unevenness yet. The grading tool follows the vertical waves; on Baltyk the pantograph keeps within 0.6 cm of the wire up to the product 1150 of the vertical value and the speed (925 before). * test(track): bound the sideways offset of an uneven track off its design The longer waves move the track about 4.5 cm sideways off its design at "uneven 18" (2 cm before), and nothing checked or stated it. The Id-14 test now bounds the peak sideways offset of the middle of the track below 5 cm, next to the vertical one, so a later change of the shares can't double it unnoticed. The doc gives the figure, and names platform edges and level crossing panels among what a rail moves away from. --------- Co-authored-by: maj00r * feat(editor): ~ shows or hides the orthophoto, Ctrl+~ downloads what the camera sees first; the speed of the camera in the View menu (#312) * feat(editor): ~ shows or hides the orthophoto, Ctrl+~ downloads what the camera sees first; the speed of the camera in the View menu ~ (the key left of 1) turns the orthophoto on and off. Ctrl+~ finds what of the ground the camera sees (rays through a grid over the screen down to the level of the ground under the camera, or as far as 2.5 km where they don't come down to it) and puts those tiles at the front of the queue of the downloads, the ones which failed tried again at once; the status line tells how many. Tab is not used, the laying and the switches have it. View > Camera speed: the speed of the free camera of the editor (x0.05 to x10, 1 as it was), how many times faster Ctrl makes it (1 to 30, 30 as it was), and in the top view as fast as the view is zoomed, so the map crosses the screen at the same pace zoomed in or out. Kept in the settings of the editor; the camera of the cab and of the free fly outside the editor unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * fix(editor): Ctrl+~ in the top view, over a scenery with no terrain under the camera and with the orthophoto off; "As it was" without the speed going with the zoom In the top view the box is the view itself, its corners on the ground. The ground under the camera is the terrain, else the scenery, else the rays go as far as the reach. The tile of the camera is taken anew by hurry(), it isn't followed while the layer is off. The top view is as fast zoomed in as out by default, as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * fix(editor): the corners of the top view on the ground put where the camera is (the view matrix is camera-relative) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * i18n(editor): Polish for the orthophoto keys and the camera speed, on top of the master's own translations Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * fix(editor): Ctrl+~ asks only for the tiles update() would ask for; the tooltip of "Track colours" back in its place After the reviews of #312: - hurry() skips the tiles outside the download area set and marks the ones outside the area the service covers as empty, as update() does, so Ctrl+~ no longer queues downloads update() drops at once (and the workers took anyway, into the disk cache, against the area set), nor requests the service can't answer. - A blank tile hurried takes the standard image first, as in update(); first_level() and outside_area() are shared by both loops, and the body of the loop of hurry() is hurry_tile(). - orthophoto_hurry() takes the level of the terrain only when it's below the camera, as the branch of the scenery already did: a camera under the terrain (a tunnel, under the heightmap) no longer flips the box of the view behind it. - The "Camera speed" menu goes after the tooltip of "Track colours", which it had taken. - #include once in editorOrthophoto.hpp. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QRgQ1K1Qu7TCsa74zsNURd --------- Co-authored-by: Claude * fix: whole-number bounds of Random() give a real number again (#416) * fix: whole-number bounds of Random() give a real number again ee3af0bf (#99, in 26.05.2) renamed RandomInt to an overload, Random(int, int). The calls with whole-number bounds that expect a real number in between took the overload and draw whole numbers since: - wheel flats given with P0 happen to 1 vehicle in 101 (before: none), the random part of a flat is a whole number of millimetres; - the chance of truck hunting is h/101 instead of h/100; - the wind starts with a whole azimuth, speed and rates of change, and its direction changes in whole degrees per second; - the tachometer below 5 km/h jumps to whole numbers. The whole-number draw is RandomInt again, keeping the shared engine and the swap of inverted bounds; the loading screen's trivia use it. Those calls take the real Random() again, as up to 26.05.1. * RandomInt: the comment says what it draws and why it has a name of its own The comment put the bug on the overloading. It was in the calls that pass whole-number bounds and expect a real number; the separate name keeps them on Random(double, double). * fix: RandomInt draws from the local engine, as up to 26.05.1 from one of its own From the review of #416: ee3af0bf moved RandomInt from an engine of its own (std::mt19937 seeded by std::random_device) to Global.random_engine, the engine of the run's seed, and only the name was taken back here. Its one caller draws the trivia of the loading screen, in init_modes, before a network client gets the seed of the session in server_hello: the server's engine was then one draw ahead of the client's, and with a fixed randomseed the trivia was the same on every start. It is drawn from Global.local_random_engine now, the engine of what one machine shows, seeded from a true random source in init_modes before the loader is made. The test of the same seed checks the shared engine with Random() and the local one with RandomInt(); a new test checks that RandomInt() doesn't move the engine of the run's seed. --------- Co-authored-by: maj00r * fix(editor): the orthophoto only on the chunks of the heightmap terrain in memory, and laid onto the ground again once it comes (#417) * fix(editor): the orthophoto only on the chunks of the heightmap terrain in memory, and laid onto the ground again once it comes Right after the editor started, the tiles of the orthophoto came from the disk cache at once and were fitted to the ground before the chunks of the heightmap terrain had come (on IRT the orthophoto was on at 24.5 s, the first chunk came at 24.5 s, the last one at 85 s). A tile with no ground under it, and none beside, stayed flat at the height of the layer (0 m, some 230 m under IRT); one partly over the ground had its holes filled from the points beside. Neither was fitted again when the ground came: only the guessed tiles were, by their middle and corners alone, and a tile with no chunk under it at all never got any. The overlay, drawn over everything, then slid with the camera (WASD, turning) instead of lying on the ground. Turning the orthophoto off and on hid it: by then the terrain was in and the tiles took their heights from it or from the edges of the tiles beside. - With the heightmap terrain (the terrain streamer active), a tile of the orthophoto, of the WMS layers and of Ctrl+~ is asked for and shown only where its chunks are in memory (terrain_streamer::ground_under): it waits while one is still to come, and where no chunk is nor will be there's no imagery at all. A scenery without the heightmap terrain is as before. - A tile remembers the points of its grid the ground didn't answer and is fitted again once the ground comes under any of them (every second point and the edges), not only the guessed tiles. No asset changes. Co-Authored-By: Claude Opus 5.5 * fix(editor): the orthophoto waits only for the chunks that will come at this distance, and lies on the other ground or the guess elsewhere After the reviews of maj00r and jerrrrycho on #417: - A tile is no longer dropped where no chunk of the heightmap terrain is nor will be. There it lies on whatever ground there is (terrain models) or on the NMT guess, as on master; a scenery with a few chunks, or with chunks removed, keeps its imagery around them. - A chunk counts as still to come only while it's being loaded or lies within the circle the streamer walks around the camera. The corners of the imagery in the 3D view, beyond that circle, no longer wait for chunks that won't load there: they lie on the guess and are sampled again when the camera comes near and the chunk loads. - terrain_streamer::ground_under() (true / false / empty) became ground_coming() (bool), the cover source of the orthophoto the coming source, and on_ground() waits_for_ground(), which only holds back a new tile. - In the scene (in_scene), the points a steep triangle leaves without a height but the heightmap terrain answers aren't kept as unanswered, so the tile isn't sampled again on every chunk that comes. The holes are counted from the heights again, as on master. --------- Co-authored-by: Claude Opus 5.5 * fix(editor): the closing doesn't wait for a geoportal service that doesn't answer (#432) * fix(editor): the closing doesn't wait for a geoportal service that doesn't answer When geoportal.gov.pl took the connection and never answered, the editor's closing stood still for tens of seconds and was killed: the WinHTTP client was synchronous and looked at the stop only between the reads of a body, so a request waiting for the answer held the closing for the timeouts (up to 20 s for the answer, a few tries a square), and the map of the place-picker downloaded with no stop at all, its std::async future waited for to the end. On Windows the client now uses WinHTTP asynchronously: each step is waited for while the stop is looked at every 50 ms, and a stop closes the request at once. The timeouts, the user agent, the size limit, the errors and the body of a response with an error status stay as they were. The map of the place-picker is given up when it goes. libcurl looked at the stop during the whole transfer already. The unit tests run the client against a local server that never answers (given up within 0.4 s of the stop), one with a body of 100 kB and one with an error status. * fix(editor): the capabilities of a WMS service being added don't hold the closing either The reading of the layers of a WMS service the user adds ran on a std::async future of the editor with no stop: closing the editor while such a service didn't answer waited for its three tries. The reading is given up when the editor goes, as the other downloads now are, and editor_http_get, left with no callers, goes. The unit test's silent server no longer waits for the client to close its connection, and the requests to the local server are skipped when the environment names a proxy, which couldn't reach it. * fix(editor): the stop of the WMS reading outlives the future waiting for it The flag was declared after the future of the reading, so it was destroyed first while the future's destructor still waited for the task reading it. --------- Co-authored-by: maj00r * revert(environment): the turbidity of the sky as it was before #227 (#410) #227 (842b7688) raised the turbidity of the sky dome for most cloud covers (3 -> 4 for a clear sky, 5 -> 6 at 0.41-0.60, one more from 0.61 up to 0.90). In the Preetham model a higher turbidity darkens the sky a lot once the sun is below the horizon: with a cover of 0.47 the zenith is about a third darker 1.4 degrees below it and half as bright 3 degrees below, the stars come out right after the sunset and the ambient light taken from the sky dome drops with it. Players report the dusk as too dark since the update. The values are put back as they were before #227, in the turbidity_of() that #323 made of the old chain of conditionals. A clear sky gets the turbidity 3 again, which #227 said breaks the model at night. Co-authored-by: maj00r * Revert "fix(physicslog): no road-vehicle logs, formatting on the writer, a slow disk and the closing kept short (#408)" This reverts commit d6c35935209a7e5b67c5a5030f660704ee91ca6f. --------- Co-authored-by: maj00r <73280030+maj00r@users.noreply.github.com> Co-authored-by: maj00r Co-authored-by: Claude Opus 5.5 Co-authored-by: Hirek193 Co-authored-by: pol102 --- CMakeLists.txt | 2 + EU07.cpp | 50 +++- McZapkie/Mover.cpp | 34 +-- application/application.cpp | 80 +++++- application/application.h | 1 + application/drivermode.cpp | 19 +- application/drivermode.h | 1 + application/editormode.cpp | 158 +++++++++- application/editormode.h | 48 +++- application/editormodelineside.cpp | 4 +- application/editormodeselftestswitch.cpp | 19 ++ application/editormodeswitchdrive.cpp | 261 +++++++++++++++-- application/editormodeswitchplace.cpp | 7 + application/editormodeswitchtemplate.cpp | 3 + application/editormodeswitchtool.cpp | 1 + application/editormodetrack.cpp | 18 +- application/scenarioloaderuilayer.cpp | 2 +- blackbox_doc.md | 16 +- editor/editorGeoMap.cpp | 8 +- editor/editorGeoMap.hpp | 2 + editor/editorHttp.cpp | 261 +++++++++++++---- editor/editorIncludeInfo.cpp | 65 +++++ editor/editorIncludeInfo.hpp | 7 + editor/editorOrthophoto.cpp | 163 +++++++++-- editor/editorOrthophoto.hpp | 27 +- editor/editorSettings.cpp | 15 + editor/editorSettings.hpp | 9 + editor/editorTerrainStreamer.cpp | 39 +++ editor/editorTerrainStreamer.hpp | 9 + global_include/interfaces/ITexture.h | 13 + lang/editor_pl.po | 66 +++++ model/AnimModel.cpp | 9 +- model/AnimModel.h | 1 + model/Texture.cpp | 119 +++++++- model/Texture.h | 27 ++ rendering/opengl33renderer.cpp | 4 +- rendering/openglparticles.cpp | 4 +- rendering/openglrenderer.cpp | 4 +- rendering/particles.cpp | 6 +- scripting/PyInt.cpp | 65 ++++- scripting/PyInt.h | 11 + scripting/pythonscreenviewer.cpp | 16 +- scripting/pythonscreenviewer.h | 4 + simulation/blackboxrecorder.cpp | 12 +- simulation/blackboxrecorder.h | 5 +- simulation/simulationenvironment.cpp | 9 +- simulation/simulationtest.cpp | 14 +- tests/unit/CMakeLists.txt | 2 + tests/unit/test_braking_curve.cpp | 195 +++++++++++++ tests/unit/test_crashsignals.cpp | 89 ++++++ tests/unit/test_editor_http.cpp | 138 +++++++++ tests/unit/test_physicslog.cpp | 145 ---------- tests/unit/test_track_uneven.cpp | 28 +- tests/unit/test_utilities.cpp | 81 +++++- tools/track_uneven_grade.py | 6 +- track_uneven_doc.md | 14 +- utilities/Globals.cpp | 7 + utilities/Globals.h | 10 + utilities/Logs.cpp | 3 + utilities/crashsignals.cpp | 234 +++++++++++++++ utilities/crashsignals.h | 25 ++ utilities/physicslog.cpp | 348 ++++------------------- utilities/physicslog.h | 119 +------- utilities/utilities.cpp | 4 +- utilities/utilities.h | 24 +- vehicle/Camera.cpp | 33 ++- vehicle/Driver.cpp | 187 +++++------- vehicle/Driver.h | 21 +- vehicle/DynObj.cpp | 50 +++- vehicle/DynObj.h | 5 + vehicle/Train.cpp | 13 +- vehicle/brakingcurve.cpp | 86 ++++++ vehicle/brakingcurve.h | 54 ++++ world/Segment.cpp | 9 +- world/TrackUneven.h | 21 +- 75 files changed, 2699 insertions(+), 970 deletions(-) create mode 100644 tests/unit/test_braking_curve.cpp create mode 100644 tests/unit/test_crashsignals.cpp create mode 100644 tests/unit/test_editor_http.cpp create mode 100644 utilities/crashsignals.cpp create mode 100644 utilities/crashsignals.h create mode 100644 vehicle/brakingcurve.cpp create mode 100644 vehicle/brakingcurve.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 75dbc5df5..294128b87 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -556,6 +556,7 @@ set(CORE_SOURCES "scene/sn_utils.cpp" "scene/regionfile.cpp" "utilities/inionlysettings.cpp" +"utilities/crashsignals.cpp" "scripting/ladderlogic.cpp" "scripting/scriptscreenrules.cpp" "scripting/scriptscreenkernels.cpp" @@ -568,6 +569,7 @@ set(CORE_SOURCES "vehicle/brakesetting.cpp" "vehicle/gaugewrap.cpp" "vehicle/drivingaid.cpp" +"vehicle/brakingcurve.cpp" "vehicle/handover.cpp" "vehicle/crew.cpp" "vehicle/horn.cpp" diff --git a/EU07.cpp b/EU07.cpp index a76564663..fa6bb15f2 100644 --- a/EU07.cpp +++ b/EU07.cpp @@ -22,9 +22,13 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others #include "simulation/simulationtest.h" #include "utilities/Globals.h" #include "utilities/Logs.h" +#include "utilities/crashsignals.h" #include "utilities/physicslog.h" +#include "version_info.h" #include #include +#include +#include #include #include #include @@ -78,8 +82,12 @@ LONG WINAPI CrashHandler(EXCEPTION_POINTERS *ExceptionInfo) dumpInfo.ExceptionPointers = ExceptionInfo; dumpInfo.ClientPointers = FALSE; - // Wybrana kombinacja flag - MINIDUMP_TYPE dumpType = MINIDUMP_TYPE(MiniDumpWithFullMemory | MiniDumpWithHandleData | MiniDumpWithThreadInfo | MiniDumpWithUnloadedModules | MiniDumpWithIndirectlyReferencedMemory | + // a small dump by default: the stacks with the memory they point to, the threads with their process and thread + // blocks (the command line with the scenery and the vehicle), the modules, the handles and the modules' data + // (Global among them). all the memory of the simulator, as large as the memory it took, only with + // "crashdump.full yes" in eu07.ini + auto const dumpflags{Global.CrashDumpFull ? MiniDumpWithFullMemory : MiniDumpWithDataSegs}; + MINIDUMP_TYPE dumpType = MINIDUMP_TYPE(dumpflags | MiniDumpWithProcessThreadData | MiniDumpWithHandleData | MiniDumpWithThreadInfo | MiniDumpWithUnloadedModules | MiniDumpWithIndirectlyReferencedMemory | MiniDumpWithFullMemoryInfo | MiniDumpWithTokenInformation); // in test mode nobody is there to close the box, and the run would wait for it until killed @@ -113,7 +121,7 @@ void finish_log() [[noreturn]] void end_test_run(std::string_view const Reason) { simulation::test().conclude(simulation::test_result::error, Reason); - // the last seconds of the physics logs, which the runner of the tests reads: a second at most is waited for them + // the last two seconds of the physics logs, which the runner of the tests reads PhysicsLogs.stop(); finish_log(); fflush(stdout); @@ -172,9 +180,15 @@ int main(int argc, char *argv[]) SetUnhandledExceptionFilter(CrashHandler); #endif #endif + // on Linux, where no dump is written, the stack of a crash in the log and on the standard error + crash_signals::install(VERSION_INFO); // init start timestamp Global.startTimestamp = std::chrono::steady_clock::now(); + // a start that failed ends with an error code, so whoever started the simulator (the starter) can tell it + // from a closing; how the simulator ends after a start that worked stays as it was + int exitcode{0}; + // quick short-circuit for standalone e3d export if (argc == 6 && std::string(argv[1]) == "-e3d") { @@ -221,34 +235,54 @@ int main(int argc, char *argv[]) } else { + // below 0 when the start failed (see eu07_application::init()) + int initresult{0}; try { - auto result{Application.init(argc, argv)}; - if (result == 0) + initresult = Application.init(argc, argv); + if (initresult == 0) { - result = Application.run(); + Application.run(); Application.exit(); } } + // an exception that ends the simulator is a crash, whether in the start or later: it says what it was in the + // log and ends with an error code catch (std::bad_alloc const &Error) { ErrorLog("Critical error, memory allocation failure: " + std::string(Error.what())); + exitcode = 1; } #ifdef _WIN32 catch (std::runtime_error const &Error) { + ErrorLog("Critical error: " + std::string(Error.what())); std::string msg = "Simulator crash occured :(\n"; msg += Error.what(); MessageBoxA(nullptr, msg.c_str(), "Simulator crashed :(", MB_ICONERROR); + exitcode = 1; + } +#else + // elsewhere one not caught here ends the simulator through std::terminate, with no word in the log. on + // Windows it is left to CrashHandler, whose dump shows where it was thrown + catch (std::exception const &Error) + { + ErrorLog("Critical error: " + std::string(Error.what())); + exitcode = 1; } #endif - // the last seconds of the physics logs, a second at most, also after an error caught above; Application.exit() stops them + // the last two seconds of the physics logs, also after an error caught above; Application.exit() stops them // otherwise, and a second stop only writes what came since PhysicsLogs.stop(); + // after a failed start or an error caught above the log thread still runs, and what it hasn't written yet + // (why the start failed) would go with the process. after Application.exit() it has stopped already + finish_log(); + if (initresult < 0) + exitcode = 1; } #ifndef _WIN32 fflush(stdout); fflush(stderr); #endif - std::_Exit(0); // skip destructors, there are ordering errors which causes segfaults + std::_Exit(exitcode); // skip destructors, there are ordering errors which causes segfaults } diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index b4ba8478d..b1735d0c5 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -940,7 +940,7 @@ void TMoverParameters::UpdatePantVolume(double dt) // Ra 2013-12: Niebugocław mówi, że w EZT nie ma potrzeby odcinać kurkiem PantPress = ScndPipePress; // ograniczenie ciśnienia do MaxPress (tylko w pantografach!) - PantPress = std::clamp(ScndPipePress, 0.0, EnginePowerSource.CollectorParameters.MaxPress); + PantPress = safe_clamp(ScndPipePress, 0.0, EnginePowerSource.CollectorParameters.MaxPress); PantVolume = (PantPress + 1.0) * 0.1; // objętość, na wypadek odcięcia kurkiem } else @@ -952,7 +952,7 @@ void TMoverParameters::UpdatePantVolume(double dt) // Ra 2013-12: Niebugocław mówi, że w EZT nabija 1.5 raz wolniej niż jak było 0.005 * (TrainType == dt_EZT ? 0.003 : 0.005) / std::max(1.0, PantPress) * (0.45 - (0.1 / PantVolume / 10 - 0.1)) / 0.45; } - PantPress = std::clamp(10.0 * PantVolume - 1.0, 0.0, EnginePowerSource.CollectorParameters.MaxPress); // tu by się przydała objętość zbiornika + PantPress = safe_clamp(10.0 * PantVolume - 1.0, 0.0, EnginePowerSource.CollectorParameters.MaxPress); // tu by się przydała objętość zbiornika } if (!PantCompFlag && PantVolume > 0.1) PantVolume -= dt * 0.0003 * std::max(1.0, PantPress * 0.5); // nieszczelności: 0.0003=0.3l/s @@ -4719,7 +4719,7 @@ bool TMoverParameters::ChangeCompressorPreset(int const State, range_t const Not auto const initialstate{CompressorListPos}; - CompressorListPos = std::clamp(State, 0, CompressorListPosNo); + CompressorListPos = safe_clamp(State, 0, CompressorListPosNo); if (Notify != range_t::local) { @@ -6579,7 +6579,7 @@ double TMoverParameters::CouplerForce(int const End, double dt) if (thiscoupler.CouplingFlag != coupling::faux || initialdistance < 0) { - thiscoupler.Dist = std::clamp(newdistance, thiscoupler.has_adapter() ? 0 : -thiscoupler.DmaxB, thiscoupler.DmaxC); + thiscoupler.Dist = safe_clamp(newdistance, thiscoupler.has_adapter() ? 0 : -thiscoupler.DmaxB, thiscoupler.DmaxC); double BetaAvg = 0; double Fmax = 0; @@ -6955,7 +6955,7 @@ double TMoverParameters::UpdateEngineRevolutions(double dt, double &dtrans, doub if (enrot != tmp) { - enrot = std::clamp(enrot + dt / dizel_AIM * (enrot < tmp ? 1.0 : -1.0 * dizel_RevolutionsDecreaseRate), // NOTE: revolutions typically drop faster than they rise + enrot = safe_clamp(enrot + dt / dizel_AIM * (enrot < tmp ? 1.0 : -1.0 * dizel_RevolutionsDecreaseRate), // NOTE: revolutions typically drop faster than they rise 0.0, std::max(tmp, enrot)); if (std::abs(tmp - enrot) < 0.001) { @@ -9089,7 +9089,9 @@ double stepped_uc_value(double const Current, double const Ramped, TUniversalCtr { Progress = 0.0; } - return safe_clamp(value, Position.MinCtrlVal, Position.MaxCtrlVal); + // added after the move to std::clamp: bounds given the other way round are put in order, as master did it + auto const [lowest, highest] = std::minmax(Position.MinCtrlVal, Position.MaxCtrlVal); + return std::clamp(value, lowest, highest); } } // namespace @@ -9203,18 +9205,18 @@ void TMoverParameters::EIMICFromFourPositions(double dt) { case 0: case 1: - eimic -= std::clamp(1.0 + eimic, 0.0, delta); // odejmuj do -1 + eimic -= safe_clamp(1.0 + eimic, 0.0, delta); // odejmuj do -1 if (eimic > 0) eimic = 0; break; case 2: - eimic -= std::clamp(0.0 + eimic, 0.0, delta); // odejmuj do 0 + eimic -= safe_clamp(0.0 + eimic, 0.0, delta); // odejmuj do 0 break; case 3: - eimic += std::clamp(0.0 - eimic, 0.0, delta); // dodawaj do 0 + eimic += safe_clamp(0.0 - eimic, 0.0, delta); // dodawaj do 0 break; case 4: - eimic += std::clamp(1.0 - eimic, 0.0, delta); // dodawaj do 1 + eimic += safe_clamp(1.0 - eimic, 0.0, delta); // dodawaj do 1 if (eimic < 0) eimic = 0; break; @@ -9336,7 +9338,7 @@ void TMoverParameters::EIMICLimit() eimic_max = 0.001; } } - eimic = std::clamp(eimic, -1.0, eimicpowerenabled ? eimic_max : 0.0); + eimic = safe_clamp(eimic, -1.0, eimicpowerenabled ? eimic_max : 0.0); } bool TMoverParameters::UpdateStopBrakeRelease(double const Demand, double const Dt) @@ -9443,7 +9445,7 @@ void TMoverParameters::SpeedCtrlRegulator(double dt, double const accfactor) eimicSpeedCtrlIntegral = 0; } auto const DesiredeimicSpeedCtrl{safe_clamp(eimicSpeedCtrlIntegral + eSCP, -SpeedCtrlUnit.DesiredPower, accfactor)}; - eimicSpeedCtrl = std::clamp(DesiredeimicSpeedCtrl, eimicSpeedCtrl - SpeedCtrlUnit.PowerDownSpeed * dt, eimicSpeedCtrl + SpeedCtrlUnit.PowerUpSpeed * dt); + eimicSpeedCtrl = safe_clamp(DesiredeimicSpeedCtrl, eimicSpeedCtrl - SpeedCtrlUnit.PowerDownSpeed * dt, eimicSpeedCtrl + SpeedCtrlUnit.PowerUpSpeed * dt); if (Vel < SpeedCtrlUnit.FullPowerVelocity) { eimicSpeedCtrl = std::min(eimicSpeedCtrl, SpeedCtrlUnit.InitialPower); @@ -10451,7 +10453,7 @@ bool TMoverParameters::AssignLoad(std::string const &Loadname, float const Amoun } LoadTypeChange = LoadType.name != Loadname; LoadType = *loadattributes; - LoadAmount = std::clamp(Amount, 0.f, MaxLoad); + LoadAmount = safe_clamp(Amount, 0.f, MaxLoad); ComputeMass(); return true; } @@ -10496,7 +10498,7 @@ bool TMoverParameters::LoadingDone(double const LSpeed, std::string_view Loadnam { // pusto lub rozładowano żądaną ilość LoadStatus = 4; // skończony rozładunek - LoadAmount = std::clamp(LoadAmount, 0.f, MaxLoad); // ładunek nie może być ujemny + LoadAmount = safe_clamp(LoadAmount, 0.f, MaxLoad); // ładunek nie może być ujemny } if (LoadAmount == 0.f) { @@ -14370,7 +14372,7 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) { SecuritySystem.MagnetLocation = Dim.L / 2 - 0.5; } - SecuritySystem.MagnetLocation = std::clamp(SecuritySystem.MagnetLocation, 0.0, Dim.L); + SecuritySystem.MagnetLocation = safe_clamp(SecuritySystem.MagnetLocation, 0.0, Dim.L); return OK; } @@ -14996,7 +14998,7 @@ bool TMoverParameters::RunAuxiliariesCommand(std::string const &Command, double } else if (Command == "CompressorPreset") { - CompressorListPos = std::clamp(static_cast(CValue1), 0, CompressorListPosNo); + CompressorListPos = safe_clamp(static_cast(CValue1), 0, CompressorListPosNo); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } else diff --git a/application/application.cpp b/application/application.cpp index 2a024bfd6..bc4b7dc1d 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -37,6 +37,9 @@ http://mozilla.org/MPL/2.0/. #include "utilities/physicslog.h" #include #include +#include +#include +#include #include #include "utilities/translation.h" @@ -54,6 +57,7 @@ http://mozilla.org/MPL/2.0/. #pragma comment(lib, "setupapi.lib") #pragma comment(lib, "dbghelp.lib") #pragma comment(lib, "version.lib") +#include #endif #ifdef __unix__ @@ -65,6 +69,36 @@ eu07_application Application; screenshot_manager screenshot_man; ui_layer uilayerstaticinitializer; +namespace +{ +#ifdef _WIN32 +// windows wakes a sleeping thread of a process which didn't ask for a finer timer in steps of up to ~15.6 ms. +// the wait of fpslimit sleeps, so a 10 ms frame slot of fpslimit 100 ended ~15.6 ms later, the pacer made it up +// with no wait in the next frame, and the frames came in turns long and short: with vsync on, shown for one or +// two refreshes of the screen. the finer timer is asked for only with fpslimit, the only steady sleeper of the +// main loop, as it costs some power for as long as it's held +bool timer_period_set{false}; +#endif + +// asks for the finer timer once, when fpslimit is set +void begin_timer_period() +{ +#ifdef _WIN32 + if (!timer_period_set && Global.minframetime.count() > 0.f) + timer_period_set = (timeBeginPeriod(1) == TIMERR_NOERROR); +#endif +} + +void end_timer_period() +{ +#ifdef _WIN32 + if (timer_period_set) + timeEndPeriod(1); + timer_period_set = false; +#endif +} +} // namespace + #ifdef _WIN32 extern "C" { @@ -140,6 +174,28 @@ void char_callback(GLFWwindow *window, unsigned int c) Application.on_char(c); } +namespace +{ + +// what glfw says went wrong during the start (init()), such as why the window or its context couldn't be made (no +// OpenGL driver, no pixel format that fits). each message once, so one repeated, for each window or worker's context, +// is told once. glfw may call this from any thread that uses it +void glfw_error_callback(int const Code, char const *Description) +{ + auto message{std::format("GLFW error 0x{:08X}: {}", static_cast(Code), Description != nullptr ? Description : "(no description)")}; + + static std::mutex reportedmutex; + static std::set reported; + { + std::scoped_lock lock(reportedmutex); + if (false == reported.insert(message).second) + return; + } + ErrorLog(message); +} + +} // namespace + // public: void eu07_application::queue_screenshot() @@ -222,7 +278,8 @@ int eu07_application::run_crashgui() return 0; } } - return -1; + // the player closed the window: the simulator closes with it, as it always has, but that is no failed start + return 1; } #if WITH_DISCORD_RPC void eu07_application::DiscordRPCService() @@ -352,6 +409,8 @@ int eu07_application::init(int Argc, char *Argv[]) ErrorLog("Failed to initialize settings! Maybe you're missing eu07.ini file?"); return result; } + // fpslimit is known now + begin_timer_period(); // the run's seed, settled once and kept in Globals: the engines come out of it. // narrowed on purpose - mt19937 and seed_of() both work on 32 bits, and that is @@ -407,7 +466,11 @@ int eu07_application::init(int Argc, char *Argv[]) { // run crashgui as early as possible if ((result = run_crashgui()) != 0) { - ErrorLog("Failed to run crash gui!"); + // above 0 the player closed the window, which is no error + if (result < 0) + ErrorLog("Failed to run crash gui!"); + else + WriteLog("Crash report window closed, closing"); return result; } } @@ -474,6 +537,11 @@ int eu07_application::init(int Argc, char *Argv[]) if (!init_network()) return -1; + // glfw's errors are told to explain a failed start. once the simulator runs they would only repeat what the + // platform can't do (no setting of the cursor position on Wayland) or what a scenery asks for in vain (old key + // codes of its launchers), every frame + glfwSetErrorCallback(nullptr); + return result; } @@ -690,6 +758,8 @@ int eu07_application::run() // fpslimit: wait for the next frame's slot (eu07/maszyna#416) if (auto const nextframe{framepacer.next_frame(frame_pacer::clock::now(), Global.minframetime)}) { + // fpslimit may come from the config block of the scenery, read after the settings + begin_timer_period(); std::this_thread::sleep_until(*nextframe); } } @@ -751,7 +821,7 @@ void eu07_application::exit() step("the black box"); simulation::Blackbox.close(); step("the physics logs"); - // what is kept of them, the black box's written last, waited for a second at most: the rest is dropped + // what is kept of them, the black box's written last PhysicsLogs.stop(); step("the modes"); for (auto &mode : m_modes) @@ -786,6 +856,7 @@ void eu07_application::exit() if (!Global.exec_on_exit.empty()) system(Global.exec_on_exit.c_str()); + end_timer_period(); step("done"); StopLogService(); auto it = Global.threads.find("LogService"); @@ -1359,6 +1430,9 @@ int eu07_application::init_locale() int eu07_application::init_glfw() { + // set before glfwInit(), so a failure of the start itself is told too + glfwSetErrorCallback(glfw_error_callback); + { int glfw_major, glfw_minor, glfw_rev; glfwGetVersion(&glfw_major, &glfw_minor, &glfw_rev); diff --git a/application/application.h b/application/application.h index 850b66e1e..881d4f073 100644 --- a/application/application.h +++ b/application/application.h @@ -33,6 +33,7 @@ public: // constructors eu07_application() = default; // methods + // 0 when the simulator started, below 0 when its start failed, above 0 when the player closed it before it started int init( int Argc, char *Argv[] ); int diff --git a/application/drivermode.cpp b/application/drivermode.cpp index 47ab3ae0c..b47a1d4df 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -31,6 +31,9 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "rendering/renderer.h" #include "utilities/Logs.h" + +#include + /* namespace input { @@ -627,6 +630,12 @@ bool driver_mode::is_command_processor() const return true; } +double driver_mode::shake_fraction() const +{ + // how far the simulation time has got from the last step of the shake towards the next one + return std::clamp(m_secondaryupdateaccumulator / m_secondaryupdaterate, 0.0, 1.0); +} + void driver_mode::update_camera(double const Deltatime) { @@ -775,7 +784,8 @@ void driver_mode::update_camera(double const Deltatime) // ale bez odbicia Camera.LookAt = Camera.Pos - simulation::Train->GetDirection() * (double)simulation::Train->Occupied()->CabOccupied; //-1 albo 1 } - auto const shakeangles{simulation::Train->Dynamic()->shake_angles()}; + auto const *dynamic{simulation::Train->Dynamic()}; + auto const shakeangles{dynamic->shake_angles(dynamic->shake_between(shake_fraction()))}; Camera.Angle.x = 0.5 * shakeangles.second; // hustanie kamery przod tyl Camera.Angle.z = shakeangles.first; // hustanie kamery na boki /* @@ -796,8 +806,9 @@ void driver_mode::update_camera(double const Deltatime) } float const shakescale{FreeFlyModeFlag ? 5.0f : 1.0f}; - auto shakencamerapos{Camera.m_owneroffset + - shakescale * glm::vec3(1.5 * Camera.m_owner->ShakeState.offset.x, 2.0 * Camera.m_owner->ShakeState.offset.y, 1.5 * Camera.m_owner->ShakeState.offset.z)}; + // the shake steps at a fixed rate, the frames come at their own: taken at the frame's moment between the steps, it moves as smoothly as the vehicle + auto const shake{Camera.m_owner->shake_between(shake_fraction())}; + auto shakencamerapos{Camera.m_owneroffset + shakescale * glm::vec3(1.5 * shake.offset.x, 2.0 * shake.offset.y, 1.5 * shake.offset.z)}; Camera.Pos = Camera.m_owner->GetWorldPosition(FreeFlyModeFlag ? glm::dvec3(shakencamerapos) : // TODO: vehicle collision box for the external vehicle camera simulation::Train->clamp_inside(shakencamerapos)); @@ -805,7 +816,7 @@ void driver_mode::update_camera(double const Deltatime) if (!Global.iPause) { // podczas pauzy nie przeliczać kątów przypadkowymi wartościami - auto const shakeangles{Camera.m_owner->shake_angles()}; + auto const shakeangles{Camera.m_owner->shake_angles(shake)}; Camera.Angle.x -= 0.5 * shakeangles.second; // hustanie kamery przod tyl Camera.Angle.z = shakeangles.first; // hustanie kamery na boki /* diff --git a/application/drivermode.h b/application/drivermode.h index 7e86e99f6..7e5b48573 100644 --- a/application/drivermode.h +++ b/application/drivermode.h @@ -97,6 +97,7 @@ private: // methods void update_camera( const double Deltatime ); + double shake_fraction() const; // handles vehicle change flag void OnKeyDown( int cKey ); void InOutKey(); diff --git a/application/editormode.cpp b/application/editormode.cpp index ab150cb7b..a40c6e081 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -14,6 +14,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include "application/editormode.h" #include "application/editormodeshared.h" #include "application/editorgestures.h" @@ -600,6 +601,9 @@ void editor_mode::ground_sources(editor_orthophoto &Layer) gather_ground_triangles(Min, Max, true, 50.0f, Out, true, Heightmap); }); Layer.height_source([](double const X, double const Z, double &Height) { return EditorTerrain.height_at(X, Z, Height); }); + // with the heightmap terrain, a new tile waits while a chunk under it is still to come; where none is nor will be, or the walk of + // the chunks doesn't reach, it lies on the other ground or on the NMT guess as before. A scenery without it as before + Layer.coming_source([](glm::dvec2 const &Min, glm::dvec2 const &Max) { return EditorTerrain.active() && EditorTerrain.ground_coming(Min, Max); }); // the imagery often comes before the terrain made from the model: it lies where the terrain will be Layer.guess_source([this](double const X, double const Z, double &Height) { if (nmt_ground(X, Z, Height)) @@ -614,6 +618,8 @@ void editor_mode::ground_sources(editor_orthophoto &Layer) editor_mode::~editor_mode() { editor_track::observe(nullptr); + // the capabilities of a WMS service being read are given up rather than waited for to their timeouts + m_wms_adding.closing = true; } std::vector editor_mode::ground_heights(std::vector const &Points, bool const Fresh, std::vector *Found) const @@ -1412,6 +1418,15 @@ bool editor_mode::update() ui()->set_status(text, false); WriteLog("Editor: " + text, logtype::generic); } + // the drives left without their switches are told once, as the scenery is opened + if (auto const stray{stray_drives().size()}; stray > 0) + { + auto const text{format(STR_P("%zu switch drive has no switch of its name: it's listed in the switch tool and marked red in the view", + "%zu switch drives have no switch of their names: they're listed in the switch tool and marked red in the view", static_cast(stray)), + stray)}; + ui()->set_notice(text); + WriteLog("Editor: " + text, logtype::generic); + } } } // after the tool has told its own status @@ -1652,6 +1667,7 @@ bool editor_mode::update() draw_build_overlay(); steps.step("laying drawn"); draw_blade_tips(); + draw_stray_drives(); draw_track_intent(); draw_tape(); steps.step("track drawn"); @@ -3309,7 +3325,7 @@ void editor_mode::toggle_include(scene::instance_handle const Instance) return; } scene::Layers.removed(Instance, false == included.removed); - m_drives_standing.reset(); + drives_changed(); ui()->set_status(format(included.removed ? STR_C("Include of \"%s\" removed") : STR_C("Include of \"%s\" restored"), included.file->c_str())); } @@ -3346,7 +3362,7 @@ void editor_mode::restore_includes(EditorSnapshot &Snapshot) } scene::Layers.removed(instance, false == scene::Layers.instance(instance).removed); } - m_drives_standing.reset(); + drives_changed(); for (auto &entry : Snapshot.directives) { auto current = scene::Layers.directive(entry.first); @@ -3391,7 +3407,7 @@ void editor_mode::select_include(scene::instance_handle const Instance) void editor_mode::set_include_directive(scene::instance_handle const Instance, std::string const &Directive) { - m_drives_standing.reset(); + drives_changed(); std::string file; std::vector values; if (scene::Layers.tracked(Instance) && editor_includes::parse_directive(Directive, file, values) && scene::Layers.instance(Instance).file != nullptr && @@ -4087,7 +4103,7 @@ void editor_mode::render_wms_adding() adding.info.reset(); adding.ticked.clear(); adding.service = url; - adding.reading = std::async(std::launch::async, [url]() { return editor_orthophoto::describe(url); }); + adding.reading = std::async(std::launch::async, [url, closing = &adding.closing]() { return editor_orthophoto::describe(url, [closing]() { return closing->load(); }); }); } if (adding.reading.valid()) { @@ -4248,6 +4264,11 @@ void editor_mode::render_view_menu() } if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("The tracks of the track mode coloured by their radius, speed or grade, with the legend in the corner")); + if (ImGui::BeginMenu(STR_C("Camera speed"))) + { + render_camera_settings(); + ImGui::EndMenu(); + } ImGui::MenuItem(STR_C("Track labels in the top view"), nullptr, &m_track_labels); if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("Zoomed in from above, the curves get their radius and length and the switches their name and type, as on a plan; where they'd crowd, some are left out")); @@ -6979,6 +7000,8 @@ void editor_mode::enter() simulation::Blackbox.close(); // the cursor drawn into the picture is the editor's: back on when it comes back, if it was chosen ui_layer::draw_cursor(m_draw_cursor); + apply_camera_settings(); + Global.EditorCameraOn = true; if (simulation::Region != nullptr) { @@ -7080,6 +7103,7 @@ void editor_mode::exit() track_sleepers::lay_in_background(true); // the driver's view has no menu to switch the drawn cursor off: the system one there ui_layer::draw_cursor(false); + Global.EditorCameraOn = false; Global.editor_tracks = false; EditorModeFlag = false; Global.ControlPicking = m_statebackup.picking; @@ -7479,6 +7503,22 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in lay_switch_mode(); break; + case GLFW_KEY_GRAVE_ACCENT: + // ~ (left of 1): the orthophoto shown or hidden; with Ctrl what the camera sees downloaded before anything else + if (false == is_press(Action) || ImGui::GetIO().WantTextInput) + break; + if (Mods & GLFW_MOD_CONTROL) + { + orthophoto_hurry(); + break; + } + if (false == anyModifier) + { + m_orthophoto.enabled(false == m_orthophoto.enabled()); + ui()->set_status(m_orthophoto.enabled() ? STR("Orthophoto on (~)") : STR("Orthophoto off (~)")); + } + break; + case GLFW_KEY_BACKSPACE: // the switch being clicked off the view: the last point taken back if (m_switch_designer.open && m_switch_designer.picking) @@ -8084,3 +8124,113 @@ void editor_mode::render_top_tracks_choice(bool const Combo) if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("The colour of the rails, to stand out on the imagery and the map")); } + +void editor_mode::apply_camera_settings() +{ + auto const &camera{EditorSettings.camera()}; + Global.EditorCameraSpeed = camera.speed; + Global.EditorCameraFast = camera.fast; + Global.EditorCameraZoomed = camera.zoomed; +} + +void editor_mode::render_camera_settings() +{ + auto &camera{EditorSettings.camera()}; + auto changed{false}; + auto release{false}; + ImGui::PushItemWidth(180.0f * Global.ui_scale); + auto speed{static_cast(camera.speed)}; + if (ImGui::SliderFloat(STR_C("Speed of the camera"), &speed, 0.05f, 10.0f, "x %.2f", ImGuiSliderFlags_Logarithmic)) + { + camera.speed = speed; + changed = true; + } + release |= ImGui::IsItemDeactivatedAfterEdit(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("How fast the arrows or WSAD move the camera, Shift a bit faster; 1 as it was")); + auto fast{static_cast(camera.fast)}; + if (ImGui::SliderFloat(STR_C("Ctrl speeds it up"), &fast, 1.0f, 30.0f, "x %.1f", ImGuiSliderFlags_Logarithmic)) + { + camera.fast = fast; + changed = true; + } + release |= ImGui::IsItemDeactivatedAfterEdit(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("How many times faster the camera goes with Ctrl held, Ctrl+Shift too; 30 as it was")); + ImGui::PopItemWidth(); + if (ImGui::Checkbox(STR_C("In the top view as fast as the view is zoomed"), &camera.zoomed)) + changed = release = true; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Zoomed in the map moves slowly, zoomed out fast: across the screen at the same pace whatever the zoom")); + ImGui::Separator(); + if (ImGui::MenuItem(STR_C("As it was"))) + { + camera = {}; + changed = release = true; + } + if (changed) + apply_camera_settings(); + if (release) + EditorSettings.save(); +} + +void editor_mode::orthophoto_hurry() +{ + if (false == m_orthophoto.enabled()) + m_orthophoto.enabled(true); + // what the camera sees of the ground: rays through a grid over the screen to the level of the ground under the camera, or as far + // as the reach of the orthophoto along it where they don't come down to it (the sky) + ImGuiIO const &io = ImGui::GetIO(); + if (io.DisplaySize.x <= 0.0f || io.DisplaySize.y <= 0.0f) + return; + auto const inverse = glm::inverse(editor_mode::projection_matrix(io.DisplaySize.x / io.DisplaySize.y) * GfxRenderer->Camera_View_Matrix()); + auto const camera{GfxRenderer->Camera_Position()}; + // the level of the ground under the camera: the terrain, else the scenery; with neither the rays go as far as the reach + std::optional level; + // only a level below the camera: one above it (in a tunnel, or flown under the terrain) would put the hits behind it + if (double ground{0.0}; m_streamer.active() && m_streamer.height_at(camera.x, camera.z, ground) && ground < camera.y) + level = ground; + else if (std::vector found; Global.EditorOrtho == false) + { + auto const heights{ground_heights({camera}, true, &found)}; + if (false == found.empty() && found.front() != 0 && heights.front() < camera.y) + level = heights.front(); + } + double constexpr reach{2500.0}; + glm::dvec2 low{camera.x, camera.z}; + glm::dvec2 high{camera.x, camera.z}; + for (int j = 0; j <= 6; ++j) + for (int i = 0; i <= 6; ++i) + { + glm::vec2 const ndc{static_cast(i) / 3.0f - 1.0f, static_cast(j) / 3.0f - 1.0f}; + auto const point = [&inverse, &ndc](float const Depth) { + auto const clip = inverse * glm::vec4(ndc, Depth, 1.0f); + return glm::dvec3{glm::vec3{clip} / clip.w}; + }; + if (Global.EditorOrtho) + { + // the view straight down: the corners of the screen are where it reaches on the ground + auto const corner{camera + point(0.0f)}; // the view matrix is camera-relative + low = glm::min(low, glm::dvec2{corner.x, corner.z}); + high = glm::max(high, glm::dvec2{corner.x, corner.z}); + continue; + } + auto direction = point(0.5f) - point(0.0f); + if (glm::length(direction) < 1e-9) + continue; + direction = glm::normalize(direction); + glm::dvec2 flat{direction.x, direction.z}; + auto distance{reach}; + if (level && direction.y < -1e-6) + distance = std::min(reach, (camera.y - *level) / -direction.y * glm::length(flat)); + if (glm::length(flat) < 1e-6) + continue; + flat = glm::normalize(flat) * distance; + glm::dvec2 const hit{camera.x + flat.x, camera.z + flat.y}; + low = glm::min(low, hit); + high = glm::max(high, hit); + } + auto const count{m_orthophoto.hurry(low, high, camera)}; + ui()->set_status(count > 0 ? format(STR_C("Orthophoto: %zu tiles of the view downloaded first (Ctrl+~)"), count) + : std::string{STR("Orthophoto: the view is all shown already (Ctrl+~)")}); +} diff --git a/application/editormode.h b/application/editormode.h index 81347c950..d25840e18 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -56,6 +56,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include #include @@ -871,6 +872,12 @@ class editor_mode : public application_mode, private editor_track::observer, pri bool orthophoto_settings_open() const; // view menu: the top view, the lanes of the roads, the structure gauge, the environment void render_view_menu(); + // View > Camera speed: the speed of the free camera, the Ctrl multiplier, in the top view as fast as it's zoomed; kept in the + // settings of the editor and handed to the camera + void render_camera_settings(); + void apply_camera_settings(); + // ~ (Ctrl): the orthophoto of what the camera sees downloaded before the rest, the ones which failed tried again at once + void orthophoto_hurry(); // time of day, day of the year, visibility, clouds and air temperature, as the scenery is seen in the editor void render_environment_window(); bool m_environment_open{false}; @@ -909,6 +916,8 @@ class editor_mode : public application_mode, private editor_track::observer, pri { std::array url{}; std::array filter{}; + // the reading is given up: the editor goes. before the reading, so it outlives the future waiting for the reading to end + std::atomic closing{false}; std::future reading; std::optional info; std::string service; // the address the capabilities were read of @@ -2635,8 +2644,8 @@ class editor_mode : public application_mode, private editor_track::observer, pri struct switch_drive { standing_template standing; - int family{-1}; - int index{0}; + int family{-1}; // -1: a drive not described for the editor, e.g. of Rainsted; it can be replaced, not turned over or moved + int index{-1}; }; std::optional find_switch_drive(TTrack const &Switch, bool Wait = true); // the drives standing in the scenery by the switch each is set to, read from the files once a frame for all the switches @@ -2656,10 +2665,45 @@ class editor_mode : public application_mode, private editor_track::observer, pri void switch_drives_committed(std::vector const &Tracks); // the drives of the switches deleted go with them, in the step of the undo history the deletion made last void drives_deleted(std::vector const &Switches); + // the file of a drive not described for the editor throwing one of the switches, empty when there's none; also one the editor + // kept beside a drive described for it + std::string undescribed_drive(std::vector const &Switches); // the drives of all the switches of the scenery set at the tips of their blades, the ones the earlier versions of the editor set at the // joint before them too: once, as the scenery is opened, with no step of the undo history; how many moved std::size_t drives_to_blade_tips(); bool m_drives_checked{false}; + // the file of each variant of the drives scanned: its family and its index in the family + std::map, std::less<>> drive_variants() const; + // the switches a template of a drive throws, by what follows its first parameter in their names: "" for a variant described for the + // editor, and for any other template whose switch events throw the track named by its first parameter, as the drives of Rainsted do; + // "a".."d" for one of a double switch, whose switches are named a..d. none for a template which isn't a drive. the ones not + // described for the editor have no family (-1) + std::vector const &drive_switches(std::string const &File, std::map, std::less<>> const &Variants); + std::map, std::less<>> m_drive_templates; // read once for each file + // a drive set to a switch the scenery hasn't got: left by a switch deleted or renamed by hand or in an earlier editor, its events + // throw nothing + struct stray_drive + { + scene::instance_handle instance{0}; + std::vector switches; // the names of the switches it throws, as its include gives them + std::string name; // of the switches missing from them + std::string file; + glm::dvec3 location{0.0}; + }; + // all the drives standing in the scenery, read from the files once while no include comes or goes + struct drives_named + { + std::vector drives; + int revision{-1}; // of the drives scanned + std::size_t instances{0}; + }; + std::optional m_drives_named; + // the include of a drive or a template changed: what's kept of the drives standing is read again + void drives_changed(); + // the drives whose switch isn't in the scenery, checked against the tracks each time + std::vector stray_drives(bool Wait = false); + void render_stray_drives(); + void draw_stray_drives(); scene::layer_handle output_layer(std::string const &Part) override; // places them in the active layer or the given one, as one step of the undo. returns: how many were placed std::size_t place_templates(std::vector const &Items, std::string &Error, scene::layer_handle Layer = scene::layer_handle{}) override; diff --git a/application/editormodelineside.cpp b/application/editormodelineside.cpp index 1c2fc9e9c..8f4f5209c 100644 --- a/application/editormodelineside.cpp +++ b/application/editormodelineside.cpp @@ -253,7 +253,7 @@ scene::layer_handle editor_mode::output_layer(std::string const &Part) std::size_t editor_mode::place_templates(std::vector const &Items, std::string &Error, scene::layer_handle const Layer) { - m_drives_standing.reset(); + drives_changed(); if (Items.empty()) return 0; if (scene::Layers.empty()) @@ -341,7 +341,7 @@ std::size_t editor_mode::move_templates(std::vector const &Instances) { - m_drives_standing.reset(); + drives_changed(); EditorSnapshot snap; for (auto const instance : Instances) { diff --git a/application/editormodeselftestswitch.cpp b/application/editormodeselftestswitch.cpp index 891ca6d68..b9c502d17 100644 --- a/application/editormodeselftestswitch.cpp +++ b/application/editormodeselftestswitch.cpp @@ -549,6 +549,25 @@ editor_mode::selftest_result editor_mode::selftest_switch(std::string const &com WriteLog("SELFTEST drives " + name + ": chosen " + (m_switch.drive >= 0 ? m_switch.drives[m_switch.drive].name : std::string{"none"}) + ", side " + std::to_string(m_switch.drive_side) + ", standing" + files + ", steps " + std::to_string(m_history.size())); return selftest_result::handled; } + if (command == "straydrives") + { + auto const stray{stray_drives(true)}; + std::string names; + for (auto const &drive : stray) + names += " " + drive.name + "(" + drive.file + ")"; + WriteLog(format("SELFTEST straydrives: %zu", stray.size()) + names); + return selftest_result::handled; + } + if (command == "drivewhose") + { + // the drive the editor tells for the switch: its file and family, -1 for one not described + std::string name; + words >> name; + auto *track{simulation::Paths.find(name)}; + auto const found{track != nullptr ? find_switch_drive(*track) : std::nullopt}; + WriteLog("SELFTEST drivewhose " + name + ": " + (found.has_value() ? found->standing.file + " family " + std::to_string(found->family) : std::string{"none"})); + return selftest_result::handled; + } if (command == "driveflip") { std::string name; diff --git a/application/editormodeswitchdrive.cpp b/application/editormodeswitchdrive.cpp index 3e0a67854..931350af1 100644 --- a/application/editormodeswitchdrive.cpp +++ b/application/editormodeswitchdrive.cpp @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "application/editormode.h" #include "application/editormodeshared.h" +#include "application/editorprojection.h" #include "editor/editorFormat.hpp" #include "editor/editorIncludeInfo.hpp" @@ -25,6 +26,7 @@ http://mozilla.org/MPL/2.0/. #include "imgui/imgui.h" #include +#include #include #include #include @@ -44,6 +46,21 @@ std::string drive_file(std::string Text) return Text; } +// the track the events of a drive find by the name: the game reads the names of the tracks lower case, the parameters of an include as +// they're written +TTrack *track_named(std::string const &Name) +{ + auto *track{simulation::Paths.find(Name)}; + return track != nullptr ? track : simulation::Paths.find(drive_file(Name)); +} + +// a template by the name of its file, with no folder: told to the user, who picks the drives by their names +std::string file_name(std::string const &File) +{ + auto const slash{File.find_last_of('/')}; + return slash != std::string::npos ? File.substr(slash + 1) : File; +} + int drive_side(std::string const &Side) { if (Side == "left") @@ -168,7 +185,8 @@ void editor_mode::switch_drives_committed(std::vector const &Tracks) drives = switch_drives_standing(); auto const found{drives->find(drive_file(track->name()))}; auto const spot{editor_track::drive_spot_of(*track)}; - if (found == drives->end() || false == spot.has_value()) + // a drive not described for the editor has no parameters known to set it with, nor a height above the rail; it stays put + if (found == drives->end() || found->second.family < 0 || false == spot.has_value()) continue; auto const &drive{found->second.standing}; auto const &included{scene::Layers.instance(drive.instance)}; @@ -221,7 +239,15 @@ bool editor_mode::place_switch_drive(TTrack &Switch) item.track = Switch.name(); item.tilt = spot->tilt; if (auto const present{find_switch_drive(Switch)}) + { + // one not described for the editor is kept: it may set the speed over the switch or carry its ballast too + if (present->family < 0) + { + tool.status = format(STR_C("Switch %s keeps its drive %s, which isn't described for the editor"), Switch.name().c_str(), file_name(present->standing.file).c_str()); + return false; + } return replace_switch_drive(Switch, tool.drive, (present->index & 1) != (driveright ? 1 : 0)); + } std::string error; if (place_templates({item}, error) == 0) { @@ -255,22 +281,147 @@ std::map const &editor_mode::switch_driv return included.removed || included.dead; })) return kept->by_switch; + auto const variants{drive_variants()}; + kept.emplace(); + kept->frame = ImGui::GetFrameCount(); + kept->revision = tool.drives_revision; + kept->instances = instances; + for (auto const &standing : standing_templates([&](std::string const &File) { return false == drive_switches(File, variants).empty(); })) + { + auto const variant{variants.find(standing.file)}; + auto const [family, index]{variant != variants.end() ? variant->second : std::pair{-1, -1}}; + // the drive of a double switch of Rainsted stands for each of its switches, a..d + for (auto const &suffix : drive_switches(standing.file, variants)) + { + // a drive described for the editor goes before one of Rainsted set to the same switch, which the editor kept beside it + auto const [entry, fresh]{kept->by_switch.try_emplace(drive_file(standing.values[0] + suffix), switch_drive{standing, family, index})}; + if (false == fresh && entry->second.family < 0 && family >= 0) + entry->second = switch_drive{standing, family, index}; + } + } + return kept->by_switch; +} + +std::vector const &editor_mode::drive_switches(std::string const &File, std::map, std::less<>> const &Variants) +{ + static std::vector const single{std::string{}}; + if (Variants.contains(File)) + return single; + auto const [found, fresh]{m_drive_templates.try_emplace(File)}; + if (fresh) + editor_includes::switched_tracks(File, found->second); + return found->second; +} + +std::map, std::less<>> editor_mode::drive_variants() const +{ + auto const &tool{m_switch}; std::map, std::less<>> variants; for (int family = 0; family < static_cast(tool.drives.size()); ++family) for (int index = 0; index < 4; ++index) if (false == tool.drives[family].files[index].empty()) variants[drive_file(tool.drives[family].files[index])] = {family, index}; - kept.emplace(); - kept->frame = ImGui::GetFrameCount(); - kept->revision = tool.drives_revision; - kept->instances = instances; - for (auto &standing : standing_templates([&](std::string const &File) { return variants.contains(File); })) + return variants; +} + +void editor_mode::drives_changed() +{ + m_drives_standing.reset(); + m_drives_named.reset(); +} + +std::vector editor_mode::stray_drives(bool const Wait) +{ + scan_switch_drives(Wait); + auto const instances{static_cast(scene::Layers.instance_count())}; + auto &kept{m_drives_named}; + if (false == kept.has_value() || kept->revision != m_switch.drives_revision || kept->instances != instances) { - auto const &[family, index]{variants[standing.file]}; - auto name{drive_file(standing.values[0])}; - kept->by_switch.try_emplace(std::move(name), switch_drive{std::move(standing), family, index}); + auto const variants{drive_variants()}; + kept.emplace(); + kept->revision = m_switch.drives_revision; + kept->instances = instances; + for (auto const &standing : standing_templates([&](std::string const &File) { return false == drive_switches(File, variants).empty(); })) + { + stray_drive drive{standing.instance, {}, {}, standing.file, standing.location}; + for (auto const &suffix : drive_switches(standing.file, variants)) + drive.switches.push_back(standing.values[0] + suffix); + kept->drives.push_back(std::move(drive)); + } + } + // a switch is told by the name, as the events of the drive find it in the game; a drive of a double switch is stray with all of its + // switches gone, while one stands it still throws it + std::vector stray; + for (auto const &drive : kept->drives) + { + auto const &included{scene::Layers.instance(drive.instance)}; + // a gate, a derailer or a turntable of the same kind of template throws a track of another kind: only a track gone counts + if (included.removed || included.dead || std::any_of(drive.switches.begin(), drive.switches.end(), [](std::string const &Name) { + auto const *track{track_named(Name)}; + return track != nullptr && false == track->m_editorremoved; + })) + continue; + std::string missing; + for (auto const &name : drive.switches) + missing += (missing.empty() ? "" : ", ") + name; + stray.push_back(drive); + stray.back().name = std::move(missing); + } + return stray; +} + +void editor_mode::render_stray_drives() +{ + auto const stray{stray_drives()}; + if (stray.empty()) + return; + ImGui::PushID("straydrives"); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.55f, 0.25f, 1.0f)); + auto const open{ImGui::TreeNode("##straydrives", STR_P("%zu drive with no switch", "%zu drives with no switch", static_cast(stray.size())), stray.size())}; + ImGui::PopStyleColor(); + item_tooltip("Drives set to a switch the scenery hasn't got, left when a switch was deleted or renamed by hand or in an earlier editor: their events throw nothing.\nA click goes to the drive and selects it, Delete removes it; or give a switch its name"); + if (open) + { + glm::dvec3 const camera{Global.pCamera.Pos}; + for (auto const &drive : stray) + { + auto const label{format("%s (%s, %.0f m)##%d", drive.name.c_str(), file_name(drive.file).c_str(), glm::length(drive.location - camera), static_cast(drive.instance))}; + if (ImGui::Selectable(label.c_str(), m_instance == drive.instance)) + { + select_include(drive.instance); + fly_to(drive.location, glm::normalize(glm::dvec3{-1.0, -0.8, -1.0}), 25.0); + } + } + ImGui::TreePop(); + } + ImGui::PopID(); +} + +// a red mark by each drive with no switch in sight, so it's seen in the view and over the photo, not only in the list +void editor_mode::draw_stray_drives() +{ + auto const stray{stray_drives()}; + if (stray.empty()) + return; + // the ones far off would only crowd the view of the whole line + auto constexpr range{3000.0}; + screen_projection const projection; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + glm::dvec3 const camera{Global.pCamera.Pos}; + for (auto const &drive : stray) + { + ImVec2 at; + if (glm::length(drive.location - camera) > range || false == projection.project(drive.location, at)) + continue; + auto const selected{m_instance == drive.instance}; + drawlist->AddCircleFilled(at, 8.0f, IM_COL32(0, 0, 0, 170)); + drawlist->AddCircle(at, 7.0f, selected ? overlay_color::selected : overlay_color::invalid, 0, 3.0f); + auto const text{format(STR_C("%s: no switch of this name"), drive.name.c_str())}; + auto const size{ImGui::CalcTextSize(text.c_str())}; + ImVec2 const corner{at.x + 12.0f, at.y - 0.5f * size.y}; + drawlist->AddRectFilled({corner.x - 3.0f, corner.y - 1.0f}, {corner.x + size.x + 3.0f, corner.y + size.y + 1.0f}, IM_COL32(0, 0, 0, 160), 3.0f); + drawlist->AddText(corner, selected ? overlay_color::selected : overlay_color::invalid, text.c_str()); } - return kept->by_switch; } void editor_mode::apply_switch_drive_choice(TTrack &Switch) @@ -280,7 +431,10 @@ void editor_mode::apply_switch_drive_choice(TTrack &Switch) place_switch_drive(Switch); return; } - if (auto const found{find_switch_drive(Switch)}; found.has_value() && remove_templates({found->standing.instance}) > 0) + auto const found{find_switch_drive(Switch)}; + if (found.has_value() && found->family < 0) + m_switch.status = refused(format(STR_C("The drive %s isn't described for the editor: it may also set the speed or carry the ballast of the switch, so it's kept as it is"), file_name(found->standing.file).c_str())); + else if (found.has_value() && remove_templates({found->standing.instance}) > 0) m_switch.status = format(STR_C("Switch %s without a drive now"), Switch.name().c_str()); } @@ -299,7 +453,15 @@ bool editor_mode::replace_switch_drive(TTrack &Switch, int const Family, bool co return false; } auto const &found{present->standing}; + // a drive not described for the editor, as one of a double switch, may set the speed over the switch or carry its ballast too: it's kept as it is + if (present->family < 0) + { + tool.status = refused(format(STR_C("The drive %s isn't described for the editor: it may also set the speed or carry the ballast of the switch, so it's kept as it is"), file_name(found.file).c_str())); + return false; + } auto const family{Family >= 0 ? Family : present->family}; + if (family >= static_cast(tool.drives.size())) + return false; auto const index{Flip ? present->index ^ 1 : present->index}; template_item item; item.file = tool.drives[family].files[index]; @@ -334,19 +496,82 @@ bool editor_mode::replace_switch_drive(TTrack &Switch, int const Family, bool co return true; } +std::string editor_mode::undescribed_drive(std::vector const &Switches) +{ + // the drives described for the editor read first: before they are, every drive would pass for one not described + scan_switch_drives(true); + std::vector names; + for (auto const *track : Switches) + if (track != nullptr) + names.push_back(drive_file(track->name())); + auto const variants{drive_variants()}; + for (auto const &standing : standing_templates([&](std::string const &File) { return false == variants.contains(File) && false == drive_switches(File, variants).empty(); })) + { + auto const &suffixes{drive_switches(standing.file, variants)}; + if (std::any_of(suffixes.begin(), suffixes.end(), [&](std::string const &Suffix) { return std::find(names.begin(), names.end(), drive_file(standing.values[0] + Suffix)) != names.end(); })) + return file_name(standing.file); + } + return {}; +} + void editor_mode::drives_deleted(std::vector const &Switches) { if (m_history.empty()) return; + // the names of the switches deleted, as the game finds them; they're retired already + std::vector deleted; for (auto const *track : Switches) + if (track != nullptr && track->eType == tt_Switch) + deleted.push_back(drive_file(track->name())); + if (deleted.empty()) + return; + auto const named = [&](std::string const &Name) { return std::find(deleted.begin(), deleted.end(), drive_file(Name)) != deleted.end(); }; + // an older scenery may have two tracks of a name, the name finding the later; the earlier one, left by the deletion of the other, + // still has the drive and the ballast, so it's looked for too + auto const stands = [](std::string const &Name) { + if (auto const *track{track_named(Name)}; track != nullptr) + return false == track->m_editorremoved; + auto const name{drive_file(Name)}; + auto const &tracks{simulation::Paths.sequence()}; + return std::any_of(tracks.begin(), tracks.end(), [&](TTrack const *Track) { return Track != nullptr && false == Track->m_editorremoved && drive_file(Track->name()) == name; }); + }; + auto const take_away = [&](scene::instance_handle const Instance) { + if (false == scene::Layers.removable(Instance)) + return; + scene::Layers.removed(Instance, true); + m_history.back().instances.push_back(Instance); + }; + auto const variants{drive_variants()}; + // each drive throwing a switch deleted, also one the editor kept beside a drive described for it; the drive of a double switch throws + // the others too, so it goes with the last of them + for (auto const &standing : standing_templates([&](std::string const &File) { return false == drive_switches(File, variants).empty(); })) { - if (track == nullptr || track->eType != tt_Switch) + auto const &suffixes{drive_switches(standing.file, variants)}; + if (std::any_of(suffixes.begin(), suffixes.end(), [&](std::string const &Suffix) { return named(standing.values[0] + Suffix); }) && + std::none_of(suffixes.begin(), suffixes.end(), [&](std::string const &Suffix) { return stands(standing.values[0] + Suffix); })) + take_away(standing.instance); + } + // the sleepers and the ballast laid by a switch, named by it as its drive is: of a double switch by the name its switches have in + // common, a..d or _a.._d, so they go with the last of them + static std::array const parts{"", "a", "b", "c", "d", "_a", "_b", "_c", "_d"}; + std::map> beds; + for (auto const &standing : standing_templates([](std::string const &) { return true; })) + { + auto const &name{standing.values[0]}; + // named by a single switch, it's this switch's alone; a switch named a beside it may be another single one + if (named(name)) + { + if (stands(name)) + continue; + } + else if (std::none_of(parts.begin(), parts.end(), [&](char const *Part) { return named(name + Part); }) || + std::any_of(parts.begin(), parts.end(), [&](char const *Part) { return stands(name + Part); })) continue; - auto const found{find_switch_drive(*track)}; - if (false == found.has_value() || false == scene::Layers.removable(found->standing.instance) || scene::Layers.instance(found->standing.instance).removed) - continue; - scene::Layers.removed(found->standing.instance, true); - m_history.back().instances.push_back(found->standing.instance); + auto const [bed, fresh]{beds.try_emplace(standing.file)}; + if (fresh) + bed->second = drive_switches(standing.file, variants).empty() && editor_includes::switch_bed(standing.file); + if (bed->second) + take_away(standing.instance); } } @@ -359,7 +584,7 @@ std::size_t editor_mode::drives_to_blade_tips() { if (track == nullptr || track->m_editorremoved || track->eType != tt_Switch) continue; - if (auto const found{find_switch_drive(*track)}; found.has_value() && scene::Layers.removable(found->standing.instance)) + if (auto const found{find_switch_drive(*track)}; found.has_value() && found->family >= 0 && scene::Layers.removable(found->standing.instance)) { switches.push_back(track); before.emplace_back(found->standing.instance, scene::Layers.directive(found->standing.instance)); diff --git a/application/editormodeswitchplace.cpp b/application/editormodeswitchplace.cpp index b35ef8c48..82028a943 100644 --- a/application/editormodeswitchplace.cpp +++ b/application/editormodeswitchplace.cpp @@ -1609,6 +1609,13 @@ bool editor_mode::replace_double_slip(TTrack &Part, editor_track::switch_templat return false; } } + // a drive not described for the editor may set the speed or carry the ballast of the slip too: the editor can neither take it + // away nor move it to the switches laid anew, which get other names, so the slip is left as it is + if (auto const drive{undescribed_drive({switches.begin(), switches.end()})}; false == drive.empty()) + { + state.status = refused(format(STR_C("The slip has the drive %s, not described for the editor, which may also set the speed or carry its ballast: it isn't laid anew"), drive.c_str())); + return false; + } struct end { TTrack *track; diff --git a/application/editormodeswitchtemplate.cpp b/application/editormodeswitchtemplate.cpp index e6a8496bd..6edef6a65 100644 --- a/application/editormodeswitchtemplate.cpp +++ b/application/editormodeswitchtemplate.cpp @@ -286,6 +286,9 @@ bool editor_mode::change_slip_template(TTrack &Part, int const Index) for (auto const *part : parts) if (false == part->Dynamics.empty()) return fail(STR_C("The slip can't be laid again while vehicles stand on it")); + // its drives go with it and the new one gets its own: a drive not described for the editor can't be told apart from them + if (auto const drive{slip.has_value() ? undescribed_drive(slip->switches) : std::string{}}; false == drive.empty()) + return fail(format(STR_C("The slip has the drive %s, not described for the editor, which may also set the speed or carry its ballast: it isn't laid anew"), drive.c_str())); // a single slip laid again joins the pair of the tracks it joined: the point given by them auto const &ends{slip.has_value() ? slip->ends : std::array{}}; auto const pair{slip.has_value() && record.type == "Rkp" ? 0.5 * (ends[0] + ends[3]) : glm::dvec3{0.0}}; diff --git a/application/editormodeswitchtool.cpp b/application/editormodeswitchtool.cpp index a37c98f70..878e18aa3 100644 --- a/application/editormodeswitchtool.cpp +++ b/application/editormodeswitchtool.cpp @@ -282,6 +282,7 @@ void editor_mode::render_switch_ui() ImGui::TextColored(ImVec4(1.0f, 0.7f, 0.2f, 1.0f), "%s", tool.status.c_str()); ImGui::PopTextWrapPos(); } + render_stray_drives(); if (ImGui::Button(STR_C("Template editor..."))) m_switch_designer.open = true; diff --git a/application/editormodetrack.cpp b/application/editormodetrack.cpp index 91bf9c027..6e0fe60c7 100644 --- a/application/editormodetrack.cpp +++ b/application/editormodetrack.cpp @@ -1171,22 +1171,34 @@ void editor_mode::render_turnout_ui() { auto const family{drive->family}; auto const variant{drive->index}; + // a drive not described for the editor is shown by its file + auto const described{family >= 0 && family < static_cast(m_switch.drives.size())}; + auto const &file{drive->standing.file}; + auto const shown{described ? m_switch.drives[family].name : format("%s (%s)", file.substr(file.find_last_of('/') + 1).c_str(), STR_C("not described"))}; if (begin_fields("##standingdrive", 0.3f)) { field_row("Drive##standing"); - if (ImGui::BeginCombo("##standing", m_switch.drives[family].name.c_str())) + if (false == described) + ImGui::TextUnformatted(shown.c_str()); + else if (ImGui::BeginCombo("##standing", shown.c_str())) { for (int i = 0; i < static_cast(m_switch.drives.size()); ++i) if (ImGui::Selectable(m_switch.drives[i].name.c_str(), family == i) && i != family) replace_switch_drive(Switch, i, false); ImGui::EndCombo(); } - if (ImGui::IsItemHovered()) + if (described && ImGui::IsItemHovered()) ImGui::SetTooltip("%s\n%s", STR_C("Puts another drive in place of the drive of this switch, on the same side"), format(STR_C("Drive: events %s+ and %s- switch it, also in the map"), Switch.name().c_str(), Switch.name().c_str()).c_str()); ImGui::EndTable(); } int side{((variant >> 1) == (variant & 1)) ? 0 : 1}; - if (segmented("standingside", side, {{0, STR_C("diverging side"), "Puts the drive of the switch on the other side of the track: the same drive, its variant for the other side"}, + if (false == described) + { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", STR_C("A drive not described for the editor, as the one of a double switch, which may also set the speed or carry the ballast of the switch: the editor keeps it as it is, it stays where it is when the switch is moved and goes when the last switch it throws is deleted")); + ImGui::PopTextWrapPos(); + } + else if (segmented("standingside", side, {{0, STR_C("diverging side"), "Puts the drive of the switch on the other side of the track: the same drive, its variant for the other side"}, {1, STR_C("other side"), "Puts the drive of the switch on the other side of the track: the same drive, its variant for the other side"}})) flip_switch_drive(Switch); } diff --git a/application/scenarioloaderuilayer.cpp b/application/scenarioloaderuilayer.cpp index 207a1756e..87366757f 100644 --- a/application/scenarioloaderuilayer.cpp +++ b/application/scenarioloaderuilayer.cpp @@ -88,7 +88,7 @@ std::vector scenarioloader_ui::get_random_trivia() json triviaData = json::parse(fileContent); // select random - int i = Random(0, static_cast(triviaData.size()) - 1); + int i = RandomInt(0, static_cast(triviaData.size()) - 1); std::string triviaStr = triviaData[i]["text"]; std::string background = triviaData[i]["background"]; if (triviaData[i].contains("scenery")) diff --git a/blackbox_doc.md b/blackbox_doc.md index 126cea033..9314b94e6 100644 --- a/blackbox_doc.md +++ b/blackbox_doc.md @@ -9,9 +9,8 @@ starter, a viewer) can replay the session on the map, or set the user's driving `blackbox yes` in `eu07.ini` writes it, with the physics logs on or off; `blackbox no` never does. With no `blackbox` entry it is written along with the physics logs, `physicslog yes` or `physicslog.trains yes`. -The former writes the `.dat` log of every driver but those of the road vehicles, which on a big scenery are -hundreds and nobody reads. The latter writes the `.dat` logs of the trains only: of each driver who drives rail -vehicles, not of the passengers either, so a big scenery gives far fewer of them still. It is never written in an +The latter writes the `.dat` logs of the trains only: of each driver who drives rail vehicles, not of the +passengers nor of the vehicles of the roads, so a big scenery gives far fewer of them. It is never written in an editor session. The file goes to `physicslog/_.blackbox` (the local time the recording started at), next to the `.dat` logs of the vehicles when those are on; they stay as they are. @@ -27,17 +26,10 @@ goes on in that driver's log, begun then if it is the first time. Back with a dr the gap in its time. A vehicle with no driver of its own, or whose own driver is passive, takes the log of the driver of its train. So the speed recorder's tape can be read from them as before, also while the simulator runs, without a log of every vehicle. A driver who writes a log of its own, with -`physicslog.trains yes` or `physicslog yes`, isn't written twice; with `physicslog yes` it is a road vehicle the -user drives whose log the black box writes, so with the black box off (`blackbox no`, or in the editor) a car the -user drives has no log. Like those of `physicslog yes`, they are written every +`physicslog.trains yes`, isn't written twice. Like those of `physicslog yes`, they are written every two seconds, each file opened only for the moment it is written to; a crash loses the last two seconds -of real time of them (at a higher time speed, more of the simulated time), up to ten on a disk which can't keep up. A file another program holds +of real time of them (at a higher time speed, more of the simulated time). A file another program holds for a while doesn't lose its lines: they are written once it can be, the last 64 MB of all such logs at most. -The writing of all the logs goes after the simulator's own reading of the disk. When it takes over a third of -those two seconds, hundreds of logs on a hard disk say, they are written less often from then on, three times as -long after a writing as it took and every ten seconds at most, and the simulator's log tells it once. -Closing the simulator waits for the logs' last lines a second at most: what isn't written by then is lost, -and the simulator's log tells how many logs were left unwritten. The recording starts once the scenery is loaded and ends when the simulator closes. Going into the editor (F11) ends it too, since the editor may take away the tracks and the vehicles it refers to; no diff --git a/editor/editorGeoMap.cpp b/editor/editorGeoMap.cpp index ab7f74b24..68b153559 100644 --- a/editor/editorGeoMap.cpp +++ b/editor/editorGeoMap.cpp @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "editor/editorGeoMap.hpp" #include "editor/editorFormat.hpp" +#include "editor/editorHttp.hpp" #include "editor/editorOrthophoto.hpp" #include "utilities/translation.h" @@ -164,6 +165,8 @@ bool parse_place(std::string const &Text, glm::dvec2 &Point) editor_map::~editor_map() { + // the download running is broken off rather than waited for to its end or its timeout + m_closing = true; if (m_request.valid()) m_request.wait(); release(); @@ -328,12 +331,13 @@ void editor_map::request(glm::vec2 const &Size) char bbox[160]; std::snprintf(bbox, sizeof(bbox), "%.1f,%.1f,%.1f,%.1f", low.x, low.y, high.x, high.y); auto const url{kMapService + "?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&LAYERS=osm&STYLES=&SRS=EPSG:2180&BBOX=" + bbox + "&WIDTH=" + std::to_string(width) + "&HEIGHT=" + std::to_string(height) + "&FORMAT=image/png"}; - m_request = std::async(std::launch::async, [url, low, high]() { + m_request = std::async(std::launch::async, [url, low, high, closing = &m_closing]() { image result; result.low = low; result.high = high; std::vector data; - if (false == editor_http_get(url, data, result.error)) + thread_local editor_http::client client; + if (false == client.get(url, data, result.error, [closing]() { return closing->load(); })) return result; int w{0}, h{0}, components{0}; // the texture loader turns the stb flip on for the whole process only once it loads its first texture: this thread diff --git a/editor/editorGeoMap.hpp b/editor/editorGeoMap.hpp index 5c160095b..a1dd07124 100644 --- a/editor/editorGeoMap.hpp +++ b/editor/editorGeoMap.hpp @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include #include #include #include @@ -86,6 +87,7 @@ class editor_map glm::vec2 m_pressed{0.f}; bool m_dragging{false}; std::future m_request; + std::atomic m_closing{false}; // the download of the map is given up: the map goes std::uint64_t m_texture{0}; glm::dvec2 m_image_low{0.0}; glm::dvec2 m_image_high{0.0}; diff --git a/editor/editorHttp.cpp b/editor/editorHttp.cpp index 81a195aeb..cbda581f0 100644 --- a/editor/editorHttp.cpp +++ b/editor/editorHttp.cpp @@ -45,15 +45,209 @@ struct client::platform #if defined(_WIN32) +namespace +{ + +DWORD constexpr kStopCheck{50}; // ms between the looks at whether the transfer is to be given up + +// what the callback of WinHTTP hands over to the thread waiting for it +struct transfer_state +{ + HANDLE done{::CreateEventW(nullptr, FALSE, FALSE, nullptr)}; // the operation begun finished or failed + HANDLE closed{::CreateEventW(nullptr, TRUE, FALSE, nullptr)}; // the request is called back no more + DWORD error{ERROR_SUCCESS}; // of the operation that failed + DWORD size{0}; // bytes available or read + + transfer_state() = default; + transfer_state(transfer_state const &) = delete; + transfer_state &operator=(transfer_state const &) = delete; + ~transfer_state() + { + if (done != nullptr) + ::CloseHandle(done); + if (closed != nullptr) + ::CloseHandle(closed); + } +}; + +void CALLBACK on_status(HINTERNET, DWORD_PTR const Context, DWORD const Status, LPVOID const Info, DWORD const Length) +{ + auto *state{reinterpret_cast(Context)}; + if (state == nullptr) + return; + switch (Status) + { + case WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE: + case WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE: + break; + case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE: + state->size = *static_cast(Info); + break; + case WINHTTP_CALLBACK_STATUS_READ_COMPLETE: + state->size = Length; + break; + case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR: + state->error = static_cast(Info)->dwError; + break; + case WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING: + ::SetEvent(state->closed); + return; + default: + return; + } + ::SetEvent(state->done); +} + +// one GET on a connection of its own. the steps of WinHTTP are asynchronous and waited for while the stop is looked at, so a +// transfer is given up at once also while a service keeps the connection waiting: the closing of the editor doesn't wait for +// the timeouts of a service that doesn't answer +class transfer +{ + public: + transfer(stop_check const &Stop, std::string &Error) : + m_stop(Stop), + m_error(Error) + { + } + ~transfer() + { + close(); + } + transfer(transfer const &) = delete; + transfer &operator=(transfer const &) = delete; + + bool open(HINTERNET const Session, std::wstring const &Host, INTERNET_PORT const Port, std::wstring const &Path, bool const Secure) + { + if (m_state.done == nullptr || m_state.closed == nullptr) + return failed(::GetLastError()); + m_connection = ::WinHttpConnect(Session, Host.c_str(), Port, 0); + if (m_connection == nullptr) + return failed(::GetLastError()); + m_request = ::WinHttpOpenRequest(m_connection, L"GET", Path.c_str(), nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, Secure ? WINHTTP_FLAG_SECURE : 0); + if (m_request == nullptr) + return failed(::GetLastError()); + auto context{reinterpret_cast(&m_state)}; + if (false == ::WinHttpSetOption(m_request, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(context))) + return failed(::GetLastError()); + if (::WinHttpSetStatusCallback(m_request, on_status, WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS | WINHTTP_CALLBACK_FLAG_HANDLES, 0) == WINHTTP_INVALID_STATUS_CALLBACK) + return failed(::GetLastError()); + m_called_back = true; + return true; + } + + bool send() + { + return step([this]() { return ::WinHttpSendRequest(m_request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, reinterpret_cast(&m_state)); }); + } + + bool receive() + { + return step([this]() { return ::WinHttpReceiveResponse(m_request, nullptr); }); + } + + DWORD status() const + { + DWORD status{0}; + DWORD size{sizeof(status)}; + ::WinHttpQueryHeaders(m_request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &status, &size, WINHTTP_NO_HEADER_INDEX); + return status; + } + + // the whole body of the response + bool read_all(std::vector &Out) + { + while (true) + { + if (m_stop()) + { + m_error = "cancelled"; + return false; + } + if (false == step([this]() { return ::WinHttpQueryDataAvailable(m_request, nullptr); })) + return false; + auto const available{m_state.size}; + if (available == 0) + return true; + if (Out.size() + available > kLargest) + { + m_error = kTooLarge; + Out.clear(); + return false; + } + auto const offset{Out.size()}; + Out.resize(offset + available); + auto const read{step([this, &Out, offset, available]() { return ::WinHttpReadData(m_request, Out.data() + offset, available, nullptr); })}; + Out.resize(offset + (read ? m_state.size : 0)); + if (false == read) + return false; + } + } + + void close() + { + if (m_request != nullptr) + { + ::WinHttpCloseHandle(m_request); + m_request = nullptr; + // the closing is the last callback: after it the state, and the buffer of a read broken off, are no longer written to + if (m_called_back) + ::WaitForSingleObject(m_state.closed, INFINITE); + m_called_back = false; + } + if (m_connection != nullptr) + { + ::WinHttpCloseHandle(m_connection); + m_connection = nullptr; + } + } + + private: + bool failed(DWORD const Code) + { + m_error = "WinHTTP error " + std::to_string(Code); + return false; + } + + // begins an operation and waits for it: false when it failed, or a stop was asked for meanwhile + template bool step(Begin const &Operation) + { + m_state.error = ERROR_SUCCESS; + if (false == Operation()) + return failed(::GetLastError()); + while (::WaitForSingleObject(m_state.done, kStopCheck) != WAIT_OBJECT_0) + { + if (m_stop()) + { + // closed at once: the operation broken off doesn't write into the buffer any more once this returns + close(); + m_error = "cancelled"; + return false; + } + } + if (m_state.error != ERROR_SUCCESS) + return failed(m_state.error); + return true; + } + + stop_check const &m_stop; + std::string &m_error; + transfer_state m_state; + HINTERNET m_connection{nullptr}; + HINTERNET m_request{nullptr}; + bool m_called_back{false}; // the closing of the request is called back +}; + +} // namespace + client::client() : m_platform(std::make_unique()) { wchar_t const *agent = L"MaSzyna-editor"; #ifdef WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY - m_platform->session = ::WinHttpOpen(agent, WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); + m_platform->session = ::WinHttpOpen(agent, WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, WINHTTP_FLAG_ASYNC); #endif if (m_platform->session == nullptr) // automatic proxy needs windows 8.1+ - m_platform->session = ::WinHttpOpen(agent, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); + m_platform->session = ::WinHttpOpen(agent, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, WINHTTP_FLAG_ASYNC); if (m_platform->session != nullptr) ::WinHttpSetTimeouts(m_platform->session, 10000, 10000, 15000, 20000); } @@ -94,64 +288,13 @@ bool client::get(std::string const &Url, std::vector &Out, std::st std::wstring const host(parts.lpszHostName, parts.dwHostNameLength); std::wstring const path = std::wstring(parts.lpszUrlPath, parts.dwUrlPathLength) + std::wstring(parts.lpszExtraInfo, parts.dwExtraInfoLength); - HINTERNET connection = ::WinHttpConnect(m_platform->session, host.c_str(), parts.nPort, 0); - HINTERNET request = connection ? ::WinHttpOpenRequest(connection, L"GET", path.c_str(), nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, - parts.nScheme == INTERNET_SCHEME_HTTPS ? WINHTTP_FLAG_SECURE : 0) - : nullptr; - auto const close = [&]() { - if (request != nullptr) - ::WinHttpCloseHandle(request); - if (connection != nullptr) - ::WinHttpCloseHandle(connection); - }; - - if (request == nullptr || !::WinHttpSendRequest(request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0) || !::WinHttpReceiveResponse(request, nullptr)) - { - Error = "WinHTTP error " + std::to_string(::GetLastError()); - close(); + transfer request{Stop, Error}; + if (false == request.open(m_platform->session, host, parts.nPort, path, parts.nScheme == INTERNET_SCHEME_HTTPS) || false == request.send() || false == request.receive()) return false; - } - - DWORD status{0}; - DWORD statussize{sizeof(status)}; - ::WinHttpQueryHeaders(request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &status, &statussize, WINHTTP_NO_HEADER_INDEX); - - for (;;) - { - if (Stop()) - { - Error = "cancelled"; - close(); - return false; - } - DWORD available{0}; - if (!::WinHttpQueryDataAvailable(request, &available)) - { - Error = "WinHTTP error " + std::to_string(::GetLastError()); - close(); - return false; - } - if (available == 0) - break; - if (Out.size() + available > kLargest) - { - Error = kTooLarge; - close(); - Out.clear(); - return false; - } - std::size_t const offset = Out.size(); - Out.resize(offset + available); - DWORD received{0}; - if (!::WinHttpReadData(request, Out.data() + offset, available, &received)) - { - Error = "WinHTTP error " + std::to_string(::GetLastError()); - close(); - return false; - } - Out.resize(offset + received); - } - close(); + auto const status{request.status()}; + if (false == request.read_all(Out)) + return false; + request.close(); if (status != 200) { diff --git a/editor/editorIncludeInfo.cpp b/editor/editorIncludeInfo.cpp index ca532f1ce..450cde5a2 100644 --- a/editor/editorIncludeInfo.cpp +++ b/editor/editorIncludeInfo.cpp @@ -548,6 +548,71 @@ bool event_names(std::string const &File, std::vector &Names) return true; } +bool switched_tracks(std::string const &File, std::vector &Suffixes) +{ + Suffixes.clear(); + template_text text; + std::string error; + if (false == read_template(File, text, error)) + { + return false; + } + // event switch + auto const tokens{tokenize(text.content)}; + std::string const first{"(p1)"}; + // a drive has the events thrown by the keys and the map, (p1)+ and (p1)-, or moves a model, lights its lamps or throws a double switch at + // once; the sleepers or the ballast of a switch may throw it on their own events too, with nothing else, but they don't drive it + bool driven{false}; + for (std::size_t idx = 0; idx + 2 < tokens.size() && false == driven; ++idx) + { + if (tokens[idx] != "event") + { + continue; + } + auto const &name{tokens[idx + 1]}; + auto const &kind{tokens[idx + 2]}; + driven = (name.size() > first.size() && name.compare(0, first.size(), first) == 0 && (name.back() == '+' || name.back() == '-')) || (kind != "switch" && kind != "trackvel"); + } + if (false == driven) + { + return true; + } + for (std::size_t idx = 0; idx + 4 < tokens.size(); ++idx) + { + if (tokens[idx] != "event" || tokens[idx + 2] != "switch" || tokens[idx + 4].compare(0, first.size(), first) != 0) + { + continue; + } + auto suffix{tokens[idx + 4].substr(first.size())}; + if (std::find(Suffixes.begin(), Suffixes.end(), suffix) == Suffixes.end()) + { + Suffixes.push_back(std::move(suffix)); + } + } + return true; +} + +bool switch_bed(std::string const &File) +{ + template_text text; + std::string error; + if (false == read_template(File, text, error)) + { + return false; + } + auto const tokens{tokenize(text.content)}; + for (std::size_t idx = 0; idx < tokens.size(); ++idx) + { + // node track ... + if (tokens[idx] == "include" || (tokens[idx] == "node" && idx + 4 < tokens.size() && tokens[idx + 4] == "track") || + (tokens[idx] == "event" && idx + 2 < tokens.size() && tokens[idx + 2] != "switch" && tokens[idx + 2] != "trackvel")) + { + return false; + } + } + return true; +} + bool signal_speeds(std::string const &File, std::vector &Speeds) { Speeds.clear(); diff --git a/editor/editorIncludeInfo.hpp b/editor/editorIncludeInfo.hpp index 7a2da9dfa..96b84b44a 100644 --- a/editor/editorIncludeInfo.hpp +++ b/editor/editorIncludeInfo.hpp @@ -90,6 +90,13 @@ int parameter_count(std::string const &File); bool signal_speeds(std::string const &File, std::vector &Speeds); // the names of the events the template defines, as they're written after "event", lower case. returns: false if the file can't be read bool event_names(std::string const &File, std::vector &Names); +// the tracks the switch events of the template throw, named by its first parameter: what follows (p1) in their names, lower case, "" +// for the track named (p1) itself, "a" for (p1)a of a double switch; none for the sleepers or the ballast of a switch, whose events only +// throw it or set its speed, with no (p1)+ or (p1)-. returns: false if the file can't be read +bool switched_tracks(std::string const &File, std::vector &Suffixes); +// true if the template can be the sleepers or the ballast of a switch: it puts no track, includes nothing and has no events but those +// throwing a switch or setting its speed. false if the file can't be read +bool switch_bed(std::string const &File); // the aspects of a block signal of the template: 4 where its events give S3, the green light flashing with the next signal at S5, // the warning two signals ahead, else 3. returns: 0 if the file can't be read int block_aspects(std::string const &File); diff --git a/editor/editorOrthophoto.cpp b/editor/editorOrthophoto.cpp index f663dd012..d3254a2c1 100644 --- a/editor/editorOrthophoto.cpp +++ b/editor/editorOrthophoto.cpp @@ -63,12 +63,6 @@ double steady_seconds() } // namespace -bool editor_http_get(std::string const &Url, std::vector &Out, std::string &Error) -{ - thread_local http_client client; - return client.get(Url, Out, Error, []() { return false; }); -} - namespace { @@ -688,7 +682,7 @@ std::string xml_element(std::string const &Xml, std::string const &Tag, std::siz } // namespace -editor_orthophoto::service_info editor_orthophoto::describe(std::string const &Service) +editor_orthophoto::service_info editor_orthophoto::describe(std::string const &Service, std::function const &Stop) { service_info info; auto url{Service}; @@ -700,8 +694,10 @@ editor_orthophoto::service_info editor_orthophoto::describe(std::string const &S // a few tries, the services drop connections and time out now and then std::vector data; auto read{false}; - for (int attempt = 0; attempt < 3 && false == read; ++attempt) - read = editor_http_get(url, data, info.error); + stop_check const stopping{Stop ? Stop : stop_check{[]() { return false; }}}; + thread_local http_client client; + for (int attempt = 0; attempt < 3 && false == read && false == stopping(); ++attempt) + read = client.get(url, data, info.error, stopping); if (false == read) return info; info.error.clear(); @@ -937,23 +933,47 @@ void editor_orthophoto::ground_arrived() { if (!m_height) return; - for (auto &entry : m_tiles) + for (auto &[key, t] : m_tiles) { - auto &t{entry.second}; - if (!t.grounded || !t.guessed) - continue; - // the middle and the corners: a chunk of the terrain is much larger than a tile, it covers some of these when it comes. A tile - // lying flat, with nothing to go by, also goes onto the model once it's in - glm::dvec2 const corner = tile_corner(entry.first); - for (auto const &[u, v] : {std::pair{0.5, 0.5}, std::pair{0.0, 0.0}, std::pair{1.0, 0.0}, std::pair{0.0, 1.0}, std::pair{1.0, 1.0}}) - if (double y; m_height(corner.x - u * tile_size, corner.y - v * tile_size, y) || (t.heights.empty() && m_guess && m_guess(corner.x - u * tile_size, corner.y - v * tile_size, y))) - { - t.grounded = false; - break; - } + if (t.grounded && ground_came(key, t)) + t.grounded = false; } } +bool editor_orthophoto::waits_for_ground(tile_key const &Key) const +{ + // a tile laid out already stays, sampled again when its ground comes (ground_came) + if (!m_coming || m_tiles.contains(Key)) + return false; + glm::dvec2 const corner = tile_corner(Key); + return m_coming(corner - glm::dvec2{tile_size}, corner); +} + +bool editor_orthophoto::ground_came(tile_key const &Key, tile const &Tile) const +{ + glm::dvec2 const corner = tile_corner(Key); + // a tile lying flat, with nothing to go by, also goes onto the model once it's in: the middle and the corners + if (Tile.guessed && Tile.heights.empty() && m_guess) + for (auto const &[u, v] : {std::pair{0.5, 0.5}, std::pair{0.0, 0.0}, std::pair{1.0, 0.0}, std::pair{0.0, 1.0}, std::pair{1.0, 1.0}}) + if (double y; m_guess(corner.x - u * tile_size, corner.y - v * tile_size, y)) + return true; + // the points the ground didn't answer, every second one of the grid (16 m) and the edges: a chunk of the terrain is about as + // large as a tile and comes over a part of it, often a band along a side; partly answered tiles count too, not only the guessed + static_assert(ground_grid % 2 == 0, "the edges of the grid are among its even points"); + int constexpr samples{ground_grid + 1}; + double constexpr step{tile_size / ground_grid}; + for (auto const index : Tile.unanswered) + { + int const i{index % samples}; + int const j{index / samples}; + if (i % 2 != 0 || j % 2 != 0) + continue; + if (double y; m_height(corner.x - i * step, corner.y - j * step, y)) + return true; + } + return false; +} + void editor_orthophoto::detach_scene() { for (auto &entry : m_tiles) @@ -1032,6 +1052,20 @@ editor_orthophoto::statistics editor_orthophoto::stats() const return out; } +int editor_orthophoto::first_level(tile const &Tile, int const Level) +{ + // a tile showing nothing yet takes the standard image first, from the disk cache at once mostly: the 4K one comes from a slow + // service a few at a time, the tiles around the camera stayed blank meanwhile though their standard images lay on the disk + if (Level > standard_pixels && Tile.level < standard_pixels) + return standard_pixels; + return Level; +} + +bool editor_orthophoto::outside_area(tile_key const &Key) const +{ + return false == m_area.empty() && 0 == m_area_tiles.count(Key); +} + int editor_orthophoto::level_for(int Distance, bool Hires) { // coarser imagery further away keeps the memory use of large radii in check @@ -1233,6 +1267,7 @@ void editor_orthophoto::sample_ground(tile_key const &Key, tile &Tile) Tile.scene_dirty = true; Tile.heights.clear(); Tile.surface.clear(); + Tile.unanswered.clear(); glm::dvec2 const corner = tile_corner(Key); glm::dvec2 const min(corner.x - tile_size, corner.y - tile_size); @@ -1304,6 +1339,21 @@ void editor_orthophoto::sample_ground(tile_key const &Key, tile &Tile) } } + // the points the ground didn't answer: the ground coming there later (the terrain loaded after the imagery, which comes from the + // disk cache at once) has the tile sampled again, rather than left at the heights filled in or guessed now + Tile.unanswered.clear(); + auto const columns{static_cast(samples)}; + for (std::size_t index = 0; index < heights.size(); ++index) + { + if (heights[index] != no_height) + continue; + // in the scene the heights come from the triangles, and a steep spot (a wall, a quarry face) gives none: where the heightmap + // terrain answers the point, its ground is there already, and ground_came() would find it again on every chunk that comes + if (double y; surface && m_height && m_height(corner.x - static_cast(index % columns) * step, corner.y - static_cast(index / columns) * step, y)) + continue; + Tile.unanswered.push_back(static_cast(index)); + } + // holes (places without ground) take the average of their neighbours, spreading inwards std::size_t missing = std::count(heights.begin(), heights.end(), no_height); if (missing == heights.size()) @@ -1630,7 +1680,7 @@ void editor_orthophoto::update(glm::dvec3 const &Camera) { tile_key const key{centre.first + dx, centre.second + dy}; // outside the download area: nothing asked for, nothing shown - if (false == m_area.empty() && 0 == m_area_tiles.count(key)) + if (outside_area(key)) { if (auto const found{m_tiles.find(key)}; found != m_tiles.end()) { @@ -1639,14 +1689,12 @@ void editor_orthophoto::update(glm::dvec3 const &Camera) } continue; } + if (waits_for_ground(key)) + continue; tile &t = m_tiles[key]; if (!in_service_area(key.first, key.second)) t.empty = true; - int level = level_for(std::max(std::abs(dx), std::abs(dy)), m_config.hires); - // a tile showing nothing yet takes the standard image first, from the disk cache at once mostly: the 4K one comes from a slow - // service a few at a time, the tiles around the camera stayed blank meanwhile though their standard images lay on the disk - if (level > standard_pixels && t.level < standard_pixels) - level = standard_pixels; + int const level = first_level(t, level_for(std::max(std::abs(dx), std::abs(dy)), m_config.hires)); if (t.empty || (t.level == level && t.alpha == m_alpha) || (t.requested == level && t.requested_alpha == m_alpha) || now < t.retry_at) continue; schedule(key, t, level, m_alpha); @@ -1713,7 +1761,8 @@ void editor_orthophoto::worker() continue; long long const dx = it->key.first - m_focus.first; long long const dy = it->key.second - m_focus.second; - long long const d = dx * dx + dy * dy; + // the tiles hurried (Ctrl+~) before all the others, the nearest of them first + long long const d = dx * dx + dy * dy - (m_urgent.count(it->key) > 0 ? (1LL << 40) : 0LL); if (d < bestdistance) { bestdistance = d; @@ -1730,6 +1779,7 @@ void editor_orthophoto::worker() { current = *best; m_queue.erase(best); + m_urgent.erase(current.key); m_running.insert(current.key); if (current.level >= hires_pixels) ++m_running_hires; @@ -1957,3 +2007,58 @@ void editor_orthophoto::draw(glm::mat4 const &ViewProjection, glm::dvec3 const & drawlist->PopTextureID(); } } + +bool editor_orthophoto::hurry_tile(tile_key const &Key, int const Distance) +{ + // as update() does: nothing asked for outside the download area, nor outside the area the service covers, where the requests + // can't be answered + if (outside_area(Key)) + return false; + auto &t{m_tiles[Key]}; + if (false == in_service_area(Key.first, Key.second)) + t.empty = true; + if (t.empty) + return false; + auto const level{first_level(t, level_for(Distance, m_config.hires))}; + t.retry_at = 0.0; + if (t.level == level && t.alpha == m_alpha) + return false; // already shown as it should be + if (false == (t.requested == level && t.requested_alpha == m_alpha)) + schedule(Key, t, level, m_alpha); + return true; +} + +std::size_t editor_orthophoto::hurry(glm::dvec2 const &Min, glm::dvec2 const &Max, glm::dvec3 const &Camera) +{ + if (false == m_enabled) + return 0; + // the tile of the camera as it is now: it isn't followed while the layer is off + m_camera_tile = camera_tile(Camera); + { + std::lock_guard lock(m_mutex); + m_focus = m_camera_tile; + } + auto const a{camera_tile(glm::dvec3{Min.x, 0.0, Min.y})}; + auto const b{camera_tile(glm::dvec3{Max.x, 0.0, Max.y})}; + tile_key const first{std::min(a.first, b.first), std::min(a.second, b.second)}; + tile_key const last{std::max(a.first, b.first), std::max(a.second, b.second)}; + auto const centre{m_camera_tile}; + int const radius = m_config.radius; + std::vector keys; + for (int y = first.second; y <= last.second; ++y) + for (int x = first.first; x <= last.first; ++x) + { + tile_key const key{x, y}; + auto const distance{std::max(std::abs(x - centre.first), std::abs(y - centre.second))}; + if (distance <= radius && hurry_tile(key, distance)) + keys.push_back(key); + } + auto const count{keys.size()}; + { + std::lock_guard lock(m_mutex); + m_urgent.clear(); + m_urgent.insert(keys.begin(), keys.end()); + } + m_wakeup.notify_all(); + return count; +} diff --git a/editor/editorOrthophoto.hpp b/editor/editorOrthophoto.hpp index d6fd43f8d..b56052e7e 100644 --- a/editor/editorOrthophoto.hpp +++ b/editor/editorOrthophoto.hpp @@ -28,8 +28,6 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Classes.h" // material_handle #include "rendering/geometrybank.h" // gfx::geometry_handle -bool editor_http_get(std::string const &Url, std::vector &Out, std::string &Error); - namespace scene { class basic_region; @@ -102,6 +100,9 @@ class editor_orthophoto editor_orthophoto(editor_orthophoto const &) = delete; editor_orthophoto &operator=(editor_orthophoto const &) = delete; + // the tiles over a rectangle of the world (x, z; what the camera sees), within the reach around the camera, asked for before anything + // else, the ones which failed tried again at once. returns: how many were put at the front of the queue + std::size_t hurry(glm::dvec2 const &Min, glm::dvec2 const &Max, glm::dvec3 const &Camera); bool enabled() const { return m_enabled; } // disabling drops the queue and returns the gpu memory of the resident tiles void enabled(bool State); @@ -117,6 +118,10 @@ class editor_orthophoto // the heights the ground will have where there's none yet, as of the terrain model on its way: a tile laid out before its // ground comes lies there, or level with the tiles beside, rather than at the height of the layer far below or above void guess_source(height_query Query) { m_guess = std::move(Query); } + // true while the ground under an XZ rectangle (Min/Max are x,z) is still to come. A new tile there waits for it, rather than + // being laid out at the height of the layer; elsewhere it lies on whatever ground there is, or on the guess, as without it + using coming_query = std::function; + void coming_source(coming_query Query) { m_coming = std::move(Query); } // the area the imagery is downloaded in, a polygon of PUWG 1992 (easting, northing): its tiles go to the disk cache in the // background, the products the settings ask for, and no tile outside it is asked for around the camera. Empty: no area, the // tiles around the camera as before @@ -176,7 +181,8 @@ class editor_orthophoto bool puwg{false}; std::string error; }; - static service_info describe(std::string const &Service); + // Stop: true to give the reading up + static service_info describe(std::string const &Service, std::function const &Stop = {}); static std::string cache_directory(); private: @@ -236,6 +242,9 @@ class editor_orthophoto float height_max{0.0f}; std::vector surface; // upward facing ground triangles clipped to the tile (3 vertices each) bool guessed{false}; // no ground under it when sampled: the heights guessed, from the terrain model or the tiles beside + // the points of the grid of the heights the ground didn't answer when sampled (rows north->south, as heights): filled from + // the points beside or guessed, and sampled again once the ground comes under one of them + std::vector unanswered; // scene geometry scene::basic_section *section{nullptr}; // section holding the shape (nullptr = not in the scene) scene::basic_cell *cell{nullptr}; // set instead of the section's shape list when the shape is translucent @@ -245,6 +254,12 @@ class editor_orthophoto }; static int level_for(int Distance, bool Hires); + // the level a tile is asked for at first: a tile showing nothing yet takes the standard image before the 4K one + static int first_level(tile const &Tile, int Level); + // the tile is outside the download area set, which then has no imagery asked for it + bool outside_area(tile_key const &Key) const; + // a tile of the view hurried: put at the front of the queue unless it's shown as it should be. true: counted among the hurried + bool hurry_tile(tile_key const &Key, int Distance); tile_key camera_tile(glm::dvec3 const &Camera) const; glm::dvec2 tile_corner(tile_key const &Key) const; // world (x,z) of the north-west corner void schedule(tile_key const &Key, tile &Tile, int Level, std::uint8_t Alpha); @@ -253,6 +268,10 @@ class editor_orthophoto void release_tile(tile &Tile); texture_slot acquire_slot(); void sample_ground(tile_key const &Key, tile &Tile); + // the ground has come under a point of the tile which had none when it was sampled + bool ground_came(tile_key const &Key, tile const &Tile) const; + // a new tile isn't asked for yet: the ground under it is still to come + bool waits_for_ground(tile_key const &Key) const; // the height of the ground sampled under a tile beside Own at the point, the tiles with guessed heights left out bool sampled_height(tile_key const &Own, double const X, double const Z, float &Height) const; void build_shape(tile_key const &Key, tile &Tile); @@ -272,6 +291,7 @@ class editor_orthophoto ground_query m_ground; height_query m_height; height_query m_guess; + coming_query m_coming; scene::basic_region *m_region{nullptr}; // region the scene geometry was put into std::multimap m_free_chunks; // geometry chunks by capacity, reused between tiles // the scene opacity is baked into the textures, which means reading the tiles again; applied once the value settles @@ -300,6 +320,7 @@ class editor_orthophoto bool m_prefetch_paused{false}; source m_prefetch_source; std::uint32_t m_prefetch_generation{0}; + std::set m_urgent; // asked for by hurry(): workers take these first; guarded by m_mutex std::atomic m_stop{false}; std::atomic m_generation{1}; diff --git a/editor/editorSettings.cpp b/editor/editorSettings.cpp index c7e162c46..dd475b183 100644 --- a/editor/editorSettings.cpp +++ b/editor/editorSettings.cpp @@ -198,6 +198,18 @@ bool editorSettings::load() layer.terms = fields[5]; m_wms_layers.push_back(layer); } + else if (key == "camera_speed") + { + parse(value, m_camera.speed); + m_camera.speed = std::clamp(m_camera.speed, 0.05, 10.0); + } + else if (key == "camera_fast") + { + parse(value, m_camera.fast); + m_camera.fast = std::clamp(m_camera.fast, 1.0, 30.0); + } + else if (key == "camera_zoomed") + m_camera.zoomed = (value == "1"); else if (key.rfind(origin_prefix, 0) == 0) { // northing;easting @@ -269,6 +281,9 @@ bool editorSettings::save() stream << "laying_heights " << (m_heights == lay_heights::points ? "points" : m_heights == lay_heights::level ? "level" : "fitted") << "\n"; for (auto const &layer : m_wms_layers) stream << "wms_layer " << (layer.visible ? 1 : 0) << ";" << layer.opacity << ";" << encoded(layer.url) << ";" << encoded(layer.layers) << ";" << encoded(layer.title) << ";" << encoded(layer.terms) << "\n"; + stream << "camera_speed " << m_camera.speed << "\n"; + stream << "camera_fast " << m_camera.fast << "\n"; + stream << "camera_zoomed " << (m_camera.zoomed ? 1 : 0) << "\n"; stream << std::fixed << std::setprecision(3); for (auto const &origin : m_orthophoto_origins) stream << origin.first << " " << origin.second.first << ";" << origin.second.second << "\n"; diff --git a/editor/editorSettings.hpp b/editor/editorSettings.hpp index 548f12b61..5223fca51 100644 --- a/editor/editorSettings.hpp +++ b/editor/editorSettings.hpp @@ -119,10 +119,19 @@ public: }; lay_heights heights() const { return m_heights; } void heights(lay_heights Heights) { m_heights = Heights; } + // the free camera: its speed, how many times faster Ctrl makes it, and in the top view as fast as the view is zoomed + struct camera_settings + { + double speed{1.0}; + double fast{30.0}; + bool zoomed{false}; // off as the editor was before: "As it was" means it + }; + camera_settings &camera() { return m_camera; } private: movement_scheme m_movement{movement_scheme::wsad}; orthophoto_settings m_orthophoto; + camera_settings m_camera; std::map> m_orthophoto_origins; std::vector m_wms_layers; double m_platform_edge{1.725}; diff --git a/editor/editorTerrainStreamer.cpp b/editor/editorTerrainStreamer.cpp index a681b1a9e..9c00017de 100644 --- a/editor/editorTerrainStreamer.cpp +++ b/editor/editorTerrainStreamer.cpp @@ -20,6 +20,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include terrain_streamer EditorTerrain; @@ -907,6 +908,44 @@ bool terrain_streamer::owns(gfx::geometry_handle const &Geometry) const return false; } +bool terrain_streamer::in_walk(chunk_key const &Key) const +{ + // the circle update() walks around the camera and around where it's heading + auto const within = [this, &Key](chunk_key const &Centre) { + auto const dx{Key.first - Centre.first}; + auto const dz{Key.second - Centre.second}; + return std::abs(dx) <= m_walkradius && std::abs(dz) <= m_walkradius && dx * dx + dz * dz <= (m_walkradius + 1) * (m_walkradius + 1); + }; + return within(m_walkhere) || within(m_walkthere); +} + +bool terrain_streamer::chunk_coming(chunk_key const &Key) const +{ + if (m_chunks.contains(Key) || m_removed.contains(Key)) + return false; + if (m_loading.contains(Key)) + return true; + // a chunk the walk doesn't reach at this distance isn't loaded, so it isn't waited for: it's taken in when the camera comes near + if (false == in_walk(Key)) + return false; + // still to come while its pack isn't read yet, or it's in its pack; not there where the pack is read without it + auto const pack{m_packs.find(heightmap::pack_of(Key))}; + if (pack == m_packs.end() || pack->second.status == pack_state::state::unknown || pack->second.status == pack_state::state::loading) + return true; + return pack->second.status == pack_state::state::ready && pack->second.file->has(Key); +} + +bool terrain_streamer::ground_coming(glm::dvec2 const &Low, glm::dvec2 const &High) const +{ + auto const first{heightmap::chunk_at(Low.x, Low.y)}; + auto const last{heightmap::chunk_at(High.x, High.y)}; + for (auto z{std::min(first.second, last.second)}; z <= std::max(first.second, last.second); ++z) + for (auto x{std::min(first.first, last.first)}; x <= std::max(first.first, last.first); ++x) + if (chunk_coming(chunk_key{x, z})) + return true; + return false; +} + bool terrain_streamer::exists(chunk_key const &Key) const { if (m_chunks.count(Key) > 0) diff --git a/editor/editorTerrainStreamer.hpp b/editor/editorTerrainStreamer.hpp index cf8407ac1..760335a75 100644 --- a/editor/editorTerrainStreamer.hpp +++ b/editor/editorTerrainStreamer.hpp @@ -81,6 +81,10 @@ class terrain_streamer std::string stats() const; // chunks in the pack files and in memory, less the removed ones; the files known so far bool exists(chunk_key const &Key) const; + // true while a chunk over an XZ rectangle (Low/High are x,z) is still to come at this distance of the camera: being loaded, or + // within the walk around the camera and in its pack or with its pack not read yet. False where all of them are in memory, where + // none is nor will be, and where the walk doesn't reach + bool ground_coming(glm::dvec2 const &Low, glm::dvec2 const &High) const; // editing; the chunks changed are written to the files by save() heightmap::manifest const &manifest() const { return m_manifest; } @@ -235,6 +239,11 @@ class terrain_streamer scene::basic_cell *cell{nullptr}; }; + // within the circle of chunks the last walk of update() asked for + bool in_walk(chunk_key const &Key) const; + // the chunk is still to come at this distance of the camera (see ground_coming) + bool chunk_coming(chunk_key const &Key) const; + void start_workers(); void stop_workers(); void worker(); diff --git a/global_include/interfaces/ITexture.h b/global_include/interfaces/ITexture.h index ce123829f..f5b4d29a5 100644 --- a/global_include/interfaces/ITexture.h +++ b/global_include/interfaces/ITexture.h @@ -21,6 +21,19 @@ struct ITexture virtual void set_components_hint(int hint) = 0; virtual void make_from_memory(size_t width, size_t height, const uint8_t *data) = 0; virtual void update_from_memory(size_t width, size_t height, const uint8_t *data) = 0; + // uploads an image from a thread with a gl context of its own, sharing the objects with the drawing one. a texture that + // can keeps the image apart until commit_thread_upload(), called on the drawing thread, puts it in place + virtual void upload_from_thread(size_t width, size_t height, const uint8_t *data) + { + update_from_memory(width, height, data); + } + // puts in place the image of the last upload_from_thread() once the gpu has it, without waiting for it. called on the + // drawing thread; false while the upload isn't done yet, to be asked again later + virtual bool commit_thread_upload() + { + // the image went in place right away + return true; + } static ITexture *null_texture() { struct NullTexture : public ITexture diff --git a/lang/editor_pl.po b/lang/editor_pl.po index 4a5bc4759..6484fdd75 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -14023,6 +14023,36 @@ msgstr "PPM wciśnięty, W / S" msgid "RMB held, A / D" msgstr "PPM wciśnięty, A / D" +msgid "%zu drive with no switch" +msgid_plural "%zu drives with no switch" +msgstr[0] "%zu napęd bez zwrotnicy" +msgstr[1] "%zu napędy bez zwrotnicy" +msgstr[2] "%zu napędów bez zwrotnicy" + +msgid "Drives set to a switch the scenery hasn't got, left when a switch was deleted or renamed by hand or in an earlier editor: their events throw nothing.\nA click goes to the drive and selects it, Delete removes it; or give a switch its name" +msgstr "Napędy ustawione na zwrotnicę, której w scenerii nie ma: zostały po zwrotnicy usuniętej lub przemianowanej ręcznie albo we wcześniejszym edytorze, ich eventy niczego nie przestawiają.\nKliknięcie przenosi do napędu i go zaznacza, Delete go usuwa; można też nadać jakiejś zwrotnicy jego nazwę" + +msgid "%s: no switch of this name" +msgstr "%s: brak zwrotnicy o tej nazwie" + +msgid "%zu switch drive has no switch of its name: it's listed in the switch tool and marked red in the view" +msgid_plural "%zu switch drives have no switch of their names: they're listed in the switch tool and marked red in the view" +msgstr[0] "%zu napęd nie ma zwrotnicy o swojej nazwie: jest na liście w narzędziu zwrotnic i na czerwono w widoku" +msgstr[1] "%zu napędy nie mają zwrotnic o swoich nazwach: są na liście w narzędziu zwrotnic i na czerwono w widoku" +msgstr[2] "%zu napędów nie ma zwrotnic o swoich nazwach: są na liście w narzędziu zwrotnic i na czerwono w widoku" + +msgid "The drive %s isn't described for the editor: it may also set the speed or carry the ballast of the switch, so it's kept as it is" +msgstr "Napęd %s nie ma opisu dla edytora: może też ustawiać prędkość albo nieść podsypkę zwrotnicy, więc zostaje bez zmian" + +msgid "The slip has the drive %s, not described for the editor, which may also set the speed or carry its ballast: it isn't laid anew" +msgstr "Rozjazd krzyżowy ma napęd %s bez opisu dla edytora, który może też ustawiać prędkość albo nieść jego podsypkę: nie zostanie ułożony od nowa" + +msgid "Switch %s keeps its drive %s, which isn't described for the editor" +msgstr "Zwrotnica %s zostaje przy swoim napędzie %s, który nie ma opisu dla edytora" + +msgid "A drive not described for the editor, as the one of a double switch, which may also set the speed or carry the ballast of the switch: the editor keeps it as it is, it stays where it is when the switch is moved and goes when the last switch it throws is deleted" +msgstr "Napęd bez opisu dla edytora, np. rozjazdu krzyżowego, który może też ustawiać prędkość albo nieść podsypkę zwrotnicy: edytor go nie zmienia, zostaje na miejscu, gdy zwrotnica się przesuwa, i znika razem z ostatnią zwrotnicą, którą przestawia" + # the wizard of a new scenery: the range of the aerial photos, given on the map and changed in the editor msgid "A fictional scenery needs no place on the map" @@ -14236,3 +14266,39 @@ msgstr "Kursor rysowany w obrazie (stream)" msgid "The pointer drawn by the editor into the frame instead of the one of the system: seen by those watching a stream\nor a recording of the window (Discord, OBS, the capture of the system), which leave the system pointer out" msgstr "Wskaźnik rysowany przez edytor w klatce zamiast systemowego: widać go w streamie\ni w nagraniu okna (Discord, OBS, przechwytywanie systemowe), które pomijają wskaźnik systemu" + +msgid "Camera speed" +msgstr "Prędkość kamery" + +msgid "Speed of the camera" +msgstr "Prędkość kamery" + +msgid "How fast the arrows or WSAD move the camera, Shift a bit faster; 1 as it was" +msgstr "Jak szybko strzałki albo WSAD przesuwają kamerę, z Shiftem trochę szybciej; 1 = jak dotąd" + +msgid "Ctrl speeds it up" +msgstr "Przyspieszenie z Ctrl" + +msgid "How many times faster the camera goes with Ctrl held, Ctrl+Shift too; 30 as it was" +msgstr "Ile razy szybciej jedzie kamera z wciśniętym Ctrl, także Ctrl+Shift; 30 = jak dotąd" + +msgid "In the top view as fast as the view is zoomed" +msgstr "W widoku z góry prędkość zależna od powiększenia" + +msgid "Zoomed in the map moves slowly, zoomed out fast: across the screen at the same pace whatever the zoom" +msgstr "Przybliżona mapa jedzie wolno, oddalona szybko: po ekranie zawsze w tym samym tempie" + +msgid "As it was" +msgstr "Przywróć domyślne" + +msgid "Orthophoto on (~)" +msgstr "Ortofoto włączone (~)" + +msgid "Orthophoto off (~)" +msgstr "Ortofoto wyłączone (~)" + +msgid "Orthophoto: %zu tiles of the view downloaded first (Ctrl+~)" +msgstr "Ortofoto: %zu kafli widoku pobieranych w pierwszej kolejności (Ctrl+~)" + +msgid "Orthophoto: the view is all shown already (Ctrl+~)" +msgstr "Ortofoto: cały widok jest już pokazany (Ctrl+~)" diff --git a/model/AnimModel.cpp b/model/AnimModel.cpp index 23af295e4..757ccd2b8 100644 --- a/model/AnimModel.cpp +++ b/model/AnimModel.cpp @@ -597,6 +597,10 @@ void TAnimModel::RaAnimate( unsigned int const Framestamp ) { if( Framestamp == m_framestamp ) { return; } auto const timedelta { Timer::GetDeltaTime() }; + // the opacities change step by step from where they are, and they start at 1. the first time the instance is + // drawn its lights take their current state at once, whether it came from the definition or from an event since: + // a fade from 1 showed a light that is off as lit for a moment, the first time it came into view + bool const transition { m_transition && m_lightsanimated }; // interpretacja ułamka zależnie od typu // case ls_Off: ustalenie czasu migotania, t<1s (f>1Hz), np. 0.1 => t=0.1 (f=10Hz) @@ -637,12 +641,13 @@ void TAnimModel::RaAnimate( unsigned int const Framestamp ) { const float transitionontime = std::min(0.25f, std::min(ontime, offtime) * 0.95f); const float transitionofftime = std::min(0.45f, std::min(ontime, offtime) * 0.95f); if (on) - opacity += m_transition ? timedelta / transitionontime : 1.f; // increase to max value + opacity = static_cast( opacity + ( transition ? timedelta / transitionontime : 1.0 ) ); // increase to max value else - opacity -= m_transition ? timedelta / transitionofftime : 1.f; // reduce to zero + opacity = static_cast( opacity - ( transition ? timedelta / transitionofftime : 1.0 ) ); // reduce to zero // Clamp the opacity opacity = std::clamp(opacity, 0.f, 1.f); } + m_lightsanimated = true; // Ra 2F1I: to by można pomijać dla modeli bez animacji, których jest większość for (const auto entry : m_animlist) { diff --git a/model/AnimModel.h b/model/AnimModel.h index e5a6841b6..7cf50fa44 100644 --- a/model/AnimModel.h +++ b/model/AnimModel.h @@ -225,6 +225,7 @@ public: float fOffTime { 1.f / 2 };// { 60.f / 45.f / 2 }; // były stałymi, teraz mogą być zmienne dla każdego egzemplarza // float fTransitionTime { fOnTime * 0.9f }; // time bool m_transition { true }; // smooth transition between light states + bool m_lightsanimated { false }; // the lights were brought to their state at least once unsigned int m_framestamp { 0 }; // id of last rendered gfx frame // true if this instance is eligible for the batched/instanced render path: diff --git a/model/Texture.cpp b/model/Texture.cpp index 9b428202b..bba3ba763 100644 --- a/model/Texture.cpp +++ b/model/Texture.cpp @@ -29,6 +29,7 @@ http://mozilla.org/MPL/2.0/. #include "winheaders.h" #include +#include #define EU07_DEFERRED_TEXTURE_UPLOAD @@ -323,6 +324,7 @@ GLint readback_format( GLint const Internalformat ) { std::array opengl_texture::units = { 0 }; GLint opengl_texture::m_activeunit = -1; +std::atomic opengl_texture::m_unitcachestale { false }; std::unordered_map opengl_texture::precompressed_formats = { @@ -729,9 +731,104 @@ void opengl_texture::update_from_memory(size_t width, size_t height, const uint8 is_static = true; is_ready = true; } - // the name may be a new one, and the unit active took the texture past the unit cache + // the name may be a new one, and the unit active took the texture past the unit cache. this runs on the python upload + // thread too (python.threadedupload), so the cache is only marked here: clearing it outright raced the drawing thread + // filling it for a multi-bind, and an object got the texture of the one drawn before it for a frame + invalidate_unit_cache(); +} + +namespace +{ +// gl objects of an image uploaded by another thread that was never put in place +void delete_thread_upload(GLuint const Texture, GLsync const Fence) +{ + if (Fence != nullptr) + glDeleteSync(Fence); + glDeleteTextures(1, &Texture); +} +} // namespace + +void opengl_texture::upload_from_thread(size_t width, size_t height, const uint8_t *raw) +{ + // a texture of its own each time: the one drawn from may be in use by the gpu for the drawing context, and writing it from + // here, with nothing to order the two contexts, could leave it incomplete or half written for a frame + texture_thread_upload upload; + upload.width = width; + upload.height = height; + glGenTextures(1, &upload.id); + glBindTexture(target, upload.id); + set_filtering(); + glTexParameteri(target, GL_TEXTURE_WRAP_S, wrap_mode_s); + glTexParameteri(target, GL_TEXTURE_WRAP_T, wrap_mode_t); + if (!glGenerateMipmap) + glTexParameteri(target, GL_GENERATE_MIPMAP, GL_TRUE); + glTexImage2D(target, 0, GL_SRGB8_ALPHA8, static_cast(width), static_cast(height), 0, GL_RGBA, GL_UNSIGNED_BYTE, raw); + if (glGenerateMipmap) + glGenerateMipmap(target); + glBindTexture(target, 0); + if (glFenceSync) + { + upload.fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); + } + if (upload.fence == nullptr) + { + // no sync objects, or no fence made: the drawing context can only be sure of the image once the upload is done + glFinish(); + } + else + { + // the drawing context asks for the fence, which signals only once it is on its way to the gpu + glFlush(); + } + + std::optional superseded; + { + std::scoped_lock lock{m_threaduploadmutex}; + superseded = std::exchange(m_threadupload, upload); + } + if (superseded.has_value()) + { + // the drawing thread didn't take it, so nothing drew from it + delete_thread_upload(superseded->id, superseded->fence); + } +} + +bool opengl_texture::commit_thread_upload() +{ + texture_thread_upload upload; + { + std::scoped_lock lock{m_threaduploadmutex}; + if (false == m_threadupload.has_value()) + return true; + // asked without waiting. the image goes in place only once the upload is done, so every context binding it after + // has it whole: the extra viewports and the windows of python.displaywindows draw in contexts of their own + if (m_threadupload->fence != nullptr) + { + // a failed query (GL_WAIT_FAILED) isn't asked again: the image would never go in place + if (glClientWaitSync(m_threadupload->fence, 0, 0) == GL_TIMEOUT_EXPIRED) + return false; + glDeleteSync(m_threadupload->fence); + } + upload = *m_threadupload; + m_threadupload.reset(); + } + + if (id != invalid_id) + glDeleteTextures(1, &id); + id = upload.id; + data_width = static_cast(upload.width); + data_height = static_cast(upload.height); + data_format = GL_SRGB8_ALPHA8; + data_components = GL_RGBA; + if (type == "internalsrc:") + { + is_static = true; + is_ready = true; + } + // the name deleted may come back for another texture, and a deleted texture isn't bound any more for (auto &unit : units) unit = -1; + return true; } void @@ -1263,6 +1360,7 @@ opengl_texture::bind(size_t unit) { return false; } + sync_unit_cache(); if (units[unit] == id) return true; if (GLAD_GL_ARB_direct_state_access) @@ -1630,6 +1728,25 @@ opengl_texture::reset_unit_cache() { m_activeunit = -1; } +void +opengl_texture::invalidate_unit_cache() { + + m_unitcachestale.store( true ); +} + +void +opengl_texture::sync_unit_cache() { + + // a plain load first: bind() calls this for every texture, and a read-modify-write each time would cost more + if( ( false == m_unitcachestale.load() ) + || ( false == m_unitcachestale.exchange( false ) ) ) { + return; + } + for( auto &unit : units ) { + unit = -1; + } +} + void opengl_texture::set_filtering() const { diff --git a/model/Texture.h b/model/Texture.h index 20221fcea..3934565a5 100644 --- a/model/Texture.h +++ b/model/Texture.h @@ -9,8 +9,11 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include #include #include +#include +#include #include "winheaders.h" #include #include "model/ResourceManager.h" @@ -19,6 +22,14 @@ http://mozilla.org/MPL/2.0/. struct texture_request; // texture data read by a worker thread, with gfx.textures.streaming +// an image uploaded by another thread into a texture of its own, waiting for the drawing thread to put it in place +struct texture_thread_upload { + GLuint id { 0 }; + GLsync fence { nullptr }; // set after the upload in the uploading context; none where the driver has no sync objects + size_t width { 0 }; + size_t height { 0 }; +}; + struct opengl_texture : public ITexture { static DDSURFACEDESC2 deserialize_ddsd(std::istream&); static DDCOLORKEY deserialize_ddck(std::istream&); @@ -47,6 +58,13 @@ struct opengl_texture : public ITexture { set_components_hint( GLint hint ) override; static void reset_unit_cache(); + // marks the unit cache as not to be trusted. safe to call from any thread: the cache itself is + // cleared by the thread drawing with it, the next time it binds textures (sync_unit_cache) + static void + invalidate_unit_cache(); + // clears the unit cache if a thread marked it as not to be trusted since. called before the cache is read + static void + sync_unit_cache(); virtual int get_width() const override { return data_width; } @@ -85,6 +103,10 @@ struct opengl_texture : public ITexture { virtual void make_from_memory(size_t width, size_t height, const uint8_t *data) override; virtual void update_from_memory(size_t width, size_t height, const uint8_t *data) override; + // the image goes into a texture of its own, and the drawing thread swaps it in after the gpu has it (commit_thread_upload). + // the texture drawn from is never written by the uploading thread + void upload_from_thread(size_t width, size_t height, const uint8_t *data) override; + bool commit_thread_upload() override; // members static constexpr GLuint invalid_id { std::numeric_limits::max() }; // id value of texture without GL resource @@ -100,6 +122,11 @@ struct opengl_texture : public ITexture { GLenum target = GL_TEXTURE_2D; static std::array units; static GLint m_activeunit; + // set by invalidate_unit_cache(), from the python upload thread too; the units themselves are touched only by the drawing thread + static std::atomic m_unitcachestale; + + std::mutex m_threaduploadmutex; + std::optional m_threadupload; // guarded by m_threaduploadmutex public: // methods diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp index 800f33dcf..3a3008a44 100644 --- a/rendering/opengl33renderer.cpp +++ b/rendering/opengl33renderer.cpp @@ -2457,6 +2457,8 @@ void opengl33_renderer::Bind_Material( material_handle const Material, TSubModel if (GLAD_GL_ARB_multi_bind) { + // the cache may have been marked stale by the python upload thread + opengl_texture::sync_unit_cache(); GLuint lastdiff = 0; size_t i; for (i = 0; i < gl::MAX_TEXTURES; i++) @@ -4338,7 +4340,7 @@ bool opengl33_renderer::Render_cab(TDynamicObject const *Dynamic, float const Li auto const luminance { Global.fLuminance * ( Dynamic->fShade > 0.0f ? Dynamic->fShade : 1.0f ) }; if( Lightlevel > 0.f ) { // crude way to light the cabin, until we have something more complete in place - light_ubs.ambient += packed_vec3( ( Dynamic->InteriorLight * Lightlevel ) * std::clamp( 1.25f - (float)luminance, 0.f, 1.f ) ); + light_ubs.ambient += packed_vec3( ( Dynamic->InteriorLight * Lightlevel ) * static_cast( std::clamp( 1.25 - luminance, 0.0, 1.0 ) ) ); light_ubo->update( light_ubs ); } diff --git a/rendering/openglparticles.cpp b/rendering/openglparticles.cpp index 3b8de9469..706e5d871 100644 --- a/rendering/openglparticles.cpp +++ b/rendering/openglparticles.cpp @@ -65,7 +65,9 @@ opengl_particles::update( opengl_camera const &Camera ) { vertex.color[ 0 ] = static_cast( particlecolor.r ); vertex.color[ 1 ] = static_cast( particlecolor.g ); vertex.color[ 2 ] = static_cast( particlecolor.b ); - vertex.color[ 3 ] = static_cast( std::clamp( particle.opacity * 255, 0.f, 255.f ) ); + // as up to 26.05.1, when clamp made the alpha a byte before clamping it: an opacity over 1 wraps + // round. through int: the byte the x86-64 compilers gave, without the undefined behaviour of that conversion + vertex.color[ 3 ] = static_cast( static_cast( particle.opacity * 255 ) ); auto const offset { glm::vec3{ particle.position - Camera.position() } }; auto const rotation { glm::angleAxis( particle.rotation, glm::vec3{ 0.f, 0.f, 1.f } ) }; diff --git a/rendering/openglrenderer.cpp b/rendering/openglrenderer.cpp index 5083c6f2f..8bef3352d 100644 --- a/rendering/openglrenderer.cpp +++ b/rendering/openglrenderer.cpp @@ -4370,8 +4370,8 @@ glm::dvec3 opengl_renderer::Update_Mouse_Position() { glm::ivec2 mousepos = Global.cursor_pos * Global.fb_size / Global.window_size; - mousepos.x = std::clamp( mousepos.x, 0, Global.fb_size.x - 1 ); - mousepos.y = std::clamp(Global.fb_size.y - mousepos.y, 0, Global.fb_size.y - 1); + mousepos.x = safe_clamp( mousepos.x, 0, Global.fb_size.x - 1 ); + mousepos.y = safe_clamp(Global.fb_size.y - mousepos.y, 0, Global.fb_size.y - 1); GLfloat pointdepth; ::glReadPixels( mousepos.x, mousepos.y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &pointdepth ); diff --git a/rendering/particles.cpp b/rendering/particles.cpp index 8ccb728dd..517fec751 100644 --- a/rendering/particles.cpp +++ b/rendering/particles.cpp @@ -168,9 +168,9 @@ smoke_source::update( double const Timedelta, bool const Onlydespawn ) { if( m_ownertype == owner_type::vehicle ) { auto const &mover { *m_owner.vehicle->MoverParameters }; - if( Global.AirTemperature <= 5.f || mover.dizel_heat.Ts < 45.f ) { - m_emitter.color = glm::vec3{ 128, 128, 128 }; - } + // NOTE: the smoke keeps the colour of its template, cold engine or not. a grey for a cold engine was once meant + // here, but the line compared instead of assigning; made an assignment, it set 128 on the 0-1 scale of the + // emitter colour, so the smoke turned pure white, glowing at night, and never changed back // a vehicle taken off the tracks (gone through a portal, or waiting in the pool of the road traffic) puffs no more, // the particles it already let out fade away as usual m_spawncount = ( diff --git a/scripting/PyInt.cpp b/scripting/PyInt.cpp index fac540019..b95b310d8 100644 --- a/scripting/PyInt.cpp +++ b/scripting/PyInt.cpp @@ -142,18 +142,24 @@ void render_task::run() } else { - std::lock_guard guard(m_target->mutex); + // the lock may be held by the drawing thread for a whole upload: waited for without the gil. the bytes stay + // valid without it, the object is immutable and held by its reference here + Py_BEGIN_ALLOW_THREADS + { + std::scoped_lock guard(m_target->mutex); - if (m_target->image.size() != expectedBytes) - m_target->image.resize(expectedBytes); + if (m_target->image.size() != expectedBytes) + m_target->image.resize(expectedBytes); - std::memcpy(m_target->image.data(), pythonBufferPtr, expectedBytes); + std::memcpy(m_target->image.data(), pythonBufferPtr, expectedBytes); - m_target->width = screenWidth; - m_target->height = screenHeight; - m_target->components = glComponents; - m_target->format = glFormat; - m_target->timestamp = std::chrono::high_resolution_clock::now(); + m_target->width = screenWidth; + m_target->height = screenHeight; + m_target->components = glComponents; + m_target->format = glFormat; + m_target->timestamp = std::chrono::high_resolution_clock::now(); + } + Py_END_ALLOW_THREADS } } @@ -232,6 +238,35 @@ void render_task::upload() const } } +void render_task::upload_from_thread() +{ + m_uploadedbyworker = true; + if (Global.python_uploadmain && m_target && m_target->shared_tex) + { + m_target->shared_tex->upload_from_thread(m_target->width, m_target->height, reinterpret_cast(m_target->image.data())); + } +} + +bool render_task::finish_upload() const +{ + if (false == Global.python_uploadmain || nullptr == m_target || nullptr == m_target->shared_tex) + return true; + // the old texture is deleted and the new name published under the lock the windows of python.displaywindows bind under, + // so none of them binds the old name once it is gone: a name bound before stays alive in its context while bound there + std::scoped_lock lock(m_target->mutex); + if (m_uploadedbyworker) + { + if (false == m_target->shared_tex->commit_thread_upload()) + return false; + } + else + { + upload(); + } + m_target->texture_id = m_target->shared_tex->get_id(); + return true; +} + void render_task::cancel() const { /* nothing to do */ } // initializes the module. returns true on success @@ -569,9 +604,11 @@ void python_taskqueue::run(GLFWwindow *Context, rendertask_sequence &Tasks, uplo // execute python code task->run(); if (Context) - task->upload(); - else { + task->upload_from_thread(); + } + { + // the drawing thread uploads the image, or puts in place the one uploaded here std::scoped_lock lock(Upload_Tasks.mutex); Upload_Tasks.data.push_back(task); } @@ -609,10 +646,8 @@ void python_taskqueue::update() { std::scoped_lock lock(m_uploadtasks.mutex); - for (auto const &task : m_uploadtasks.data) - task->upload(); - - m_uploadtasks.data.clear(); + // a task whose image a worker uploaded stays until the gpu has the image + std::erase_if(m_uploadtasks.data, [](std::shared_ptr const &Task) { return Task->finish_upload(); }); } void python_taskqueue::error() diff --git a/scripting/PyInt.h b/scripting/PyInt.h index c8c410397..3259b418a 100644 --- a/scripting/PyInt.h +++ b/scripting/PyInt.h @@ -67,6 +67,9 @@ struct python_rt int width; int height; std::string image; + // gl name of the texture with the last image put in place, for the windows of python.displaywindows (0: none yet). the image + // uploaded by a worker gets a texture of its own, so the name changes with each one + size_t texture_id{0}; std::chrono::high_resolution_clock::time_point timestamp; }; @@ -80,7 +83,13 @@ class render_task render_task(PyObject *Renderer, std::shared_ptr Input, std::shared_ptr Target) : m_renderer(Renderer), m_input(Input), m_target(Target) {} // methods void run(); + // uploads the image on the drawing thread void upload() const; + // uploads the image on a worker with a gl context of its own (python.threadedupload); finish_upload() puts it in place + void upload_from_thread(); + // on the drawing thread: uploads the image, or puts in place the one a worker uploaded. false while the gpu hasn't got + // the latter yet, to be called again + bool finish_upload() const; void cancel() const; auto target() const -> std::shared_ptr { @@ -92,6 +101,8 @@ class render_task PyObject *m_renderer{nullptr}; std::shared_ptr m_input{nullptr}; std::shared_ptr m_target{nullptr}; + // set by upload_from_thread(); read by the drawing thread after the task was handed over under the lock of the queue + bool m_uploadedbyworker{false}; }; class python_taskqueue diff --git a/scripting/pythonscreenviewer.cpp b/scripting/pythonscreenviewer.cpp index 4da50151e..5a3491af7 100644 --- a/scripting/pythonscreenviewer.cpp +++ b/scripting/pythonscreenviewer.cpp @@ -30,7 +30,7 @@ void texture_window_cursor_pos(GLFWwindow *win, double x, double y) } python_screen_viewer::python_screen_viewer(std::shared_ptr rt, std::shared_ptr> touchlist, std::string const &surfacename) - : m_rt(rt), m_touchlist(touchlist) + : m_rt(rt), m_touchlist(touchlist), m_initialtexture(rt->shared_tex->get_id()) { for (const auto &viewport : Global.python_viewports) { @@ -90,7 +90,7 @@ void python_screen_viewer::threadfunc() glActiveTexture(GL_TEXTURE0); if (Global.python_sharectx) { - glBindTexture(GL_TEXTURE_2D, static_cast(m_rt->shared_tex->get_id())); + bind_shared_texture(); } else { GLuint tex; @@ -146,6 +146,8 @@ void python_screen_viewer::threadfunc() } glfwMakeContextCurrent(window->window); + if (Global.python_sharectx) + bind_shared_texture(); gl::program::unbind(); gl::buffer::unbind(); @@ -188,6 +190,16 @@ void python_screen_viewer::threadfunc() } } +void python_screen_viewer::bind_shared_texture() const +{ + // bound each frame: each image uploaded by a worker comes in a texture of its own, and a name deleted comes back for + // a later one, so a name seen before may be another texture already. bound under the lock the drawing thread deletes + // the old texture under, so the name read here is never one already gone + std::scoped_lock guard(m_rt->mutex); + size_t const texture = m_rt->texture_id; + glBindTexture(GL_TEXTURE_2D, static_cast(texture != 0 ? texture : m_initialtexture)); +} + void python_screen_viewer::notify_window_fb_size(GLFWwindow const *window, int w, int h) const { for (auto const &conf : m_windows) { diff --git a/scripting/pythonscreenviewer.h b/scripting/pythonscreenviewer.h index ccd78f0ef..41b52a7e2 100644 --- a/scripting/pythonscreenviewer.h +++ b/scripting/pythonscreenviewer.h @@ -31,8 +31,12 @@ class python_screen_viewer gl::scene_ubs m_ubs; std::atomic_bool m_exit = false; + // the texture of the screen when the viewer was made, read on the drawing thread: shown until an image is put in place + size_t m_initialtexture{0}; void threadfunc(); + // with python.sharectx, binds the texture with the last image of the screen, in the context of the window made current + void bind_shared_texture() const; public: python_screen_viewer(std::shared_ptr rt, std::shared_ptr> touchlist, std::string const &name); diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index 9e979e2ca..5b224b666 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -247,10 +247,9 @@ void blackbox_recorder::update(double const Deltatime) { std::scoped_lock lock{m_mutex}; m_time += Deltatime; - // the tape of the driver the user is with, unless it writes its own: with "physicslog yes" each driver but one of a - // road vehicle does. the tapes are files of their own: they go on after the recording ends in the editor, and with - // a recording which couldn't be made - if (m_time >= m_tapedue) { + // with the physics logs on, each driver writes its own all the time. the tapes are files of their own: they go on + // after the recording ends in the editor, and with a recording which couldn't be made + if (false == WriteLogFlag && m_time >= m_tapedue) { keep_tape_line(); m_tapedue = std::max(m_tapedue + tapeinterval, m_time); } @@ -510,13 +509,10 @@ void blackbox_recorder::keep_tape_line() { auto const *driver{vehicle->Mechanik != nullptr && vehicle->Mechanik->primary() ? vehicle->Mechanik : vehicle->ctOwner}; if (driver == nullptr) return; - auto const &name{driver->physicslog_name()}; - // its log, the driver's own or written here, before the logs of the other drivers: the closing drops those it has - // no time for, on a hard disk with hundreds of them - PhysicsLogs.put_first(name); // a driver writing its own, of a train with "physicslog.trains yes", isn't written twice if (driver->writes_physicslog()) return; + auto const &name{driver->physicslog_name()}; if (m_tapes.insert(name).second) { PhysicsLogs.begin(name, TController::physicslog_header()); WriteLog(std::format("Black box: the physics log \"{}\" begun", PhysicsLogs.shown(name))); diff --git a/simulation/blackboxrecorder.h b/simulation/blackboxrecorder.h index 18ee052c4..a3aaf5d0f 100644 --- a/simulation/blackboxrecorder.h +++ b/simulation/blackboxrecorder.h @@ -88,9 +88,8 @@ private: void write_map(); static std::vector> stop_point_headings(); void write_cab(); - // the line of the log of the driver the user is with, unless that driver writes its own (the physics logs, a road - // vehicle's driver not even with "physicslog yes"), to its log, physicslog/.dat, as the physics logs would - // have it. a driver's log is begun at the first line given for that driver, and goes on + // with the physics logs off, the line of the log of the driver the user is with, to its log, physicslog/.dat, + // as the physics logs would have it. a driver's log is begun at the first line given for that driver, and goes on // while the user looks around outside or is in another vehicle of that driver; back with it, after the gap void keep_tape_line(); // the clock, the user's vehicle, the vehicles, the switches and the signals diff --git a/simulation/simulationenvironment.cpp b/simulation/simulationenvironment.cpp index 10ef80f05..4e8c0e5f7 100644 --- a/simulation/simulationenvironment.cpp +++ b/simulation/simulationenvironment.cpp @@ -26,11 +26,12 @@ namespace { float turbidity_of( float const Overcast ) { + if( Overcast <= 0.10 ) { return 3.f; } if( Overcast <= 0.20 ) { return 4.f; } - if( Overcast <= 0.40 ) { return 5.f; } - if( Overcast <= 0.60 ) { return 6.f; } - if( Overcast <= 0.70 ) { return 7.f; } - if( Overcast <= 0.80 ) { return 8.f; } + if( Overcast <= 0.60 ) { return 5.f; } + if( Overcast <= 0.70 ) { return 6.f; } + if( Overcast <= 0.80 ) { return 7.f; } + if( Overcast <= 0.90 ) { return 8.f; } return 9.f; } diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp index 2efa57291..d32fd0e72 100644 --- a/simulation/simulationtest.cpp +++ b/simulation/simulationtest.cpp @@ -17,7 +17,6 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/physicslog.h" #include "utilities/utilities.h" -#include "vehicle/Driver.h" #include "vehicle/DynObj.h" #include "world/Event.h" #include "world/MemCell.h" @@ -46,15 +45,6 @@ double elapsed_wall_time() return std::chrono::duration(std::chrono::steady_clock::now() - Global.startTimestamp).count(); } -// the physics log of the driver of the vehicle, or of its train's when that one is passive, written before the logs of -// the other drivers: the closing at the end of the run drops those it has no time for -void put_physicslog_first(TDynamicObject const &Vehicle) -{ - auto const *driver { Vehicle.Mechanik != nullptr && Vehicle.Mechanik->primary() ? Vehicle.Mechanik : Vehicle.ctOwner }; - if (driver != nullptr) - PhysicsLogs.put_first(driver->physicslog_name()); -} - } // namespace namespace simulation { @@ -135,13 +125,11 @@ void test_manager::start() } for (auto const &name : Global.test.vehicles) { - auto const *vehicle { simulation::Vehicles.find(name) }; - if (vehicle == nullptr) + if (simulation::Vehicles.find(name) == nullptr) { finish(test_result::error, std::format("the scenery has no vehicle {} (test.vehicle)", name)); return; } - put_physicslog_first(*vehicle); } // a pause set by the scenery or the settings would never be lifted, nobody is there to press the key Global.iPause = 0; diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index e24db024f..d06c83445 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -32,6 +32,8 @@ add_executable(${UNIT_TESTS_NAME} # and the fouling points of the switches, widened in the curves as the gauge is "${CMAKE_SOURCE_DIR}/editor/editorGauge.cpp" "${CMAKE_SOURCE_DIR}/editor/editorFouling.cpp" + # and the http client the editor fetches its aids with + "${CMAKE_SOURCE_DIR}/editor/editorHttp.cpp" ${UNIT_TEST_CASES}) # the core library brings the game's build settings along diff --git a/tests/unit/test_braking_curve.cpp b/tests/unit/test_braking_curve.cpp new file mode 100644 index 000000000..7102d06e0 --- /dev/null +++ b/tests/unit/test_braking_curve.cpp @@ -0,0 +1,195 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/brakingcurve.h" + +#include +#include + +// the deceleration the AI asks for on its way down to a stop or a lower speed ahead, outside of the final approach +// (TController::adjust_desired_speed_for_braking_curve). in shunting the brake table of the consist isn't worked out +// and stays at zero; planned from it, the curve asked for next to no braking, and shunting engines ran through the +// signals they were to stop at. + +namespace { + +auto constexpr tablesize{20}; +using brake_values = std::array; + +// what the AI holds in shunting: nothing worked out +struct zeroed_table { + brake_values a0{}; + brake_values a1{}; + + braking_curve::brake_table table() const { return {a0.data(), a1.data(), tablesize, 100.0}; } +}; + +// a train brake that gives the same deceleration at every speed, full service 0.05 + 12 * 0.1 = 1.25 m/s2 +struct flat_table { + brake_values a0{}; + brake_values a1{}; + + flat_table() { + a0.fill(0.05); + a1.fill(0.1); + } + braking_curve::brake_table table() const { return {a0.data(), a1.data(), tablesize, 120.0}; } +}; + +braking_curve::approach stop_at(double const Speed, double const Distance) { + braking_curve::approach approach{}; + approach.speed = Speed; + approach.target = 0.0; + approach.distance = Distance; + approach.offset = 0.0; // the braking point of a stop, outside of a train, is the stop itself (VelNext * multiplier) + approach.speedup_horizon = 30.0 / 3.6; + approach.fill_horizon = 30.0 / 3.6; + return approach; +} + +// the AI in shunting leaves the brake alone for a demand weaker than this (TController::fAccThreshold) +auto constexpr shunting_brake_threshold{-0.2}; + +struct shunting_run { + double speed; // [km/h] + double left; // to the stop point [m] + bool braked_at_once; +}; + +// a shunting engine braking to a stop point the way the AI drives it: the brake follows the demand once it is past +// the threshold, the engine coasts otherwise. the braking curve gives way near the point to the final approach, at +// walking pace (10 km/h, 5 km/h in the last 10 m) +shunting_run brake_to_point(double const Speed, double const Distance, zeroed_table const &Table) { + auto const table{Table.table()}; + auto const timestep{0.1}; + shunting_run run{Speed, Distance, false}; + run.braked_at_once = braking_curve::demand(stop_at(run.speed, run.left), &table) < shunting_brake_threshold; + while ((run.speed > (run.left > 10.0 ? 10.0 : 5.0)) && (run.left > -50.0)) { + auto const demand{braking_curve::demand(stop_at(run.speed, run.left), &table)}; + auto const acceleration{demand < shunting_brake_threshold ? demand : 0.0}; + run.speed = std::max(0.0, run.speed + 3.6 * acceleration * timestep); + run.left -= run.speed / 3.6 * timestep; + } + return run; +} + +} // namespace + +TEST_CASE("braking curve: a brake table left at zero isn't known, one worked out is") { + CHECK_FALSE(zeroed_table{}.table().known()); + CHECK(flat_table{}.table().known()); +} + +TEST_CASE("braking curve: shunting to a point asks for the constant deceleration over the distance left") { + zeroed_table const shunting; + auto const table{shunting.table()}; + auto approach{stop_at(33.0, 186.0)}; + SUBCASE("coasting") { approach.acceleration = 0.0; } + SUBCASE("still speeding up") { approach.acceleration = 0.2; } + + auto const demand{braking_curve::demand(approach, &table)}; + + CHECK(demand == doctest::Approx(-33.0 * 33.0 / (25.92 * 186.0 + 0.1))); + CHECK(demand == doctest::Approx(braking_curve::demand(approach, nullptr))); + // enough for the AI to put the brake on + CHECK(demand < shunting_brake_threshold); +} + +TEST_CASE("braking curve: a shunting engine braking to a point gets down to walking pace short of it") { + zeroed_table const shunting; + auto speed{0.0}; + auto distance{0.0}; + SUBCASE("33 km/h, 186 m") { + speed = 33.0; + distance = 186.0; + } + SUBCASE("40 km/h, 186 m") { + speed = 40.0; + distance = 186.0; + } + SUBCASE("33 km/h, 120 m") { + speed = 33.0; + distance = 120.0; + } + SUBCASE("25 km/h, 60 m") { + speed = 25.0; + distance = 60.0; + } + CAPTURE(speed); + CAPTURE(distance); + + auto const run{brake_to_point(speed, distance, shunting)}; + + CHECK(run.braked_at_once); + CHECK(run.left > 0.0); + CHECK(run.speed <= 10.0); +} + +TEST_CASE("braking curve: a train with a worked out brake table plans along the shape of its brake") { + flat_table const train; + auto const table{train.table()}; + auto approach{stop_at(80.0, 600.0)}; + approach.offset = 20.0; + approach.fill_horizon = 6.0; + approach.speedup_horizon = 5.0; + + SUBCASE("before the brake is applied, the room it takes to fill is kept") { + auto const room{580.0 - 80.0 / 3.6 * 6.0}; + auto const demand{braking_curve::demand(approach, &table)}; + CHECK(demand == doctest::Approx(braking_curve::shaped_demand(80.0, 0.0, room + 0.1 / 25.92, 0.0, table))); + // with the same deceleration at every speed the shape is the constant deceleration over that room + CHECK(demand == doctest::Approx(-(80.0 / 3.6) * (80.0 / 3.6) / (2.0 * room)).epsilon(0.01)); + } + SUBCASE("once the brake is applied, the whole distance is used") { + approach.brake_applied = true; + auto const demand{braking_curve::demand(approach, &table)}; + CHECK(demand == doctest::Approx(braking_curve::shaped_demand(80.0, 0.0, 580.0 + 0.1 / 25.92, 0.0, table))); + } + SUBCASE("still speeding up, it plans from the speed reached once the brake acts") { + approach.acceleration = 0.3; + auto const reached{80.0 + 3.6 * 5.0 * 0.3}; + auto const distance{600.0 - (80.0 + reached) * 0.5 / 3.6 * 5.0}; + auto const demand{braking_curve::demand(approach, &table)}; + CHECK(demand == doctest::Approx(braking_curve::shaped_demand(reached, 0.0, distance - 20.0 + 0.1 / 25.92, 0.0, table))); + } +} + +TEST_CASE("braking curve: a train gets the demand it got before the curve moved out of the AI") { + // a table that grips harder as the train slows, on a gradient; the demands were worked out with the + // code of TController::adjust_desired_speed_for_braking_curve before the move (origin/master 80fd5aad) + brake_values a0{}; + brake_values a1{}; + for (auto i{1}; i <= tablesize; ++i) { + a0[i] = 0.12 - 0.003 * i; + a1[i] = 0.06 - 0.001 * i; + } + braking_curve::brake_table const table{a0.data(), a1.data(), tablesize, 120.0}; + REQUIRE(table.full_braking(80.0) == doctest::Approx(0.645)); + REQUIRE(table.full_braking(10.0) == doctest::Approx(0.825)); + + auto approach{stop_at(80.0, 600.0)}; + approach.offset = 20.0; + approach.gravity = 0.1; + approach.speedup_horizon = 5.0; + approach.fill_horizon = 6.0; + auto expected{0.0}; + SUBCASE("downhill, coasting, the brake still to be applied") { expected = -0.4926656801067293; } + SUBCASE("downhill, the brake applied") { + approach.brake_applied = true; + expected = -0.37739905908238147; + } + SUBCASE("downhill, still speeding up") { + approach.acceleration = 0.3; + expected = -0.5330117415264249; + } + SUBCASE("uphill, down to 40 km/h") { + approach = stop_at(100.0, 900.0); + approach.target = 40.0; + approach.gravity = -0.08; + approach.speedup_horizon = 5.0; + approach.fill_horizon = 6.0; + expected = -0.40930710539221765; + } + + CHECK(braking_curve::demand(approach, &table) == doctest::Approx(expected).epsilon(1e-7)); +} diff --git a/tests/unit/test_crashsignals.cpp b/tests/unit/test_crashsignals.cpp new file mode 100644 index 000000000..4c4dd1e86 --- /dev/null +++ b/tests/unit/test_crashsignals.cpp @@ -0,0 +1,89 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scratch.h" + +#include "utilities/crashsignals.h" + +// the stack of a crash on Linux (utilities/crashsignals.h): written to the log and to the standard error, after which +// the signal ends the process as it always did. the crash happens in a child process, which the test watches +#if defined(__linux__) + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace { + +std::string read_all(int const File) { + std::string text; + std::array buffer{}; + for (auto count{::read(File, buffer.data(), buffer.size())}; count > 0; count = ::read(File, buffer.data(), buffer.size())) + text.append(buffer.data(), static_cast(count)); + return text; +} + +std::string read_file(std::string const &Path) { + std::ifstream file{Path, std::ios::binary}; + return {std::istreambuf_iterator{file}, std::istreambuf_iterator{}}; +} + +// the child: the report goes to the pipe in place of the standard error, no core dump is left behind +[[noreturn]] void crash_in_child(std::array const &Pipe, std::string const &Log) { + // a child stuck before the crash (a lock some other thread held at the fork) ends anyway, and the test with it + alarm(10); + dup2(Pipe[1], STDERR_FILENO); + close(Pipe[0]); + close(Pipe[1]); + rlimit const nocore{0, 0}; + setrlimit(RLIMIT_CORE, &nocore); + + crash_signals::install("test version 1.2"); + crash_signals::set_log_path(Log); + raise(SIGSEGV); + _exit(0); // not reached: the signal ends the child +} + +} // namespace + +TEST_CASE("crash signals: a crash writes its stack to the log and to the standard error, and still ends by its signal") { + test::scratch_folder const folder{"crash_signals"}; + auto const log{folder.write("log.txt", "the last line of the log\n")}; + + std::array pipe_ends{}; + REQUIRE(pipe(pipe_ends.data()) == 0); + auto const child{fork()}; + REQUIRE(child >= 0); + if (child == 0) + crash_in_child(pipe_ends, log); + + close(pipe_ends[1]); + auto const errors{read_all(pipe_ends[0])}; + close(pipe_ends[0]); + int status{0}; + REQUIRE(waitpid(child, &status, 0) == child); + + CAPTURE(errors); + // the process ends as it would without the handler + CHECK(WIFSIGNALED(status)); + CHECK(WTERMSIG(status) == SIGSEGV); + // the report on the standard error, which the starter shows + CHECK(errors.find("Crash: signal 11 (SIGSEGV) at address 0x") != std::string::npos); + CHECK(errors.find("Version: test version 1.2") != std::string::npos); + CHECK(errors.find("Stack (addr2line") != std::string::npos); + // with the frames of the program that crashed + CHECK(errors.find("eu07_unit_tests") != std::string::npos); + // and the same at the end of the log, after what it held + auto const logtext{read_file(log)}; + CAPTURE(logtext); + CHECK(logtext.starts_with("the last line of the log\n")); + CHECK(logtext.find("Crash: signal 11 (SIGSEGV)") != std::string::npos); + CHECK(logtext.find("eu07_unit_tests") != std::string::npos); +} + +#endif diff --git a/tests/unit/test_editor_http.cpp b/tests/unit/test_editor_http.cpp new file mode 100644 index 000000000..ffdfe9959 --- /dev/null +++ b/tests/unit/test_editor_http.cpp @@ -0,0 +1,138 @@ +#include "stdafx.h" +#include "doctest.h" +#include "editor/editorHttp.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +// a service on this machine. with no reply it takes the connection and the request and never answers, as geoportal.gov.pl +// does now and then +class local_server { + public: + explicit local_server(std::string Reply = {}) : + m_reply(std::move(Reply)) { + m_acceptor.open(asio::ip::tcp::v4()); + m_acceptor.bind({asio::ip::address_v4::loopback(), 0}); + m_acceptor.listen(); + m_port = m_acceptor.local_endpoint().port(); + m_thread = std::jthread{[this]() { serve(); }}; + } + ~local_server() { + m_done = true; + // a connection of its own wakes the server waiting for one + asio::ip::tcp::socket wake{m_context}; + asio::error_code ignored; + wake.connect({asio::ip::address_v4::loopback(), m_port}, ignored); + wake.close(ignored); + m_thread.join(); + } + local_server(local_server const &) = delete; + local_server &operator=(local_server const &) = delete; + + std::string url() const { + return std::format("http://127.0.0.1:{}/wcs?REQUEST=GetCapabilities", m_port); + } + + private: + void serve() { + while (false == m_done) { + asio::ip::tcp::socket socket{m_context}; + asio::error_code error; + m_acceptor.accept(socket, error); + if (error) + return; + if (false == m_reply.empty()) { + answer(socket); + continue; + } + // the request is left without an answer, the connection open, until the server goes + while (false == m_done) + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + } + + // the reply once the whole request is read, then the connection closed + void answer(asio::ip::tcp::socket &Socket) const { + asio::error_code error; + asio::streambuf request; + asio::read_until(Socket, request, "\r\n\r\n", error); + if (!error) + asio::write(Socket, asio::buffer(m_reply), error); + Socket.shutdown(asio::ip::tcp::socket::shutdown_both, error); + } + + std::string const m_reply; + asio::io_context m_context; + asio::ip::tcp::acceptor m_acceptor{m_context}; + unsigned short m_port{0}; + std::atomic m_done{false}; + std::jthread m_thread; +}; + +// the requests to the local server would go to a proxy named in the environment, which can't reach it +bool proxied() { + for (char const *variable : {"http_proxy", "HTTP_PROXY", "all_proxy", "ALL_PROXY"}) { + if (char const *value{std::getenv(variable)}; value != nullptr && *value != '\0') + return true; + } + return false; +} + +} // namespace + +TEST_CASE("editor http: a request a service doesn't answer is given up as soon as a stop is asked for") { + if (false == editor_http::available() || proxied()) + return; // a build with no http client, or a proxy in the way + local_server server; + auto const start{std::chrono::steady_clock::now()}; + auto const elapsed = [start]() { return std::chrono::duration(std::chrono::steady_clock::now() - start).count(); }; + editor_http::client client; + std::vector data; + std::string error; + // the stop comes while the client waits for the answer, long before any of its timeouts + auto const got{client.get(server.url(), data, error, [&elapsed]() { return elapsed() > 0.3; })}; + CHECK_FALSE(got); + CHECK_FALSE(error.empty()); + // the receive timeout is 20 s; the transfer ends within a moment of the stop (libcurl looks at it about once a second) + CHECK(elapsed() < 5.0); +} + +TEST_CASE("editor http: the whole body of a response is read") { + if (false == editor_http::available() || proxied()) + return; + std::string body(100000, '\0'); + for (std::size_t i = 0; i < body.size(); ++i) + body[i] = static_cast('a' + i % 26); + local_server server{std::format("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", body.size(), body)}; + editor_http::client client; + std::vector data; + std::string error; + CHECK(client.get(server.url(), data, error, []() { return false; })); + CHECK(error.empty()); + CHECK(std::string(data.begin(), data.end()) == body); +} + +TEST_CASE("editor http: the body of an error is kept with the status in the error") { + if (false == editor_http::available() || proxied()) + return; + // the terrain model service tells a place outside of its coverage in the body of an error + std::string const body{"outside requested coverage"}; + local_server server{std::format("HTTP/1.1 400 Bad Request\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", body.size(), body)}; + editor_http::client client; + std::vector data; + std::string error; + CHECK_FALSE(client.get(server.url(), data, error, []() { return false; })); + CHECK(error == "HTTP 400"); + CHECK(std::string(data.begin(), data.end()) == body); +} diff --git a/tests/unit/test_physicslog.cpp b/tests/unit/test_physicslog.cpp index 32fadec03..7a341b4f1 100644 --- a/tests/unit/test_physicslog.cpp +++ b/tests/unit/test_physicslog.cpp @@ -7,14 +7,10 @@ #include #include #include -#include -#include #include #include #include #include -#include -#include // the physics logs are kept and written by a thread of their own every so often, each file opened only to be written to @@ -126,18 +122,6 @@ TEST_CASE("physicslog: stopping writes what is kept at once, and what comes afte CHECK(folder.read("EN57-1001") == std::string{header} + "0.0500 0.0000\r\n0.1000 0.0000\r\n"); } -TEST_CASE("physicslog: stopping drops the logs past the time it waits for them") { - log_folder folder{"closingwait"}; - { - physicslog_writer logs{folder.path(), std::chrono::hours{1}, std::chrono::milliseconds{0}}; - logs.begin("EU07-005", header); - logs.append("EU07-005", "0.0500 0.0000\r\n"); - logs.stop(); - // the writing of the stop, left behind, is waited for by the writer going - } - CHECK_FALSE(std::filesystem::exists(folder.path() / "EU07-005.dat")); -} - TEST_CASE("physicslog: the lines of a log whose file can't be written are kept, with its header, for the next try") { log_folder folder{"failed"}; physicslog_writer logs{folder.path(), std::chrono::hours{1}}; @@ -157,63 +141,6 @@ TEST_CASE("physicslog: the lines of a log whose file can't be written are kept, CHECK(folder.read("EU07-005") == std::string{header} + "0.0500 0.0000\r\n0.1000 0.5000\r\n0.1500 1.0000\r\n"); } -TEST_CASE("physicslog: a log whose file can't be written keeps the lines given as values too, in the order given with the text") { - log_folder folder{"failedvalues"}; - physicslog_writer logs{folder.path(), std::chrono::hours{1}}; - - physicslog_values first; - first.time = 0.05; - physicslog_values second; - second.time = 0.10; - physicslog_values last; - last.time = 0.20; - std::filesystem::create_directories(folder.path() / "EU07-008.dat"); - logs.begin("EU07-008", header); - logs.append("EU07-008", first); - logs.flush(); - // given while the file can't be written: after the lines kept, as text and as values - logs.append("EU07-008", second); - logs.append("EU07-008", "text\r\n"); - logs.append("EU07-008", last); - logs.flush(); - CHECK(std::filesystem::is_directory(folder.path() / "EU07-008.dat")); - - std::filesystem::remove(folder.path() / "EU07-008.dat"); - logs.flush(); - auto const text{folder.read("EU07-008")}; - CHECK(text.starts_with(std::string{header} + "0.0500 ")); - CHECK(text.find("\r\n0.1000 ") != std::string::npos); - CHECK(text.find("\r\ntext\r\n0.2000 ") != std::string::npos); - CHECK(text.find("0.1000 ") < text.find("\r\ntext\r\n")); -} - -TEST_CASE("physicslog: the logs put first are written before the others, each in the order of the names") { - // the logs of a writing as the writer has them, by their names - std::map taken{{"EN57-1001", 0}, {"EU07-005", 0}, {"SM42-002", 0}, {"ST44-001", 0}, {"ET22-001", 0}}; - std::vector *> order; - for (auto &log : taken) - order.push_back(&log); - physicslog_writer::writing_order(order, {"ST44-001", "SM42-002", "SP42-001"}); - std::vector names; - for (auto const *log : order) - names.push_back(log->first); - CHECK(names == std::vector{"SM42-002", "ST44-001", "EN57-1001", "ET22-001", "EU07-005"}); -} - -TEST_CASE("physicslog: a log put first is written as the others are") { - log_folder folder{"first"}; - physicslog_writer logs{folder.path(), std::chrono::hours{1}}; - - logs.put_first("SM42-002"); - logs.begin("EU07-005", header); - logs.append("EU07-005", "0.0500 0.0000\r\n"); - logs.begin("SM42-002", header); - logs.append("SM42-002", "0.0500 1.0000\r\n"); - logs.flush(); - CHECK(folder.read("EU07-005") == std::string{header} + "0.0500 0.0000\r\n"); - CHECK(folder.read("SM42-002") == std::string{header} + "0.0500 1.0000\r\n"); -} - TEST_CASE("physicslog: a log begun anew while its file can't be written drops what was kept for it") { log_folder folder{"failedbegun"}; physicslog_writer logs{folder.path(), std::chrono::hours{1}}; @@ -311,75 +238,3 @@ TEST_CASE("physicslog: what is kept is written when the writer goes") { } CHECK(folder.read("ST44-001") == std::string{header} + "0.0500 0.0000\r\n"); } - -TEST_CASE("physicslog: a log written by someone else before is added to after what it holds") { - log_folder folder{"after"}; - std::filesystem::create_directories(folder.path()); - { - std::ofstream before{folder.path() / "SU45-001.dat"}; - before << "earlier run\n"; - } - physicslog_writer logs{folder.path(), std::chrono::hours{1}}; - - logs.append("SU45-001", "0.0500 0.0000\r\n"); - logs.flush(); - logs.append("SU45-001", "0.1000 0.0000\r\n"); - logs.flush(); - CHECK(folder.read("SU45-001") == "earlier run\n0.0500 0.0000\r\n0.1000 0.0000\r\n"); -} - -TEST_CASE("physicslog: the writings go on every interval while they're quick, and less often once they take long") { - using namespace std::chrono_literals; - using duration = std::chrono::steady_clock::duration; - // quick: the interval - CHECK(physicslog_writer::wait_after(2000ms, duration{0}) == duration{2000ms}); - CHECK(physicslog_writer::wait_after(2000ms, duration{500ms}) == duration{2000ms}); - // a third of the interval: still the interval - CHECK(physicslog_writer::wait_after(2100ms, duration{700ms}) == duration{2100ms}); - // longer: three times the writing, the disk busy with the logs a quarter of the time - CHECK(physicslog_writer::wait_after(2000ms, duration{1s}) == duration{3s}); - CHECK(physicslog_writer::wait_after(2000ms, duration{3s}) == duration{9s}); - // five intervals at most, however long the writing took: the lines of a longer wait would make it longer still - CHECK(physicslog_writer::wait_after(2000ms, duration{4s}) == duration{10s}); - CHECK(physicslog_writer::wait_after(2000ms, duration{60s}) == duration{10s}); -} - -TEST_CASE("physicslog: a line given as its values is written as the stream of them always wrote it") { - log_folder folder{"values"}; - physicslog_writer logs{folder.path(), std::chrono::hours{1}}; - - physicslog_values line; - line.time = 0.05; - line.wheelspeed = 1.23456; - line.acceleration = -0.5; - line.mainctrl = 3; - line.direction = 1; - line.command = "ShuntVelocity"; - line.value1 = 40.0; - // a float of the vehicle, widened as the stream widened it - line.enginetemperature = 50.1f; - line.vehiclespeed = 36.0; - logs.begin("SM31-001", header); - logs.append("SM31-001", line); - logs.flush(); - CHECK(folder.read("SM31-001") == std::string{header} + - "0.0500 1.2346 -0.5000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 3 0 0.0000 0.0000 1 " - "ShuntVelocity 40.0000 0.0000 0 0 50.1000 0.0000 0.0000 0.0000 36.0000\r\n"); -} - -TEST_CASE("physicslog: lines given as values and as text are written in the order given") { - log_folder folder{"order"}; - physicslog_writer logs{folder.path(), std::chrono::hours{1}}; - - physicslog_values first; - first.time = 0.05; - physicslog_values last; - last.time = 0.15; - logs.append("EP09-001", first); - logs.append("EP09-001", "text\r\n"); - logs.append("EP09-001", last); - logs.flush(); - auto const text{folder.read("EP09-001")}; - CHECK(text.starts_with("0.0500 ")); - CHECK(text.find("\r\ntext\r\n0.1500 ") != std::string::npos); -} diff --git a/tests/unit/test_track_uneven.cpp b/tests/unit/test_track_uneven.cpp index b55de1644..a97791a32 100644 --- a/tests/unit/test_track_uneven.cpp +++ b/tests/unit/test_track_uneven.cpp @@ -63,7 +63,8 @@ TEST_CASE("uneven track: the cab keeps what the ride on the track doesn't stand TEST_CASE("uneven track: measures as the Id-14 limits for its value") { // appendix 1, class C at 80 km/h: 18 mm vertically, 17 mm sideways, 16 mm of twist on 5 m, gauge +10/-8 mm, 20 mm of cross level, J = 5.3 - auto const amplitude{track_uneven::stray_per_mm * 18.0 * 1000.0}; // mm + auto const amplitude{track_uneven::stray_up_per_mm * 18.0 * 1000.0}; // mm + auto const sideways{track_uneven::stray_side_per_mm * 18.0 * 1000.0}; // mm double const gauge{1.435}; double const step{0.5}; int const steps{4000}; @@ -76,6 +77,7 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") double level{0.0}; double j{0.0}; double away{0.0}; + double aside{0.0}; for (int line = 0; line < lines; ++line) { auto const heading{glm::pi() * (line + 0.37) / lines}; @@ -85,6 +87,7 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") std::array, 2> up; std::array, 2> side; std::vector middle; + std::vector across_middle; for (int i = 0; i < steps; ++i) { auto const point{start + along * (i * step)}; @@ -93,9 +96,11 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") auto const sign{rail == 0 ? 1.0 : -1.0}; auto const stray{track_uneven::field(point + across * (sign * 0.5 * gauge))}; up[rail].push_back((stray.y - sign * 0.5 * track_uneven::level(point, across)) * amplitude); - side[rail].push_back(glm::dot(stray, across) * amplitude); + side[rail].push_back(glm::dot(stray, across) * sideways); } - middle.push_back(track_uneven::field(point).y * amplitude); + auto const centre{track_uneven::field(point)}; + middle.push_back(centre.y * amplitude); + across_middle.push_back(glm::dot(centre, across) * sideways); } std::vector verticals; std::vector horizontals; @@ -120,6 +125,7 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") wander += peak(gauges) / lines; level += peak(levels) / lines; away += peak(middle) / lines; + aside += peak(across_middle) / lines; j += (deviation(verticals) + deviation(horizontals) + deviation(twists) + 0.5 * deviation(gauges)) / 3.5 / lines; } CHECK(vertical == doctest::Approx(18.0).epsilon(0.1)); @@ -128,7 +134,11 @@ TEST_CASE("uneven track: measures as the Id-14 limits for its value") CHECK(wander == doctest::Approx(10.0).epsilon(0.2)); CHECK(level == doctest::Approx(20.0).epsilon(0.1)); CHECK(j == doctest::Approx(5.3).epsilon(0.2)); - CHECK(away < 40.0); // the long waves go past the 15 mm off the survey marks of appendix 1a + // the long waves go past the 15 mm off the survey marks of appendix 1a: most of the height of a track spectrum is in them, the 10 m chord + // hardly sees them + CHECK(away < 60.0); + // and sideways: about 4.5 cm, which a platform edge or the panels of a level crossing laid on the design are off the rails by + CHECK(aside < 50.0); } TEST_CASE("uneven track: a place strays the same every time") @@ -136,11 +146,11 @@ TEST_CASE("uneven track: a place strays the same every time") // no random numbers: changing these changes how every uneven track in every scenery looks glm::dvec3 const place{1234.5, 0.0, -678.9}; auto const stray{track_uneven::field(place)}; - CHECK(stray.x == doctest::Approx(0.309777548158).epsilon(1e-9)); - CHECK(stray.y == doctest::Approx(0.311350299745).epsilon(1e-9)); - CHECK(stray.z == doctest::Approx(-0.328429734019).epsilon(1e-9)); - CHECK(track_uneven::level(place, {1.0, 0.0, 0.0}) == doctest::Approx(0.53 * -0.178598957983).epsilon(1e-9)); - CHECK(track_uneven::level(place, {0.0, 0.0, 1.0}) == doctest::Approx(0.53 * -0.868291889902).epsilon(1e-9)); + CHECK(stray.x == doctest::Approx(0.158385385505).epsilon(1e-9)); + CHECK(stray.y == doctest::Approx(0.356190053667).epsilon(1e-9)); + CHECK(stray.z == doctest::Approx(0.200372098150).epsilon(1e-9)); + CHECK(track_uneven::level(place, {1.0, 0.0, 0.0}) == doctest::Approx(0.35 * -0.178598957983).epsilon(1e-9)); + CHECK(track_uneven::level(place, {0.0, 0.0, 1.0}) == doctest::Approx(0.35 * -0.868291889902).epsilon(1e-9)); } TEST_CASE("uneven track: tracks laid towards each other meet at one cant") diff --git a/tests/unit/test_utilities.cpp b/tests/unit/test_utilities.cpp index 48d10e8b1..458b79eed 100644 --- a/tests/unit/test_utilities.cpp +++ b/tests/unit/test_utilities.cpp @@ -2,9 +2,15 @@ #include "doctest.h" #include "scratch.h" +#include +#include + #include "utilities/Globals.h" #include "utilities/utilities.h" +#include +#include + // the helpers of utilities/utilities.cpp and utilities.h as they behave now: the numbers and texts they give, their // oddities included. the ones which look like mistakes are listed in COVERAGE.md. the helpers which read from a // parser (LoadPoint, the sets, the map) are in test_parser.cpp @@ -112,16 +118,31 @@ TEST_CASE("utilities: clearing a flag needs all of its bits set") { TEST_CASE("utilities: random whole numbers are within the bounds, both included, given in any order") { std::set seen; for (auto draw{0}; draw < 200; ++draw) { - auto const value{Random(3, 7)}; + auto const value{RandomInt(3, 7)}; CHECK(value >= 3); CHECK(value <= 7); seen.insert(value); - auto const swapped{Random(7, 3)}; + auto const swapped{RandomInt(7, 3)}; CHECK(swapped >= 3); CHECK(swapped <= 7); } CHECK(seen.size() == 5); - CHECK(Random(5, 5) == 5); + CHECK(RandomInt(5, 5) == 5); +} + +TEST_CASE("utilities: whole-number bounds still give a real number in between") { + // the wind, the wheel flats, the truck hunting and the tachometer draw with whole-number bounds + static_assert(std::is_same_v); + auto fractions{0}; + for (auto draw{0}; draw < 50; ++draw) { + auto const value{Random(0, 4)}; + CHECK(value >= 0.0); + CHECK(value <= 4.0); + if (value != std::floor(value)) { + ++fractions; + } + } + CHECK(fractions > 0); } TEST_CASE("utilities: random numbers are within the bounds given in any order") { @@ -154,17 +175,37 @@ TEST_CASE("utilities: random numbers are within the bounds given in any order") } TEST_CASE("utilities: the same seed gives the same random numbers") { - std::vector first; + std::vector first; Global.random_engine.seed(42); for (auto draw{0}; draw < 5; ++draw) { - first.push_back(Random(0, 1000000)); + first.push_back(Random(0.0, 1000000.0)); } - std::vector second; + std::vector second; Global.random_engine.seed(42); for (auto draw{0}; draw < 5; ++draw) { - second.push_back(Random(0, 1000000)); + second.push_back(Random(0.0, 1000000.0)); } CHECK(first == second); + std::vector localfirst; + Global.local_random_engine.seed(42); + for (auto draw{0}; draw < 5; ++draw) { + localfirst.push_back(RandomInt(0, 1000000)); + } + std::vector localsecond; + Global.local_random_engine.seed(42); + for (auto draw{0}; draw < 5; ++draw) { + localsecond.push_back(RandomInt(0, 1000000)); + } + CHECK(localfirst == localsecond); +} + +TEST_CASE("utilities: the whole numbers are drawn from the local engine, not from that of the run's seed") { + // the trivia of the loading screen is drawn before a network client gets the seed of the session + Global.random_engine.seed(5); + auto const first{Random()}; + Global.random_engine.seed(5); + RandomInt(0, 9); + CHECK(Random() == first); } TEST_CASE("utilities: the local random numbers have an engine of their own") { @@ -681,12 +722,30 @@ TEST_CASE("utilities: the sign of a number, and a number rounded to a whole one" CHECK(Round(-2.5) == -2); } -TEST_CASE("utilities: a value is kept within bounds, given in any order") { +TEST_CASE("utilities: a value is kept within bounds; inverted bounds give the upper one, as the old clamp did") { CHECK(safe_clamp(5, 0, 3) == 3); - CHECK(safe_clamp(5, 3, 0) == 3); - CHECK(safe_clamp(-1, 3, 0) == 0); - CHECK(safe_clamp(2.0, 3.0, 1.0) == 2.0); + CHECK(safe_clamp(-1, 0, 3) == 0); + CHECK(safe_clamp(2, 0, 3) == 2); CHECK(safe_clamp(2.0, 2.0, 2.0) == 2.0); + // inverted bounds: always the upper bound, whatever the value + CHECK(safe_clamp(5, 3, 0) == 0); + CHECK(safe_clamp(-1, 3, 0) == 0); + CHECK(safe_clamp(2.0, 3.0, 1.0) == 1.0); + // NaN as the old clamp had it: a NaN value stays NaN, a NaN bound doesn't clamp + auto const notanumber{std::numeric_limits::quiet_NaN()}; + CHECK(std::isnan(safe_clamp(notanumber, 0.0, 1.0))); + CHECK(safe_clamp(2.0, 0.0, notanumber) == 2.0); + CHECK(safe_clamp(-1.0, notanumber, 1.0) == -1.0); + // what the helper gives for arguments in the order and of the signs of two calls (these checks don't call + // them): the AI braking test, whose demand is the stronger of the two (negative) bounds, as up to 26.05.1 + double const threshold{-0.45}; + CHECK(safe_clamp(0.3, threshold * 1.01, threshold * 1.21) == doctest::Approx(threshold * 1.21)); + CHECK(safe_clamp(-0.6, threshold * 1.01, threshold * 1.21) == doctest::Approx(threshold * 1.21)); + // and the bump at a rail joint, 0 in place of the value as up to 26.05.1: the figure is capped from above + // only, and above 68% of the top speed it is negative + CHECK(safe_clamp(0.0, 160.0, 160.0 - (150.0 + 160.0 * 0.32)) == doctest::Approx(-41.2)); + CHECK(safe_clamp(0.0, 4.0, -0.5) == -0.5); + CHECK(safe_clamp(0.0, 4.0, 5.0) == 4.0); } TEST_CASE("utilities: a value is wrapped into a range, as an angle into the full circle") { diff --git a/tools/track_uneven_grade.py b/tools/track_uneven_grade.py index 81df2ce2a..ba60be900 100644 --- a/tools/track_uneven_grade.py +++ b/tools/track_uneven_grade.py @@ -38,10 +38,10 @@ CURVE_STEP = 1.0 / 2500.0 # a difference of curvature that counts as a change, RISE = 0.0273 * 4.5 # how fast pressure lifts a pantograph, m/s, by TDynamicObject::Update GAP_MOST = 0.006 # the gap to the wire allowed; at 0.01 m the voltage goes and the main breaker trips OVERSPEED = 1.1 # a driver can go this much over the speed of the track -# as up_waves and the dip of the joints in world/TrackUneven.h -STRAY_PER_MM, DIP_SHARE, DIP_REACH = 0.00145, 0.4, 3.0 +# as up_waves, stray_up_per_mm and the dip of the joints in world/TrackUneven.h +STRAY_PER_MM, DIP_SHARE, DIP_REACH = 0.00229, 0.4, 3.0 GOLDEN = math.pi * (3.0 - math.sqrt(5.0)) -UP_WAVES = [(2 * math.pi / length * math.cos(GOLDEN * i), 2 * math.pi / length * math.sin(GOLDEN * i), GOLDEN * (i + 1), share) for i, (length, share) in enumerate(zip((8.3, 11.9, 16.7, 23.9, 37.1, 47.3, 61.9, 83.3), (.14, .19, .22, .22, .23, .23, .23, .23)))] +UP_WAVES = [(2 * math.pi / length * math.cos(GOLDEN * i), 2 * math.pi / length * math.sin(GOLDEN * i), GOLDEN * (i + 1), share) for i, (length, share) in enumerate(zip((8.0, 11.6, 16.9, 24.6, 35.8, 52.0, 75.6, 110.0), (.0761, .1058, .1393, .176, .2175, .2651, .3215, .3887)))] TOKEN = re.compile(r"//[^\n]*|\S+") NUMBER = re.compile(r"^[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?$") diff --git a/track_uneven_doc.md b/track_uneven_doc.md index e4822b971..1899abdc3 100644 --- a/track_uneven_doc.md +++ b/track_uneven_doc.md @@ -46,15 +46,17 @@ A track with `uneven 18` measures as follows (`tests/unit/test_track_uneven.cpp` | parameter | result | Id-14 | |--------------------------|--------|-----------| | vertical irregularities | 18 mm | 18 mm | -| horizontal irregularities | 19 mm | 17 mm | +| horizontal irregularities | 17 mm | 17 mm | | twist on a 5 m base | 15 mm | 16 mm | | gauge | ±10 mm | +10/-8 mm | -| cross level | 20 mm | 20 mm | -| J index | 6.1 | 5.3 | +| cross level | 21 mm | 20 mm | +| J index | 5.7 | 5.3 | + +Id-14 only gives the scale of the value: how a track at that value measures. What the waves look like follows the track spectra of the literature, see "How it works". ## How it works -Unevenness is a displacement field that depends on the position on the map, made of waves 5-42 m long. Vertically there are fewer short waves, so the rails come near the peak value more often, and there are also waves of 47-83 m: they hardly count on the 10 m chord, the body rises and falls on them, and a pantograph keeps up with them. Nothing in it is random: one place bends the same way on every run. A track that is moved gets the waves of its new place. +Unevenness is a displacement field that depends on the position on the map, made of waves 7-90 m long sideways and 8-110 m long vertically, about the bands D1-D3 of EN 13848. Their heights follow the shape of the track spectra of the US FRA and of ORE B176 (the German spectrum): a power spectral density of `Wc² / (W² (W² + Wc²))`, `Wc = 0.8245 rad/m`, so the longer a wave, the higher it is. Most of the height is in the long waves: they hardly count on the 10 m chord, the body rises and falls on them slowly, and the cab hardly feels them. At `uneven 18` a track goes up to about 5 cm up or down and about 4.5 cm sideways off its design over the long waves, and the short ones of 7-10 m, the ones the cab shakes on, are a few millimetres. Nothing in it is random: one place bends the same way on every run. A track that is moved gets the waves of its new place. Each component joins separately: @@ -67,7 +69,7 @@ The ends of joined paths meet in the middle between them, with one vector across The rails, the top of the ballast, `sleepermodel`, the axles, the roll of the body and the cab shake follow the unevenness. The slope of the ballast takes up the difference, and its foot stays as designed, on the ground. -Models from includes (e.g. switch drives and timbers), the terrain and the catenary don't follow it, so at large values a rail shifts away from such a model by a few centimetres. +Models from includes (e.g. switch drives and timbers), platform edges, level crossing panels, the terrain and the catenary don't follow it, so at large values a rail shifts away from such a model by a few centimetres, sideways up to about 4.5 cm at `uneven 18`. On a track with unevenness the track itself shakes the cab, in place of two of the sources of shake that were there before, as far as it has something to put in their place. It goes by the track under the vehicle, and on a switch by the path set and what its joined tracks allow. Dips at the joints and cross level replace nothing, as they don't shake the cab all the way along or sideways. On tracks with no unevenness everything works as before. @@ -83,7 +85,7 @@ On a track with unevenness the track itself shakes the cab, in place of two of t This is about the cab only. The physics, derailment included, and the noise of the wheels still use the lateral acceleration. -A pantograph rises at the rate set by the pressure, about 0.14 m/s, and a gap to the wire over 1 cm cuts the voltage and trips the main breaker. Unevenness adds to this at high speed. On the tracks of Bałtyk a simulation gives a gap of 0.6 cm when the vertical value times the speed in km/h is 925, for example 8 mm at 120 km/h, 13 mm at 70 km/h and 23 mm at 40 km/h. The values in the Id-14 table are higher than that. The wire alone can do it too: at `tor0290` on Bałtyk it rises by about 1%, so a pantograph keeps up to about 46 km/h there, and above that the breaker trips on a straight track as well. +A pantograph rises at the rate set by the pressure, about 0.14 m/s, and a gap to the wire over 1 cm cuts the voltage and trips the main breaker. Unevenness adds to this at high speed. On the tracks of Bałtyk a simulation gives a gap of 0.6 cm when the vertical value times the speed in km/h is 1150, for example 9.6 mm at 120 km/h, 16 mm at 70 km/h and 29 mm at 40 km/h. The values in the Id-14 table are higher than that. The wire alone can do it too: at `tor0290` on Bałtyk it rises by about 1%, so a pantograph keeps up to about 46 km/h there, and above that the breaker trips on a straight track as well. The physics takes the curve radius and the grade from the design, so unevenness doesn't change them. It adds only the cross level towards derailment, about 0.06 m/s² at `uneven 18` against a threshold of about 3.2 m/s². diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 90c206dfa..e920849b2 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -1410,6 +1410,12 @@ bool global_settings::ConfigParseDebug(cParser& Parser, const std::string& token return true; } + if (token == "crashdump.full") + { + ParseOne(Parser, CrashDumpFull); + return true; + } + if (token == "showsystemconsole") { ParseOne(Parser, ShowSystemConsole); @@ -1890,6 +1896,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "fullphysics", FullPhysics ); export_as_text( Output, "debuglog", iWriteLogEnabled ); export_as_text( Output, "multiplelogs", MultipleLogs ); + export_as_text( Output, "crashdump.full", CrashDumpFull ); export_as_text( Output, "showsystemconsole", ShowSystemConsole ); export_as_text( Output, "logs.filter", DisabledLogTypes ); Output diff --git a/utilities/Globals.h b/utilities/Globals.h index ceb9948c4..3b1441240 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -119,6 +119,10 @@ struct global_settings { bool priorityLoadText3D{false}; // ladowanie T3D priorytetowo int iWriteLogEnabled{ 3 }; // maska bitowa: 1-zapis do pliku, 2-okienko, 4-nazwy torów bool MultipleLogs{ false }; + // the dump written when the simulator crashes (Windows): a small one by default, with the stacks, the threads, the + // modules, the memory the stacks point to and the modules' data. "crashdump.full yes" writes all the memory of the + // simulator instead, as large as the memory it took + bool CrashDumpFull{ false }; // the black box of the session (blackbox_doc.md): "blackbox yes" writes it whatever the physics logs, "blackbox no" // never, and with no entry it is written along with the physics logs std::optional BlackBox; @@ -201,6 +205,12 @@ struct global_settings { bool EditorOrtho{ false }; float EditorOrthoExtent{ 150.f }; int EditorOrthoTracks{ 0 }; // the railway in the top view of the editor: 0 whole, 1 without the ballast, 2 the rails alone + // the free camera of the editor: its speed set in the View menu, the Ctrl multiplier of it, and in the top view whether it goes as far + // as the view reaches, so the map moves across the screen as fast zoomed in as out + bool EditorCameraOn{ false }; // the editor is on: its camera goes by the settings below + double EditorCameraSpeed{ 1.0 }; + double EditorCameraFast{ 30.0 }; + bool EditorCameraZoomed{ false }; GLint iMaxTextureSize{ 4096 }; // maksymalny rozmiar tekstury GLint iMaxCabTextureSize{ 4096 }; // largest allowed texture in vehicle cab int iMultisampling{ 2 }; // tryb antyaliasingu: 0=brak,1=2px,2=4px,3=8px,4=16px diff --git a/utilities/Logs.cpp b/utilities/Logs.cpp index e0949aba6..f4032d808 100644 --- a/utilities/Logs.cpp +++ b/utilities/Logs.cpp @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "utilities/Logs.h" +#include "utilities/crashsignals.h" #include @@ -115,6 +116,8 @@ void LogService() { std::string filename = Global.MultipleLogs ? "logs/log (" + filename_scenery() + ") " + filename_date() + ".txt" : "log.txt"; output.open(filename, std::ios::trunc); + // the stack of a crash on Linux goes to the end of this file + crash_signals::set_log_path(filename); } output << msg << "\n"; output.flush(); diff --git a/utilities/crashsignals.cpp b/utilities/crashsignals.cpp new file mode 100644 index 000000000..fa62e8955 --- /dev/null +++ b/utilities/crashsignals.cpp @@ -0,0 +1,234 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "utilities/crashsignals.h" + +#if defined(__linux__) + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace { + +// the handler may only call what is safe in a signal: no allocation, no locks, no streams. so what it needs is +// kept in fixed buffers, filled in beforehand, and written with write() + +constexpr std::array crash_signal_list{SIGSEGV, SIGBUS, SIGFPE, SIGILL, SIGABRT}; +// a handler that hangs (a crash inside the allocator or the loader, which backtrace() may need) ends this long after +constexpr unsigned int crash_report_timeout_seconds{5}; + +// a text of fixed size, filled outside the handler and read in it +template struct fixed_text { + std::array text{}; + std::atomic ready{false}; + + void set(std::string_view const Text) { + ready = false; + auto const length{std::min(Text.size(), text.size() - 1)}; + std::copy_n(Text.data(), length, text.data()); + text[length] = '\0'; + ready = true; + } + char const *get() const { return ready ? text.data() : nullptr; } +}; + +fixed_text<1024> &log_path() { + static fixed_text<1024> path; + return path; +} + +fixed_text<256> &version_text() { + static fixed_text<256> version; + return version; +} + +// the stack the handler runs on, so an overflow of the main thread's own stack is reported too +std::array &alternate_stack() { + static std::array stack{}; + return stack; +} + +void write_all(int const File, std::string_view Text) { + while (false == Text.empty()) { + auto const written{::write(File, Text.data(), Text.size())}; + if (written <= 0) + return; + Text.remove_prefix(static_cast(written)); + } +} + +void write_hex(int const File, std::uintptr_t const Value) { + constexpr std::size_t digits{sizeof(Value) * 2}; + constexpr std::string_view hexdigits{"0123456789abcdef"}; + std::array text{'0', 'x'}; + for (std::size_t digit = 0; digit < digits; ++digit) + text[2 + digit] = hexdigits[(Value >> (4 * (digits - 1 - digit))) & 0xF]; + write_all(File, {text.data(), text.size()}); +} + +void write_decimal(int const File, int const Value) { + std::array text{}; + auto position{text.size()}; + auto rest{static_cast(Value < 0 ? -Value : Value)}; + do { + text[--position] = static_cast('0' + rest % 10); + rest /= 10; + } while (rest != 0 && position > 1); + if (Value < 0) + text[--position] = '-'; + write_all(File, {text.data() + position, text.size() - position}); +} + +std::string_view signal_name(int const Signal) { + switch (Signal) { + case SIGSEGV: + return "SIGSEGV"; + case SIGBUS: + return "SIGBUS"; + case SIGFPE: + return "SIGFPE"; + case SIGILL: + return "SIGILL"; + case SIGABRT: + return "SIGABRT"; + default: + return "?"; + } +} + +// the signal being reported, for a report that hangs +std::atomic &crash_signal() { + static std::atomic signal{0}; + return signal; +} + +// a report that hangs is given up: the process ends by the signal of the crash, as it would have without the handler +void handle_report_timeout(int) { + auto const crashsignal{crash_signal().load()}; + raise(crashsignal); + // it is blocked while its own handler runs, which this one interrupted + sigset_t unblocked; + sigemptyset(&unblocked); + sigaddset(&unblocked, crashsignal); + sigprocmask(SIG_UNBLOCK, &unblocked, nullptr); +} + +struct crash_stack { + std::array frames{}; + int count{0}; +}; + +void write_report(int const File, int const Signal, siginfo_t const *Info, crash_stack const &Stack) { + write_all(File, "\nCrash: signal "); + write_decimal(File, Signal); + write_all(File, " ("); + write_all(File, signal_name(Signal)); + write_all(File, ")"); + // the address of the fault; an abort has none + if (Signal != SIGABRT && Info != nullptr) { + write_all(File, " at address "); + write_hex(File, reinterpret_cast(Info->si_addr)); + } + write_all(File, "\n"); + if (auto const *version{version_text().get()}) { + write_all(File, "Version: "); + write_all(File, version); + write_all(File, "\n"); + } + write_all(File, "Stack (addr2line -f -C -e ):\n"); + backtrace_symbols_fd(Stack.frames.data(), Stack.count, File); +} + +void handle_crash_signal(int const Signal, siginfo_t *Info, void *) { + crash_signal() = Signal; + struct sigaction timeout{}; + timeout.sa_handler = handle_report_timeout; + sigemptyset(&timeout.sa_mask); + sigaction(SIGALRM, &timeout, nullptr); + alarm(crash_report_timeout_seconds); + + crash_stack stack; + stack.count = backtrace(stack.frames.data(), static_cast(stack.frames.size())); + + if (auto const *path{log_path().get()}) { + if (auto const log{::open(path, O_WRONLY | O_APPEND | O_CLOEXEC)}; log >= 0) { + write_report(log, Signal, Info, stack); + ::close(log); + } + } + write_report(STDERR_FILENO, Signal, Info, stack); + + // the handler was taken off as it was called (SA_RESETHAND): the signal does what it always did + raise(Signal); +} + +} // namespace + +namespace crash_signals { + +void install(std::string_view const Version) { + static std::atomic installed{false}; + if (installed.exchange(true)) + return; + + version_text().set(Version); + + // backtrace() loads what it needs on its first call, which allocates: done here, not in the handler + std::array warmup{}; + backtrace(warmup.data(), static_cast(warmup.size())); + + stack_t alternate{}; + alternate.ss_sp = alternate_stack().data(); + alternate.ss_size = alternate_stack().size(); + sigaltstack(&alternate, nullptr); + + struct sigaction action{}; + action.sa_sigaction = handle_crash_signal; + action.sa_flags = SA_SIGINFO | SA_ONSTACK | SA_RESETHAND; + // another crash signal of the same thread waits until the report is written, rather than starting a second one in + // its middle (a fault that comes while it is blocked still ends the process). a crash of another thread at the + // same moment may still write its report alongside + sigemptyset(&action.sa_mask); + for (auto const crashsignal : crash_signal_list) + sigaddset(&action.sa_mask, crashsignal); + for (auto const crashsignal : crash_signal_list) + sigaction(crashsignal, &action, nullptr); +} + +void set_log_path(std::string_view const Path) { + // whole, so the report finds the file wherever the simulator stands then + std::error_code error; + auto const path{std::filesystem::absolute(std::filesystem::path{Path}, error)}; + log_path().set(error ? std::string{Path} : path.string()); +} + +} // namespace crash_signals + +#else + +namespace crash_signals { + +void install(std::string_view) {} +void set_log_path(std::string_view) {} + +} // namespace crash_signals + +#endif diff --git a/utilities/crashsignals.h b/utilities/crashsignals.h new file mode 100644 index 000000000..feb526869 --- /dev/null +++ b/utilities/crashsignals.h @@ -0,0 +1,25 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include + +// the stack of a crash on Linux, where no dump is written: a signal of a fault (SIGSEGV, SIGBUS, SIGFPE, SIGILL) or +// SIGABRT writes the stack of the thread that took it to the log and to the standard error, which the starter shows, +// and then ends the simulator as the signal always did (a core dump where the system makes one). the addresses are +// read with addr2line on the eu07 file of the same version, which carries its symbols. elsewhere it does nothing +namespace crash_signals { + +// sets the handlers up, once. Version goes into the report, to tell which eu07 file the addresses belong to +void install(std::string_view Version); +// the log file the report is added to, once the log has opened it +void set_log_path(std::string_view Path); + +} // namespace crash_signals diff --git a/utilities/physicslog.cpp b/utilities/physicslog.cpp index d37ea69e7..208fc7b01 100644 --- a/utilities/physicslog.cpp +++ b/utilities/physicslog.cpp @@ -14,22 +14,13 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include #include #include -#include -#include #include -#include #include #include #include -#if defined(__linux__) -#include -#include -#endif - physicslog_writer PhysicsLogs; namespace { @@ -76,64 +67,14 @@ void tell(std::string const &Text) noexcept { } } -// the disk work of the calling thread after everyone else's: the simulation reading its textures and sounds, and the -// pages of its memory, from the same disk doesn't wait behind the logs, which on a hard disk are seconds of seeking -// when there are hundreds of them -void lower_disk_priority() noexcept { -#ifdef _WIN32 - // the background mode: the thread's disk work at the very low priority, its memory pages the first to be let go of - // and, the documentation doesn't say, maybe its processor time lower too. a disk the simulation keeps busy without a - // pause serves the logs slowly then, the more lines waiting in memory meanwhile; a game reads in bursts, not without - // end. a thread which can't have it writes as it did before - static_cast(::SetThreadPriority(::GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN)); -#elif defined(__linux__) && defined(SYS_ioprio_set) - // the lowest of the best effort class rather than the idle one, which a disk always busy would never serve: the - // lines would be kept in memory with no end. the constants of linux/ioprio.h, which not every system has - constexpr int whothread{1}; // IOPRIO_WHO_PROCESS, of the calling thread with 0 - constexpr int classbesteffort{2}; - constexpr int classshift{13}; - constexpr int lowest{7}; - static_cast(::syscall(SYS_ioprio_set, whothread, 0, (classbesteffort << classshift) | lowest)); -#endif -} - } // namespace -void physicslog_values::append_to(std::string &Text) const { - std::ostringstream line; - line << std::fixed << std::setprecision(4) << time << " " << wheelspeed << " " << acceleration << " " << couplerdistance << " " << couplerforce << " " - << tractionforce << " " << frictionforce << " " << brakeforce << " " << brakepressure << " " << pipepressure << " " << motorcurrent << " " - << mainctrl << " " << scndctrl << " " << brakectrl << " " << localbrake << " " << direction << " " << command << " " << value1 << " " - << value2 << " " << security << " " << wheelslip << " " << enginetemperature << " " << oiltemperature << " " << watertemperature << " " - << wateraux << " " << vehiclespeed << "\r\n"; - Text.append(line.str()); -} - -void physicslog_writer::pending::to_text() { - if (values.empty()) - return; - // made aside and added at once: a text which can't be made, out of memory, leaves the log as it was - std::string lines; - for (auto const &line : values) - line.append_to(lines); - text.append(lines); - values.clear(); -} - -physicslog_writer::physicslog_writer(std::filesystem::path Folder, std::chrono::milliseconds const Interval, std::chrono::milliseconds const ClosingWait) : - m_folder{std::move(Folder)}, m_shownfolder{m_folder.generic_string()}, m_interval{Interval}, m_closingwait{ClosingWait} {} +physicslog_writer::physicslog_writer(std::filesystem::path Folder, std::chrono::milliseconds const Interval) : + m_folder{std::move(Folder)}, m_shownfolder{m_folder.generic_string()}, m_interval{Interval} {} physicslog_writer::~physicslog_writer() { try { stop(); - // the writings left behind by the stops use the object, which goes - std::vector> closings; - { - std::scoped_lock lock{m_mutex}; - closings.swap(m_closings); - } - for (auto const &closing : closings) - closing.wait(); } catch (...) { // at the end of the process: what the logs couldn't keep, memory or a file, isn't to end it worse } @@ -145,33 +86,18 @@ void physicslog_writer::begin(std::string const &Name, std::string_view const He lines.fresh = true; lines.header.assign(Header); lines.text.clear(); - lines.values.clear(); start(); } void physicslog_writer::append(std::string const &Name, std::string_view const Line) { std::scoped_lock lock{m_mutex}; - auto &lines{m_pending[Name]}; - // after the lines given as values before it - lines.to_text(); - lines.text.append(Line); + m_pending[Name].text.append(Line); start(); } -void physicslog_writer::append(std::string const &Name, physicslog_values Values) { - std::scoped_lock lock{m_mutex}; - m_pending[Name].values.push_back(std::move(Values)); - start(); -} - -void physicslog_writer::put_first(std::string const &Name) { - std::scoped_lock lock{m_mutex}; - m_first.insert(Name); -} - void physicslog_writer::flush() { std::scoped_lock files{m_filemutex}; - write(writing::flush); + write(); } bool physicslog_writer::flush_for(std::chrono::milliseconds const Timeout) { @@ -180,7 +106,7 @@ bool physicslog_writer::flush_for(std::chrono::milliseconds const Timeout) { auto done{std::make_shared>()}; auto ended{done->get_future()}; std::thread([this, done] { - flush_safely(writing::flush); + flush_safely(); done->set_value(); }).detach(); return ended.wait_for(Timeout) == std::future_status::ready; @@ -189,16 +115,12 @@ bool physicslog_writer::flush_for(std::chrono::milliseconds const Timeout) { void physicslog_writer::stop() { std::jthread thread; bool itself; - closing_time closeby; { std::scoped_lock lock{m_mutex}; m_stopped = true; // taken by the first to stop, so it's joined once thread = std::move(m_thread); itself = m_writer == std::this_thread::get_id(); - // the time the closing's writing has: the logs not written by then are dropped. a writing the thread has begun - // ends at the log at hand, leaving the others to it - closeby = closing_begun(); } // the stop asked outside the lock, which waking the writer takes if (thread.joinable()) @@ -209,55 +131,9 @@ void physicslog_writer::stop() { thread.detach(); return; } - if (close_aside(thread, closeby)) - return; - // no thread for it, out of memory say: written here, the logs past the time dropped all the same if (thread.joinable()) thread.join(); - flush_safely(writing::closing); -} - -physicslog_writer::closing_time physicslog_writer::closing_begun() { - std::erase_if(m_closings, [](std::shared_future const &Closing) { return Closing.wait_for(std::chrono::seconds{0}) == std::future_status::ready; }); - // a closing not done yet keeps its time: a stop after it (the simulator stops the logs twice) doesn't wait the - // longer, nor give the writing of the first more of it - if (auto const before{m_closeby.load()}; before != 0 && false == m_closings.empty()) - return {std::chrono::steady_clock::time_point{std::chrono::steady_clock::duration{before}}, false}; - auto const closeby{std::chrono::steady_clock::now() + m_closingwait}; - m_closeby = closeby.time_since_epoch().count(); - return {closeby, true}; -} - -bool physicslog_writer::close_aside(std::jthread &Thread, closing_time const Closeby) noexcept { - // the thread ended and the rest written on a thread of its own, left behind if it isn't done in time: a disk which - // doesn't answer holds up the writing of a file, which no time given cuts short. the simulator ends with _Exit then, - // the writing with it - auto started{false}; - try { - auto done{std::make_shared>()}; - std::shared_future const closing{done->get_future()}; - { - std::scoped_lock lock{m_mutex}; - m_closings.push_back(closing); - } - // the writer moved into the lambda: if its thread can't be started, the writer is ended (joined) with it - std::thread([this, done, writer = std::move(Thread)]() mutable { - if (writer.joinable()) - writer.join(); - flush_safely(writing::closing); - done->set_value(); - }).detach(); - started = true; - // told by the stop which gave the time, not again by one after it - if (closing.wait_until(Closeby.by) != std::future_status::ready && Closeby.fresh) - tell(std::format("Bad physics log: the closing doesn't wait for the writing longer than {:.1f} s, the logs not written by then are lost", - std::chrono::duration{m_closingwait}.count())); - return true; - } catch (...) { - // out of memory, or no thread to be had: the writer, if it wasn't moved, is ended by the caller. a thread begun - // already, the line of the log failing after it, does the writing: not the caller as well, which would wait for it - return started; - } + flush_safely(); } std::filesystem::path physicslog_writer::file(std::string const &Name) const { @@ -279,12 +155,6 @@ std::string physicslog_writer::shown(std::string const &Name) const { return m_shownfolder + '/' + file_name(Name); } -std::chrono::steady_clock::duration physicslog_writer::wait_after(std::chrono::milliseconds const Interval, std::chrono::steady_clock::duration const Took) { - // no longer than five intervals: the lines of a longer wait would make the next writing take the longer still, the - // waits growing with no end, and a crash would lose more of them - return std::clamp(Took * 3, Interval, Interval * 5); -} - void physicslog_writer::start() { if (m_stopped || m_thread.joinable()) return; @@ -293,199 +163,101 @@ void physicslog_writer::start() { } void physicslog_writer::run(std::stop_token const &Stop) { - lower_disk_priority(); // woken by every stop asked, by stop() or by the end of the thread itself. the lock taken once first: the writer is // either about to wait, and sees the stop, or waiting already std::stop_callback const wake{Stop, [this] { { std::scoped_lock lock{m_mutex}; } m_wake.notify_all(); }}; - std::chrono::steady_clock::duration wait{m_interval}; while (false == Stop.stop_requested()) { { std::unique_lock lock{m_mutex}; // woken early only to stop, which writes the rest itself - if (m_wake.wait_for(lock, wait, [&Stop] { return Stop.stop_requested(); })) + if (m_wake.wait_for(lock, m_interval, [&Stop] { return Stop.stop_requested(); })) return; } - auto const start{std::chrono::steady_clock::now()}; - // a stop come meanwhile ends the writing at the log at hand, the others left to the closing's - auto const logs{flush_safely(writing::thread)}; - auto const took{std::chrono::steady_clock::now() - start}; - wait = wait_after(m_interval, took); - if (wait > m_interval && false == m_slowtold) { - m_slowtold = true; - using seconds = std::chrono::duration; - try { - WriteLog(std::format("Physics logs: writing {} of them took {:.1f} s, over a third of the {:.1f} s between writings; they're " - "written less often from now on, every {:.1f} s at most", - logs, seconds{took}.count(), seconds{m_interval}.count(), seconds{m_interval * 5}.count())); - } catch (...) { - // out of memory for a line of the log: the logs are written all the same - } - } + flush_safely(); } } -std::size_t physicslog_writer::flush_safely(writing const Mode) noexcept { +void physicslog_writer::flush_safely() noexcept { try { - std::scoped_lock files{m_filemutex}; - return write(Mode); + flush(); } catch (std::exception const &Error) { tell(std::string{"Bad physics log: the writing failed ("} + Error.what() + "), the lines taken for it are lost"); } catch (...) { tell("Bad physics log: the writing failed, the lines taken for it are lost"); } - return 0; } -bool physicslog_writer::past_closing() const { - auto const closeby{m_closeby.load()}; - return closeby != 0 && std::chrono::steady_clock::now().time_since_epoch().count() >= closeby; -} - -void physicslog_writer::keep(std::map &Failed, std::vector *> const &Left) { - // cut before the lock, which the simulation waits on to give its lines: only what came since is added under it - auto const most{std::max(keptwhilefailingleast, keptwhilefailing / std::max(Failed.size(), 1))}; - for (auto &[name, lines] : Failed) { - // the values the writing failed to make into text, out of memory say, made into it again, before the lock: as - // text they go before what came since - try { - lines.to_text(); - } catch (std::exception const &) { - // kept as values, below - } - keep_last(lines.text, most); - } - // tried again the next time, before what came since; a file held by another program for a while doesn't lose - // them, nor its header - std::scoped_lock lock{m_mutex}; - for (auto &[name, lines] : Failed) - put_back(name, lines); - for (auto *log : Left) - put_back(log->first, log->second); -} - -void physicslog_writer::put_back(std::string const &Name, pending &Lines) { - auto &now{m_pending[Name]}; - // a log begun anew since drops them - if (now.fresh) - return; - // the lines in the order given: those kept, then those come since, as text and as values. values kept before text - // come since are made into text first, as those before a line given as text are; values which can't be, out of - // memory, are dropped then, as the order can't be kept otherwise - if (false == now.text.empty() && false == Lines.values.empty()) { - try { - Lines.to_text(); - } catch (std::exception const &) { - Lines.values.clear(); - } - } - Lines.text.append(now.text); - // added at once, allocated first: one failing moves none of them - if (Lines.values.empty()) - Lines.values = std::move(now.values); - else - Lines.values.insert(Lines.values.end(), std::make_move_iterator(now.values.begin()), std::make_move_iterator(now.values.end())); - now = std::move(Lines); -} - -std::size_t physicslog_writer::write(writing const Mode) { +void physicslog_writer::write() { std::map taken; - std::set first; - std::vector *> order; { std::scoped_lock lock{m_mutex}; - if (m_pending.empty()) - return 0; - // a stop come before the thread's writing: the lines are all the closing's, left as they are - if (Mode == writing::thread && m_closeby.load() != 0) - return 0; - // had before the lines are taken: without the memory for it they're left for the next writing - first = m_first; - order.reserve(m_pending.size()); taken.swap(m_pending); } - auto const logs{taken.size()}; + if (taken.empty()) + return; std::error_code error; std::filesystem::create_directories(m_folder, error); - std::ranges::transform(taken, std::back_inserter(order), [](auto &Log) { return &Log; }); - writing_order(order, first); std::map failed; - std::size_t dropped{0}; - std::size_t reached{0}; - for (auto *log : order) { - // a stop come while the thread writes: the logs it hasn't come to are left to the closing's writing, which has - // them with the lines given since, those put first first - if (Mode == writing::thread && m_closeby.load() != 0) - break; - ++reached; - auto &[name, lines]{*log}; - // past the time the closing gives the writing: dropped, as the closing doesn't wait for it any longer - if (Mode == writing::closing && past_closing()) { - ++dropped; + for (auto &[name, lines] : taken) { + if (lines.text.empty() && false == lines.fresh) + continue; + // a log going wrong otherwise, out of memory say, is kept for the next try as one whose file can't be written: + // the others are written still, and the writer goes on + auto written{false}; + std::string problem{"can't write"}; + try { + written = write_log(name, lines); + } catch (std::exception const &Error) { + problem = std::string{"failed ("} + Error.what() + ") to write"; + } + if (written) { + if (m_failed.erase(name) > 0) + WriteLog("Physics log: " + shown(name) + " written again"); continue; } - if (false == write_taken(name, lines)) - failed.emplace(name, std::move(lines)); + if (m_failed.insert(name).second) + ErrorLog("Bad physics log: " + problem + " " + shown(name) + ", its last lines are kept for the next try"); + failed.emplace(name, std::move(lines)); } - if (dropped > 0) - tell(std::format("Bad physics log: {} of them not written, past the {:.1f} s the closing waits for them", dropped, - std::chrono::duration{m_closingwait}.count())); - // what is left of the order: the logs the thread hasn't come to - order.erase(order.begin(), order.begin() + static_cast(reached)); - if (false == failed.empty() || false == order.empty()) - keep(failed, order); - return logs; -} - -bool physicslog_writer::write_taken(std::string const &Name, pending &Lines) { - // a log going wrong otherwise, out of memory say, is kept for the next try as one whose file can't be written: - // the others are written still, and the writer goes on - auto written{false}; - std::string problem{"can't write"}; - try { - // the text of the lines given as values, here on the writer's thread rather than the simulation's - Lines.to_text(); - if (Lines.text.empty() && false == Lines.fresh) - return true; - written = write_log(Name, Lines); - } catch (std::exception const &Error) { - problem = std::string{"failed ("} + Error.what() + ") to write"; + if (failed.empty()) + return; + // cut before the lock, which the simulation waits on to give its lines: only what came since is added under it + auto const most{std::max(keptwhilefailingleast, keptwhilefailing / failed.size())}; + for (auto &[name, lines] : failed) + keep_last(lines.text, most); + // tried again the next time, before what came since; a file held by another program for a while doesn't lose + // them, nor its header. a log begun anew since drops them + std::scoped_lock lock{m_mutex}; + for (auto &[name, lines] : failed) { + auto &now{m_pending[name]}; + if (now.fresh) + continue; + lines.text.append(now.text); + now = std::move(lines); } - if (written) { - if (m_failed.erase(Name) > 0) - WriteLog("Physics log: " + shown(Name) + " written again"); - return true; - } - if (m_failed.insert(Name).second) - ErrorLog("Bad physics log: " + problem + " " + shown(Name) + ", its last lines are kept for the next try"); - return false; } bool physicslog_writer::write_log(std::string const &Name, pending const &Lines) const { auto const path{file(Name)}; - // one write to the file: the header of a log begun with its lines, not the one after the other - std::string begun; - if (Lines.fresh) - begun = Lines.header + Lines.text; - std::string_view const text{Lines.fresh ? std::string_view{begun} : std::string_view{Lines.text}}; - // in text mode, as the logs were always written: on Windows their lines, which end with "\r\n", end with "\r\r\n". - // a log added to is opened at its end (ate), and where that is, its length, is what it's cut back to if the lines - // are written in part only, a disk filling up say: else they'd be written twice, the next time. the disk isn't - // asked for the length before, one access less of hundreds of logs - std::ofstream stream{path, Lines.fresh ? std::ios::out | std::ios::trunc : std::ios::out | std::ios::app | std::ios::ate}; - if (false == stream.is_open()) - return false; - auto const before{Lines.fresh ? std::streamoff{0} : static_cast(stream.tellp())}; - stream.write(text.data(), static_cast(text.size())); + std::error_code error; + // how long it was, to be cut back to if the lines are written in part only, a disk filling up say: else they'd be + // written twice, the next time + auto const before{Lines.fresh ? 0 : std::filesystem::file_size(path, error)}; + auto const existed{false == Lines.fresh && false == static_cast(error)}; + // in text mode, as the logs were always written: on Windows their lines, which end with "\r\n", end with "\r\r\n" + std::ofstream stream{path, Lines.fresh ? std::ios::out | std::ios::trunc : std::ios::out | std::ios::app}; + if (stream.is_open()) { + if (Lines.fresh) + stream << Lines.header; + stream << Lines.text; + } stream.close(); if (false == stream.fail()) return true; - // a log begun is written anew from its header the next time anyway - if (false == Lines.fresh && before >= 0) { - std::error_code error; - std::filesystem::resize_file(path, static_cast(before), error); - } + if (existed) + std::filesystem::resize_file(path, before, error); return false; } diff --git a/utilities/physicslog.h b/utilities/physicslog.h index 286df7e87..0f397d27c 100644 --- a/utilities/physicslog.h +++ b/utilities/physicslog.h @@ -9,12 +9,9 @@ http://mozilla.org/MPL/2.0/. #pragma once -#include -#include #include #include #include -#include #include #include #include @@ -22,60 +19,18 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include -#include - -// a line of a driver's physics log as its values, taken as the simulation goes and made into text by the thread which -// writes the logs: the text, a stream of 26 values, is what a line costs, and the drivers of a big scenery give twenty -// lines a second each. the columns as physicslog_header of the driver names them -struct physicslog_values { - double time{0.0}; - double wheelspeed{0.0}; - double acceleration{0.0}; - double couplerdistance{0.0}; - double couplerforce{0.0}; - double tractionforce{0.0}; - double frictionforce{0.0}; - double brakeforce{0.0}; - double brakepressure{0.0}; - double pipepressure{0.0}; - double motorcurrent{0.0}; - int mainctrl{0}; - int scndctrl{0}; - double brakectrl{0.0}; - double localbrake{0.0}; - int direction{0}; - std::string command; - double value1{0.0}; - double value2{0.0}; - int security{0}; - int wheelslip{0}; - double enginetemperature{0.0}; - double oiltemperature{0.0}; - double watertemperature{0.0}; - double wateraux{0.0}; - double vehiclespeed{0.0}; - - // the line, as the logs always had it, at the end of Text - void append_to(std::string &Text) const; -}; // the physics logs, /.dat, what no file name may have on Windows replaced in the name (a spawned vehicle's // has a ':'), the same on every system. the lines given are kept, and written every two seconds by a thread of its own, // each file opened only for the moment it is written to: the logs of hundreds of vehicles hold no files open, and the -// simulation doesn't wait for the disk. a crash loses the last two seconds of real time of them, up to ten on a disk -// which can't keep up (below). lines whose file can't be written, held by another program say, are kept for the next -// try: the last 64 MB of them all at most. the thread's disk work goes after everyone else's, and a disk slower than the -// logs need (a hard disk, hundreds of them) gets them less often, so the simulation reading from it doesn't wait behind -// them. the closing waits for the writing a second at most (below) +// simulation doesn't wait for the disk. a crash loses the last two seconds of real time of them. lines whose file can't +// be written, held by another program say, are kept for the next try: the last 64 MB of them all at most class physicslog_writer { public: - explicit physicslog_writer(std::filesystem::path Folder = "physicslog", std::chrono::milliseconds Interval = std::chrono::seconds{2}, - std::chrono::milliseconds ClosingWait = std::chrono::seconds{1}); + explicit physicslog_writer(std::filesystem::path Folder = "physicslog", std::chrono::milliseconds Interval = std::chrono::seconds{2}); physicslog_writer(physicslog_writer const &) = delete; physicslog_writer &operator=(physicslog_writer const &) = delete; - // stops, writing what is kept, and waits for the writings a stop left behind: the object goes. the simulator's, - // global, never goes this way: the process ends with _Exit + // stops, writing what is kept ~physicslog_writer(); // starts the log Name anew: its file is emptied and Header written into it, the next time the logs are written. @@ -83,20 +38,12 @@ public: void begin(std::string const &Name, std::string_view Header); // Line at the end of the log Name. a log not begun is added to as its file stands void append(std::string const &Name, std::string_view Line); - // the same, a line of the values, made into text by the writer's thread when it writes the log - void append(std::string const &Name, physicslog_values Values); - // the log Name written before the others, at each writing: the logs of the vehicles the user was in, and of the - // tested trains, which a closing short of time would otherwise drop by the order of their names - void put_first(std::string const &Name); // writes what is kept, now void flush(); // as flush, waited for no longer than Timeout: then false, and the writing goes on by itself, on a thread left // behind. for the end of the process, the files held up or the disk not answering bool flush_for(std::chrono::milliseconds Timeout); - // writes what is kept and ends the thread, waiting for it ClosingWait at most: the logs whose turn hasn't come by - // then are dropped, and the writing of the one at hand (a disk not answering) is left behind, going on by itself. a - // writing of the thread under way ends at the log at hand, leaving the others to the closing's, which has them with - // the lines given since, those put first first. what is given after is written by a flush, or by the next stop + // writes what is kept and ends the thread. what is given after is written by a flush, or at the end void stop(); // the file of the log Name: /.dat, with < > : " / \ | ? * and the control characters of the name // replaced by _, and _ before a name Windows keeps for a device (con, nul, com1...). the bytes of the code page of a @@ -105,84 +52,36 @@ public: std::filesystem::path file(std::string const &Name) const; // the same, for the log of the simulator std::string shown(std::string const &Name) const; - // the wait of the thread before its next writing, after one which took Took: the interval, or three times as long - // as the writing was when that's longer, five intervals at most. a disk which can't keep up is then busy with the - // logs a quarter of the time rather than all of it, and their lines wait in memory the longer - static std::chrono::steady_clock::duration wait_after(std::chrono::milliseconds Interval, std::chrono::steady_clock::duration Took); - // the logs taken for a writing, pointers to the entries of a map by their names, put in the order they're written: - // those put first (First) before the others, each in the order they were - template static void writing_order(std::vector &Logs, std::set const &First) { - std::ranges::stable_partition(Logs, [&First](Log const *Each) { return First.contains(Each->first); }); - } private: - // a writing: a flush; the thread's, which a stop ends at the log at hand, leaving the others to the closing's; or the - // closing's, which drops the logs past the time the stop gives it - enum class writing { flush, thread, closing }; - - // the end of the time a stop gives the writing. fresh: given by this stop, not by one before it still under way - struct closing_time { - std::chrono::steady_clock::time_point by; - bool fresh{true}; - }; - struct pending { bool fresh{false}; // its file is to be emptied first, and the header written into it std::string header; std::string text; - // the lines given as values since, after the text: made into text when written - std::vector values; - - // the lines of the values at the end of the text - void to_text(); }; - // the time of a stop: the one of a closing still under way, if there's one. called with m_mutex held - closing_time closing_begun(); - // the writer ended and the rest written by a thread of its own, waited for until Closeby. returns: false if no - // thread could be had for it, out of memory say; Thread may be the writer still then - bool close_aside(std::jthread &Thread, closing_time Closeby) noexcept; // the thread, on the first line given, unless stopped. called with m_mutex held void start(); void run(std::stop_token const &Stop); // as flush, letting nothing out: on the writer's thread, or at the end of the process, an exception would end the - // simulator. what was taken for a writing which failed as a whole is lost, the next one goes on with what came since. - // returns: the number of logs there were to write - std::size_t flush_safely(writing Mode) noexcept; - // called with m_filemutex held. returns: the number of logs there were to write - std::size_t write(writing Mode); - // the log Name taken for a writing written into its file, the problem told once if it can't be. returns: false if - // it wasn't, its lines to be kept for the next try - bool write_taken(std::string const &Name, pending &Lines); - // whether the time a stop gave the writing is over - bool past_closing() const; - // the logs taken for a writing and not written kept for the next, before what came since, their values too: Failed, - // whose file couldn't be written, cut to their last lines, and Left, which a stop left to the closing's writing, as - // they were taken: their values are made into text by that writing, which drops them past its time, not on the way - // unless text was given since - void keep(std::map &Failed, std::vector *> const &Left); - // Lines of the log Name, taken for a writing, put back before the lines given since. called with m_mutex held - void put_back(std::string const &Name, pending &Lines); + // simulator. what was taken for a writing which failed as a whole is lost, the next one goes on with what came since + void flush_safely() noexcept; + // called with m_filemutex held + void write(); // the lines of the log Name written into its file. returns: true if they all were bool write_log(std::string const &Name, pending const &Lines) const; std::filesystem::path const m_folder; std::string const m_shownfolder; std::chrono::milliseconds const m_interval; - std::chrono::milliseconds const m_closingwait; - // the end of the time the last stop gave the writing, of the steady clock; 0 before the first stop - std::atomic m_closeby{0}; std::mutex m_mutex; // the lines kept and the thread std::map m_pending; - std::set m_first; // the logs put first bool m_stopped{false}; std::condition_variable m_wake; std::jthread m_thread; std::thread::id m_writer; // of the thread, kept after it is taken to be joined: the writer knows itself by it - std::vector> m_closings; // the writings of the stops, which may outlast them std::mutex m_filemutex; // the files are written one batch at a time, so the lines of a log stay in order std::set m_failed; // the logs whose file couldn't be written, told once - bool m_slowtold{false}; // the writings were told to take longer than the interval allows, once; the thread's own }; // the physics logs of the drivers (physicslog yes), and those the black box writes of the user's vehicles diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index edc694852..61a059e35 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -150,11 +150,11 @@ double Random(double min, double max) return dist(Global.random_engine); } -int Random(int min, int max) +int RandomInt(int min, int max) { if (max < min) { std::swap(min, max); } // std::uniform_int_distribution requires min <= max (inverted bounds are UB) std::uniform_int_distribution dist(min, max); - return dist(Global.random_engine); + return dist(Global.local_random_engine); } std::uint64_t true_random_seed() diff --git a/utilities/utilities.h b/utilities/utilities.h index 25ee3882c..0cefb6c11 100644 --- a/utilities/utilities.h +++ b/utilities/utilities.h @@ -64,7 +64,12 @@ inline long Round(double const f) } double Random(double a, double b); -int Random(int min, int max); +// whole numbers from min to max, both included. a name of its own keeps the calls of Random() with whole-number +// bounds (the wind, the wheel flats, the truck hunting, the tachometer) on Random(double, double), which draws the +// real number in between that they expect. drawn from the local engine, as up to 26.05.1 from an engine of its own: it +// picks what one machine shows (the trivia of the loading screen), and a draw from the engine of the run's seed would +// put that engine out of step with the other machines of a network session +int RandomInt(int min, int max); /// @author lxvia /// @brief Returns a random seed from the system's entropy source, if available. Otherwise, falls back to a clock-based seed. @@ -293,17 +298,18 @@ template bool is_equal(T const &Left, T const &Right, T const Epsil return Left == Right; } -// Tolerant clamp. Unlike std::clamp, this does NOT invoke undefined behaviour when -// the bounds are inverted (Lo > Hi) - it normalizes them instead. This restores the -// pre-refactor behaviour of the old custom clamp() for code paths where the bounds are -// computed at runtime and can legitimately cross (e.g. AI acceleration/braking limits, -// physics jolt calculations), where std::clamp's UB produced wrong results. +// Tolerant clamp, the old custom clamp() of the project (up to 26.05.1). Unlike +// std::clamp, this does NOT invoke undefined behaviour when the bounds are inverted +// (Lo > Hi): the lower bound is applied first and the upper one last, so inverted +// bounds give the upper bound, as the old clamp() did. Every call of the old clamp() +// whose bounds can cross (they come from the .fiz, the .mmd or the window, or are +// computed from such values) uses it, so it gives what it gave before the move to +// std::clamp. Where the code keeps the bounds in order, std::clamp gives the same. +// New code uses std::clamp. template constexpr Type_ safe_clamp( Type_ const Value, Type_ const Lo, Type_ const Hi ) { - return ( Hi < Lo ) - ? std::clamp( Value, Hi, Lo ) - : std::clamp( Value, Lo, Hi ); + return std::min( std::max( Value, Lo ), Hi ); } // keeps the provided value in specified range 0-Range, as if the range was circular buffer diff --git a/vehicle/Camera.cpp b/vehicle/Camera.cpp index e2fe58464..fe1a85c9a 100644 --- a/vehicle/Camera.cpp +++ b/vehicle/Camera.cpp @@ -62,6 +62,30 @@ TCamera::OnCommand( command_data const &Command ) { // threshold position on stick between walk lerp and walk/run lerp auto const stickthreshold = 2.0 / 3.0; + // the free camera of the editor as fast as its View menu sets it, Ctrl by the multiplier set there, in the top view by how far it reaches + auto editorscale { 1.0 }; + auto editorfast { -1.0 }; + if( Global.EditorCameraOn && m_owner == nullptr ) { + editorscale = Global.EditorCameraSpeed; + if( Global.EditorOrtho && Global.EditorCameraZoomed ) { + editorscale *= std::clamp( static_cast( Global.EditorOrthoExtent ) / 150.0, 0.02, 200.0 ); + } + editorfast = Global.EditorCameraFast; + } + // how many times faster the fast command of a move makes it: the editor's own, or the free fly's (Default) and the cab's (Cab) + auto const fastness = [&]( bool const Fast, double const Editor, double const Default, double const Cab ) { + if( false == Fast ) { + return 1.0; + } + if( editorfast > 0.0 ) { + return Editor; + } + if( false == FreeFlyModeFlag ) { + return 1.0; + } + return m_owner == nullptr ? Default : Cab; + }; + bool iscameracommand { true }; switch( Command.command ) { @@ -82,7 +106,7 @@ TCamera::OnCommand( command_data const &Command ) { // if( movespeed == 0.0 ) { break; } // enable to fix external cameras in place - auto const speedmultiplier = true == FreeFlyModeFlag && Command.command == user_command::movehorizontalfast ? m_owner == nullptr ? 30.0 : 5.0 : 1.0; + auto const speedmultiplier = editorscale * fastness( Command.command == user_command::movehorizontalfast, editorfast, 30.0, 5.0 ); // left-right m_moverate.x = ComputeAxisSpeed(Command.param1, walkspeed, movespeed, stickthreshold) * speedmultiplier; @@ -101,7 +125,7 @@ TCamera::OnCommand( command_data const &Command ) { // if( movespeed == 0.0 ) { break; } // enable to fix external cameras in place - auto const speedmultiplier = true == FreeFlyModeFlag && Command.command == user_command::moveverticalfast ? m_owner == nullptr ? 10.0 : 3.0 : 1.0; + auto const speedmultiplier = editorscale * fastness( Command.command == user_command::moveverticalfast, std::max( 1.0, editorfast / 3.0 ), 10.0, 3.0 ); // up-down m_moverate.y = ComputeAxisSpeed(Command.param1, walkspeed, movespeed, stickthreshold) * speedmultiplier; @@ -192,9 +216,12 @@ void TCamera::Update() bool TCamera::SetMatrix( glm::dmat4 &Matrix ) const { + // the roll (z) is multiplied in first, so it acts last, about the line of sight: the sway of the cab tilts the view + // the same way wherever the head is turned, as it did in 26.05. the order matters only with a roll (the cab shake, + // or the angles of a camera entry of the scenery) + Matrix = glm::rotate(Matrix, -(double)Angle.z, glm::dvec3(0, 0, 1)); // po wyłączeniu tego kręci się pojazd, a sceneria nie Matrix = glm::rotate(Matrix, -(double)Angle.x, glm::dvec3(1, 0, 0)); Matrix = glm::rotate(Matrix, -(double)Angle.y, glm::dvec3(0, 1, 0)); // w zewnętrznym widoku: kierunek patrzenia - Matrix = glm::rotate(Matrix, -(double)Angle.z, glm::dvec3(0, 0, 1)); // po wyłączeniu tego kręci się pojazd, a sceneria nie if( m_owner != nullptr && false == DebugCameraFlag ) { diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 2b3633433..99c6a951e 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -21,6 +21,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/physicslog.h" #include "vehicle/Train.h" #include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" #include "vehicle/handover.h" #include "vehicle/timetableservice.h" #include "world/mtable.h" @@ -212,6 +213,7 @@ void TSpeedPos::Clear() fSectionVelocityDist = 0.0; //brak długości fPointDist = 0.0; fDist = 0.0; + bSeenAhead = false; vPos = glm::dvec3(0, 0, 0); trTrack = nullptr; // brak wskaźnika }; @@ -328,6 +330,9 @@ bool TSpeedPos::Update() // trzeba zazanaczyć, że minięty iFlags |= spElapsed; } + else { + bSeenAhead = true; + } if (iFlags & spTrack) { // road/track if (trTrack) { @@ -413,9 +418,18 @@ bool TSpeedPos::IsProperSemaphor(TOrders order) return false; // true gdy zatrzymanie, wtedy nie ma po co skanować dalej } +// how far behind the head an event found in the scan may lie and still count as one the head had ahead [m] +constexpr double SeenAheadTolerance { 5.0 }; + bool TSpeedPos::Set(basic_event *event, double dist, double length, TOrders order) { // zapamiętanie zdarzenia fDist = dist; + // an event already behind the head when found (under a train set across a signal) wasn't passed by it. the + // distance is found in steps of a metre from the position of the memory cell, so a signal just ahead of the head + // may come out a few metres behind it: those still count as seen ahead. the price is that a train set less than + // the tolerance past a signal at stop is still reported to pass it; a train standing that close to a signal can't + // be told from one stopped just short of it, which really passes the signal if it goes on + bSeenAhead = ( dist >= -SeenAheadTolerance ); iFlags = spEvent; evEvent = event; vPos = event->input_location(); // współrzędne eventu albo komórki pamięci (zrzutować na tor?) @@ -910,6 +924,7 @@ void TController::CheckSignalPassed( TSpeedPos const &Point, bool const Passedbe { if( Passedbefore || false == TestFlag( Point.iFlags, spElapsed ) + || false == Point.bSeenAhead // found already behind the head: the train stood across it, it didn't pass it || ( mvOccupied->CategoryFlag & 1 ) == 0 ) { // railway only return; } @@ -2346,10 +2361,10 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, } TableClear(); - // the logs of all but the road vehicles, begun at once as they always were. one of a train only at its first line - // (update_logs): every crew is made primary here, and the drivers but one of a train with crews in more vehicles - // are made passive before it starts, so they get no file with only the header - if( WriteLogFlag && false == drives_road_vehicle() ) { + // the logs of all, begun at once as they always were. one of a train only at its first line (update_logs): every + // crew is made primary here, and the drivers but one of a train with crews in more vehicles are made passive + // before it starts, so they get no file with only the header + if( WriteLogFlag ) { begin_physicslog(); } @@ -5387,38 +5402,38 @@ std::string_view TController::physicslog_header() { "\r\n"; } -physicslog_values TController::physicslog_line() const { - // the values only: the writer of the logs makes them into text on its own thread - physicslog_values line; - line.time = ElapsedTime; - line.wheelspeed = fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot); - line.acceleration = mvControlling->AccS; - line.couplerdistance = mvOccupied->Couplers[1].Dist; - line.couplerforce = mvOccupied->Couplers[1].CForce; - line.tractionforce = mvOccupied->Ft; - line.frictionforce = mvOccupied->Ff; - line.brakeforce = mvOccupied->Fb; - line.brakepressure = mvOccupied->BrakePress; - line.pipepressure = mvOccupied->PipePress; - line.motorcurrent = mvControlling->Im; - line.mainctrl = static_cast(mvControlling->MainCtrlPos); - line.scndctrl = static_cast(mvControlling->ScndCtrlPos); - line.brakectrl = mvOccupied->fBrakeCtrlPos; - line.localbrake = mvOccupied->LocalBrakePosA; - line.direction = static_cast(mvControlling->DirActive); - line.command = ( mvOccupied->CommandIn.Command.empty() ? "none" : mvOccupied->CommandIn.Command.c_str() ); - line.value1 = mvOccupied->CommandIn.Value1; - line.value2 = mvOccupied->CommandIn.Value2; - line.security = static_cast(mvControlling->SecuritySystem.is_blinking()); - line.wheelslip = static_cast(mvControlling->SlippingWheels); - // floats, as the stream wrote them: widened to double - line.enginetemperature = mvControlling->dizel_heat.Ts; - line.oiltemperature = mvControlling->dizel_heat.To; - line.watertemperature = mvControlling->dizel_heat.temperatura1; - line.wateraux = mvControlling->dizel_heat.temperatura2; - // vehicle speed [km/h], the second column is the wheel speed, which stays at 0 while the wheels are locked in a skid - line.vehiclespeed = mvOccupied->V * 3.6; - return line; +std::string TController::physicslog_line() const { + std::ostringstream line; + line << std::fixed << std::setprecision( 4 ) + << ElapsedTime << " " + << fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot) << " " + << mvControlling->AccS << " " + << mvOccupied->Couplers[1].Dist << " " + << mvOccupied->Couplers[1].CForce << " " + << mvOccupied->Ft << " " + << mvOccupied->Ff << " " + << mvOccupied->Fb << " " + << mvOccupied->BrakePress << " " + << mvOccupied->PipePress << " " + << mvControlling->Im << " " + << int(mvControlling->MainCtrlPos) << " " + << int(mvControlling->ScndCtrlPos) << " " + << mvOccupied->fBrakeCtrlPos << " " + << mvOccupied->LocalBrakePosA << " " + << int(mvControlling->DirActive) << " " + << ( mvOccupied->CommandIn.Command.empty() ? "none" : mvOccupied->CommandIn.Command.c_str() ) << " " + << mvOccupied->CommandIn.Value1 << " " + << mvOccupied->CommandIn.Value2 << " " + << int(mvControlling->SecuritySystem.is_blinking()) << " " + << int(mvControlling->SlippingWheels) << " " + << mvControlling->dizel_heat.Ts << " " + << mvControlling->dizel_heat.To << " " + << mvControlling->dizel_heat.temperatura1 << " " + << mvControlling->dizel_heat.temperatura2 << " " + // vehicle speed [km/h], the second column is the wheel speed, which stays at 0 while the wheels are locked in a skid + << mvOccupied->V * 3.6 + << "\r\n"; + return line.str(); } void TController::begin_physicslog() @@ -8213,54 +8228,6 @@ uphill_coasting_speed( double const Distance, double const Gravity ) { return 3.6 * std::sqrt( 2.0 * std::max( 0.01, -Gravity ) * std::max( 0.0, Distance ) ); } -// resultant acceleration [m/s2] to ask for now so that a steady application of the pneumatic brake takes the train -// from Velocity down to Target [km/h] over Distance [m], with the brake force following the speed the way the -// consist brake table says it does (cast iron blocks grip harder as the train slows) -struct consist_brake_table { - double const *a0; // deceleration at handle position 1, by speed - double const *a1; // deceleration added by each quarter of a position, by speed - int size; // entries, up to the vehicle's top speed - double vmax; // the vehicle's top speed [km/h] - - // deceleration [m/s2] of a full service application at Kmh - double full_braking( double const Kmh ) const { - auto const index { std::clamp( static_cast( size * Kmh / std::max( 1.0, vmax ) ), 1, size ) }; - return std::max( 0.01, a0[ index ] + 12.0 * a1[ index ] ); } -}; - -static double -shaped_braking_demand( - double const Velocity, double const Target, double const Distance, double const Gravity, - consist_brake_table const &Table ) { - - auto const fullbraking = [&Table]( double const Kmh ) { - return Table.full_braking( Kmh ); }; - auto const travel = [Velocity, Target, Gravity, &fullbraking]( double const Ratio ) { - auto const steps { 24 }; - auto const step { ( Velocity - Target ) / steps }; - auto distance { 0.0 }; - for( auto i { 0 }; i < steps; ++i ) { - auto const kmh { Target + ( i + 0.5 ) * step }; - auto const deceleration { Ratio * fullbraking( kmh ) - Gravity }; - if( deceleration <= 0.001 ) { - return std::numeric_limits::max(); - } - distance += ( kmh / 3.6 ) * ( step / 3.6 ) / deceleration; - } - return distance; }; - - auto low { 0.0 }; - auto high { 3.0 }; - if( travel( high ) > Distance ) { - return Gravity - high * fullbraking( Velocity ); - } - for( auto i { 0 }; i < 30; ++i ) { - auto const middle { 0.5 * ( low + high ) }; - ( travel( middle ) > Distance ? low : high ) = middle; - } - return Gravity - high * fullbraking( Velocity ); -} - // outside of max safe range: follow the braking curve down to the speed ahead, Vel is the present speed in the // direction of travel void @@ -8287,43 +8254,19 @@ TController::adjust_desired_speed_for_braking_curve( double const Vel ) { ( VelNext == 0.0 ) && is_train() && ( OrderCurrentGet() & Obey_train ) ? stopping_margin() : // the same stopping point as the final approach VelNext * braking_distance_multiplier( static_cast( VelNext ) ) ); - // a pneumatic brake acts on the state the train will be in once it has responded; while the - // train is still speeding up, plan the deceleration from there, so more is asked for at once - auto velocity { Vel }; - auto distance { ActualProximityDist }; - if( ( BrakeSystem == TBrakeSystem::Pneumatic ) - && ( AbsAccS > 0.0 ) ) { - auto const horizon { brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ) }; - velocity = Vel + 3.6 * horizon * AbsAccS; - distance = std::max( 0.5 * ActualProximityDist, ActualProximityDist - ( Vel + velocity ) * 0.5 / 3.6 * horizon ); - } - auto const brakingroom { - std::max( - distance - brakingpointoffset, - std::min( - distance, - brakingpointoffset ) ) }; - auto deceleration { ( VelNext * VelNext - velocity * velocity ) / ( 25.92 * brakingroom + 0.1 ) }; - if( ( BrakeSystem == TBrakeSystem::Pneumatic ) && ( velocity > VelNext ) ) { - // follow the shape of the consist brake force over speed rather than assume a constant - // deceleration, over the distance left once the brake has had time to fill (while the - // train is still speeding up, the prediction above has taken that off already) - auto room { brakingroom }; - if( ( AbsAccS <= 0.0 ) - && ( BrakeCtrlPosition <= 0.0 ) ) { // only while the brake is still to be applied: once it acts, the room it needs to respond is behind - // making for a passenger stop only the time the brake takes to fill: the look-ahead the horizon - // keeps as its floor was set for the stops at a signal, and a vehicle that brakes with its - // independent brake, which leaves the train brake handle where it is, kept braking earlier - // and earlier the whole way in, to crawl the last tens of metres to the stop point - auto const brakea0 { bStopTargetIsPassengerStop ? 1.0 : fBrake_a0[ 0 ] }; - room = std::max( - 0.5 * brakingroom, - brakingroom - Vel / 3.6 * brake_response_horizon( mvOccupied, BrakeSystem, 1.0, brakea0 ) ); - } - deceleration = shaped_braking_demand( - velocity, VelNext, room + 0.1 / 25.92, fAccGravity, - { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax } ); - } + // both plans of a pneumatic brake are made from the brake table of the consist; with none (in shunting it isn't + // worked out) the braking curve is the constant deceleration over the distance left, as before them + braking_curve::brake_table const braketable { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax }; + // making for a passenger stop only the time the brake takes to fill: the look-ahead the horizon + // keeps as its floor was set for the stops at a signal, and a vehicle that brakes with its + // independent brake, which leaves the train brake handle where it is, kept braking earlier + // and earlier the whole way in, to crawl the last tens of metres to the stop point + auto const fillbrakea0 { bStopTargetIsPassengerStop ? 1.0 : fBrake_a0[ 0 ] }; + braking_curve::approach const approach { + Vel, VelNext, ActualProximityDist, brakingpointoffset, fAccGravity, AbsAccS, BrakeCtrlPosition > 0.0, + brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ), + brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fillbrakea0 ) }; + auto const deceleration { braking_curve::demand( approach, BrakeSystem == TBrakeSystem::Pneumatic ? &braketable : nullptr ) }; AccDesired = std::min( AccDesired, deceleration ); // najpierw hamuje mocniej, potem zluzuje if( Vel <= VelNext ) { return; @@ -8374,7 +8317,7 @@ TController::adjust_desired_speed_for_final_approach( double const Vel ) { AccDesired = ( BrakeSystem == TBrakeSystem::Pneumatic ? // cast iron blocks grip harder as the train comes to a stand - shaped_braking_demand( + braking_curve::shaped_demand( Vel, VelNext, stoppingroom, fAccGravity, { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax } ) : ( VelNext * VelNext - Vel * Vel ) / ( 25.92 * stoppingroom ) ); diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 113be3b94..0aaf70707 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -20,7 +20,6 @@ http://mozilla.org/MPL/2.0/. #include "utilities/translation.h" #include "application/driverhints.h" #include "vehicle/blackbox.h" -#include "utilities/physicslog.h" auto const EU07_AI_ACCELERATION = 0.05; auto const EU07_AI_NOACCELERATION = -0.05; @@ -165,6 +164,7 @@ class TSpeedPos int iFlags{ spNone }; // flagi typu wpisu do tabelki bool bMoved{ false }; // czy przesunięty (dotyczy punktu zatrzymania w peronie) double fMoved{ 0.0 }; // ile przesunięty (dotyczy punktu zatrzymania w peronie) + bool bSeenAhead{ false }; // the head of the train had it ahead once: only such a point can be passed by the train glm::dvec3 vPos; // współrzędne XYZ do liczenia odległości struct { @@ -739,22 +739,17 @@ private: public: TDynamicObject const *Vehicle() const { return pVehicle; } - // the physics log (physicslog/.dat): the name of its file without the extension, its first line, with - // its line end, and the values of a line of it as the vehicle is now, which the writer of the logs makes into text. - // the black box keeps the lines of the vehicle the user is in when its driver doesn't write its own + // the physics log (physicslog/.dat): the name of its file without the extension, its first line and + // a line of it as the vehicle is now, each with its line end. the black box keeps the lines of the vehicle the + // user is in, to write its log at the end when the logs of all the vehicles are off std::string const &physicslog_name() const { return VehicleName; } - // whether it writes its physics log itself: with "physicslog yes" all but the drivers of road vehicles, with - // "physicslog.trains yes" one who drives rail vehicles. a driver made primary later begins its log then. the cars of - // a big scenery are hundreds, whose logs nobody reads and which a hard disk can't keep up with; the black box writes - // the log of one the user is in + // whether it writes its physics log itself: all with "physicslog yes", with "physicslog.trains yes" one who drives + // rail vehicles. a driver made primary later begins its log then bool writes_physicslog() const { - return ( WriteLogFlag && false == drives_road_vehicle() ) || ( WriteTrainLogFlag && is_train() && primary() ); } - // a driver of a road vehicle; not one of no vehicle - bool drives_road_vehicle() const { - return mvOccupied != nullptr && is_car(); } + return WriteLogFlag || ( WriteTrainLogFlag && is_train() && primary() ); } static std::string_view physicslog_header(); - physicslog_values physicslog_line() const; + std::string physicslog_line() const; TDynamicObject *Vehicle( end const Side ) const { return pVehicles[ Side ]; } private: diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index ce94a0609..7a301930a 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -27,6 +27,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Driver.h" #include +#include #include #include #include "utilities/Globals.h" @@ -1162,7 +1163,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) continue; } - auto const dist { std::clamp( MoverParameters->Couplers[ i ].Dist / 2.0, -MoverParameters->Couplers[ i ].DmaxB, 0.0 ) }; + auto const dist { safe_clamp( MoverParameters->Couplers[ i ].Dist / 2.0, -MoverParameters->Couplers[ i ].DmaxB, 0.0 ) }; if( dist >= 0.0 ) { continue; } @@ -2446,6 +2447,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" ShakeSpring.Init( 125.0 ); BaseShake = baseshake_config {}; ShakeState = shake_state {}; + ShakeStateBefore = shake_state {}; // McZapkie-250202 /* @@ -2604,7 +2606,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" initial_track = MyTrack; iNumAxles = 2; // McZapkie-090402: odleglosc miedzy czopami skretu lub osiami - fAxleDist = std::clamp( + fAxleDist = safe_clamp( std::max( MoverParameters->BDist, MoverParameters->ADist ), 0.2, //żeby się dało wektory policzyć MoverParameters->Dim.L - 0.2 ); // nie mogą być za daleko bo będzie "walenie w mur" @@ -3202,7 +3204,7 @@ TDynamicObject::update_load_offset() { 0.0 : 100.0 * MoverParameters->LoadAmount / MoverParameters->MaxLoad ) }; - LoadOffset = std::lerp( MoverParameters->LoadType.offset_min, 0.f, safe_clamp( 0.0, loadpercentage * 0.01, 1.0 ) ); + LoadOffset = std::lerp( MoverParameters->LoadType.offset_min, 0.f, safe_clamp( 0.0, 1.0, loadpercentage * 0.01 ) ); } void @@ -3849,20 +3851,21 @@ bool TDynamicObject::Update(double dt, double dt1) // crude bump simulation, drop down on even axles, move back up on // the odd ones // MoverParameters->AccVert += (MoverParameters->Vel*0.1f) * - double const headroom = std::clamp( - MoverParameters->Vmax - ( MoverParameters->Vel + MoverParameters->Vmax * 0.32f ), - 0.0, MoverParameters->Vmax ); + // the arguments keep the order they had up to 26.05.1, 0 in place of the value and the figure in place of the + // upper limit, so they work out as the old clamp worked them out up to 26.05.1: the headroom is + // Vmax - (Vel + 0.32 Vmax) whatever its sign, and the bump is capped from above only + double const headroom = safe_clamp( 0.0, MoverParameters->Vmax, MoverParameters->Vmax - ( MoverParameters->Vel + MoverParameters->Vmax * 0.32f ) ); double const jolt = headroom * .05f * ( MyTrack->iDamageFlag * 0.25f ); if (MyTrack->eType == tt_Normal) { - MoverParameters->AccVert += std::clamp( jolt, 0.0, 4.0 ); + MoverParameters->AccVert += safe_clamp( 0.0, 4.0, jolt ); } else if (MyTrack->eType == tt_Switch) { - double const accHorizontal = std::clamp( jolt, 0.0, 1.0 ) * ((axleindex % 2) != 0 ? 1 : -1); + double const accHorizontal = safe_clamp( 0.0, 1.0, jolt ) * ((axleindex % 2) != 0 ? 1 : -1); MoverParameters->AccS += accHorizontal; MoverParameters->AccN += accHorizontal; - MoverParameters->AccVert += std::clamp( jolt, 0.0, 2.0 ); + MoverParameters->AccVert += safe_clamp( 0.0, 2.0, jolt ); } } ++axleindex; @@ -8337,6 +8340,8 @@ void TDynamicObject::OverheadTrack(float o) void TDynamicObject::update_shake( double const Timedelta ) { + + ShakeStateBefore = ShakeState; // Ra: mechanik powinien być telepany niezależnie od pozycji pojazdu // Ra: trzeba zrobić model bujania głową i wczepić go do pojazdu @@ -8461,9 +8466,32 @@ TDynamicObject::axle_passed_joint( axle_sounds &Axle, double const Move, int con std::pair TDynamicObject::shake_angles() const { + return shake_angles( ShakeState ); +} + +std::pair +TDynamicObject::shake_angles( shake_state const &State ) const { + return { - std::atan( ShakeState.velocity.x * BaseShake.angle_scale.x ), - std::atan( ShakeState.velocity.z * BaseShake.angle_scale.z ) }; + std::atan( State.velocity.x * BaseShake.angle_scale.x ), + std::atan( State.velocity.z * BaseShake.angle_scale.z ) }; +} + +TDynamicObject::shake_state +TDynamicObject::shake_between( double const Fraction ) const { + + if( Fraction >= 1.0 ) { + return ShakeState; + } + auto const between { []( glm::dvec3 const &Before, glm::dvec3 const &After, double const Part ) { + return glm::dvec3 { + std::lerp( Before.x, After.x, Part ), + std::lerp( Before.y, After.y, Part ), + std::lerp( Before.z, After.z, Part ) }; } }; + auto const part { std::max( Fraction, 0.0 ) }; + return { + between( ShakeStateBefore.velocity, ShakeState.velocity, part ), + between( ShakeStateBefore.offset, ShakeState.offset, part ) }; } void diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index db427e34d..4db7d32c3 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -925,6 +925,11 @@ public: glm::dvec3 velocity{}; // current shaking vector glm::dvec3 offset{}; // overall shake-driven offset from base position } ShakeState; + shake_state ShakeStateBefore; // the state before the last step of update_shake + // the shake between the last two steps of update_shake: 0 the state before the last step, 1 the state after it. + // the steps are fixed and the frames aren't, so the camera takes the state at its own moment between the two + shake_state shake_between( double const Fraction ) const; + std::pair shake_angles( shake_state const &State ) const; glm::dvec3 modelShake; }; diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 24d3132f6..8bf948096 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -9828,7 +9828,7 @@ bool TTrain::Update(double const Deltatime) { double b = Console::AnalogCalibrateGet(0); b = b * 8.0 - 2.0; - b = std::clamp(b, -2.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic + b = safe_clamp(b, -2.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia mvOccupied->BrakeLevelSet(b); } @@ -9836,7 +9836,7 @@ bool TTrain::Update(double const Deltatime) { double b = Console::AnalogCalibrateGet(0); b = b * 7.0 - 1.0; - b = std::clamp(b, -1.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic + b = safe_clamp(b, -1.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia mvOccupied->BrakeLevelSet(b); } @@ -9844,7 +9844,7 @@ bool TTrain::Update(double const Deltatime) { double b = Console::AnalogCalibrateGet(0); b = b * (mvOccupied->Handle->GetPos(bh_MAX) - mvOccupied->Handle->GetPos(bh_MIN)) + mvOccupied->Handle->GetPos(bh_MIN); - b = std::clamp(b, mvOccupied->Handle->GetPos(bh_MIN), mvOccupied->Handle->GetPos(bh_MAX)); // przycięcie zmiennej do granic + b = safe_clamp(b, mvOccupied->Handle->GetPos(bh_MIN), mvOccupied->Handle->GetPos(bh_MAX)); // przycięcie zmiennej do granic ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia mvOccupied->BrakeLevelSet(b); } @@ -11463,8 +11463,11 @@ glm::dvec3 TTrain::clamp_inside(glm::dvec3 const &Point) const return Point; } - return {std::clamp(Point.x, (double)Cabine[iCabn].CabPos1.x, (double)Cabine[iCabn].CabPos2.x), std::clamp(Point.y, (double)Cabine[iCabn].CabPos1.y + 0.5, (double)Cabine[iCabn].CabPos2.y + 1.8), - std::clamp(Point.z, (double)Cabine[iCabn].CabPos1.z, (double)Cabine[iCabn].CabPos2.z)}; + // the bounds come from the .mmd as written, and some cabs have them reversed (the B cars of SA134 and 21xM, + // ET40, 754...); std::clamp is undefined for those and on MSVC makes the camera jump between the two bounds + // every frame, as its result is fed back here. safe_clamp keeps the camera on the upper bound, as 26.05 did + return {safe_clamp(Point.x, (double)Cabine[iCabn].CabPos1.x, (double)Cabine[iCabn].CabPos2.x), safe_clamp(Point.y, (double)Cabine[iCabn].CabPos1.y + 0.5, (double)Cabine[iCabn].CabPos2.y + 1.8), + safe_clamp(Point.z, (double)Cabine[iCabn].CabPos1.z, (double)Cabine[iCabn].CabPos2.z)}; } const TTrain::screenentry_sequence &TTrain::get_screens() diff --git a/vehicle/brakingcurve.cpp b/vehicle/brakingcurve.cpp new file mode 100644 index 000000000..d39ee2868 --- /dev/null +++ b/vehicle/brakingcurve.cpp @@ -0,0 +1,86 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/brakingcurve.h" + +#include +#include + +namespace braking_curve { + +double brake_table::full_braking(double const Kmh) const { + auto const index{std::clamp(static_cast(size * Kmh / std::max(1.0, vmax)), 1, size)}; + return std::max(0.01, a0[index] + 12.0 * a1[index]); +} + +bool brake_table::known() const { + // a worked out table holds at least the rolling resistance term at every speed + return a0[size] > 0.0; +} + +double shaped_demand(double const Velocity, double const Target, double const Distance, double const Gravity, brake_table const &Table) { + + auto const travel = [Velocity, Target, Gravity, &Table](double const Ratio) { + auto const steps{24}; + auto const step{(Velocity - Target) / steps}; + auto distance{0.0}; + for (auto i{0}; i < steps; ++i) { + auto const kmh{Target + (i + 0.5) * step}; + auto const deceleration{Ratio * Table.full_braking(kmh) - Gravity}; + if (deceleration <= 0.001) { + return std::numeric_limits::max(); + } + distance += (kmh / 3.6) * (step / 3.6) / deceleration; + } + return distance; + }; + + auto low{0.0}; + auto high{3.0}; + if (travel(high) > Distance) { + return Gravity - high * Table.full_braking(Velocity); + } + for (auto i{0}; i < 30; ++i) { + auto const middle{0.5 * (low + high)}; + (travel(middle) > Distance ? low : high) = middle; + } + return Gravity - high * Table.full_braking(Velocity); +} + +double demand(approach const &Approach, brake_table const *Pneumatictable) { + + // a pneumatic brake acts on the state the train will be in once it has responded; while the + // train is still speeding up, plan the deceleration from there, so more is asked for at once + // both plans are made from the brake table of the consist; with none (in shunting it isn't worked out, and planning + // from its zeroes would ask for no braking at all) the braking curve is the constant deceleration over the distance left + auto const *table{(Pneumatictable != nullptr) && Pneumatictable->known() ? Pneumatictable : nullptr}; + auto velocity{Approach.speed}; + auto distance{Approach.distance}; + if ((table != nullptr) && (Approach.acceleration > 0.0)) { + auto const horizon{Approach.speedup_horizon}; + velocity = Approach.speed + 3.6 * horizon * Approach.acceleration; + distance = std::max(0.5 * Approach.distance, Approach.distance - (Approach.speed + velocity) * 0.5 / 3.6 * horizon); + } + auto const brakingroom{std::max(distance - Approach.offset, std::min(distance, Approach.offset))}; + if ((table == nullptr) || (velocity <= Approach.target)) { + return (Approach.target * Approach.target - velocity * velocity) / (25.92 * brakingroom + 0.1); + } + // follow the shape of the consist brake force over speed rather than assume a constant + // deceleration, over the distance left once the brake has had time to fill (while the + // train is still speeding up, the prediction above has taken that off already) + auto room{brakingroom}; + if ((Approach.acceleration <= 0.0) && (false == Approach.brake_applied)) { + // only while the brake is still to be applied: once it acts, the room it needs to respond is behind + room = std::max(0.5 * brakingroom, brakingroom - Approach.speed / 3.6 * Approach.fill_horizon); + } + return shaped_demand(velocity, Approach.target, room + 0.1 / 25.92, Approach.gravity, *table); +} + +} // namespace braking_curve diff --git a/vehicle/brakingcurve.h b/vehicle/brakingcurve.h new file mode 100644 index 000000000..6ed40d9bb --- /dev/null +++ b/vehicle/brakingcurve.h @@ -0,0 +1,54 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +// the deceleration the AI asks for on its way down to a lower speed or a stop ahead, outside of the final +// approach (TController::adjust_desired_speed_for_braking_curve) +namespace braking_curve { + +// the deceleration table of the consist brake, by speed (TController::fBrake_a0, fBrake_a1). it is worked out +// for a train only (Obey_train, Bank); in shunting it stays at zero +struct brake_table { + double const *a0; // deceleration at handle position 1, by speed; a0[1..size] + double const *a1; // deceleration added by each quarter of a position, by speed + int size; // entries, up to the vehicle's top speed + double vmax; // the vehicle's top speed [km/h] + + // deceleration [m/s2] of a full service application at Kmh + double full_braking(double Kmh) const; + // whether the table is worked out + bool known() const; +}; + +// resultant acceleration [m/s2] to ask for now so that a steady application of the pneumatic brake takes the train +// from Velocity down to Target [km/h] over Distance [m], with the brake force following the speed the way the +// table says it does (cast iron blocks grip harder as the train slows) +double shaped_demand(double Velocity, double Target, double Distance, double Gravity, brake_table const &Table); + +// where the train is on its way down to Target +struct approach { + double speed; // present speed in the direction of travel [km/h] + double target; // speed to get down to [km/h] + double distance; // to where the speed is to be down [m] + double offset; // the braking point that far short of it [m] + double gravity; // tangential acceleration of the gradient [m/s2], negative uphill + double acceleration; // present acceleration of the train [m/s2] + bool brake_applied; // the train brake handle is past running + double speedup_horizon; // how long the present acceleration lasts while speeding up [s] + double fill_horizon; // how long the brake takes to fill once applied [s] +}; + +// acceleration [m/s2] to ask for now, negative to brake. with the worked out table of a pneumatic brake +// (Pneumatictable) the demand follows the brake: planned from the state the train is in once the brake has +// responded, along the shape of its force over speed. without one (nullptr for another brake, or a table left at +// zero, as in shunting) it is the constant deceleration over the distance left +double demand(approach const &Approach, brake_table const *Pneumatictable); + +} // namespace braking_curve diff --git a/world/Segment.cpp b/world/Segment.cpp index 5e0f47116..1398b3347 100644 --- a/world/Segment.cpp +++ b/world/Segment.cpp @@ -439,7 +439,10 @@ glm::dvec3 TSegment::stray( glm::dvec3 const &Point, track_uneven::amounts const glm::dvec3 result { 0.0 }; if( m_setting.uneven ) { auto const field { track_uneven::field( Point ) }; - result = glm::dvec3 { field.x * Amount.side, field.y * Amount.up, field.z * Amount.side } * track_uneven::stray_per_mm; + result = glm::dvec3 { + field.x * Amount.side * track_uneven::stray_side_per_mm, + field.y * Amount.up * track_uneven::stray_up_per_mm, + field.z * Amount.side * track_uneven::stray_side_per_mm }; result.y -= pOwner->joint_dip( Distance ); } if( m_setting.buckled && m_pieces.empty() ) { @@ -493,7 +496,7 @@ void TSegment::settle_vertex( gfx::basic_vertex &Vertex, glm::dvec3 const &Origi return; } auto const amount { m_setting.uneven ? pOwner->uneven_at( Distance, m_setting.path ) : track_uneven::amounts {} }; - Vertex.position.y -= static_cast( share * track_uneven::stray_per_mm * amount.cross * track_uneven::level( Origin + glm::dvec3 { Position }, glm::dvec3 { Parallel } ) * across / gauge ); + Vertex.position.y -= static_cast( share * track_uneven::stray_up_per_mm * amount.cross * track_uneven::level( Origin + glm::dvec3 { Position }, glm::dvec3 { Parallel } ) * across / gauge ); Vertex.position += glm::vec3 { share * stray( Origin + glm::dvec3 { Vertex.position }, amount, Distance, glm::dvec3 { Parallel } ) }; } @@ -532,7 +535,7 @@ void TSegment::RaPositionGet(double const fDistance, glm::dvec3 &position, glm:: auto const gauge { std::max( std::abs( pOwner->fTrackWidth ), 0.1f ) }; glm::dvec3 const across { -std::cos( rotation.z ), 0.0, -std::sin( rotation.z ) }; auto const amount { m_setting.uneven ? pOwner->uneven_at( fDistance, m_setting.path ) : track_uneven::amounts {} }; - rotation.x += static_cast( track_uneven::stray_per_mm * ( + rotation.x += static_cast( track_uneven::stray_up_per_mm * ( amount.up * track_uneven::roll( position, across, gauge ) + amount.cross * track_uneven::level( position, across ) / gauge ) ); position += track_uneven::across_only( stray( position, amount, fDistance, across ), across ); diff --git a/world/TrackUneven.h b/world/TrackUneven.h index 8e0f07750..12b1fb7c2 100644 --- a/world/TrackUneven.h +++ b/world/TrackUneven.h @@ -20,13 +20,16 @@ http://mozilla.org/MPL/2.0/. #include // Track unevenness: a displacement field over the plan of the scenery, so everything at one place moves together: joined tracks, the -// paths of a switch, sleepers, axles. Waves 5-42 m long, shares after the German track spectrum with the long waves cut down; up and down to 83 m. -// The "uneven" value is the peak deviation of a rail on a 10 m chord, as in PLK Id-14 appendix 1; see test_track_uneven.cpp. +// paths of a switch, sleepers, axles. Waves 7-90 m long sideways and 8-110 m up and down, about the bands D1-D3 of EN 13848. Their amplitudes +// follow the shape of the track spectra of FRA and ORE B176, S ~ Wc^2 / (W^2 (W^2 + Wc^2)) with Wc = 0.8245 rad/m: the longer a wave, the +// higher it is. The "uneven" value only sets the scale: the peak deviation of a rail on a 10 m chord, as PLK Id-14 appendix 1 measures it; +// see test_track_uneven.cpp. namespace track_uneven { inline constexpr float most { 100.f }; // largest value of the attributes, mm -inline constexpr double stray_per_mm { 0.00145 }; // field amplitude per mm of "uneven", m -inline constexpr double cross_share { 0.53 }; // share of the field amplitude the rails settle apart by +inline constexpr double stray_up_per_mm { 0.00229 }; // amplitude of the field up and down per mm of "uneven", m +inline constexpr double stray_side_per_mm { 0.0031 }; // amplitude of the field sideways per mm of "uneven", m +inline constexpr double cross_share { 0.35 }; // share of the vertical amplitude the rails settle apart by inline constexpr double fade { 20.0 }; // length over which a track goes from the value at its end to its own, m inline constexpr double dip_share { 0.4 }; // joint dip depth per mm of "uneven", mm inline constexpr double dip_reach { 3.0 }; // reach of the dip on each side of a joint, m @@ -182,12 +185,12 @@ wave_set make_waves( double const Turn, std::array const & return result; } -inline constexpr std::array wave_lengths { 5.3, 7.1, 9.7, 13.1, 17.9, 23.9, 31.7, 41.9 }; -inline constexpr std::array wave_shares { 0.0721, 0.0997, 0.1344, 0.1703, 0.1549, 0.1386, 0.1226, 0.1074 }; +// each wave stands for a band of the spectrum, the lengths in a constant ratio, so its share goes as the square root of S(W) * W +inline constexpr std::array wave_lengths { 7.0, 10.1, 14.5, 20.9, 30.1, 43.4, 62.5, 90.0 }; +inline constexpr std::array wave_shares { 0.0435, 0.0617, 0.082, 0.1045, 0.1294, 0.1579, 0.1909, 0.23 }; -// fewer short ones than sideways: the rails come near the limit in the vertical more often, with the peak still at it. -// The long ones hardly count on the 10 m chord: the body rises and falls on them, slowly enough for a pantograph to keep up -inline wave_set<8> const up_waves { make_waves<8>( 0.0, { 8.3, 11.9, 16.7, 23.9, 37.1, 47.3, 61.9, 83.3 }, { 0.14, 0.19, 0.22, 0.22, 0.23, 0.23, 0.23, 0.23 } ) }; +// the same shape. The long ones hardly count on the 10 m chord and the cab hardly feels them: the body rises and falls on them +inline wave_set<8> const up_waves { make_waves<8>( 0.0, { 8.0, 11.6, 16.9, 24.6, 35.8, 52.0, 75.6, 110.0 }, { 0.0761, 0.1058, 0.1393, 0.176, 0.2175, 0.2651, 0.3215, 0.3887 } ) }; inline wave_set<8> const x_waves { make_waves( 1.1, wave_lengths, wave_shares ) }; inline wave_set<8> const z_waves { make_waves( 2.3, wave_lengths, wave_shares ) }; // the tilt along each axis of the plan. Long waves only: with the short ones the cross level reaching its limit would break the limit of twist From f15ea40575cc4062e6e8bea01e917dca431b46ee Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 22 Nov 2026 19:23:40 +0100 Subject: [PATCH 096/136] test(scripting): the image memory test makes fewer images, to finish in time under coverage (#427) The dropped images were 20 of 64 MB, each filled pixel by pixel. Under the GCC -O0 --coverage build that sometimes took longer than the 20 s a screen has to draw, so the check got -1. 4 dropped images, twice the memory of a screen, still prove that dropped images don't count. --- tests/unit/test_script_screen_host.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/unit/test_script_screen_host.cpp b/tests/unit/test_script_screen_host.cpp index 6add4f008..dc1cfa2f8 100644 --- a/tests/unit/test_script_screen_host.cpp +++ b/tests/unit/test_script_screen_host.cpp @@ -1239,7 +1239,10 @@ return { } )"}; -// white when the images a screen holds are held to its memory, and the images it dropped don't count +// white when the images a screen holds are held to its memory, and the images it dropped don't count. an image of +// 4096 x 4096 is 64 MB, half the memory of a screen: the second one kept is refused, and the 4 dropped ones (twice +// the memory) would be refused too if the dropped ones counted. no more of them: each is filled pixel by pixel, slowly +// in the coverage build (GCC -O0 --coverage), and with 20 of them the screen sometimes didn't draw in its 20 s there constexpr std::string_view image_memory_script{R"( local kept = {} local ok, message = pcall(function() @@ -1248,7 +1251,7 @@ end) local refused = not ok and message:find("memory limit exceeded", 1, true) ~= nil and #kept < 100 kept = nil local dropped = pcall(function() - for i = 1, 20 do local image = eu07.image(4096, 4096) end + for i = 1, 4 do local image = eu07.image(4096, 4096) end end) return { render = function(state) From 3c3c773ff46080b697c7b788c7a7b62503c5d8df Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:11:07 +0100 Subject: [PATCH 097/136] test(scenarios): the buckle cases run with physics.derailment new (#423) * test(scenarios): the buckle cases run with physics.derailment new eu07_td_buckle_derails waits for the "derailed on buckled track" line, which only the criteria of physics.derailment new write. It was written with new as the default; since monitor is the default (0645096e) the criteria only log "derailment monitor: ... overturned at 46 km/h on track tdo_n222" and the train runs on to Przystanek, so the case failed. The case sets the mode itself now. eu07_td_buckle_event sets it too: under monitor its "no Bad driving" check said nothing about the criteria. * docs(scenarios): the buckle cases and the derailment mode they set --- tests/scenarios/README.md | 9 +++++++++ tests/scenarios/cases/eu07_td_buckle_derails.json | 4 ++-- tests/scenarios/cases/eu07_td_buckle_event.json | 4 ++-- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index 7e9ceef7c..f65d96fb2 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -278,6 +278,15 @@ pushed, runs onto `tor1k` (`eventall2`), with the train still moving, and the bl locomotive coupled to the coaches (it couples about 70 s after the start). A driver that leaves its hand brake on under Connect pulls against it for good and the case ends as a standstill after 300 s. +The `eu07_td_buckle_*` cases (fragment `td_buckle_event.scn`) run the timetable train of +`td_timetable.scn` and buckle the curve `tdo_n222`, about 950 m ahead of it, with a `trackbuckle` +event of `vars.amplitude` at 10:35. Both have `physics.derailment new` in `ini`: the default, +`monitor`, leaves the decision to the legacy draw and only logs what the criteria would do +(`derailment monitor: ... overturned at 46 km/h on track tdo_n222`), so the train runs on to +Przystanek whatever the buckle. With 600 mm over a main lobe of 8 m the locomotive overturns on +the buckle at 46 km/h, 1036 m from the start (`Bad driving: ... derailed on buckled track`); with +30 mm it keeps on the rails and stops at Przystanek after 1400 m. + The `*_td_crew_*` cases (eu07/maszyna#510, fragment `td_crew.scn`) are about the crew command of a `putvalues` event, `Crew: `: cab 1 or -1 puts an AI driver in cab A or B of the vehicle named, 0 takes its AI driver off. The vehicle is named in the text, so the events are diff --git a/tests/scenarios/cases/eu07_td_buckle_derails.json b/tests/scenarios/cases/eu07_td_buckle_derails.json index 5caaa60b6..8506736a5 100644 --- a/tests/scenarios/cases/eu07_td_buckle_derails.json +++ b/tests/scenarios/cases/eu07_td_buckle_derails.json @@ -1,5 +1,5 @@ { - "description": "EU07 on td.scn on the td/rozklad timetable; at 10:35, as it leaves, the curve tdo_n222 about 950 m ahead buckles hard with a trackbuckle event: 600 mm out of the curve over a main lobe of 8 m (an equivalent radius of 9 m, about 30 m for the body on axles 11 m apart). The AI doesn't see it and runs into it at the 46 km/h it has there: the locomotive leaves the rails on the buckle and stops short of Przystanek.", + "description": "EU07 on td.scn on the td/rozklad timetable; at 10:35, as it leaves, the curve tdo_n222 about 950 m ahead buckles hard with a trackbuckle event: 600 mm out of the curve over a main lobe of 8 m (an equivalent radius of 9 m, about 30 m for the body on axles 11 m apart). The AI doesn't see it and runs into it at the 46 km/h it has there: with physics.derailment new (the default, monitor, only logs what the criteria would do and the train runs on) the locomotive leaves the rails on the buckle and stops short of Przystanek.", "base_scenery": "td.scn", "time": "10:34", "fragment": "td_buckle_event.scn", @@ -7,7 +7,7 @@ "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic", "amplitude": "600 8" }, - "ini": ["gfxrenderer null"], + "ini": ["gfxrenderer null", "physics.derailment new"], "duration": 240, "timeout": 600, "checks": [ diff --git a/tests/scenarios/cases/eu07_td_buckle_event.json b/tests/scenarios/cases/eu07_td_buckle_event.json index 192fa9b5a..13e0da7bc 100644 --- a/tests/scenarios/cases/eu07_td_buckle_event.json +++ b/tests/scenarios/cases/eu07_td_buckle_event.json @@ -1,5 +1,5 @@ { - "description": "EU07 on td.scn on the td/rozklad timetable; at 10:35, as it leaves, the curve tdo_n222 about 950 m ahead buckles with a trackbuckle event (30 mm out of the curve, as the heat does: an equivalent radius of 330 m, too little to derail it). The track is laid again during the game and the train keeps on it to Przystanek.", + "description": "EU07 on td.scn on the td/rozklad timetable; at 10:35, as it leaves, the curve tdo_n222 about 950 m ahead buckles with a trackbuckle event (30 mm out of the curve, as the heat does: an equivalent radius of 330 m, too little to derail it). The track is laid again during the game and the train keeps on it to Przystanek, with physics.derailment new: the criteria decide, as in eu07_td_buckle_derails.", "base_scenery": "td.scn", "time": "10:34", "fragment": "td_buckle_event.scn", @@ -7,7 +7,7 @@ "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic", "amplitude": "30" }, - "ini": ["gfxrenderer null"], + "ini": ["gfxrenderer null", "physics.derailment new"], "duration": 240, "timeout": 600, "checks": [ From 677795e595ba45f7d13b8c26ea0014f4a3518a6e Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:11:51 +0100 Subject: [PATCH 098/136] test(scenarios): brakes cut out once a train formed by coupling stands (#282) (#436) An EU07 couples on the run to a cut of 16 coaches with P alone and 8 wagons with G, 541 m, and runs it on as a train: a train on G, whose coaches have their brakes cut out (Cw-1 19.9). The inspector looks at the train at 4 km/h as it couples and leaves the cut-outs to reinspect_brakes(), which makes them as the train stands just after. Taking the driver off at 38 km/h shows it: the train stops at 0.27 m/s2 over 211 m, against 0.57 m/s2 over 99 m with every brake working (the second case, with ai.brakesetting.cw1 no). stops_driverless takes optional min_deceleration and max_deceleration. --- tests/scenarios/README.md | 22 +++++- ...07_td_reinspect_brakes_after_coupling.json | 69 ++++++++++++++++++ ..._td_reinspect_brakes_legacy_inspector.json | 71 +++++++++++++++++++ tests/scenarios/cases/td_reinspect_brakes.scn | 33 +++++++++ tests/scenarios/run.py | 17 +++-- 5 files changed, 207 insertions(+), 5 deletions(-) create mode 100644 tests/scenarios/cases/eu07_td_reinspect_brakes_after_coupling.json create mode 100644 tests/scenarios/cases/eu07_td_reinspect_brakes_legacy_inspector.json create mode 100644 tests/scenarios/cases/td_reinspect_brakes.scn diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index f65d96fb2..b85f0f8cf 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -341,6 +341,23 @@ brake of the Vectron switched on), and `event0` of the track gives the driver `O starts up, charges the brake pipe and leaves on time (the stop after 209 s and 1393 m); without the `H` the pipe stays below 1 bar and the case ends as a standstill after 300 s. +`eu07_td_reinspect_brakes_after_coupling` (fragment `td_reinspect_brakes.scn`, eu07/maszyna#350 and #282) is about the +wagon inspector of the AI (`TController::AutoRewident()`) on a train formed by coupling. An EU07 stands cold on the line +from Stacja1 (`koniec`) and a cut stands 45 m ahead of it, braked, with nobody in it: 16 coaches with P alone (BDhpumn) +and next to the locomotive 8 empty wagons with G and P (401W), 541 m of wagons. `event0` of the locomotive's track gives +the driver `Shunt -3 3`, once: couple to the cut with the coupler and the brake hose and run it on as a train +(`Obey_train`), waiting for the way, which `event2` of `tdo_n231`, in front of the cut, gives as a `SetVelocity 40 40` +(no signal of the line is in sight). Over 500 m of wagons make it a train on G (Cw-1 §19.1), where the brake of a wagon +without G is cut out (§19.9). The inspector looks at the train as the AI couples, at 4 km/h (t=69 s), too fast for it to +cut a brake out, and leaves that for the next standstill: `reinspect_brakes()` cuts the 16 coaches out as the train stands +a moment later, its brakes applied by the empty pipe of the cut. Neither the physicslog nor the black box has the brakes +of the wagons, so the case tells by how the train brakes: `event2` of `tdo_n240` takes the driver off at 38 km/h, which +leaves the brake valve in the emergency position, and braked by the locomotive and the 8 wagons alone the train stops 29 s +and 211 m later, a mean deceleration of 0.27 m/s² (`stops_driverless` with `max_deceleration` 0.40). With every brake +working it stops at 0.57 m/s², 99 m: that is `eu07_td_reinspect_brakes_legacy_inspector`, the same run with the inspector +of the earlier releases (`ai.brakesetting.cw1 no`), which cuts no brake out, and also what a build whose +`reinspect_brakes()` does nothing gives for the first case, which then fails. The test passes 150 s after the driver goes. + ### Cases on a mission of a scenery The cases made from players' reports (eu07/maszyna#421, #506, #524, #525) run a whole mission @@ -433,7 +450,10 @@ the row instead, logged by builds from this branch on. (1 m), `hold` (60 s): the black box has the vehicle lose its driver at `min_speed` or faster, stand `within` seconds later and stay within `max_creep` of where it stopped for the rest of the recording, or until it gets a driver again, at least `hold` seconds. The physicslog can't - tell: the driver writes it, so it ends when the driver goes. + tell: the driver writes it, so it ends when the driver goes. Optional `min_deceleration`, + `max_deceleration` (m/s²): the mean deceleration of that stop, from the speed the driver left at + and the way to the stop (v²/2s), has to be within them, e.g. a train some of whose brakes are + cut out stops slower. - `moves` `vehicle`, `min_speed`, optional `direction` (`front`, or `rear`): the black box has the vehicle reach `min_speed` with that end leading (the physicslog speed has no direction). diff --git a/tests/scenarios/cases/eu07_td_reinspect_brakes_after_coupling.json b/tests/scenarios/cases/eu07_td_reinspect_brakes_after_coupling.json new file mode 100644 index 000000000..be4b96feb --- /dev/null +++ b/tests/scenarios/cases/eu07_td_reinspect_brakes_after_coupling.json @@ -0,0 +1,69 @@ +{ + "description": "eu07/maszyna#350, #282: an EU07 on td.scn couples on the run (Shunt -3 3) to a cut standing on the line, 16 coaches with P alone and 8 empty wagons with G and P, 541 m of wagons, and runs it on as a train (Obey_train): a train on G (Cw-1 19.1), so the brakes of the coaches are to be cut out (19.9). The inspector looks at the train as it couples, at 4 km/h, and leaves the cut-outs for the standstill; reinspect_brakes() makes them as the train stands just after. The driver taken off at 38 km/h leaves the brake valve in the emergency position: braked by the locomotive and the 8 wagons alone the train stops at some 0.27 m/s2, over 210 m (with every brake working, 0.57 m/s2 over 99 m).", + "base_scenery": "td.scn", + "fragment": "td_reinspect_brakes.scn", + "vars": { + "locomotive": "pkp\\4e_v1 4e-004 4e", + "cut": [ + "node -1 0 {{vehicle}}_c01 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c02 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c03 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c04 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c05 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c06 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c07 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c08 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c09 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c10 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c11 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c12 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c13 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c14 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c15 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c16 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w1 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w2 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w3 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w4 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w5 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w6 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w7 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w8 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 0 0 enddynamic" + ] + }, + "track_events": { + "koniec": "event0 autotest_wake", + "tdo_n231": "event2 autotest_way", + "tdo_n240": "event2 autotest_crew_off" + }, + "test_config": [ + "test.timeout 1200", + "test.standstill 600" + ], + "expect": "pass", + "timeout": 600, + "checks": [ + { + "type": "couples", + "vehicle": "{{vehicle}}", + "other": "{{vehicle}}_w8" + }, + { + "type": "stops_driverless", + "vehicle": "{{vehicle}}", + "min_speed": 30, + "within": 90, + "hold": 60, + "min_deceleration": 0.15, + "max_deceleration": 0.4 + }, + { + "type": "log_lacks", + "pattern": "derailed" + }, + { + "type": "log_lacks", + "pattern": "collided" + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_reinspect_brakes_legacy_inspector.json b/tests/scenarios/cases/eu07_td_reinspect_brakes_legacy_inspector.json new file mode 100644 index 000000000..e3a03c2da --- /dev/null +++ b/tests/scenarios/cases/eu07_td_reinspect_brakes_legacy_inspector.json @@ -0,0 +1,71 @@ +{ + "description": "The train of eu07_td_reinspect_brakes_after_coupling with the inspector of the releases before eu07/maszyna#350 (ai.brakesetting.cw1 no), which cuts no brake out: every brake of the train works, and the emergency stop after the driver is taken off at 38 km/h comes at some 0.57 m/s2, over 99 m. It shows what the deceleration check of that case tells apart.", + "base_scenery": "td.scn", + "fragment": "td_reinspect_brakes.scn", + "vars": { + "locomotive": "pkp\\4e_v1 4e-004 4e", + "cut": [ + "node -1 0 {{vehicle}}_c01 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c02 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c03 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c04 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c05 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c06 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c07 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c08 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c09 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c10 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c11 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c12 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c13 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c14 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c15 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c16 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w1 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w2 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w3 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w4 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w5 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w6 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w7 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w8 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 0 0 enddynamic" + ] + }, + "track_events": { + "koniec": "event0 autotest_wake", + "tdo_n231": "event2 autotest_way", + "tdo_n240": "event2 autotest_crew_off" + }, + "test_config": [ + "test.timeout 1200", + "test.standstill 600" + ], + "expect": "pass", + "timeout": 600, + "checks": [ + { + "type": "couples", + "vehicle": "{{vehicle}}", + "other": "{{vehicle}}_w8" + }, + { + "type": "stops_driverless", + "vehicle": "{{vehicle}}", + "min_speed": 30, + "within": 60, + "hold": 60, + "min_deceleration": 0.45 + }, + { + "type": "log_lacks", + "pattern": "derailed" + }, + { + "type": "log_lacks", + "pattern": "collided" + } + ], + "ini": [ + "ai.brakesetting.cw1 no" + ] +} diff --git a/tests/scenarios/cases/td_reinspect_brakes.scn b/tests/scenarios/cases/td_reinspect_brakes.scn new file mode 100644 index 000000000..37c76550a --- /dev/null +++ b/tests/scenarios/cases/td_reinspect_brakes.scn @@ -0,0 +1,33 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// on the line from Stacja1 to Stacja2 (flat, curves of 600 m): a locomotive with an AI driver stands cold +// (trainset velocity 0) on koniec, its front 35 m past point 1 of the track, facing point 2, towards Stacja2; +// a cut of wagons (vars.cut) stands, braked as well and with nobody in it, ahead of it, its front 56 m past +// point 1 of tdo_n222, some 45 m in front of the locomotive. +trainset none koniec 35.0 0.0 +node -1 0 {{vehicle}} dynamic {{locomotive}} 0 headdriver 0 0 enddynamic +endtrainset + +trainset none tdo_n222 56.0 0.0 +{{cut}} +endtrainset + +// event0 of the locomotive's track (the case's track_events) runs while the locomotive stands there. it wakes +// the driver and gives it, once, the order to couple to the cut ahead and run it on as a train: Shunt -3 3, +// Connect (with the coupler and the brake hose) then Obey_train, which waits for the way to be given. the AI +// couples on the run, at some 4 km/h, and the wagon inspector of the train run looks at the new train then, +// before it stands. +node -1 0 autotest_ordered memcell 0 0 0 ordered 0 0 none endmemcell +event autotest_wake multiple 0 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event autotest_order PutValues 0 none 0 0 0 Shunt -3 3 endevent +event autotest_order_given UpdateValues 0 autotest_ordered * 1 * endevent + +// the way: no signal of the line is in sight, so event2 of tdo_n231 (the case's track_events), 40 m in front of +// the cut, gives the speed a signal at proceed would, 40 km/h, which the AI reads as it scans the track ahead +event autotest_way PutValues 0 none 0 0 0 SetVelocity 40 40 endevent + +// event2 of tdo_n240 (the case's track_events), some 700 m on, as the locomotive runs over it pushing the train: +// the driver is taken off (Crew: 0 0), which leaves the brake valve in the emergency position, so the +// train stops on the brakes it has. the pass comes 150 s later, with the train standing. +event autotest_crew_off multiple 0 none autotest_driver_off autotest_pass endevent +event autotest_driver_off putvalues 0 none 0 0 0 Crew:{{vehicle}} 0 0 endevent +event autotest_pass UpdateValues 150 __test.result the_train_was_stopped_with_the_brakes_it_has 1 * endevent diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py index fd1941577..35e923bee 100644 --- a/tests/scenarios/run.py +++ b/tests/scenarios/run.py @@ -705,9 +705,11 @@ def check_driver_changes(box, vehicle, to, after=0.0, before=None): return True, f"{vehicle} has driver {to} from t={change.time:.1f}s to the end (t={box.end_time:.1f}s)" -def check_stops_driverless(box, vehicle, min_speed, within, stop_speed=0.5, max_creep=1.0, hold=60.0): +def check_stops_driverless(box, vehicle, min_speed, within, stop_speed=0.5, max_creep=1.0, hold=60.0, + min_deceleration=None, max_deceleration=None): """The vehicle loses its driver at `min_speed` or faster, stands `within` seconds later and stays where it - stopped, to the end of the recording or until it gets a driver again.""" + stopped, to the end of the recording or until it gets a driver again. With the decelerations, the mean one of + that stop (from the speed and the way to the stop, m/s²) has to be within them: how well the train brakes.""" states, why = _vehicle_states(box, vehicle) if states is None: return False, why @@ -734,8 +736,15 @@ def check_stops_driverless(box, vehicle, min_speed, within, stop_speed=0.5, max_ if fastest > stop_speed or creep > max_creep: return False, f"{vehicle} stood at t={stop.time:.1f}s, then moved {creep:.1f} m at up to {fastest:.1f} km/h with no driver" way = sum(math.dist(a.position, b.position) for a, b in zip(after, after[1:]) if b.time <= stop.time) - return True, (f"{vehicle} lost its driver at t={left.time:.1f}s at {abs(left.speed):.1f} km/h, stood {stop.time - left.time:.0f}s " - f"and {way:.0f} m later, moved {creep:.2f} m in the {until - stop.time:.0f}s {alone}") + stopped = (f"{vehicle} lost its driver at t={left.time:.1f}s at {abs(left.speed):.1f} km/h, stood {stop.time - left.time:.0f}s " + f"and {way:.0f} m later") + # v² / 2s: the black box lists a vehicle once a second, so the way is closer to the truth than the time + deceleration = (abs(left.speed) / 3.6) ** 2 / (2 * way) if way > 0 else math.inf + if ((min_deceleration is not None and deceleration < min_deceleration) + or (max_deceleration is not None and deceleration > max_deceleration)): + bounds = f"{min_deceleration if min_deceleration is not None else 0:g}..{max_deceleration if max_deceleration is not None else 'any'}" + return False, f"{stopped}: a mean deceleration of {deceleration:.2f} m/s², outside {bounds}" + return True, f"{stopped} ({deceleration:.2f} m/s²), moved {creep:.2f} m in the {until - stop.time:.0f}s {alone}" def check_moves(box, vehicle, min_speed, direction="front"): From 57a0a71f4825bf5717f7c31d6599209b5986b67c Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:12:15 +0100 Subject: [PATCH 099/136] fix(ci): build and run the shader validator again (#437) * fix(ci): build and run the shader validator again - gl/glsl_common.h and gl/shader.cpp include utilities/Globals.h and utilities/Logs.h now, so the stand-in headers of the validator move to ci_shadervalidator/utilities/. - gl/ubo.h needs std::span and gl/shader.cpp uses contains(), so the script builds with -std=c++20. The stand-in stdafx.h gives , and , which the precompiled header of the simulator gives otherwise. - build.sh runs from any directory and stops on the first error. - glslang defines the GL_ARB_gpu_shader5 macro without the #extension directive, so light_common.glsl took its textureGather() path without the extension enabled and 25 material shaders failed on desktop GL with the shadows on. The validator adds the directive which the simulator gives on the drivers with the extension. - The shader goes to the temporary directory of the system instead of a fixed /tmp, a shader which can't be preprocessed fails instead of ending the run, the shaders go in name order and the failed ones are listed at the end. * fix(ci): write the validated shader to a unique temporary file The shader validator wrote every preprocessed shader to a file with a fixed name in the temporary directory (/tmp/shader on Linux) and opened it with std::ofstream. In a shared /tmp anyone can create that name in advance, as a file or a link to another file, and the validator would then write through it (Sonar rule S5443, publicly writable directories). The shader now goes to a file with a unique name which is created exclusively: mkstemp() on Linux, and on Windows, which has no mkstemp(), a random name opened with fopen_s(..., "wx"), which fails when the file exists. The file is removed after glslangValidator has checked it, and when it cannot be written completely. glslangValidator gets the stage with -S, so the file still needs no extension. * docs(ci): the standalone validator no longer checks the PCF fallback path The comment of has_gl_extension() said the validator compiles the 16-tap PCF fallback of light_common.glsl. Since the validator adds the GL_ARB_gpu_shader5 directive itself, it checks the textureGather() path. --- ci_shadervalidator/build.sh | 7 +- ci_shadervalidator/main.cpp | 99 +++++++++++++++++--- ci_shadervalidator/stdafx.h | 5 + ci_shadervalidator/{ => utilities}/Globals.h | 0 ci_shadervalidator/{ => utilities}/Logs.h | 0 gl/shader.cpp | 6 +- 6 files changed, 101 insertions(+), 16 deletions(-) rename ci_shadervalidator/{ => utilities}/Globals.h (100%) rename ci_shadervalidator/{ => utilities}/Logs.h (100%) diff --git a/ci_shadervalidator/build.sh b/ci_shadervalidator/build.sh index b0207f6ed..fe13b9c63 100755 --- a/ci_shadervalidator/build.sh +++ b/ci_shadervalidator/build.sh @@ -1,2 +1,7 @@ #!/bin/sh -g++ -std=c++17 -O2 -DSHADERVALIDATOR_STANDALONE ../ref/glad/src/glad.c ../gl/glsl_common.cpp ../gl/shader.cpp main.cpp -I../ref/glad/include -I../ref/glm -I. -o validateshaders +# builds the shader validator next to this script. it compiles gl/shader.cpp and gl/glsl_common.cpp of the +# simulator against the stand-in headers of this directory (stdafx.h, utilities/Globals.h, utilities/Logs.h) +# and needs glslangValidator on PATH to run. run validateshaders from this directory +set -e +cd "$(dirname "$0")" +${CXX:-g++} -std=c++20 -O2 -DSHADERVALIDATOR_STANDALONE ../ref/glad/src/glad.c ../gl/glsl_common.cpp ../gl/shader.cpp main.cpp -I../ref/glad/include -I../ref/glm -I. -o validateshaders diff --git a/ci_shadervalidator/main.cpp b/ci_shadervalidator/main.cpp index 65ad54b2a..bd7db0523 100644 --- a/ci_shadervalidator/main.cpp +++ b/ci_shadervalidator/main.cpp @@ -1,20 +1,70 @@ #include "stdafx.h" #include "../gl/shader.h" #include "../gl/glsl_common.h" -#include "Globals.h" +#include "utilities/Globals.h" #include -#include +#include #include #include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif _global Global; +// writes the text to a new file with a unique name in the temporary directory of the system and returns its path, +// or an empty string when it cannot be written. the file is created exclusively, so nothing put in a shared /tmp +// under a name known in advance (a file or a link) is written through +std::string write_temp_file(std::string const &text) +{ + std::string path = (std::filesystem::temp_directory_path() / "maszyna-shader-XXXXXX").string(); + std::FILE *file = nullptr; +#ifdef _WIN32 + // no mkstemp() in the CRT; a random name, opened with "x", which fails when the file is there already + std::random_device random; + for (int attempt = 0; attempt < 100 && file == nullptr; ++attempt) { + path.replace(path.size() - 6, 6, std::to_string(100000 + random() % 900000)); + if (fopen_s(&file, path.c_str(), "wx") != 0) + file = nullptr; + } +#else + int const descriptor = mkstemp(path.data()); + if (descriptor != -1) { + file = fdopen(descriptor, "w"); + if (file == nullptr) { + close(descriptor); + std::remove(path.c_str()); + } + } +#endif + if (file == nullptr) + return {}; + + bool const written = std::fwrite(text.data(), 1, text.size(), file) == text.size(); + if (std::fclose(file) != 0 || !written) { + std::remove(path.c_str()); + return {}; + } + return path; +} + bool check_shader(std::string filename) { gl::shader shader_processor; gl::glsl_common_setup(); - std::pair source = shader_processor.process_source(filename, "../shaders/"); + std::pair source; + try { + source = shader_processor.process_source(filename, "../shaders/"); + } + catch (gl::shader_exception const &e) { + std::cout << "failed to preprocess: " << e.what() << std::endl; + return false; + } std::string stage; if (source.first == GL_VERTEX_SHADER) @@ -26,11 +76,26 @@ bool check_shader(std::string filename) else return false; - std::ofstream file("/tmp/shader"); - file << source.second; - file.close(); + // glslang defines the GL_ARB_gpu_shader5 macro without the #extension directive, so light_common.glsl + // takes its textureGather() path, which needs the extension enabled on desktop GL 3.30. has_gl_extension() + // of gl/shader.cpp has no GL context here and says no, so the directive which the simulator gives on the + // drivers with the extension is added here + std::string const gpu_shader5 = "#extension GL_ARB_gpu_shader5 : enable\n"; + if (!Global.gfx_usegles && source.second.find(gpu_shader5) == std::string::npos) { + std::size_t const version_end = source.second.find('\n'); + if (version_end != std::string::npos) + source.second.insert(version_end + 1, gpu_shader5); + } - int ret = system(("glslangValidator -S " + stage + " /tmp/shader").c_str()); + // the stage is given with -S, so the file needs no extension + std::string const path = write_temp_file(source.second); + if (path.empty()) { + std::cout << "cannot write the shader to the temporary directory" << std::endl; + return false; + } + + int ret = system(("glslangValidator -S " + stage + " \"" + path + "\"").c_str()); + std::remove(path.c_str()); return ret == 0; } @@ -90,24 +155,32 @@ bool check_shader_confs(std::string filename) int main() { - bool suc = true; + // in name order, so the runs can be compared + std::vector shaders; for (auto &f : std::filesystem::recursive_directory_iterator("../shaders/")) { if (!f.is_regular_file()) continue; - std::string relative = std::filesystem::relative(f.path(), "../shaders/").string(); if (f.path().extension() != ".frag" && f.path().extension() != ".geom" && f.path().extension() != ".vert") continue; + shaders.push_back(std::filesystem::relative(f.path(), "../shaders/").generic_string()); + } + std::sort(shaders.begin(), shaders.end()); + + std::vector failed; + for (auto const &relative : shaders) { std::cout << "== validating shader " << relative << ": " << std::flush; if (!check_shader_confs(relative)) - suc = false; + failed.push_back(relative); } - if (suc) - std::cout << "==== all checks ok" << std::endl; + if (failed.empty()) + std::cout << "==== all checks ok (" << shaders.size() << " shaders)" << std::endl; else { - std::cout << "==== checks failed" << std::endl; + std::cout << "==== checks failed for " << failed.size() << " of " << shaders.size() << " shaders:" << std::endl; + for (auto const &relative : failed) + std::cout << relative << std::endl; return 1; } diff --git a/ci_shadervalidator/stdafx.h b/ci_shadervalidator/stdafx.h index 5e0560889..093baa4d2 100644 --- a/ci_shadervalidator/stdafx.h +++ b/ci_shadervalidator/stdafx.h @@ -1,6 +1,11 @@ #pragma once +// stands in for the precompiled header of the simulator, with what gl/shader.cpp, gl/glsl_common.cpp and the +// headers they include take from it #define GLM_ENABLE_EXPERIMENTAL #define GLM_FORCE_CTOR_INIT #include +#include +#include #include +#include #include diff --git a/ci_shadervalidator/Globals.h b/ci_shadervalidator/utilities/Globals.h similarity index 100% rename from ci_shadervalidator/Globals.h rename to ci_shadervalidator/utilities/Globals.h diff --git a/ci_shadervalidator/Logs.h b/ci_shadervalidator/utilities/Logs.h similarity index 100% rename from ci_shadervalidator/Logs.h rename to ci_shadervalidator/utilities/Logs.h diff --git a/gl/shader.cpp b/gl/shader.cpp index c276cdef8..feb5d95dc 100644 --- a/gl/shader.cpp +++ b/gl/shader.cpp @@ -30,8 +30,10 @@ namespace { // SHADERVALIDATOR_STANDALONE gates out the GL queries because the offline // shader validator tool links glad.c but never calls gladLoadGL(); the // function pointers stay null and a real call would crash. Returning -// false there means the standalone validator simply compiles the original -// 16-tap PCF fallback path in light_common.glsl, which is what we want. +// false there adds no #extension directive. For desktop GL the validator +// adds GL_ARB_gpu_shader5 itself (ci_shadervalidator/main.cpp), since +// glslang defines that macro anyway, so light_common.glsl is validated on +// its textureGather() path, not on the 16-tap PCF fallback. bool has_gl_extension(char const *name) { #ifdef SHADERVALIDATOR_STANDALONE (void)name; From 7059644209d48157bdfd9748677cfbafd87e2dc0 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:13:18 +0100 Subject: [PATCH 100/136] fix(editor): a model file named outside the code page no longer crashes the first track selection (#470) * fix(editor): a model file named outside the code page no longer crashes the first track selection The first selection of a track builds the track property list, and with it the sleeper and timber model choices. pack_models() walked the whole models/ tree and turned the name of every .t3d/.e3d into a narrow string before looking at whether it was a sleeper at all. On Windows that goes through the ANSI code page, so a single model file anywhere under models/ named with a character the code page lacks threw std::system_error "No mapping for the Unicode character exists in the target multi-byte code page" out of the editor frame and the editor stopped (GE#560). The conversions are now in a try, as in the editor's other folder scans: a file whose name can't be converted is left out (the game couldn't load it by that name anyway) and the scan goes on. Names that convert give the same list as before. The scan itself moved to world/SleeperPack.cpp in the core library as pack_models(root), which pack_models() calls once with models/, so the unit tests can run it on a folder of their own. * fix(launcher): a vehicle folder named outside the code page is skipped by the skin scan scan_textures() keeps the folder of each textures.txt as a wide path and get_vehicle() turns it into a narrow name with no try. On Windows a folder under dynamic/ named with a character the code page lacks threw the same std::system_error out of the editor's vehicle tool, the launcher and the vehicle picker. Such a folder is now left out of the scan, as the model scan does with such a file. --- CMakeLists.txt | 1 + launcher/textures_scanner.cpp | 12 +++- tests/unit/test_sleeper_models.cpp | 67 ++++++++++++++++++++++ world/SleeperModels.cpp | 55 +----------------- world/SleeperPack.cpp | 91 ++++++++++++++++++++++++++++++ world/TrackSleepers.h | 4 ++ 6 files changed, 175 insertions(+), 55 deletions(-) create mode 100644 tests/unit/test_sleeper_models.cpp create mode 100644 world/SleeperPack.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 294128b87..ddffc7402 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -550,6 +550,7 @@ set(CORE_SOURCES "McZapkie/derailment.cpp" "McZapkie/collision.cpp" "world/TrackCheck.cpp" +"world/SleeperPack.cpp" "McZapkie/Oerlikon_ESt.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" diff --git a/launcher/textures_scanner.cpp b/launcher/textures_scanner.cpp index 741f978ca..480bd5671 100644 --- a/launcher/textures_scanner.cpp +++ b/launcher/textures_scanner.cpp @@ -9,8 +9,18 @@ void ui::vehicles_bank::scan_textures() if (f->path().filename() != "textures.txt") continue; + auto const folder{std::filesystem::relative(f->path().parent_path(), "dynamic/", error)}; + try { + // the vehicles are kept by narrow names. on Windows a folder named with a character the code page lacks + // can't be given one and would throw at the first vehicle; the game couldn't load it by that name anyway + [[maybe_unused]] auto const name{folder.generic_string()}; + } + catch (std::system_error const &) { + continue; + } + ctx_path = folder; + std::fstream stream(f->path(), std::ios_base::binary | std::ios_base::in); - ctx_path = std::filesystem::relative(f->path().parent_path(), "dynamic/", error); std::string line; while (std::getline(stream, line)) diff --git a/tests/unit/test_sleeper_models.cpp b/tests/unit/test_sleeper_models.cpp new file mode 100644 index 000000000..05d90ab32 --- /dev/null +++ b/tests/unit/test_sleeper_models.cpp @@ -0,0 +1,67 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scratch.h" + +#include "world/TrackSleepers.h" + +#include +#include +#include + +// the models of sleepers and timbers the track editor lists (world/TrackSleepers.h), found by the names of the files in a +// folder. a file named with a character the code page lacks is left out, rather than throwing out of the scan (GE#560) + +namespace { + +void write_model(std::filesystem::path const &Path, std::string const &Content) { + std::filesystem::create_directories(Path.parent_path()); + std::ofstream file{Path, std::ios::binary}; + file << Content; +} + +// whether the name can be turned into the narrow names of the code page: on Windows a Chinese character can't be with any +// of the single byte pages, where the narrow names are UTF-8 it can +bool narrow_name(std::filesystem::path const &Path) { + try { + static_cast(Path.generic_string()); + return true; + } catch (std::exception const &) { + return false; + } +} + +} // namespace + +TEST_CASE("sleeper models: a file named outside of the code page is left out, the rest is listed") { + test::scratch_folder const folder{"sleeper_models"}; + auto const root{folder.root()}; + write_model(root / "pkp" / "podklad_a.t3d", "Name: podklad\n"); + write_model(root / "pkp" / "podrozjazd_b.t3d", "Name: begin\nName: main\nName: end\n"); + auto const odd{root / "pkp" / std::filesystem::path{u8"podklad_\u4e2d.t3d"}}; + write_model(odd, "Name: podklad\n"); + // nor any other model of the folder named so, looked at before its name tells it's no sleeper + write_model(root / "drzewa" / std::filesystem::path{u8"drzewo_\u4e2d.e3d"}, ""); + write_model(root / "drzewa" / "drzewo.e3d", ""); + REQUIRE(std::filesystem::exists(odd)); + + std::vector models; + REQUIRE_NOTHROW(models = track_sleepers::pack_models(root)); + + auto const listed{narrow_name(odd)}; + REQUIRE(models.size() == (listed ? 3u : 2u)); + // the timbers first, then by the name + CHECK(models[0].name == "pkp/podrozjazd_b"); + CHECK(models[0].timber); + CHECK(models[1].name == "pkp/podklad_a"); + CHECK_FALSE(models[1].timber); + if (listed) { + CHECK(models[2].name.find("pkp/podklad_") == 0); + } +} + +TEST_CASE("sleeper models: a folder missing lists none") { + test::scratch_folder const folder{"sleeper_models_missing"}; + std::vector models; + REQUIRE_NOTHROW(models = track_sleepers::pack_models(folder.root() / "missing")); + CHECK(models.empty()); +} diff --git a/world/SleeperModels.cpp b/world/SleeperModels.cpp index ad3c791c8..ada63d3a6 100644 --- a/world/SleeperModels.cpp +++ b/world/SleeperModels.cpp @@ -23,8 +23,6 @@ http://mozilla.org/MPL/2.0/. #include #include -#include -#include #include namespace track_sleepers { @@ -237,44 +235,6 @@ double plain_length( TTrack const &Track ) { return 2.0 * ( 0.5 * std::abs( Track.fTrackWidth ) + rail_reach + beam_overhang ); } -namespace { - -// the model of sleepers or timbers of the file added to those found, once by its name, what goes wrong left in the error -void add_pack_model( std::filesystem::directory_entry const &Entry, std::filesystem::path const &Root, std::error_code &Error, std::vector &Models ) { - - namespace fs = std::filesystem; - if( false == Entry.is_regular_file( Error ) ) { - return; - } - auto const extension { ToLower( Entry.path().extension().string() ) }; - if( extension != ".t3d" && extension != ".e3d" ) { - return; - } - auto name { ToLower( fs::relative( Entry.path(), Root, Error ).replace_extension().generic_string() ) }; - if( Error || name.empty() ) { - return; - } - if( name.find( "podklad" ) == std::string::npos && name.find( "podrozjazd" ) == std::string::npos - && name.find( "sleeper" ) == std::string::npos && name.find( "timber" ) == std::string::npos ) { - return; - } - // a timber model has the parts it's put together from, told by their names in the file - std::ifstream file { Entry.path(), std::ios::binary }; - std::string const content { std::istreambuf_iterator( file ), std::istreambuf_iterator() }; - auto const has = [ &extension, &content ]( std::string const &Part ) { - return ( - extension == ".t3d" ? - content.find( "Name: " + Part + "\n" ) != std::string::npos || content.find( "Name: " + Part + " " ) != std::string::npos - || content.find( "Name: " + Part + "\r" ) != std::string::npos : - content.find( std::string { '\0' } + Part + '\0' ) != std::string::npos ); }; - auto const timber { has( "begin" ) && has( "main" ) && has( "end" ) }; - if( std::ranges::none_of( Models, [ &name ]( pack_model const &Model ) { return Model.name == name; } ) ) { - Models.emplace_back( std::move( name ), timber ); - } -} - -} // namespace - std::vector const &pack_models() { static std::vector models; @@ -283,20 +243,7 @@ std::vector const &pack_models() { return models; } scanned = true; - namespace fs = std::filesystem; - std::error_code error; - auto const root { fs::path { paths::models } }; - fs::recursive_directory_iterator entry { root, fs::directory_options::follow_directory_symlink | fs::directory_options::skip_permission_denied, error }; - fs::recursive_directory_iterator const end; - while( entry != end ) { - if( error ) { - break; - } - add_pack_model( *entry, root, error, models ); - entry.increment( error ); - } - std::ranges::sort( models, []( pack_model const &Left, pack_model const &Right ) { - return ( Left.timber != Right.timber ? Left.timber : Left.name < Right.name ); } ); + models = pack_models( std::filesystem::path { paths::models } ); return models; } diff --git a/world/SleeperPack.cpp b/world/SleeperPack.cpp new file mode 100644 index 000000000..b04c573bb --- /dev/null +++ b/world/SleeperPack.cpp @@ -0,0 +1,91 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" + +#include "world/TrackSleepers.h" +#include "utilities/utilities.h" + +#include +#include +#include +#include + +// the models of sleepers and timbers found among the files of a folder, by their names; apart from the models drawn, so the +// unit tests can look through a folder of their own + +namespace track_sleepers { + +namespace { + +// the model of sleepers or timbers of the file added to those found, once by its name, what goes wrong left in the error +void add_pack_model( std::filesystem::directory_entry const &Entry, std::filesystem::path const &Root, std::error_code &Error, std::vector &Models ) { + + namespace fs = std::filesystem; + if( false == Entry.is_regular_file( Error ) ) { + return; + } + // a name with a character the code page lacks throws as it's turned into the narrow names the models are loaded by, which + // couldn't open the file anyway: the file is left out, not the rest of the folder with it + std::string extension; + std::string name; + try { + extension = ToLower( Entry.path().extension().string() ); + if( extension != ".t3d" && extension != ".e3d" ) { + return; + } + name = ToLower( fs::relative( Entry.path(), Root, Error ).replace_extension().generic_string() ); + } + catch( std::exception const & ) { + return; + } + if( Error || name.empty() ) { + return; + } + if( name.find( "podklad" ) == std::string::npos && name.find( "podrozjazd" ) == std::string::npos + && name.find( "sleeper" ) == std::string::npos && name.find( "timber" ) == std::string::npos ) { + return; + } + // a timber model has the parts it's put together from, told by their names in the file + std::ifstream file { Entry.path(), std::ios::binary }; + std::string const content { std::istreambuf_iterator( file ), std::istreambuf_iterator() }; + auto const has = [ &extension, &content ]( std::string const &Part ) { + return ( + extension == ".t3d" ? + content.find( "Name: " + Part + "\n" ) != std::string::npos || content.find( "Name: " + Part + " " ) != std::string::npos + || content.find( "Name: " + Part + "\r" ) != std::string::npos : + content.find( std::string { '\0' } + Part + '\0' ) != std::string::npos ); }; + auto const timber { has( "begin" ) && has( "main" ) && has( "end" ) }; + if( std::ranges::none_of( Models, [ &name ]( pack_model const &Model ) { return Model.name == name; } ) ) { + Models.emplace_back( std::move( name ), timber ); + } +} + +} // namespace + +std::vector pack_models( std::filesystem::path const &Root ) { + + namespace fs = std::filesystem; + std::vector models; + std::error_code error; + fs::recursive_directory_iterator entry { Root, fs::directory_options::follow_directory_symlink | fs::directory_options::skip_permission_denied, error }; + fs::recursive_directory_iterator const end; + while( entry != end ) { + if( error ) { + break; + } + add_pack_model( *entry, Root, error, models ); + entry.increment( error ); + } + std::ranges::sort( models, []( pack_model const &Left, pack_model const &Right ) { + return ( Left.timber != Right.timber ? Left.timber : Left.name < Right.name ); } ); + return models; +} + +} // namespace track_sleepers diff --git a/world/TrackSleepers.h b/world/TrackSleepers.h index a22bcb94a..9acd9dc25 100644 --- a/world/TrackSleepers.h +++ b/world/TrackSleepers.h @@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/. #include #include +#include #include #include #include @@ -123,6 +124,9 @@ struct pack_model { // the models of sleepers and timbers in the scenery data, found once in models/ by the names of their files telling sleepers // or timbers: podklad, podrozjazd, sleeper, timber. the timber ones first, then by the name std::vector const &pack_models(); +// the models of sleepers and timbers among the files under the folder given, named relative to it, in the same order; a file +// named with a character the code page lacks is left out +std::vector pack_models( std::filesystem::path const &Root ); // the beams of the track placed anew, as instances of the parts of the model void lay( TTrack &Track ); // the beams of the tracks around the track to be placed again, as they depend on where it runs From a3f4bd4f0d952f7912bbe3c5044194e2f350d4dc Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:13:37 +0100 Subject: [PATCH 101/136] fix(ai): a train standing past a signal when its speed table is traced hasn't passed it (#473) * fix(ai): a train standing past a signal when its speed table is traced hasn't passed it Since #409 a point of the speed table found behind the head counts as passed only when the head had it ahead once, but a point found up to 5 m behind the head still counted as seen ahead (SeenAheadTolerance), whether the train moved or stood. A train set at a stand 0.5-4.5 m past a signal at stop therefore found the signal behind its head at its first look ahead, the next update marked it elapsed, and the test mode ended with "signal passed at danger" at 13.6 s with the train at 0 km/h (EU07 on td.scn at stacja1_j; set 6 m or 20 m past, no report). The tolerance is kept for a moving train, which may be just passing a point found at its head. A standing train passes nothing: a point found behind its head counts as seen ahead only once an update finds it ahead. The rule moves out of TSpeedPos into vehicle/signalpassing.{h,cpp}, so it is unit tested; the blackbox record of passed signals follows it as before. Measured with the head set 0.5-6 m past and 0.5-2 m short of the signal on tor1k: the distance the scan finds is the head's own distance from the memory cell (to the micrometre there), so a train standing 0.5 m short still gets the signal ahead and passes it if it goes on. Tests: tests/unit/test_signal_passing.cpp (6 cases), and the scenario cases test_mode_standing_1m_past_signal and test_mode_standing_4m_past_signal (fragment td_past_red_signal.scn), which ended as signals passed at danger before and run into their timeout now. * test(scenarios): the shunting AI stops before a signal at stop on td.scn Two cases for the shunting fix of #409, left out of it: an EU07 with no timetable (its AI shunts) starting at 30 km/h about 150 m before the exit signal stacja1_j at stop, alone (eu07_td_shunt_red_signal) and pushing three coaches (eu07_td_shunt_push_red_signal), has to stop before the signal and stay there. They come from #340, whose braking was sharper; run on the code of #409 they stop after 145 m and 141 m, with the signal 151 m from the start, so the checks of #340 (no more than 150 m, below 40 km/h) hold as they were. * fix(sonar): count the metres of the signal passing test in an integer SonarCloud rule cpp:S2193 (a for loop counter of floating type) flagged the loop that moves the head a metre at a time in tests/unit/test_signal_passing.cpp and made the new reliability rating of the pull request fail the quality gate. The counter is now an int; it took whole values only, so every case runs the same number of steps as before. * fix(ai): the gap of a standing train a few decimetres short of a signal noted at seen_ahead_when_found --- CMakeLists.txt | 1 + tests/scenarios/README.md | 14 +- .../cases/eu07_td_shunt_push_red_signal.json | 24 ++++ .../cases/eu07_td_shunt_red_signal.json | 19 +++ tests/scenarios/cases/td_past_red_signal.scn | 7 + tests/scenarios/cases/td_shunt_red_signal.scn | 7 + .../test_mode_standing_1m_past_signal.json | 16 +++ .../test_mode_standing_4m_past_signal.json | 16 +++ tests/unit/test_signal_passing.cpp | 128 ++++++++++++++++++ vehicle/Driver.cpp | 28 ++-- vehicle/Driver.h | 3 +- vehicle/signalpassing.cpp | 30 ++++ vehicle/signalpassing.h | 38 ++++++ 13 files changed, 312 insertions(+), 19 deletions(-) create mode 100644 tests/scenarios/cases/eu07_td_shunt_push_red_signal.json create mode 100644 tests/scenarios/cases/eu07_td_shunt_red_signal.json create mode 100644 tests/scenarios/cases/td_past_red_signal.scn create mode 100644 tests/scenarios/cases/td_shunt_red_signal.scn create mode 100644 tests/scenarios/cases/test_mode_standing_1m_past_signal.json create mode 100644 tests/scenarios/cases/test_mode_standing_4m_past_signal.json create mode 100644 tests/unit/test_signal_passing.cpp create mode 100644 vehicle/signalpassing.cpp create mode 100644 vehicle/signalpassing.h diff --git a/CMakeLists.txt b/CMakeLists.txt index ddffc7402..200adcf30 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -571,6 +571,7 @@ set(CORE_SOURCES "vehicle/gaugewrap.cpp" "vehicle/drivingaid.cpp" "vehicle/brakingcurve.cpp" +"vehicle/signalpassing.cpp" "vehicle/handover.cpp" "vehicle/crew.cpp" "vehicle/horn.cpp" diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index b85f0f8cf..321b65479 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -135,7 +135,7 @@ Python 3.10+, no extra packages. Options: `cmake-build-*/bin/Release/eu07*.exe`. The build needs the `--test` and `-ini` command line options. - name one or more cases to run only those, e.g. `run.py ... eu07_td_timetable`. -- `-j N` runs N cases at once. Each case prints its results when it is done. The 22 cases +- `-j N` runs N cases at once. Each case prints its results when it is done. The 42 cases that aren't `slow` take about 30 s with `-j 4` and 2 minutes one at a time, loading included. - `--watch` runs a case the old way, in a visible window in real time (or faster with `--timespeed N`), closed after the case's `duration`; the exit code isn't checked then. For @@ -236,6 +236,11 @@ starting at `vars.velocity` km/h; with `track_friction` 0.03 it locks the wheels and slides past the signal, so those cases set `test.fail_if_stop_overran no`. `td_red_signal_pass.scn` adds the `test_pass` event, which `test_mode_pass` puts as `event0` on `tor1k`, the track in front of the signal. +`td_shunt_red_signal.scn` is the same with no timetable, so the AI shunts (Shunt) towards the signal at +stop, starting `vars.offset` m into `tdo_n1734`: `eu07_td_shunt_red_signal` alone and +`eu07_td_shunt_push_red_signal` pushing three coaches, both from 30 km/h, have to stop before the signal, +151 m from the start (the shunting AI used to coast up to it and pass it at about 28 km/h, fixed +by #409). They stop after 145 m and 141 m. `eu07_td_departure_station_capitals` runs an EU07 from where `td_timetable.scn` puts it, with the W4 of Stacja1 about 35 m ahead, on a timetable of its own (`td_departure_station_capitals.txt`, fragment `td_departure_station.scn`): @@ -259,6 +264,13 @@ standstill of 100 s ends the test although the traffic runs on (counting every v into the test timeout). `test_mode_pass_while_moving` reports the pass from `event2` of `tor1k` (the direction the train runs), as the train runs onto it, with `test.no_movement_before_pass no`, so the test ends with the train still moving. +`test_mode_standing_1m_past_signal` and `test_mode_standing_4m_past_signal` (fragment `td_past_red_signal.scn`) set +the td/rozklad train at a stand with its head 1 m and 4 m past the exit signal at stop (the memory cell of the +signal is 51 m into `tor1k`). The driver finds the signal behind the head at its first look ahead, 13.6 s in, and a +standing train passes nothing, so both run into their timeout. When a signal found up to 5 m behind the head +still counted as one the head had ahead, standing or not, both ended as signals passed at danger at 13.6 s (a +train set 6 m or 20 m past didn't). Starting at 0 km/h the driver doesn't wake up within the case, so they start at +0.1 km/h, as `td_red_signal.scn` does. The `en57_2000_automatic_coupler_*` cases (issue #86) share `td_automatic_coupler_hit.scn`: an EN57-2000 unit without a driver runs at `vars.velocity` km/h into a standing one, from diff --git a/tests/scenarios/cases/eu07_td_shunt_push_red_signal.json b/tests/scenarios/cases/eu07_td_shunt_push_red_signal.json new file mode 100644 index 000000000..243d37641 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_shunt_push_red_signal.json @@ -0,0 +1,24 @@ +{ + "description": "EU07 shunting on td.scn (no timetable, so its AI drives under Shunt), pushing three coaches with no route set, the first coach starting at 30 km/h about 150 m before the exit signal stacja1_j at stop: stops before the signal and stays there.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_shunt_red_signal.scn", + "vars": { + "offset": "0.0", + "velocity": "30", + "consist": [ + "node -1 0 {{vehicle}}_w1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_w2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_w3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + ] + }, + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "max_speed", "limit": 40 }, + { "type": "stops", "moving_speed": 5, "stop_speed": 0.5, "hold": 5 }, + { "type": "stays_stopped", "moving_speed": 5, "stop_speed": 0.5 }, + { "type": "distance", "max": 150 } + ] +} diff --git a/tests/scenarios/cases/eu07_td_shunt_red_signal.json b/tests/scenarios/cases/eu07_td_shunt_red_signal.json new file mode 100644 index 000000000..bc23046cd --- /dev/null +++ b/tests/scenarios/cases/eu07_td_shunt_red_signal.json @@ -0,0 +1,19 @@ +{ + "description": "EU07 shunting on td.scn (no timetable, so its AI drives under Shunt) with no route set, starting at 30 km/h about 150 m before the exit signal stacja1_j at stop: stops before the signal and stays there.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_shunt_red_signal.scn", + "vars": { + "offset": "0.0", + "velocity": "30", + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "max_speed", "limit": 40 }, + { "type": "stops", "moving_speed": 5, "stop_speed": 0.5, "hold": 5 }, + { "type": "stays_stopped", "moving_speed": 5, "stop_speed": 0.5 }, + { "type": "distance", "max": 150 } + ] +} diff --git a/tests/scenarios/cases/td_past_red_signal.scn b/tests/scenarios/cases/td_past_red_signal.scn new file mode 100644 index 000000000..e5e68da5f --- /dev/null +++ b/tests/scenarios/cases/td_past_red_signal.scn @@ -0,0 +1,7 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// the timetable train of td.scn (td/rozklad) set at a stand past the exit signal stacja1_j, which stays at stop +// (no route): the head {{offset}} m into tor1k, whose memory cell of the signal is 51 m into the track. the train +// starts at 0.1 km/h, as in td_red_signal.scn: set at 0 its AI driver doesn't wake up within the case +trainset td/rozklad tor1k {{offset}} 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_shunt_red_signal.scn b/tests/scenarios/cases/td_shunt_red_signal.scn new file mode 100644 index 000000000..649427247 --- /dev/null +++ b/tests/scenarios/cases/td_shunt_red_signal.scn @@ -0,0 +1,7 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// like td_red_signal_moving.scn (no route, the exit signal stacja1_j about 150 m ahead of the start of +// tdo_n1734 stays at stop), but the train has no timetable, so its AI driver shunts (Shunt), and it +// starts {{offset}} m into tdo_n1734, already moving at {{velocity}} km/h. +trainset none tdo_n1734 {{offset}} {{velocity}} +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/test_mode_standing_1m_past_signal.json b/tests/scenarios/cases/test_mode_standing_1m_past_signal.json new file mode 100644 index 000000000..4157dc52d --- /dev/null +++ b/tests/scenarios/cases/test_mode_standing_1m_past_signal.json @@ -0,0 +1,16 @@ +{ + "description": "Test mode, no signal passed at danger for a train set past a signal: EU07 on td.scn standing with its head 1 m past the exit signal stacja1_j at stop (no route). Its driver finds the signal behind the head at its first look ahead, about 13 s in; a standing train passes nothing, so it isn't a signal passed at danger, and the case runs into its timeout.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_past_red_signal.scn", + "vars": { + "offset": "52.0", + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 60, + "timeout": 600, + "checks": [ + { "type": "max_speed", "limit": 1 }, + { "type": "distance", "max": 1 } + ] +} diff --git a/tests/scenarios/cases/test_mode_standing_4m_past_signal.json b/tests/scenarios/cases/test_mode_standing_4m_past_signal.json new file mode 100644 index 000000000..b0b668873 --- /dev/null +++ b/tests/scenarios/cases/test_mode_standing_4m_past_signal.json @@ -0,0 +1,16 @@ +{ + "description": "Test mode, no signal passed at danger for a train set past a signal: EU07 on td.scn standing with its head 4 m past the exit signal stacja1_j at stop (no route). Its driver finds the signal behind the head at its first look ahead, about 13 s in; a standing train passes nothing, so it isn't a signal passed at danger, and the case runs into its timeout.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_past_red_signal.scn", + "vars": { + "offset": "55.0", + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 60, + "timeout": 600, + "checks": [ + { "type": "max_speed", "limit": 1 }, + { "type": "distance", "max": 1 } + ] +} diff --git a/tests/unit/test_signal_passing.cpp b/tests/unit/test_signal_passing.cpp new file mode 100644 index 000000000..16d3cd9eb --- /dev/null +++ b/tests/unit/test_signal_passing.cpp @@ -0,0 +1,128 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/signalpassing.h" + +// when a signal in the AI's speed table counts as passed by the train (TController::CheckSignalPassed): the test +// mode reports a signal at stop passed that way as "passed at danger", the blackbox records every passed signal. a +// train set or standing past a signal at the start of a scenario didn't pass it; within 5 m of the signal the test +// mode used to report it all the same. + +namespace { + +// a point of the speed table the way TSpeedPos keeps it: found by the scan of the route, then updated as the head +// moves on (TController::TableCheck: UpdateDistance, Update, CheckSignalPassed) +struct table_point { + double distance; // ahead of the head [m], negative behind it + bool seen_ahead; + bool elapsed{false}; + int passes{0}; // reports of the point passed + + table_point(double const Distance, bool const Standing) + : distance(Distance), seen_ahead(signal_passing::seen_ahead_when_found(Distance, Standing)) { + move(0.0); // the first update comes with the next check of the table, the train hasn't moved yet + } + + // the head moves Metres on, and the table updates the point + void move(double const Metres) { + distance -= Metres; + auto const elapsedbefore{elapsed}; + elapsed = elapsed || distance < 0.0; + seen_ahead = signal_passing::seen_ahead_on_update(distance, seen_ahead); + if (signal_passing::passed_now(elapsedbefore, elapsed, seen_ahead)) { + ++passes; + } + } + + // the head moves Metres on in steps of a metre + void run(double const Metres) { + for (int moved{0}; moved < Metres; ++moved) { + move(1.0); + } + } +}; + +auto constexpr standing{true}; +auto constexpr moving{false}; + +} // namespace + +TEST_CASE("signal passing: a train standing past a signal when its table is traced hasn't passed it") { + auto behind{0.0}; + // 1-4.5 m: reported as passed at danger before; 20 m: the train standing across the signal of #409 + SUBCASE("0.5 m") { behind = 0.5; } + SUBCASE("1 m") { behind = 1.0; } + SUBCASE("2 m") { behind = 2.0; } + SUBCASE("3 m") { behind = 3.0; } + SUBCASE("4 m") { behind = 4.0; } + SUBCASE("4.9 m") { behind = 4.9; } + SUBCASE("20 m") { behind = 20.0; } + CAPTURE(behind); + + table_point signal{-behind, standing}; + CHECK_FALSE(signal.seen_ahead); + // standing there a while, then pulling away from it + for (auto check{0}; check < 10; ++check) { + signal.move(0.0); + } + signal.run(200.0); + CHECK(signal.passes == 0); +} + +TEST_CASE("signal passing: a train standing short of a signal passes it when it moves on") { + auto ahead{0.0}; + SUBCASE("at the signal") { ahead = 0.0; } + SUBCASE("0.5 m") { ahead = 0.5; } + SUBCASE("10 m") { ahead = 10.0; } + SUBCASE("150 m") { ahead = 150.0; } + CAPTURE(ahead); + + table_point signal{ahead, standing}; + CHECK(signal.seen_ahead); + signal.move(0.0); + CHECK(signal.passes == 0); + signal.run(ahead + 50.0); + CHECK(signal.passes == 1); +} + +TEST_CASE("signal passing: a moving train passing a signal its table finds just behind the head passes it") { + // the table traced anew in motion, the head right at the signal: the distance is found in steps of a metre, + // so a signal just ahead may come out a little behind + auto behind{0.0}; + SUBCASE("0.5 m") { behind = 0.5; } + SUBCASE("3 m") { behind = 3.0; } + SUBCASE("at the tolerance") { behind = signal_passing::moving_tolerance; } + CAPTURE(behind); + + table_point signal{-behind, moving}; + CHECK(signal.seen_ahead); + CHECK(signal.passes == 1); + signal.run(100.0); + CHECK(signal.passes == 1); +} + +TEST_CASE("signal passing: a signal found further behind a moving train than the tolerance wasn't passed by it") { + table_point signal{-(signal_passing::moving_tolerance + 0.5), moving}; + CHECK_FALSE(signal.seen_ahead); + signal.run(100.0); + CHECK(signal.passes == 0); +} + +TEST_CASE("signal passing: a train that overruns a signal and stops past it passes it once") { + // the overrun counts while the train moves; a table traced again with the train standing 3 m past the signal + // (a change of direction and back, a new order) doesn't count it again + table_point approach{150.0, moving}; + approach.run(153.0); + CHECK(approach.passes == 1); + + table_point traced_again{-3.0, standing}; + traced_again.run(50.0); + CHECK(traced_again.passes == 0); +} + +TEST_CASE("signal passing: the report of a pass needs the point to become elapsed in this very update") { + CHECK(signal_passing::passed_now(false, true, true)); + CHECK_FALSE(signal_passing::passed_now(true, true, true)); // elapsed before + CHECK_FALSE(signal_passing::passed_now(false, false, true)); // still ahead + CHECK_FALSE(signal_passing::passed_now(false, true, false)); // the head never had it ahead +} diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 99c6a951e..a25ed392c 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -23,6 +23,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/brakesetting.h" #include "vehicle/brakingcurve.h" #include "vehicle/handover.h" +#include "vehicle/signalpassing.h" #include "vehicle/timetableservice.h" #include "world/mtable.h" #include "world/stationnames.h" @@ -330,9 +331,7 @@ bool TSpeedPos::Update() // trzeba zazanaczyć, że minięty iFlags |= spElapsed; } - else { - bSeenAhead = true; - } + bSeenAhead = signal_passing::seen_ahead_on_update( fDist, bSeenAhead ); if (iFlags & spTrack) { // road/track if (trTrack) { @@ -418,18 +417,14 @@ bool TSpeedPos::IsProperSemaphor(TOrders order) return false; // true gdy zatrzymanie, wtedy nie ma po co skanować dalej } -// how far behind the head an event found in the scan may lie and still count as one the head had ahead [m] -constexpr double SeenAheadTolerance { 5.0 }; - -bool TSpeedPos::Set(basic_event *event, double dist, double length, TOrders order) +bool TSpeedPos::Set(basic_event *event, double dist, double length, TOrders order, bool const Standing) { // zapamiętanie zdarzenia fDist = dist; - // an event already behind the head when found (under a train set across a signal) wasn't passed by it. the - // distance is found in steps of a metre from the position of the memory cell, so a signal just ahead of the head - // may come out a few metres behind it: those still count as seen ahead. the price is that a train set less than - // the tolerance past a signal at stop is still reported to pass it; a train standing that close to a signal can't - // be told from one stopped just short of it, which really passes the signal if it goes on - bSeenAhead = ( dist >= -SeenAheadTolerance ); + // an event already behind the head when found (under a train set across a signal) wasn't passed by it. a moving + // train may be just passing it, and the distance is found in steps of a metre, so for a moving train an event a + // little behind the head still counts as seen ahead. a standing train passes nothing: an event found behind its + // head counts only once an update finds it ahead + bSeenAhead = signal_passing::seen_ahead_when_found( dist, Standing ); iFlags = spEvent; evEvent = event; vPos = event->input_location(); // współrzędne eventu albo komórki pamięci (zrzutować na tor?) @@ -646,7 +641,7 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) fCurrentDistance + ProjectEventOnTrack( pEvent, pTrack, fLastDir ), OrderCurrentGet() ) ) { */ - if (newspeedpoint.Set(pEvent, GetDistanceToEvent(pTrack, pEvent, fLastDir, fCurrentDistance), fLength, OrderCurrentGet())) + if (newspeedpoint.Set(pEvent, GetDistanceToEvent(pTrack, pEvent, fLastDir, fCurrentDistance), fLength, OrderCurrentGet(), mvOccupied->Vel < EU07_AI_NOMOVEMENT)) { fDistance = newspeedpoint.fDist; // jeśli sygnał stop, to nie ma potrzeby dalej skanować @@ -922,9 +917,8 @@ std::uint8_t passing_flags_of( TSpeedPos const &Point, double const Speedatsigna void TController::CheckSignalPassed( TSpeedPos const &Point, bool const Passedbefore ) const { - if( Passedbefore - || false == TestFlag( Point.iFlags, spElapsed ) - || false == Point.bSeenAhead // found already behind the head: the train stood across it, it didn't pass it + // not bSeenAhead: found already behind the head, the train stood across it or past it, it didn't pass it + if( false == signal_passing::passed_now( Passedbefore, TestFlag( Point.iFlags, spElapsed ), Point.bSeenAhead ) || ( mvOccupied->CategoryFlag & 1 ) == 0 ) { // railway only return; } diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 0aaf70707..87dccd030 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -184,7 +184,8 @@ class TSpeedPos void UpdateDistance( double dist ) { fDist -= dist; } - bool Set(basic_event *e, double d, double length, TOrders order = Wait_for_orders); + // Standing: the train stands, so an event found behind its head wasn't passed by it + bool Set(basic_event *e, double d, double length, TOrders order = Wait_for_orders, bool Standing = false); void Set(TTrack *t, double d, int f); std::string TableText() const; std::string GetName() const; diff --git a/vehicle/signalpassing.cpp b/vehicle/signalpassing.cpp new file mode 100644 index 000000000..58d691760 --- /dev/null +++ b/vehicle/signalpassing.cpp @@ -0,0 +1,30 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/signalpassing.h" + +namespace signal_passing { + +bool seen_ahead_when_found( double const Distance, bool const Standing ) { + + return Distance >= ( Standing ? 0.0 : -moving_tolerance ); +} + +bool seen_ahead_on_update( double const Distance, bool const Seenahead ) { + + return Seenahead || Distance >= 0.0; +} + +bool passed_now( bool const Elapsedbefore, bool const Elapsed, bool const Seenahead ) { + + return Elapsed && !Elapsedbefore && Seenahead; +} + +} // namespace signal_passing diff --git a/vehicle/signalpassing.h b/vehicle/signalpassing.h new file mode 100644 index 000000000..33f2e5265 --- /dev/null +++ b/vehicle/signalpassing.h @@ -0,0 +1,38 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +// when a point of the AI's speed table (a signal above all) counts as passed by the train: the test mode's +// "signal passed at danger" and the blackbox record of passed signals (TController::CheckSignalPassed) +namespace signal_passing { + +// how far behind the head a point found by the scan of a moving train may lie and still count as one the head +// had ahead [m]. GetDistanceToEvent() finds the distance in steps of a metre from the position of the memory +// cell, so a signal just ahead of the head may come out a little behind it +inline constexpr double moving_tolerance { 5.0 }; + +// whether a point the scan finds Distance [m] ahead of the head (negative: behind it) counts as one the head had +// ahead. a moving train may be just passing it, so a point up to moving_tolerance behind counts. a standing train +// isn't passing anything: a point found behind its head was passed before (a train set or stopped past a signal), +// and counts only once an update finds it ahead. +// known gap: the distance can be off by about half a metre (GetDistanceToEvent() takes the nearest of samples a +// metre apart), so a train standing a few decimetres short of a signal may find it just behind the head, and if it +// then runs past it at stop, that isn't reported. a tolerance for a standing train wouldn't close it: the first +// update marks a point behind the head elapsed (TSpeedPos::Update()), so such a train would be reported as passing +// the signal at once, while it stands short of it. the AI stops 8-15 m short of a signal +bool seen_ahead_when_found( double Distance, bool Standing ); + +// whether the head had the point ahead, after an update finds it Distance [m] ahead of the head +bool seen_ahead_on_update( double Distance, bool Seenahead ); + +// whether an update of a point reports it as passed: it became elapsed in this update, and the head had it ahead +bool passed_now( bool Elapsedbefore, bool Elapsed, bool Seenahead ); + +} // namespace signal_passing From 419bec12853e3b9930bd067b1b942acbd0fccfe4 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:13:46 +0100 Subject: [PATCH 102/136] test(camera): pin the order of the rotations of TCamera::SetMatrix (#414) (#474) The roll of the camera is multiplied in first, so it turns the view about the line of sight. 623c4f82 once moved it last, which nodded the view up and down when looking out of a side window with the cab swaying; #414 put it back. The new tests check the axes of the view matrix for several pitch, yaw and roll values: the line of sight follows the pitch and the yaw whatever the roll, the roll turns the up and right axes about the line of sight, and in the cab the view out of a side window stays level. With the roll moved back last, all three test cases fail. The test binary now compiles vehicle/Camera.cpp itself, with stubs for the command queue and the clock. The smoke colour of a cold diesel (#413) stays untested: it lives in rendering/particles.cpp, which needs the world environment and a whole vehicle to link. --- tests/unit/CMakeLists.txt | 2 + tests/unit/COVERAGE.md | 2 + tests/unit/test_camera.cpp | 156 +++++++++++++++++++++++++++++++++++++ 3 files changed, 160 insertions(+) create mode 100644 tests/unit/test_camera.cpp diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index d06c83445..180285912 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -34,6 +34,8 @@ add_executable(${UNIT_TESTS_NAME} "${CMAKE_SOURCE_DIR}/editor/editorFouling.cpp" # and the http client the editor fetches its aids with "${CMAKE_SOURCE_DIR}/editor/editorHttp.cpp" + # the camera, for the order of its rotations (test_camera.cpp) + "${CMAKE_SOURCE_DIR}/vehicle/Camera.cpp" ${UNIT_TEST_CASES}) # the core library brings the game's build settings along diff --git a/tests/unit/COVERAGE.md b/tests/unit/COVERAGE.md index 9b677fbed..4f7f4d657 100644 --- a/tests/unit/COVERAGE.md +++ b/tests/unit/COVERAGE.md @@ -124,6 +124,8 @@ Notes to the table: - The small headers with the logic of a single part are all run in full: `vehicle/doorwings.h`, `gaugeduplicates.h`, `gaugepositions.h`, `holdcoillever.h`, `lightsprogrammer.h`, `mainctrlact.h`, `mirrors.h`, `scripting/scriptscreendrawing.h`, `scriptscreenkernels.h`, `scriptscreenprogram.h`, `scriptscreens.h`, `utilities/dictionary.h` and `vehicle/blackbox.h`. - `vehicle/brakesetting.cpp` and `vehicle/odometer.cpp` (the brake setting of the wagons, the odometer store) joined the library on master after that run. In the run of `bac9954a` their tests (`test_brake_setting.cpp`, `test_odometer.cpp`) run 94.1% (144 of 153) and 87.9% (189 of 215) of their lines, and all 14 and 26 of 28 of their functions. - The script hosts (`scriptscreens.cpp`, `luaprogram.cpp`, `wasmprogram.cpp`) aren't in the library. The test binary compiles them itself, with the real runtimes. +- `vehicle/Camera.cpp` isn't in the library either. The test binary compiles it for the order of the camera's rotations (`test_camera.cpp`, #414), with stubs for the command queue and the clock that `TCamera::Update()` reaches for. +- The colour of the smoke of a cold diesel (#413) isn't tested: the fix is in `smoke_source::update()` (`rendering/particles.cpp`), which needs the world environment (sky, sun, precipitation, sounds) and a whole `TDynamicObject` to link. - `scene/scenelayers.h`, `scene/scenenode.h` and `scene/scenenodegroups.h` are in the report with a few lines each: the parser reports the files it includes to the scenery, which the tests replace with stubs (`engine_stubs.cpp`). ### The parser, the helpers and the PLC diff --git a/tests/unit/test_camera.cpp b/tests/unit/test_camera.cpp new file mode 100644 index 000000000..684fadb56 --- /dev/null +++ b/tests/unit/test_camera.cpp @@ -0,0 +1,156 @@ +#include "stdafx.h" +#include "doctest.h" + +#include +#include +#include +#include + +#include "input/command.h" +#include "utilities/Timer.h" +#include "vehicle/Camera.h" + +// the view matrix of the camera (TCamera::SetMatrix): the pitch (Angle.x) and the yaw (Angle.y) give the line of sight, +// the roll (Angle.z) turns the view about that line, wherever the camera looks. The roll comes from the sway of the cab +// (drivermode.cpp) or the angles of a camera entry of the scenery. Multiplied in last, it once acted about the world's z +// axis instead, and nodded the view up and down when looking out of a side window (623c4f82, put back in #414). +// vehicle/Camera.cpp isn't in the core library; the test binary compiles it itself (tests/unit/CMakeLists.txt) + +// the parts of the engine TCamera::Update() reaches for, which no test here runs: the command queue and the clock +// (simulation::Commands itself is in test_script_screen_host.cpp) +bool command_queue::pop(command_data &, uint32_t const) { // NOSONAR signature from input/command.h + return false; +} + +double Timer::GetDeltaRenderTime() { // NOSONAR signature from utilities/Timer.h + return 0.0; +} + +namespace { + +// the axes of the view in the world, from the view matrix +struct view_axes { + glm::dvec3 eye; + glm::dvec3 forward; // the line of sight + glm::dvec3 up; + glm::dvec3 right; +}; + +view_axes axes(TCamera const &Camera) { + glm::dmat4 matrix{1.0}; + REQUIRE(Camera.SetMatrix(matrix)); + auto const toworld{glm::inverse(matrix)}; + return { + glm::dvec3{toworld * glm::dvec4{0.0, 0.0, 0.0, 1.0}}, + glm::dvec3{toworld * glm::dvec4{0.0, 0.0, -1.0, 0.0}}, + glm::dvec3{toworld * glm::dvec4{0.0, 1.0, 0.0, 0.0}}, + glm::dvec3{toworld * glm::dvec4{1.0, 0.0, 0.0, 0.0}}}; +} + +void check_equal(glm::dvec3 const &Actual, glm::dvec3 const &Expected) { + CAPTURE(Actual.x); + CAPTURE(Actual.y); + CAPTURE(Actual.z); + CHECK(Actual.x == doctest::Approx(Expected.x).epsilon(1e-9)); + CHECK(Actual.y == doctest::Approx(Expected.y).epsilon(1e-9)); + CHECK(Actual.z == doctest::Approx(Expected.z).epsilon(1e-9)); +} + +// the free camera, at Position, turned by Angle (pitch, yaw, roll) +TCamera free_camera(glm::dvec3 const &Position, glm::vec3 const &Angle) { + TCamera camera; + camera.Init(Position, glm::dvec3{Angle}, nullptr); + return camera; +} + +struct turn { + float pitch; + float yaw; +}; + +// the camera looking ahead (-z), out of the left and the right side window, back, up and down at an angle +std::vector const turns{ + {0.f, 0.f}, + {0.f, static_cast(std::numbers::pi / 2)}, + {0.3f, static_cast(-std::numbers::pi / 2)}, + {-0.4f, static_cast(std::numbers::pi)}, + {0.2f, 0.7f}, + {-0.6f, -2.1f}, +}; + +std::vector const rolls{0.1f, -0.2f, 0.5f}; + +} // namespace + +TEST_CASE("camera: the pitch and the yaw give the line of sight, the roll leaves it as it is (#414)") { + glm::dvec3 const position{120.0, 4.5, -300.0}; + for (auto const &turn : turns) { + auto const pitch{static_cast(turn.pitch)}; + auto const yaw{static_cast(turn.yaw)}; + // the yaw from -z towards -x, the pitch up from the ground, as TCamera::RaLook() works them out + glm::dvec3 const sight{-std::sin(yaw) * std::cos(pitch), std::sin(pitch), -std::cos(yaw) * std::cos(pitch)}; + for (auto const roll : {0.f, rolls[0], rolls[1], rolls[2]}) { + CAPTURE(turn.pitch); + CAPTURE(turn.yaw); + CAPTURE(roll); + auto const view{axes(free_camera(position, {turn.pitch, turn.yaw, roll}))}; + check_equal(view.eye, position); + check_equal(view.forward, sight); + } + } +} + +TEST_CASE("camera: the roll turns the view about the line of sight, wherever the camera looks (#414)") { + for (auto const &turn : turns) { + auto const level{axes(free_camera({}, {turn.pitch, turn.yaw, 0.f}))}; + for (auto const roll : rolls) { + CAPTURE(turn.pitch); + CAPTURE(turn.yaw); + CAPTURE(roll); + auto const rolled{axes(free_camera({}, {turn.pitch, turn.yaw, roll}))}; + auto const angle{static_cast(roll)}; + // the up of the view leans towards the left by the roll, and stays square to the line of sight + check_equal(rolled.up, std::cos(angle) * level.up - std::sin(angle) * level.right); + check_equal(rolled.right, std::cos(angle) * level.right + std::sin(angle) * level.up); + CHECK(glm::dot(rolled.up, rolled.forward) == doctest::Approx(0.0).epsilon(1e-9)); + } + } +} + +// the camera in the cab: the eye in the cab, looking at a point ahead of the vehicle (TCamera::LookAt), the head turned +// by the yaw and the pitch, the sway of the cab given as the roll. The camera needs no more of the vehicle than that it +// has one, so the vehicle is a zeroed block of its size, never used as an object (as the neighbours in vehicle.cpp) +static_assert(alignof(TDynamicObject) <= __STDCPP_DEFAULT_NEW_ALIGNMENT__); + +TEST_CASE("camera: in the cab, the sway leaves the view out of a side window level (#414)") { + std::vector vehicle(sizeof(TDynamicObject)); // zeroed + + glm::dvec3 const eye{10.0, 2.0, -5.0}; + // the vehicle heading north-east on level track + auto const ahead{glm::normalize(glm::dvec3{1.0, 0.0, -1.0})}; + glm::dvec3 const left{ahead.z, 0.0, -ahead.x}; // the vehicle's left, flat + + for (auto const head : {-1, 1}) { // turned to the right, to the left + for (auto const roll : {0.1f, -0.15f}) { + CAPTURE(head); + CAPTURE(roll); + + TCamera camera; + camera.Init(eye, {}, reinterpret_cast(vehicle.data())); // NOSONAR see above + camera.LookAt = eye + ahead; + camera.vUp = {0.f, 1.f, 0.f}; + camera.Angle = {0.f, static_cast(head * std::numbers::pi / 2), roll}; + + auto const view{axes(camera)}; + check_equal(view.eye, eye); + // out of the window to the left or the right, still level, whatever the sway (the yaw is a float, a hair + // off a right angle) + auto const yaw{static_cast(camera.Angle.y)}; + check_equal(view.forward, std::sin(yaw) * left + std::cos(yaw) * ahead); + CHECK(glm::dot(view.forward, static_cast(head) * left) == doctest::Approx(1.0).epsilon(1e-6)); + // the sway tilts the view about that line by its angle + CHECK(glm::dot(view.up, view.forward) == doctest::Approx(0.0).epsilon(1e-9)); + CHECK(view.up.y == doctest::Approx(std::cos(static_cast(roll))).epsilon(1e-9)); + } + } +} From d7b4238bb84b8980fd4b4bd4b640746df36bc9e8 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:14:41 +0100 Subject: [PATCH 103/136] test(scenarios): the L053 poranek cases now fail on the station's SM42 (#477) * test(scenarios): the L053 poranek cases now fail on the station's SM42 #409 fixed what both l053_poranek_tme222158_debica cases were marked xfail for: the EP07 on Tm4 stops at the checkpoint, and the ET21 no longer stands off the wire at Debica Towarowa. Run on staging f15ea405, neither passes yet: TME222158 gets to Debica and reports there, but the station's SM42-1096, ordered to uncouple at step 10 of deb_sm42_stat, pushes its cut past debica_k_sem_info at danger and never gets the coupler off, so the station never gives TME222158 step 1 and both runs end as a standstill (4347 s and 4576 s of simulation time). The xfail marks stay, with that reason. * test(scenarios): the README table names the staging run of the L053 poranek rows --- tests/scenarios/README.md | 7 ++++--- tests/scenarios/cases/l053_poranek_tme222158_debica.json | 2 +- .../cases/l053_poranek_tme222158_debica_et21.json | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index 321b65479..2638272c7 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -399,15 +399,16 @@ track it stands on). The first of them may be the one to couple (`Shunt -2 -3`): first order is `Connect` releases the hand brake a cold locomotive starts with (`eu07_td_cold_connect`). The mission trains of velocity 0.1 wait for their signal and need nothing. -The cases and what they showed on master of 2026-11-11: +The cases and what they showed on master of 2026-11-11 (the two L053 poranek rows also on +staging f15ea405 of 2026-11-23): | case | report | result | | --- | --- | --- | | `wrzosy_pxe336080_couples` | #524 | passes: ordered to, the locomotive couples to the rake (`couples`, 262 s) and takes it out of the depot (696 s). The scenery itself gives no such order | | `baltyk_skm1_roj55324_shunting_signal` | #525 | passes, with four seeds: the unit on the siding is let into the platforms 4 minutes after the start, once the shunter beside it has done its first moves, and leaves at 10:42 | | `baltyk_skm1_roj55321_departure` | #525 | passes, with three seeds: the unit in the platform leaves at 10:34 | -| `l053_poranek_tme222158_debica` | #421 | `xfail`: the train is never let into Debica, the station jams 4 minutes after the start: the AI of EP07-338'16 passes the shunting signal Tm4 at stop at 29 km/h and stops 20 m beyond the checkpoint the station waits for it at | -| `l053_poranek_tme222158_debica_et21` | #421 | `xfail`: with an ET21, as in the report, the locomotive stops for good at Debica Towarowa: running round the wagons it stands on the headshunt 20 m past the end of the overhead wire, and its driver never gets out of `Prepare_engine` | +| `l053_poranek_tme222158_debica` | #421 | `xfail`: on master of 2026-11-11 the station jammed 4 minutes after the start, the AI of EP07-338'16 passed the shunting signal Tm4 at stop at 29 km/h. Since #409 (staging f15ea405, 2026-11-23) the EP07 stops at the checkpoint and TME222158 gets to Debica, but the station's SM42-1096 jams it: ordered to uncouple at step 10 of `deb_sm42_stat` it pushes its cut past `debica_k_sem_info` at danger and never gets the coupler off, so the station never sends TME222158 on | +| `l053_poranek_tme222158_debica_et21` | #421 | `xfail`: on master of 2026-11-11, with an ET21 as in the report, the locomotive stopped for good at Debica Towarowa, on the headshunt 20 m past the end of the overhead wire, and its driver never got out of `Prepare_engine`. Since #409 (staging f15ea405) the ET21 gets through Debica Towarowa (steps 1-5 of `dt_tme222158_stat`) to Debica, then fails on the SM42 as `l053_poranek_tme222158_debica` does | | `l053_poludnie_roj32134_debica` | #506 | passes: both trains run and the unit ends at Debica after 6134 s; no train in its way | In the L053 sceneries the test mode logs a signal passed at danger for several shunting diff --git a/tests/scenarios/cases/l053_poranek_tme222158_debica.json b/tests/scenarios/cases/l053_poranek_tme222158_debica.json index 6fbc141e7..cba4a9830 100644 --- a/tests/scenarios/cases/l053_poranek_tme222158_debica.json +++ b/tests/scenarios/cases/l053_poranek_tme222158_debica.json @@ -10,7 +10,7 @@ "reason": "tme222158_got_the_exit_signal_at_debica" }, "slow": true, - "xfail": "eu07/maszyna#421 is not reached: with every train driven by AI Debica jams 4 minutes after the start, the AI of EP07-338'16 passes the shunting signal Tm4 at stop at 29 km/h and stops 20 m beyond the checkpoint before it (tor1834:event0), so RPE23113 never reports there and TME222158 is never let into the station", + "xfail": "eu07/maszyna#421 is not reached, the station's SM42 jams Debica: since #409 EP07-338'16 stops at the checkpoint before Tm4 (tor1834:event0) and TME222158 is let in and reports at Debica (deb_tme222158_stat c 0), but SM42-1096, ordered to uncouple at step 10 of deb_sm42_stat, pushes its cut past debica_k_sem_info at danger and never gets the coupler off (\"Uncoupling [sm42-1096]: actuating and compressing buffers... from front\" for the rest of the run), so it never does step 11 and the station never gives TME222158 step 1: standstill after 4347 s", "physicslog": false, "ini": [ "file.binary.terrain no" diff --git a/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json b/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json index 4f169fea7..62785a518 100644 --- a/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json +++ b/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json @@ -16,7 +16,7 @@ "reason": "tme222158_got_the_exit_signal_at_debica" }, "slow": true, - "xfail": "eu07/maszyna#421: the ET21 stands for good at Debica Towarowa with the shunting signal at Ms2. Running round the wagons it stops on the headshunt 20 m past the end of the overhead wire (the wire ends at z 4804 over tor2466, the locomotive stands at z 4786), loses power, and its driver never gets out of Prepare_engine; the ET22 the scenery has there now gets through", + "xfail": "eu07/maszyna#421 is not reached, the station's SM42 jams Debica, as in l053_poranek_tme222158_debica: since #409 the ET21 no longer stands off the wire at Debica Towarowa, it gets through steps 1-5 of dt_tme222158_stat, takes the wagons to Debica and reports there (deb_tme222158_stat c 0), but SM42-1096, ordered to uncouple at step 10 of deb_sm42_stat, pushes its cut past debica_k_sem_info at danger and never gets the coupler off (\"Uncoupling [sm42-1096]: actuating and compressing buffers... from front\" for the rest of the run), so it never does step 11 and the station never gives TME222158 step 1: standstill after 4576 s", "physicslog": false, "ini": [ "file.binary.terrain no" From 02c4c8169493dd5f0aabc96fc3cff47898c2daee Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:14:50 +0100 Subject: [PATCH 104/136] refactor: the line breaker state as an enum class, fcfuH without the text round trip (L16) (#478) * refactor(cab): the cab's state of the line breaker is an enum class TTrain::m_linebreakerstate kept 0, 1 and 2 for open, closed and closing (the closing control held long enough). It is linebreaker::state now, which linebreaker::pressed() takes too; every comparison and assignment names the state. Nothing writes the state out: it isn't in the Python dictionary of the cab, the black box, the physics log or the network. No change in behaviour (eu07/maszyna#148). * refactor(physics): fcfuH takes fcfu without writing it out and reading it back A definition of an induction motor drive without fcfuH gave the dynamic brake fcfu through text: std::to_string() of the value as the default of extract_value(). The loader assigns it now. For any figure of up to six decimals the value is the same to the bit (the test compares both ways over more than 70000 figures, and through the loader); the game's definitions have one or two. Only a figure of more than six decimals, which the text rounded to six, or one past the largest value, which read back as 0 from "inf", gives another; the test pins both (eu07/maszyna#99). --- McZapkie/Mover.cpp | 6 +- tests/unit/test_fcfuh_default.cpp | 153 ++++++++++++++++++++++++++++++ tests/unit/test_linebreaker.cpp | 37 ++++---- vehicle/Train.cpp | 42 ++++---- vehicle/Train.h | 3 +- vehicle/linebreaker.cpp | 6 +- vehicle/linebreaker.h | 17 +++- 7 files changed, 215 insertions(+), 49 deletions(-) create mode 100644 tests/unit/test_fcfuh_default.cpp diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index b1735d0c5..5143b359a 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -13759,7 +13759,11 @@ void TMoverParameters::LoadFIZ_EngineInductionMotor(std::string const &Input) extract_value(eimc[eimc_f_DU], "DU", Input, ""); extract_value(eimc[eimc_f_I0], "I0", Input, ""); extract_value(eimc[eimc_f_cfu], "fcfu", Input, ""); - extract_value(eimc[eimc_f_cfuH], "fcfuH", Input, std::to_string(eimc[eimc_f_cfu])); + if (false == extract_value(eimc[eimc_f_cfuH], "fcfuH", Input, "")) + { + // without its own figure the dynamic brake takes the one of the traction + eimc[eimc_f_cfuH] = eimc[eimc_f_cfu]; + } extract_value(eimc[eimc_p_F0], "F0", Input, ""); extract_value(eimc[eimc_p_a1], "a1", Input, ""); extract_value(eimc[eimc_p_Pmax], "Pmax", Input, ""); diff --git a/tests/unit/test_fcfuh_default.cpp b/tests/unit/test_fcfuh_default.cpp new file mode 100644 index 000000000..437164060 --- /dev/null +++ b/tests/unit/test_fcfuh_default.cpp @@ -0,0 +1,153 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "utilities/utilities.h" + +#include +#include +#include +#include +#include +#include + +using test::definition; +using test::vehicle; + +// the figure of the voltage by the frequency of an induction motor drive in the dynamic brake (fcfuH) takes the +// one of the traction (fcfu) when the definition has none. the loader took it by writing fcfu out with +// std::to_string() and reading the text back as the default of fcfuH (eu07/maszyna#99); it assigns it now + +namespace { + +// a figure read from a line the way TMoverParameters::LoadFIZ_EngineInductionMotor() reads fcfu +double read_fcfu(std::string const &Text) { + double fcfu{0.0}; + extract_value(fcfu, "fcfu", "fcfu=" + Text, ""); + return fcfu; +} + +// fcfuH missing, the way the loader took it before: the figure written out with six decimals in the C locale +// (the game never sets another) and read back +double fcfuh_before(double const Fcfu) { + double fcfuh{-1.0}; + extract_value(fcfuh, "fcfuH", "", std::to_string(Fcfu)); + return fcfuh; +} + +// the bits of the value, which tell -0.0 from 0.0 too +std::uint64_t bits(double const Value) { + std::uint64_t result; + std::memcpy(&result, &Value, sizeof(result)); + return result; +} + +// the value with all its digits, for the message +std::string exact(double const Value) { + char text[64]; + std::snprintf(text, sizeof(text), "%.17g", Value); + return text; +} + +// a generator of its own (splitmix64), for the same numbers on every platform +struct numbers { + std::uint64_t state{0x2545f4914f6cdd1dull}; + std::uint64_t next() { + auto value{state += 0x9e3779b97f4a7c15ull}; + value = (value ^ (value >> 30)) * 0xbf58476d1ce4e5b9ull; + value = (value ^ (value >> 27)) * 0x94d049bb133111ebull; + return value ^ (value >> 31); + } +}; + +// the decimal text of Integer / 10^Decimals, as a definition could hold it +std::string decimal(std::uint64_t const Integer, int const Decimals, bool const Negative) { + auto digits{std::to_string(Integer)}; + if (Decimals > 0) { + if (digits.size() <= static_cast(Decimals)) { + digits.insert(0, Decimals + 1 - digits.size(), '0'); + } + digits.insert(digits.size() - Decimals, "."); + } + return (Negative ? "-" : "") + digits; +} + +} // namespace + +TEST_CASE("fcfuH: the figure of the traction is the same, assigned or written out and read back, for every figure of up to six decimals") { + // any decimal figure of up to six decimals: the value read from it lies within half a millionth of it, so + // std::to_string() writes the figure itself and the text reads back to the very same value. checked over the + // figures the game's definitions use (33.5 to 81.5) and the ones around them, and over many others, of up + // to six decimals and up to 18 digits, of either sign + auto compared{0}; + auto const check{[&](std::string const &Text) { + auto const fcfu{read_fcfu(Text)}; + auto const before{fcfuh_before(fcfu)}; + if (bits(before) != bits(fcfu)) { + FAIL_CHECK("fcfu=" << Text << " was " << exact(before) << " as fcfuH, now " << exact(fcfu)); + } + ++compared; + }}; + // every figure of up to two decimals, from -10 to 200 + for (auto hundredths{-1000}; hundredths <= 20000; ++hundredths) { + check(decimal(static_cast(std::abs(hundredths)), 2, hundredths < 0)); + } + // every figure of up to six decimals around the ones of the game's definitions + for (auto const figure : {33.5, 40.1, 43.7, 45.18, 46.8, 47.6, 48.9, 49.0, 81.5}) { + auto const millionths{static_cast(figure * 1e6 + 0.5)}; + for (auto offset{-2000}; offset <= 2000; ++offset) { + check(decimal(static_cast(millionths + offset), 6, false)); + } + } + // figures of 0 to 6 decimals and 1 to 18 digits + numbers random; + for (auto decimals{0}; decimals <= 6; ++decimals) { + for (auto digits{1}; digits <= 18; ++digits) { + std::uint64_t limit{1}; + for (auto digit{0}; digit < digits; ++digit) { + limit *= 10; + } + for (auto sample{0}; sample < 400; ++sample) { + check(decimal(random.next() % limit, decimals, (sample & 1) != 0)); + } + } + } + // the way of writing it doesn't matter, only the value + for (auto const text : {"4.76e1", "47.60", "+47.6", "0047.6", "476e-1", "0", "-0", "1e15", "-1e-6", "1e300"}) { + check(text); + } + // nor does a figure the stream can't read, which reads as 0 + for (auto const text : {"abc", "-", "x47.6"}) { + check(text); + } + CHECK(compared > 70000); +} + +TEST_CASE("fcfuH: where the two ways part, figures no definition has") { + // no definition of the game has such a figure (they have one or two decimals, from 33.5 to 81.5). more than + // six decimals: std::to_string() rounded the value to six, the figure is taken as it's written now + CHECK(fcfuh_before(read_fcfu("0.1234567")) == read_fcfu("0.123457")); + CHECK(fcfuh_before(read_fcfu("1e-7")) == 0.0); + CHECK(read_fcfu("1e-7") == 1e-7); + // a figure past the largest value reads as infinite (with MSVC; the largest value with GCC): written out it + // was "inf", which the stream doesn't read, so the dynamic brake got 0 where it gets the traction's figure now + auto const huge{read_fcfu("1e999")}; + CHECK(huge > 1e300); + if (std::isinf(huge)) { + CHECK(fcfuh_before(huge) == 0.0); + } +} + +TEST_CASE("fcfuH: the loader gives the dynamic brake the traction's figure when the definition has none") { + for (auto const fcfu : {"43.7", "45.18", "49", "0.000001", "1e2"}) { + CAPTURE(fcfu); + // the EU47's definition has fcfu only + vehicle eu47{definition::fiz("e186_v2/eu47").set("Engine", "fcfu", fcfu)}; + CHECK(eu47->eimc[eimc_f_cfu] == read_fcfu(fcfu)); + CHECK(bits(eu47->eimc[eimc_f_cfuH]) == bits(eu47->eimc[eimc_f_cfu])); + CHECK(bits(eu47->eimc[eimc_f_cfuH]) == bits(fcfuh_before(read_fcfu(fcfu)))); + // its own figure is kept + vehicle own{definition::fiz("e186_v2/eu47").set("Engine", "fcfu", fcfu).set("Engine", "fcfuH", "40.1")}; + CHECK(own->eimc[eimc_f_cfu] == read_fcfu(fcfu)); + CHECK(own->eimc[eimc_f_cfuH] == read_fcfu("40.1")); + } +} diff --git a/tests/unit/test_linebreaker.cpp b/tests/unit/test_linebreaker.cpp index 126e3307c..9b36b817f 100644 --- a/tests/unit/test_linebreaker.cpp +++ b/tests/unit/test_linebreaker.cpp @@ -9,6 +9,7 @@ using test::consist; using test::definition; +using linebreaker::state; namespace { @@ -16,7 +17,7 @@ namespace { // the cab keeps of the line breaker follows the vehicle, the breaker closes while the lever is on and can close struct lever { TMoverParameters &mover; - int breaker{0}; // as TTrain::m_linebreakerstate: 0 open, 1 closed + state breaker{state::open}; // as TTrain::m_linebreakerstate bool on{false}; void press() { @@ -26,8 +27,8 @@ struct lever { break; case linebreaker::toggle::open: on = false; - if (breaker == 1 && mover.MainSwitch(false)) { - breaker = 0; + if (breaker == state::closed && mover.MainSwitch(false)) { + breaker = state::open; } break; default: @@ -36,14 +37,14 @@ struct lever { } // TTrain::Update() void update() { - if (breaker == 0 && mover.Mains) { - breaker = 1; + if (breaker == state::open && mover.Mains) { + breaker = state::closed; } - if (breaker == 1 && false == mover.Mains) { - breaker = 0; + if (breaker == state::closed && false == mover.Mains) { + breaker = state::open; } - if (on && breaker == 0 && mover.MainSwitchCheck()) { - breaker = mover.MainSwitch(true) ? 1 : 0; + if (on && breaker == state::open && mover.MainSwitchCheck()) { + breaker = mover.MainSwitch(true) ? state::closed : state::open; } } }; @@ -53,15 +54,15 @@ struct lever { TEST_CASE("line breaker: a press of the toggle closes an open breaker and opens a closed one") { using enum linebreaker::toggle; for (auto const latching : {false, true}) { - CHECK(linebreaker::pressed(0, latching, false) == close); - CHECK(linebreaker::pressed(1, latching, true) == open); - CHECK(linebreaker::pressed(1, latching, false) == open); + CHECK(linebreaker::pressed(state::open, latching, false) == close); + CHECK(linebreaker::pressed(state::closed, latching, true) == open); + CHECK(linebreaker::pressed(state::closed, latching, false) == open); // freshly closed, the cab finishes closing it first - CHECK(linebreaker::pressed(2, latching, true) == none); + CHECK(linebreaker::pressed(state::closing, latching, true) == none); } // a lever left on over an open breaker goes off; push buttons have no position to keep - CHECK(linebreaker::pressed(0, true, true) == open); - CHECK(linebreaker::pressed(0, false, true) == close); + CHECK(linebreaker::pressed(state::open, true, true) == open); + CHECK(linebreaker::pressed(state::open, false, true) == close); } TEST_CASE("line breaker: the EP05's lever goes off with the converter overload relay tripped (eu07/maszyna#394)") { @@ -72,7 +73,7 @@ TEST_CASE("line breaker: the EP05's lever goes off with the converter overload r REQUIRE(test::start_up(driver, line)); REQUIRE(ep05.Mains); REQUIRE(ep05.ConverterFlag); - lever ws{ep05, 1, true}; + lever ws{ep05, state::closed, true}; // the converter overload relay knocks the line breaker out, as the cab does it when the converter is // switched on together with the compressor; the lever stays on @@ -80,7 +81,7 @@ TEST_CASE("line breaker: the EP05's lever goes off with the converter overload r ep05.MainSwitch(false, range_t::local); ws.update(); REQUIRE_FALSE(ep05.Mains); - REQUIRE(ws.breaker == 0); + REQUIRE(ws.breaker == state::open); CHECK(ws.on); // with the relay tripped the breaker doesn't close test::drive(driver, line, 5.0); @@ -106,7 +107,7 @@ TEST_CASE("line breaker: the EP05's lever goes off with the converter overload r ws.press(); ws.update(); CHECK(ep05.Mains); - CHECK(ws.breaker == 1); + CHECK(ws.breaker == state::closed); // and the next press opens it ws.press(); CHECK_FALSE(ws.on); diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 8bf948096..3f2cbebae 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -3748,7 +3748,7 @@ void TTrain::OnCommand_linebreakertoggle(TTrain *Train, command_data const &Comm { // only impulse switches react to release events // NOTE: we presume dedicated state switch is of impulse type - if (Train->m_linebreakerstate == 0) + if (Train->m_linebreakerstate == linebreaker::state::open) { // ...after opening circuit, or holding for too short time to close it OnCommand_linebreakeropen(Train, Command); @@ -3801,14 +3801,14 @@ void TTrain::OnCommand_linebreakeropen(TTrain *Train, command_data const &Comman // play sound immediately when the switch is hit, not after release Train->fMainRelayTimer = 0.0f; - if (Train->m_linebreakerstate == 0) + if (Train->m_linebreakerstate == linebreaker::state::open) { return; } // already in the desired state if (true == Train->mvControlled->MainSwitch(false, Train->mvControlled->MainSwitchRange())) { - Train->m_linebreakerstate = 0; + Train->m_linebreakerstate = linebreaker::state::open; if (Train->mvControlled->MainSwitchRange() != range_t::local) { // the engines of the vehicles in multiple stopped along: their two-state switches go off too, left on @@ -3883,7 +3883,7 @@ void TTrain::OnCommand_linebreakerclose(TTrain *Train, command_data const &Comma Train->ggMainButton.UpdateValue(0.5, Train->dsbSwitch); } - if (Train->m_linebreakerstate == 1) + if (Train->m_linebreakerstate == linebreaker::state::closed) { return; } // already in the desired state @@ -3891,10 +3891,10 @@ void TTrain::OnCommand_linebreakerclose(TTrain *Train, command_data const &Comma // we don't need to start the diesel twice, but the other types (with impulse switch setup) still need to be launched // NOTE: this behaviour should depend on MainOnButton presence and type_delayed // TODO: change it when/if vehicle definition files get their proper switch types - if (Train->m_linebreakerstate == 2 && Train->mvControlled->EngineType == TEngineType::ElectricSeriesMotor) + if (Train->m_linebreakerstate == linebreaker::state::closing && Train->mvControlled->EngineType == TEngineType::ElectricSeriesMotor) { // try to finalize state change of the line breaker, set the state based on the outcome - Train->m_linebreakerstate = Train->mvControlled->MainSwitch(true, Train->mvControlled->MainSwitchRange()) ? 1 : 0; + Train->m_linebreakerstate = Train->mvControlled->MainSwitch(true, Train->mvControlled->MainSwitchRange()) ? linebreaker::state::closed : linebreaker::state::open; } // on button release reset the closing timer Train->fMainRelayTimer = 0.0f; @@ -8762,16 +8762,16 @@ bool TTrain::Update(double const Deltatime) { // train state update // line breaker: - if (m_linebreakerstate == 0 && true == mvControlled->Mains) + if (m_linebreakerstate == linebreaker::state::open && true == mvControlled->Mains) { // crude way to sync state of the linebreaker with ai-issued commands - m_linebreakerstate = 1; + m_linebreakerstate = linebreaker::state::closed; } - if (m_linebreakerstate == 1 && false == (mvControlled->Mains || mvControlled->dizel_startup)) + if (m_linebreakerstate == linebreaker::state::closed && false == (mvControlled->Mains || mvControlled->dizel_startup)) { // crude way to catch cases where the main was knocked out // because the state of the line breaker isn't changed to match, we need to do it here manually - m_linebreakerstate = 0; + m_linebreakerstate = linebreaker::state::open; } if (is_hold_coil_lever(ggMainOffButton) && hold_coil_lever::cuts_off(ggMainOffButton.GetDesiredValue())) { @@ -8781,10 +8781,10 @@ bool TTrain::Update(double const Deltatime) // put the lever back on to match, like the line breaker state above ggMainOffButton.UpdateValue(0.0); } - else if (m_linebreakerstate == 2) + else if (m_linebreakerstate == linebreaker::state::closing) { // the hold coil was cut off while the closing button was held, the line breaker won't close on its release - m_linebreakerstate = 0; + m_linebreakerstate = linebreaker::state::open; } } @@ -8808,18 +8808,18 @@ bool TTrain::Update(double const Deltatime) // if the button disconnecting the line breaker is down prevent the timer from accumulating fMainRelayTimer = 0.0f; } - if (m_linebreakerstate == 0 && fMainRelayTimer > mvControlled->InitialCtrlDelay) + if (m_linebreakerstate == linebreaker::state::open && fMainRelayTimer > mvControlled->InitialCtrlDelay) { // wlaczanie WSa z opoznieniem // mark the line breaker as ready to close; for electric series vehicles with impulse switch the setup is completed on button release - m_linebreakerstate = 2; + m_linebreakerstate = linebreaker::state::closing; } // for diesels and/or vehicles with toggle switch setup we complete the engine start here // TODO: make it a test for main_on_bt of type push_delayed instead - if (m_linebreakerstate == 2 && (ggMainOnButton.SubModel == nullptr || mvControlled->EngineType != TEngineType::ElectricSeriesMotor)) + if (m_linebreakerstate == linebreaker::state::closing && (ggMainOnButton.SubModel == nullptr || mvControlled->EngineType != TEngineType::ElectricSeriesMotor)) { // try to finalize state change of the line breaker, set the state based on the outcome - m_linebreakerstate = mvControlled->MainSwitch(true, mvControlled->MainSwitchRange()) ? 1 : 0; + m_linebreakerstate = mvControlled->MainSwitch(true, mvControlled->MainSwitchRange()) ? linebreaker::state::closed : linebreaker::state::open; } // the switches of the other vehicles in multiple update_remote_linebreakers(Deltatime); @@ -9393,10 +9393,10 @@ bool TTrain::Update(double const Deltatime) btLampkaSHP.Turn(mvOccupied->SecuritySystem.is_cabsignal_blinking()); btLampkaCzuwakaSHP.Turn(btLampkaSHP.GetValue() || btLampkaCzuwaka.GetValue()); - btLampkaWylSzybki.Turn(m_linebreakerstate == 2 || mvControlled->Mains); - btLampkaWylSzybkiOff.Turn(m_linebreakerstate != 2 && !mvControlled->Mains); - btLampkaMainBreakerReady.Turn(mvControlled->MainsInitTimeCountdown <= 0.0 && m_linebreakerstate != 2 && !mvControlled->Mains); - btLampkaMainBreakerBlinkingIfReady.Turn(m_linebreakerstate == 2 || mvControlled->Mains || mvControlled->MainsInitTimeCountdown < 0.0 && simulation::Time.data().wMilliseconds > 500); + btLampkaWylSzybki.Turn(m_linebreakerstate == linebreaker::state::closing || mvControlled->Mains); + btLampkaWylSzybkiOff.Turn(m_linebreakerstate != linebreaker::state::closing && !mvControlled->Mains); + btLampkaMainBreakerReady.Turn(mvControlled->MainsInitTimeCountdown <= 0.0 && m_linebreakerstate != linebreaker::state::closing && !mvControlled->Mains); + btLampkaMainBreakerBlinkingIfReady.Turn(m_linebreakerstate == linebreaker::state::closing || mvControlled->Mains || mvControlled->MainsInitTimeCountdown < 0.0 && simulation::Time.data().wMilliseconds > 500); btLampkaPrzetw.Turn(mvOccupied->Power110vIsAvailable); btLampkaPrzetwOff.Turn(!mvOccupied->Power110vIsAvailable); @@ -11808,7 +11808,7 @@ void TTrain::set_cab_controls(int const Cab) // line breaker if (ggMainButton.SubModel != nullptr) { // instead of single main button there can be on/off pair - ggMainButton.PutValue(ggMainButton.type() == TGaugeType::push ? 0.5f : m_linebreakerstate > 0 ? 1.f : 0.f); + ggMainButton.PutValue(ggMainButton.type() == TGaugeType::push ? 0.5f : m_linebreakerstate != linebreaker::state::open ? 1.f : 0.f); } // line breakers of the other vehicles in multiple for (std::size_t index = 0; index < m_remotelinebreakers.size(); ++index) diff --git a/vehicle/Train.h b/vehicle/Train.h index e6cc0f3ba..c079c3f18 100644 --- a/vehicle/Train.h +++ b/vehicle/Train.h @@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Button.h" #include "vehicle/Gauge.h" #include "vehicle/enginestart.h" +#include "vehicle/linebreaker.h" #include "audio/sound.h" #include "scripting/PyInt.h" #include "input/command.h" @@ -553,7 +554,7 @@ class TTrain { TMoverParameters *mvThird { nullptr }; // trzeci człon (SN61) TMoverParameters *mvPantographUnit { nullptr }; // nearest pantograph equipped unit // helper variable, to prevent immediate switch between closing and opening line breaker circuit - int m_linebreakerstate { 0 }; // 0: open, 1: closed, 2: freshly closed (and yes this is awful way to go about it) + linebreaker::state m_linebreakerstate { linebreaker::state::open }; static const commandhandler_map m_commandhandlers; control_mapper m_controlmapper; diff --git a/vehicle/linebreaker.cpp b/vehicle/linebreaker.cpp index 97eae0325..cc9b2f008 100644 --- a/vehicle/linebreaker.cpp +++ b/vehicle/linebreaker.cpp @@ -12,11 +12,11 @@ http://mozilla.org/MPL/2.0/. namespace linebreaker { -toggle pressed(int const Breakerstate, bool const Latchinglever, bool const Leveron) { - if (Breakerstate == 1) { +toggle pressed(state const Breakerstate, bool const Latchinglever, bool const Leveron) { + if (Breakerstate == state::closed) { return toggle::open; } - if (Breakerstate != 0) { + if (Breakerstate != state::open) { return toggle::none; } // the line breaker is open; a lever left on goes off first diff --git a/vehicle/linebreaker.h b/vehicle/linebreaker.h index 370e992cc..e87312dd1 100644 --- a/vehicle/linebreaker.h +++ b/vehicle/linebreaker.h @@ -12,6 +12,13 @@ http://mozilla.org/MPL/2.0/. // the line breaker (main switch, WS) controls of the cab namespace linebreaker { +// the state the cab keeps of the line breaker, besides the vehicle's own (TMoverParameters::Mains) +enum class state : int { + open, + closed, + closing // the closing control was held long enough; the line breaker closes when it's released, or right away +}; + enum class toggle : int { none, // the press does nothing close, // the control goes to its on position, and the line breaker closes if it can @@ -19,10 +26,10 @@ enum class toggle : int { }; // what a press of the line breaker toggle does. Breakerstate is the state the cab keeps of the line -// breaker (0: open, 1: closed, 2: freshly closed). Latchinglever is a single two-state switch which -// stays where it was put, Leveron that it stands in its on position. such a lever doesn't follow the -// line breaker: knocked out (by the converter overload relay, say) the breaker opens with the lever -// left on, and the lever has to go off before it can be put on again (eu07/maszyna#394) -toggle pressed(int Breakerstate, bool Latchinglever, bool Leveron); +// breaker. Latchinglever is a single two-state switch which stays where it was put, Leveron that it +// stands in its on position. such a lever doesn't follow the line breaker: knocked out (by the converter +// overload relay, say) the breaker opens with the lever left on, and the lever has to go off before it +// can be put on again (eu07/maszyna#394) +toggle pressed(state Breakerstate, bool Latchinglever, bool Leveron); } // namespace linebreaker From d3e6736f788918e0cfc0f4124aa6a2bf0c0df11d Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:15:02 +0100 Subject: [PATCH 105/136] fix(ai): the braking margin ends once the independent brake is on (#479) * fix(ai): the braking margin ends once the independent brake is on The braking curve outside the final approach keeps the room the brake takes to fill only while the brake is still to be applied. It took the train brake handle past running as the only sign that the brake was on. A vehicle that runs alone, a light locomotive or a railcar such as the SN61, brakes with its independent brake and leaves the handle in running, so the margin never ended for it: on every look it planned to stop short by the distance the brake takes to fill, slowed down too early, released, braked again, and crawled the last tens of metres to a W4 or a signal at stop. This followed #264 and #297. The independent brake now counts as well (braking_curve::brake_acting, LocalBrakePosA above 0). On td.scn the light EU07 reaches the W4 of Przystanek 6.6 s sooner and covers the last 100 m in 20.3 s instead of 26.3 s; on a 20 per mille downgrade it reaches a signal at stop 11.7 s sooner (last 100 m in 20.6 s instead of 31.7 s), with 3 applications of the independent brake in the last 300 m instead of 5. A train braking with the train brake runs as before (its physicslog is the same byte for byte). * test(scenarios): light locomotive, railcar and train stopping down a 20 per mille gradient The *_td_downgrade_w4_signal cases run on a line the fragment adds beside td.scn: 300 m level, then 3000 m down a gradient of 20 per mille under a wire fed by a substation of its own. The train stops at the W4 of Dol 1500 m down the gradient and then before a signal at stop 1100 m further down. They run with a light EU07 and an SN61 alone, which brake with the independent brake, and with an EU07 and three coaches, which brakes with the train brake. eu07_coaches_td_timetable is that train on the td/rozklad timetable to Przystanek. They show the approach to a stop: before the previous commit the light EU07 needed 31.7 s for the last 100 m to the signal, now 20.6 s; the train with coaches runs the same in both. * fix(ai): the braking margin counts the independent brake only on a vehicle that has one * test(scenarios): the light EU07 and the SN61 stop at the signal down the gradient in time --- tests/scenarios/README.md | 18 +- .../eu07_coaches_td_downgrade_w4_signal.json | 42 ++ .../cases/eu07_coaches_td_timetable.json | 40 ++ .../cases/eu07_td_downgrade_w4_signal.json | 47 ++ .../cases/sn61_td_downgrade_w4_signal.json | 47 ++ tests/scenarios/cases/td_downgrade.txt | 20 + .../cases/td_downgrade_w4_signal.scn | 518 ++++++++++++++++++ tests/scenarios/run.py | 21 +- tests/unit/test_braking_curve.cpp | 35 ++ vehicle/Driver.cpp | 10 +- vehicle/brakingcurve.cpp | 4 + vehicle/brakingcurve.h | 8 +- 12 files changed, 803 insertions(+), 7 deletions(-) create mode 100644 tests/scenarios/cases/eu07_coaches_td_downgrade_w4_signal.json create mode 100644 tests/scenarios/cases/eu07_coaches_td_timetable.json create mode 100644 tests/scenarios/cases/eu07_td_downgrade_w4_signal.json create mode 100644 tests/scenarios/cases/sn61_td_downgrade_w4_signal.json create mode 100644 tests/scenarios/cases/td_downgrade.txt create mode 100644 tests/scenarios/cases/td_downgrade_w4_signal.scn diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index 2638272c7..bf5467018 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -254,6 +254,16 @@ the td/rozklad train, an EU07 with three coaches, with its head 80 m past the W4 under the consist, behind the head, and the driver still counts Stacja1 and leaves at 10:35, since the scan of the route begins at the last vehicle and keeps a W4 behind the head. +`eu07_coaches_td_timetable` is the timetable case with the EU07 and three coaches, a train that brakes with the train +brake, beside the light EU07 and the SN61 alone, which brake with the independent brake. The `*_td_downgrade_w4_signal` +cases (fragment `td_downgrade_w4_signal.scn`, timetable `td_downgrade.txt`) run on a line the fragment adds beside the +tracks of td.scn, at x = -3000: 300 m level, then 3000 m down a gradient of 20 per mille, under an overhead wire fed +by a substation of its own (`gr_pwr`; the wire on the section `pwr01` of td.scn gave the EU07 no voltage). The train +starts on the level at the W4 of Gora, stops at the W4 of Dol 1500 m down the gradient, leaves at 10:38 and stops before +`gr_sem`, a signal at stop 1100 m further down (a memory cell with `SetVelocity 0 0` and the event that reads it, no +model), about 1590 m and 2690 m from the start. The three trains are the light EU07, the SN61 alone and the EU07 with +three coaches. + The `test_mode_*` cases show the ends of the test mode: `test_mode_pass` (exit 0, the pass event), `test_mode_signal_passed_at_danger` (exit 11), `test_mode_timeout` (exit 12, from `test.timeout`), `test_mode_standstill` (exit 13, from `test.standstill`) and @@ -428,9 +438,11 @@ the row instead, logged by builds from this branch on. - `max_speed` `limit`, `tolerance`: never goes faster than `limit + tolerance`. - `brakes` `min_pressure`: after moving off, brake cylinder pressure reaches `min_pressure` bar (physicslog pressures are in bar whatever its header says; the brake pipe runs at 5.0). -- `stops` `moving_speed`, `stop_speed`, `hold`, optional `min_distance`, `max_distance`: after - reaching `moving_speed`, stays at or below `stop_speed` for `hold` seconds; with the distances, - that stop has to be between them (metres travelled, as in `distance`). +- `stops` `moving_speed`, `stop_speed`, `hold`, optional `min_distance`, `max_distance`, `max_time`, + `nth`: after reaching `moving_speed`, stays at or below `stop_speed` for `hold` seconds; with the + distances, that stop has to be between them (metres travelled, as in `distance`), with `max_time` + it has to begin by then (seconds of the physicslog). `nth` (default 1) takes a later stop: each + stop after the first counts once the train has reached `moving_speed` again. - `stays_stopped` `moving_speed`, `stop_speed`: after moving off and stopping, never goes above `stop_speed` again. - `distance` `min`, `max`: total distance travelled. The physicslog has no position, so the diff --git a/tests/scenarios/cases/eu07_coaches_td_downgrade_w4_signal.json b/tests/scenarios/cases/eu07_coaches_td_downgrade_w4_signal.json new file mode 100644 index 000000000..1faae73ff --- /dev/null +++ b/tests/scenarios/cases/eu07_coaches_td_downgrade_w4_signal.json @@ -0,0 +1,42 @@ +{ + "description": "An EU07 with three coaches on the line of eu07_td_downgrade_w4_signal, down a gradient of 20 per mille: stops at the W4 of Dol, then before the signal at stop. A train braking with the train brake, the control of the light EU07 and SN61 cases.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_downgrade_w4_signal.scn", + "timetable": "td_downgrade.txt", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic" + ] + }, + "duration": 540, + "timeout": 900, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 150 + }, + { + "type": "max_speed", + "limit": 80, + "tolerance": 3 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 1500, + "max_distance": 1700 + }, + { + "type": "distance", + "min": 2550, + "max": 2750 + } + ] +} diff --git a/tests/scenarios/cases/eu07_coaches_td_timetable.json b/tests/scenarios/cases/eu07_coaches_td_timetable.json new file mode 100644 index 000000000..c8621c3b0 --- /dev/null +++ b/tests/scenarios/cases/eu07_coaches_td_timetable.json @@ -0,0 +1,40 @@ +{ + "description": "EU07 with three coaches on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek with the train brake.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic" + ] + }, + "duration": 360, + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 150 + }, + { + "type": "max_speed", + "limit": 90, + "tolerance": 3 + }, + { + "type": "brakes", + "min_pressure": 0.5 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 0, + "min_distance": 1380, + "max_distance": 1420 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_downgrade_w4_signal.json b/tests/scenarios/cases/eu07_td_downgrade_w4_signal.json new file mode 100644 index 000000000..e26f6180d --- /dev/null +++ b/tests/scenarios/cases/eu07_td_downgrade_w4_signal.json @@ -0,0 +1,47 @@ +{ + "description": "A light EU07 on a line of its own beside td.scn, down a gradient of 20 per mille on a timetable: stops at the W4 of Dol 1500 m down the gradient, leaves at 10:38 and stops before the signal gr_sem at stop 1100 m further down. The EU07 alone brakes with its independent brake.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_downgrade_w4_signal.scn", + "timetable": "td_downgrade.txt", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 540, + "timeout": 900, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 150 + }, + { + "type": "max_speed", + "limit": 80, + "tolerance": 3 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 1500, + "max_distance": 1700 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 2550, + "max_distance": 2750, + "max_time": 355, + "nth": 2 + }, + { + "type": "distance", + "min": 2550, + "max": 2750 + } + ] +} diff --git a/tests/scenarios/cases/sn61_td_downgrade_w4_signal.json b/tests/scenarios/cases/sn61_td_downgrade_w4_signal.json new file mode 100644 index 000000000..033313dc0 --- /dev/null +++ b/tests/scenarios/cases/sn61_td_downgrade_w4_signal.json @@ -0,0 +1,47 @@ +{ + "description": "An SN61 railcar alone on the line of eu07_td_downgrade_w4_signal, down a gradient of 20 per mille: stops at the W4 of Dol, then before the signal at stop. The SN61 alone brakes with its independent brake.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_downgrade_w4_signal.scn", + "timetable": "td_downgrade.txt", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\sn61_v2 SN61-13 SN61_v1 0 headdriver 0 0 enddynamic" + }, + "duration": 540, + "timeout": 900, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 150 + }, + { + "type": "max_speed", + "limit": 80, + "tolerance": 3 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 1500, + "max_distance": 1700 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 2550, + "max_distance": 2750, + "max_time": 366, + "nth": 2 + }, + { + "type": "distance", + "min": 2550, + "max": 2750 + } + ] +} diff --git a/tests/scenarios/cases/td_downgrade.txt b/tests/scenarios/cases/td_downgrade.txt new file mode 100644 index 000000000..ddc50d031 --- /dev/null +++ b/tests/scenarios/cases/td_downgrade.txt @@ -0,0 +1,20 @@ +________________________________________________________________ +[ Rodzaj i numer pociagu | TEST26 ] +[ Kategoria | RO ] +[________________________________________________|______________] +[ | Gora ] +[ Relacja pociagu | Koniec ] +[________________________________________________|______________] +[ Wymagany % ciezaru hamujacego | 88% ] +[________________________________________________|______________] +[ Seria i obciazenie lokomotywy | EU07 210 ] +[________________________________________________|______________] +[ | | Gora 2 | | ] +[ | 80 | R1,L,H,RT,PP 2 10.35 | ] +[ | |----------------------------------1----------|---] +[ | | Dol 1 10.37 | 4 ] +[ |_____| R1,+,L,H,PP 1 10.38 | ] +[ | 80 |----------------------------------1----------|---] +[ | | Koniec 1 10.45 | 7 ] +[ | | R1 1 10.46 | ] +[_______|_____|__________________________________1__________|___] diff --git a/tests/scenarios/cases/td_downgrade_w4_signal.scn b/tests/scenarios/cases/td_downgrade_w4_signal.scn new file mode 100644 index 000000000..ffa43ecc3 --- /dev/null +++ b/tests/scenarios/cases/td_downgrade_w4_signal.scn @@ -0,0 +1,518 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a line of its own, away from the tracks of td.scn: 300 m level, then 3000 m down a gradient of 20 per mille, +// under an overhead wire. +// the train starts on the level, with the W4 of Gora about 40 m ahead, and runs on the timetable {{timetable}}: +// Gora 10:35 -> Dol, a W4 1500 m down the gradient (stop, leaves at 10:38) -> the signal gr_sem, 1100 m further +// down, which stays at stop. the line goes on 400 m past the signal +node -1 0 gr_00 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -200.0 0.0 +0 +endtrack +node -1 0 gr_01 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -100.0 0.0 +0 +endtrack +node -1 0 gr_02 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 0.0 0.0 +0 +event2 gora#1_stopinfo +endtrack +node -1 0 gr_03 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 0.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 58.00 100.0 0.0 +0 +endtrack +node -1 0 gr_04 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 58.00 100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 56.00 200.0 0.0 +0 +endtrack +node -1 0 gr_05 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 56.00 200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 54.00 300.0 0.0 +0 +endtrack +node -1 0 gr_06 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 54.00 300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 52.00 400.0 0.0 +0 +endtrack +node -1 0 gr_07 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 52.00 400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 50.00 500.0 0.0 +0 +endtrack +node -1 0 gr_08 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 50.00 500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 48.00 600.0 0.0 +0 +endtrack +node -1 0 gr_09 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 48.00 600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 46.00 700.0 0.0 +0 +endtrack +node -1 0 gr_10 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 46.00 700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 44.00 800.0 0.0 +0 +endtrack +node -1 0 gr_11 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 44.00 800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 42.00 900.0 0.0 +0 +endtrack +node -1 0 gr_12 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 42.00 900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 40.00 1000.0 0.0 +0 +endtrack +node -1 0 gr_13 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 40.00 1000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 38.00 1100.0 0.0 +0 +endtrack +node -1 0 gr_14 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 38.00 1100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 36.00 1200.0 0.0 +0 +endtrack +node -1 0 gr_15 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 36.00 1200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 34.00 1300.0 0.0 +0 +endtrack +node -1 0 gr_16 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 34.00 1300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 32.00 1400.0 0.0 +0 +endtrack +node -1 0 gr_17 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 32.00 1400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 30.00 1500.0 0.0 +0 +event2 dol#1_stopinfo +endtrack +node -1 0 gr_18 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 30.00 1500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 28.00 1600.0 0.0 +0 +endtrack +node -1 0 gr_19 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 28.00 1600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 26.00 1700.0 0.0 +0 +endtrack +node -1 0 gr_20 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 26.00 1700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 24.00 1800.0 0.0 +0 +endtrack +node -1 0 gr_21 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 24.00 1800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 22.00 1900.0 0.0 +0 +endtrack +node -1 0 gr_22 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 22.00 1900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 20.00 2000.0 0.0 +0 +endtrack +node -1 0 gr_23 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 20.00 2000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 18.00 2100.0 0.0 +0 +endtrack +node -1 0 gr_24 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 18.00 2100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 16.00 2200.0 0.0 +0 +endtrack +node -1 0 gr_25 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 16.00 2200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 14.00 2300.0 0.0 +0 +endtrack +node -1 0 gr_26 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 14.00 2300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 12.00 2400.0 0.0 +0 +endtrack +node -1 0 gr_27 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 12.00 2400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 10.00 2500.0 0.0 +0 +endtrack +node -1 0 gr_28 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 10.00 2500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 8.00 2600.0 0.0 +0 +event2 gr_sem_info +endtrack +node -1 0 gr_29 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 8.00 2600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 6.00 2700.0 0.0 +0 +endtrack +node -1 0 gr_30 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 6.00 2700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 4.00 2800.0 0.0 +0 +endtrack +node -1 0 gr_31 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 4.00 2800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 2.00 2900.0 0.0 +0 +endtrack +node -1 0 gr_32 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 2.00 2900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 0.00 3000.0 0.0 +0 +endtrack +// the overhead wire along the whole line, as td.scn has it: 5.6 m above the rail, the carrier 1.7 m higher, fed by +// a substation of its own +node -1 0 gr_pwr tractionpowersource -3000.0 60.00 0.0 3400 0 0.01 2000 1.0 3 60.0 end +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -300.0 +-3000.0 65.60 -200.0 +-3000.0 67.30 -300.0 +-3000.0 67.30 -200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -200.0 +-3000.0 65.60 -100.0 +-3000.0 67.30 -200.0 +-3000.0 67.30 -100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -100.0 +-3000.0 65.60 0.0 +-3000.0 67.30 -100.0 +-3000.0 67.30 0.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 0.0 +-3000.0 63.60 100.0 +-3000.0 67.30 0.0 +-3000.0 65.30 100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 63.60 100.0 +-3000.0 61.60 200.0 +-3000.0 65.30 100.0 +-3000.0 63.30 200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 61.60 200.0 +-3000.0 59.60 300.0 +-3000.0 63.30 200.0 +-3000.0 61.30 300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 59.60 300.0 +-3000.0 57.60 400.0 +-3000.0 61.30 300.0 +-3000.0 59.30 400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 57.60 400.0 +-3000.0 55.60 500.0 +-3000.0 59.30 400.0 +-3000.0 57.30 500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 55.60 500.0 +-3000.0 53.60 600.0 +-3000.0 57.30 500.0 +-3000.0 55.30 600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 53.60 600.0 +-3000.0 51.60 700.0 +-3000.0 55.30 600.0 +-3000.0 53.30 700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 51.60 700.0 +-3000.0 49.60 800.0 +-3000.0 53.30 700.0 +-3000.0 51.30 800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 49.60 800.0 +-3000.0 47.60 900.0 +-3000.0 51.30 800.0 +-3000.0 49.30 900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 47.60 900.0 +-3000.0 45.60 1000.0 +-3000.0 49.30 900.0 +-3000.0 47.30 1000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 45.60 1000.0 +-3000.0 43.60 1100.0 +-3000.0 47.30 1000.0 +-3000.0 45.30 1100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 43.60 1100.0 +-3000.0 41.60 1200.0 +-3000.0 45.30 1100.0 +-3000.0 43.30 1200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 41.60 1200.0 +-3000.0 39.60 1300.0 +-3000.0 43.30 1200.0 +-3000.0 41.30 1300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 39.60 1300.0 +-3000.0 37.60 1400.0 +-3000.0 41.30 1300.0 +-3000.0 39.30 1400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 37.60 1400.0 +-3000.0 35.60 1500.0 +-3000.0 39.30 1400.0 +-3000.0 37.30 1500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 35.60 1500.0 +-3000.0 33.60 1600.0 +-3000.0 37.30 1500.0 +-3000.0 35.30 1600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 33.60 1600.0 +-3000.0 31.60 1700.0 +-3000.0 35.30 1600.0 +-3000.0 33.30 1700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 31.60 1700.0 +-3000.0 29.60 1800.0 +-3000.0 33.30 1700.0 +-3000.0 31.30 1800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 29.60 1800.0 +-3000.0 27.60 1900.0 +-3000.0 31.30 1800.0 +-3000.0 29.30 1900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 27.60 1900.0 +-3000.0 25.60 2000.0 +-3000.0 29.30 1900.0 +-3000.0 27.30 2000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 25.60 2000.0 +-3000.0 23.60 2100.0 +-3000.0 27.30 2000.0 +-3000.0 25.30 2100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 23.60 2100.0 +-3000.0 21.60 2200.0 +-3000.0 25.30 2100.0 +-3000.0 23.30 2200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 21.60 2200.0 +-3000.0 19.60 2300.0 +-3000.0 23.30 2200.0 +-3000.0 21.30 2300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 19.60 2300.0 +-3000.0 17.60 2400.0 +-3000.0 21.30 2300.0 +-3000.0 19.30 2400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 17.60 2400.0 +-3000.0 15.60 2500.0 +-3000.0 19.30 2400.0 +-3000.0 17.30 2500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 15.60 2500.0 +-3000.0 13.60 2600.0 +-3000.0 17.30 2500.0 +-3000.0 15.30 2600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 13.60 2600.0 +-3000.0 11.60 2700.0 +-3000.0 15.30 2600.0 +-3000.0 13.30 2700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 11.60 2700.0 +-3000.0 9.60 2800.0 +-3000.0 13.30 2700.0 +-3000.0 11.30 2800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 9.60 2800.0 +-3000.0 7.60 2900.0 +-3000.0 11.30 2800.0 +-3000.0 9.30 2900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 7.60 2900.0 +-3000.0 5.60 3000.0 +-3000.0 9.30 2900.0 +-3000.0 7.30 3000.0 +0.4 4.0 3 0.04 vis +endtraction + +// the W4 of the two stations of the timetable; the middle of the consist 2 m before it, leaves on time +include ip/pkp/w4n.inc gora#1 -2997.3 60.00 -60.0 180 0 0 2 202 end +include ip/pkp/w4n.inc dol#1 -2997.3 30.00 1500.0 180 0 0 2 202 end +// a signal at stop: what the AI reads of one, a memory cell with SetVelocity 0 0 and the event that reads it +node -1 0 gr_sem_mem memcell -2997.3 8.00 2600.0 SetVelocity 0.0 0.0 none endmemcell +event gr_sem_info getvalues 5.0 gr_sem_mem endevent + +trainset {{timetable}} gr_02 0.0 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py index 35e923bee..2dcec6f0d 100644 --- a/tests/scenarios/run.py +++ b/tests/scenarios/run.py @@ -482,25 +482,42 @@ def check_brakes(rows, min_pressure, moving_speed=20): return False, f"brake cylinder pressure never reached {min_pressure} bar after moving off" -def check_stops(rows, moving_speed, stop_speed, hold, min_distance=None, max_distance=None): +def check_stops(rows, moving_speed, stop_speed, hold, min_distance=None, max_distance=None, max_time=None, nth=1): + """The nth stop of `hold` seconds after moving off at `moving_speed` (each stop after the first counts once the + train is moving at `moving_speed` again).""" start = _first_moving(rows, moving_speed) if start is None: return False, f"never reached {moving_speed} km/h" dist = _distances(rows) stopped_at = None + held = 0 + moving = True for i in range(start, len(rows)): r = rows[i] + if not moving: + moving = r[COL_VELOCITY] >= moving_speed + continue if r[COL_VELOCITY] <= stop_speed: if stopped_at is None: stopped_at = i if r[COL_TIME] - rows[stopped_at][COL_TIME] >= hold: + held += 1 + if held < nth: + stopped_at = None + moving = False + continue where = dist[stopped_at] - detail = f"came to a stop at t={rows[stopped_at][COL_TIME]:.1f}s after {where:.0f} m" + when = rows[stopped_at][COL_TIME] + detail = f"came to a stop at t={when:.1f}s after {where:.0f} m" if (min_distance is not None and where < min_distance) or (max_distance is not None and where > max_distance): return False, f"{detail}, wanted between {min_distance} and {max_distance} m" + if max_time is not None and when > max_time: + return False, f"{detail}, wanted by t={max_time}s" return True, detail else: stopped_at = None + if held: + return False, f"stopped {held} times for {hold}s after moving off, wanted stop {nth}" return False, f"did not stay below {stop_speed} km/h for {hold}s after moving off" diff --git a/tests/unit/test_braking_curve.cpp b/tests/unit/test_braking_curve.cpp index 7102d06e0..6bcf92fc7 100644 --- a/tests/unit/test_braking_curve.cpp +++ b/tests/unit/test_braking_curve.cpp @@ -154,6 +154,41 @@ TEST_CASE("braking curve: a train with a worked out brake table plans along the } } +TEST_CASE("braking curve: the train brake handle or the independent brake counts as braking") { + CHECK_FALSE(braking_curve::brake_acting(0.0, 0.0)); + // the handle in its release or filling positions is below running + CHECK_FALSE(braking_curve::brake_acting(-1.0, 0.0)); + CHECK(braking_curve::brake_acting(1.0, 0.0)); + CHECK(braking_curve::brake_acting(0.5, 0.0)); + // a light locomotive or a railcar alone brakes with the independent brake, the handle stays in running + CHECK(braking_curve::brake_acting(0.0, 0.25)); + CHECK(braking_curve::brake_acting(-1.0, 1.0)); + CHECK(braking_curve::brake_acting(2.0, 0.5)); +} + +TEST_CASE("braking curve: a vehicle braking with its independent brake uses the whole distance, as with the train brake") { + // before, only the train brake handle counted: a light locomotive that had put its independent brake on still + // planned, on every look, to stop short by the distance the brake takes to fill, so it slowed down too early + // and crawled the last tens of metres to the stop + flat_table const light; + auto const table{light.table()}; + auto approach{stop_at(60.0, 300.0)}; + approach.offset = 20.0; + approach.fill_horizon = 8.0; + approach.brake_applied = braking_curve::brake_acting(0.0, 0.3); + + auto const demand{braking_curve::demand(approach, &table)}; + + CHECK(demand == doctest::Approx(braking_curve::shaped_demand(60.0, 0.0, 280.0 + 0.1 / 25.92, 0.0, table))); + auto trainbrake{approach}; + trainbrake.brake_applied = braking_curve::brake_acting(1.0, 0.0); + CHECK(demand == doctest::Approx(braking_curve::demand(trainbrake, &table))); + auto released{approach}; + released.brake_applied = braking_curve::brake_acting(0.0, 0.0); + // with no brake on, the room to fill is kept, and more is asked for + CHECK(braking_curve::demand(released, &table) < demand); +} + TEST_CASE("braking curve: a train gets the demand it got before the curve moved out of the AI") { // a table that grips harder as the train slows, on a gradient; the demands were worked out with the // code of TController::adjust_desired_speed_for_braking_curve before the move (origin/master 80fd5aad) diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index a25ed392c..5630cdea1 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -8256,8 +8256,16 @@ TController::adjust_desired_speed_for_braking_curve( double const Vel ) { // independent brake, which leaves the train brake handle where it is, kept braking earlier // and earlier the whole way in, to crawl the last tens of metres to the stop point auto const fillbrakea0 { bStopTargetIsPassengerStop ? 1.0 : fBrake_a0[ 0 ] }; + // once the brake is on, the room it takes to fill is behind; a vehicle running alone brakes with its + // independent brake and leaves the train brake handle in running, so that brake counts as well braking_curve::approach const approach { - Vel, VelNext, ActualProximityDist, brakingpointoffset, fAccGravity, AbsAccS, BrakeCtrlPosition > 0.0, + Vel, VelNext, ActualProximityDist, brakingpointoffset, fAccGravity, AbsAccS, + braking_curve::brake_acting( + BrakeCtrlPosition, + // IncLocalBrakeLevel() moves the independent brake handle on a vehicle without one too + ( mvOccupied->LocalBrake == TLocalBrake::PneumaticBrake || mvOccupied->LocalBrake == TLocalBrake::HydraulicBrake ) ? + mvOccupied->LocalBrakePosA : + 0.0 ), brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ), brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fillbrakea0 ) }; auto const deceleration { braking_curve::demand( approach, BrakeSystem == TBrakeSystem::Pneumatic ? &braketable : nullptr ) }; diff --git a/vehicle/brakingcurve.cpp b/vehicle/brakingcurve.cpp index d39ee2868..1cd1397aa 100644 --- a/vehicle/brakingcurve.cpp +++ b/vehicle/brakingcurve.cpp @@ -25,6 +25,10 @@ bool brake_table::known() const { return a0[size] > 0.0; } +bool brake_acting(double const Trainbrakeposition, double const Localbrakeposition) { + return (Trainbrakeposition > 0.0) || (Localbrakeposition > 0.0); +} + double shaped_demand(double const Velocity, double const Target, double const Distance, double const Gravity, brake_table const &Table) { auto const travel = [Velocity, Target, Gravity, &Table](double const Ratio) { diff --git a/vehicle/brakingcurve.h b/vehicle/brakingcurve.h index 6ed40d9bb..3b49597e5 100644 --- a/vehicle/brakingcurve.h +++ b/vehicle/brakingcurve.h @@ -40,11 +40,17 @@ struct approach { double offset; // the braking point that far short of it [m] double gravity; // tangential acceleration of the gradient [m/s2], negative uphill double acceleration; // present acceleration of the train [m/s2] - bool brake_applied; // the train brake handle is past running + bool brake_applied; // the brake the train slows down with is applied (brake_acting) double speedup_horizon; // how long the present acceleration lasts while speeding up [s] double fill_horizon; // how long the brake takes to fill once applied [s] }; +// whether the train is braking already, for approach::brake_applied: the train brake handle is past running +// (Trainbrakeposition above 0), or the independent brake is applied (Localbrakeposition above 0). a vehicle that +// runs alone, a light locomotive or a railcar, brakes with the independent brake and leaves the train brake +// handle in running +bool brake_acting(double Trainbrakeposition, double Localbrakeposition); + // acceleration [m/s2] to ask for now, negative to brake. with the worked out table of a pneumatic brake // (Pneumatictable) the demand follows the brake: planned from the state the train is in once the brake has // responded, along the shape of its force over speed. without one (nullptr for another brake, or a table left at From 3ccd4fe73ff4a9cdd2f5fe12c1b6854e9d9fd03a Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:15:27 +0100 Subject: [PATCH 106/136] fix(ai): read the motor parameters of ESMVelocity() within the table (#486) * fix(ai): read the motor parameters of ESMVelocity() within the table TController::ESMVelocity() indexed MotorParam with the field shunting step of the next master controller position. For a position with a step of its own that index is RList[].ScndAct, the sixth column of the RList rows of the .fiz, which readRList() takes as it is. A step of 11 or more read past the 11 entries of MotorParam. The pole flux is now read through motor_param(), which keeps the index inside the table, as MomentumF() in the same loop and Momentum() already do. Nothing changes for a .fiz with valid steps. The unit tests show the loader keeping an out-of-range ScndAct and motor_param() clamping it; ESMVelocity() itself is in Driver.cpp, which the unit tests don't build. * test(scenarios): a Traxx, with a brake handle with a time chamber, starting up None of the cases had a driver's brake handle with a time chamber (MHZ_K5P, MHZ_6P, M394, Knorr, St113, FVel6, FVE408), for which the AI getting the vehicle ready has a rule of its own for releasing the train brake (5775493b2). Three cases run a Traxx (E186, MHZ_6P) on td.scn: the timetable run from a trainset ready to depart, the same from a cold start, and the locomotive standing ready to depart with nobody in it until a driver is put in. In each the driver puts the handle to running and leaves. * test: read the EP09 definition into a json with '=', not braces GCC takes nlohmann::ordered_json in braces for an initializer list and makes an array holding the parsed object, so at("RList") threw on the Linux build (type_error 304); MSVC kept the object. --- tests/scenarios/README.md | 10 ++++ tests/scenarios/cases/traxx_td_crew_add.json | 31 ++++++++++ tests/scenarios/cases/traxx_td_timetable.json | 17 ++++++ .../cases/traxx_td_timetable_cold.json | 20 +++++++ tests/unit/test_motor_param_bounds.cpp | 57 +++++++++++++++++++ vehicle/Driver.cpp | 6 +- 6 files changed, 139 insertions(+), 2 deletions(-) create mode 100644 tests/scenarios/cases/traxx_td_crew_add.json create mode 100644 tests/scenarios/cases/traxx_td_timetable.json create mode 100644 tests/scenarios/cases/traxx_td_timetable_cold.json create mode 100644 tests/unit/test_motor_param_bounds.cpp diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index bf5467018..5ddc77dca 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -242,6 +242,16 @@ stop, starting `vars.offset` m into `tdo_n1734`: `eu07_td_shunt_red_signal` alon 151 m from the start (the shunting AI used to coast up to it and pass it at about 28 km/h, fixed by #409). They stop after 145 m and 141 m. +The `traxx_*` cases run a Traxx (E186, `p160dc`), whose driver's brake handle (MHZ_6P) has a time +chamber, like the MHZ_K5P, M394, Knorr, St113, FVel6 and FVE408 handles, which no other case has: the +AI getting such a locomotive ready has a rule of its own for releasing the train brake (5775493b2, +#444). `traxx_td_timetable` is the timetable run from a trainset ready to depart, +`traxx_td_timetable_cold` the same from a cold start (`td_cold_timetable.scn`, the handle in its +holding position, the brake pipe low), and `traxx_td_crew_add` the locomotive standing ready to depart +with nobody in it, the handle in its holding position and the brake pipe charged, until a driver is +put in (`td_crew.scn`, as `eu07_td_crew_add`). In all three the driver puts the handle to running +within a second of starting and leaves. + `eu07_td_departure_station_capitals` runs an EU07 from where `td_timetable.scn` puts it, with the W4 of Stacja1 about 35 m ahead, on a timetable of its own (`td_departure_station_capitals.txt`, fragment `td_departure_station.scn`): its first row, the station of departure, gives no arrival time and is written in capitals (`STACJA1`), the relation diff --git a/tests/scenarios/cases/traxx_td_crew_add.json b/tests/scenarios/cases/traxx_td_crew_add.json new file mode 100644 index 000000000..9d6200a1b --- /dev/null +++ b/tests/scenarios/cases/traxx_td_crew_add.json @@ -0,0 +1,31 @@ +{ + "description": "As eu07_td_crew_add, with a Traxx (E186, p160dc) standing ready to depart (trainset velocity 0.1) with nobody in it: its brake handle, one with a time chamber (MHZ_6P), in the holding position and the brake pipe and the control reservoir at running pressure. The AI driver put in cab A 20 s after the start gets the locomotive ready, puts the handle to running and leaves through the exit signal.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_crew.scn", + "vars": { + "trainsets": [ + "trainset none tdo_n1734 0.0 0.1", + "node -1 0 {{vehicle}} dynamic pkp/e186_v2 146_226-6 p160dc 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "crew": [ + "event autotest_crew_put putvalues 0 none 0 0 0 Crew:{{vehicle}} 1 0 endevent", + "event autotest_crew_on multiple 20 none autotest_crew_put autotest_crew_waits endevent", + "node -1 0 autotest_crew_on_launcher eventlauncher 0 0 0 -1 none 1034 autotest_crew_on end" + ] + }, + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Crew: \\[autotest_traxx_td_crew_add\\] an AI driver takes cab A" }, + { "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "ai", "after": 15, "before": 30 }, + { "type": "starts", "min_speed": 20, "within": 240 }, + { "type": "moves", "vehicle": "{{vehicle}}", "direction": "front", "min_speed": 20 }, + { "type": "log_lacks", "pattern": "derailed" }, + { "type": "log_lacks", "pattern": "collided" } + ] +} diff --git a/tests/scenarios/cases/traxx_td_timetable.json b/tests/scenarios/cases/traxx_td_timetable.json new file mode 100644 index 000000000..51d84860b --- /dev/null +++ b/tests/scenarios/cases/traxx_td_timetable.json @@ -0,0 +1,17 @@ +{ + "description": "Traxx (E186, p160dc) on td.scn, AI driver on the td/rozklad timetable: a driver's brake handle with a time chamber (MHZ_6P), for which the AI getting the locomotive ready has a rule of its own for releasing the train brake (5775493b2, #444). Starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/e186_v2 146_226-6 p160dc 0 headdriver 0 0 enddynamic" + }, + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "brakes", "min_pressure": 0.5 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/scenarios/cases/traxx_td_timetable_cold.json b/tests/scenarios/cases/traxx_td_timetable_cold.json new file mode 100644 index 000000000..bfdb833a2 --- /dev/null +++ b/tests/scenarios/cases/traxx_td_timetable_cold.json @@ -0,0 +1,20 @@ +{ + "description": "As traxx_td_timetable, from a cold start: the trainset stands with velocity 0, so the locomotive starts braked, its brake handle (MHZ_6P, with a time chamber) in the holding position and the brake pipe below running pressure. The driver gets the order to run as a train, starts the locomotive, puts the handle to running, charges the brake pipe and leaves on time.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_cold_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/e186_v2 146_226-6 p160dc 0 headdriver 0 0 enddynamic" + }, + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "brakes", "min_pressure": 0.5 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/unit/test_motor_param_bounds.cpp b/tests/unit/test_motor_param_bounds.cpp new file mode 100644 index 000000000..5d44c7331 --- /dev/null +++ b/tests/unit/test_motor_param_bounds.cpp @@ -0,0 +1,57 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +#include + +#include + +using test::definition; +using test::vehicle; + +// the field shunting step a position of the master controller selects (RList, its sixth column ScndAct) indexes the +// motor parameter table, MotorParam, which has MotorParametersArraySize + 1 entries. The loader takes ScndAct from the +// .fiz as it is, so the readers of the table (TMoverParameters::Momentum(), MomentumF(), TController::ESMVelocity()) +// go through motor_param(), which keeps the index inside the table + +namespace { + +// the RList rows of the EP09 with the ScndAct of the first position replaced +nlohmann::ordered_json ep09_rlist_with_scndact(std::string const &Scndact) { + std::ifstream file{std::string{EU07_UNIT_TESTS_DATA} + "/fiz/ep09_v2/104e.json"}; + REQUIRE(file.good()); + // '=' rather than braces: GCC takes a json in braces for an initializer list, an array holding it + auto const ep09 = nlohmann::ordered_json::parse(file); + auto rows = ep09.at("RList").at("rows"); + REQUIRE(rows.size() > 1); + rows[1][5] = Scndact; + return rows; +} + +} // namespace + +TEST_CASE("motor parameters: the ScndAct of an RList row is read from the .fiz as it is") { + vehicle ep09{definition::fiz("ep09_v2/104e")}; + // the first position of the EP09 runs on field shunting step 2 + CHECK(ep09->RList[1].ScndAct == 2); + CHECK(&ep09->motor_param(ep09->RList[1].ScndAct) == &ep09->MotorParam[2]); + + // a .fiz giving a step beyond the table: nothing checks it on loading + vehicle broken{definition::fiz("ep09_v2/104e").set("RList", "rows", ep09_rlist_with_scndact("20"))}; + CHECK(broken->RList[1].ScndAct == 20); + CHECK(broken->RList[1].ScndAct > MotorParametersArraySize); +} + +TEST_CASE("motor parameters: motor_param() keeps a step from the .fiz inside the table") { + vehicle broken{definition::fiz("ep09_v2/104e").set("RList", "rows", ep09_rlist_with_scndact("20"))}; + auto const &table{broken->MotorParam}; + // past the end: the last entry, rather than memory beyond the table + CHECK(&broken->motor_param(broken->RList[1].ScndAct) == &table[MotorParametersArraySize]); + CHECK(&broken->motor_param(MotorParametersArraySize + 1) == &table[MotorParametersArraySize]); + // below the start: the first entry + CHECK(&broken->motor_param(-1) == &table[0]); + // inside the table: the entry itself + for (int step = 0; step <= MotorParametersArraySize; ++step) { + CHECK(&broken->motor_param(step) == &table[step]); + } +} diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 5630cdea1..086ff43ad 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -2726,8 +2726,10 @@ double TController::ESMVelocity(bool Main) } IF = std::min(IF, mvControlling->Imax*fCurrentCoeff); double R = mvControlling->RList[MCPN].R + mvControlling->CircuitRes + mvControlling->RList[MCPN].Mn*mvControlling->WindingRes; - double pole = mvControlling->MotorParam[SCPN].fi * - std::max(abs(IF) / (abs(IF) + mvControlling->MotorParam[SCPN].Isat) - mvControlling->MotorParam[SCPN].fi0, 0.0); + // SCPN may come from the .fiz (RList ScndAct) unchecked: read it with the bounds-safe accessor, as MomentumF() does + auto const &motorparam{mvControlling->motor_param(SCPN)}; + double pole = motorparam.fi * + std::max(abs(IF) / (abs(IF) + motorparam.Isat) - motorparam.fi0, 0.0); double Us = abs(mvControlling->EngineVoltage) - IF*R; double ns = std::max(0.0, Us / (pole*mvControlling->RList[MCPN].Mn)); ESMVel = ns * mvControlling->WheelDiameter*M_PI*3.6/mvControlling->Transmision.Ratio; From fa13d4b4a25084e515a93f77f35b45c4c7344460 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:15:40 +0100 Subject: [PATCH 107/136] fix(editor): Esc in the road window goes back to the select tool when nothing is being drawn (#487) Esc in the road window only called road_cancel(), which gives up the road being drawn but never changes the tool, so with the build or place tool chosen every Esc left that tool in use and the next click started another road. Now the first Esc still gives up the road being drawn (or led out of a road or a junction, or the Alt+drag of the heights) and keeps the tool; with nothing going on Esc switches to the select tool, the way the first and the next Esc work in the track field of work. The decision is editor_road::tool_after_escape(), covered by unit tests. Fixes #348 --- application/editormode.cpp | 5 ++++ editor/editorRoad.hpp | 7 ++++++ tests/unit/test_road_escape.cpp | 44 +++++++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+) create mode 100644 tests/unit/test_road_escape.cpp diff --git a/application/editormode.cpp b/application/editormode.cpp index a40c6e081..cfc0287c6 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -7454,7 +7454,12 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in } if (is_press(Action)) { + // in the road window the first Esc gives up the road being drawn, the next one goes back to the selection + auto const &road{m_roadtool}; + auto const next{editor_road::tool_after_escape(road.tool, road.chain || road.branchroad != nullptr || road.branchjunction != nullptr, road.lifting)}; road_cancel(); + if (road.window && ui()->mode() != nodebank_panel::TRACK) + road_choose_tool(next); } // the first Esc drops what is going on in the track mode, the next one goes back to the selection if (is_press(Action) && ui()->mode() == nodebank_panel::TRACK) diff --git a/editor/editorRoad.hpp b/editor/editorRoad.hpp index c1b23433f..51498b143 100644 --- a/editor/editorRoad.hpp +++ b/editor/editorRoad.hpp @@ -173,6 +173,13 @@ class editor_road // Radius: of the axis of that road; Layout: what the road is like. the lanes it has along its axis are the ones the roundabout gets. // Island: what the middle is covered with, "none" to leave the ground showing static std::vector roundabout(glm::dvec3 const &Centre, double const Radius, road_node::state const &Layout, std::string const &Island); + // the tool of the road window (0 select, 1 build, 2 place) Esc leaves. while a road is being drawn, or led out of the side of + // a road or a junction, or the selected points are dragged up or down, the tool in use stays and Esc gives that up; with + // nothing going on Esc goes back to the selection + static constexpr int tool_after_escape(int const Tool, bool const Drawing, bool const Lifting) + { + return (Drawing || Lifting) ? Tool : 0; + } private: // takes down what depends on the listed pieces and junctions, lets the caller change them, then builds it all again diff --git a/tests/unit/test_road_escape.cpp b/tests/unit/test_road_escape.cpp new file mode 100644 index 000000000..31fbc1a21 --- /dev/null +++ b/tests/unit/test_road_escape.cpp @@ -0,0 +1,44 @@ +// Esc in the road window (GH#348): the first one gives up what is going on, the next one goes back to the selection + +#include "stdafx.h" +#include "doctest.h" +#include "editor/editorRoad.hpp" + +namespace { + +constexpr int select_tool{0}; +constexpr int build_tool{1}; +constexpr int place_tool{2}; + +} // namespace + +TEST_CASE("Esc with the build tool and no road being drawn goes back to the selection") { + CHECK(editor_road::tool_after_escape(build_tool, false, false) == select_tool); +} + +TEST_CASE("Esc while a road is being drawn or led out of a road or a junction keeps the build tool") { + CHECK(editor_road::tool_after_escape(build_tool, true, false) == build_tool); +} + +TEST_CASE("Esc with the place tool goes back to the selection, the tool has nothing being drawn") { + CHECK(editor_road::tool_after_escape(place_tool, false, false) == select_tool); +} + +TEST_CASE("Esc while the selected points are dragged up or down keeps the tool, the drag is given up") { + CHECK(editor_road::tool_after_escape(select_tool, false, true) == select_tool); + CHECK(editor_road::tool_after_escape(build_tool, false, true) == build_tool); +} + +TEST_CASE("Esc with the selection tool stays with it") { + CHECK(editor_road::tool_after_escape(select_tool, false, false) == select_tool); +} + +TEST_CASE("two Esc presses from the build tool in the middle of a road: the road given up, then the selection") { + auto tool{build_tool}; + bool drawing{true}; + tool = editor_road::tool_after_escape(tool, drawing, false); + drawing = false; // what the first Esc gives up + CHECK(tool == build_tool); + tool = editor_road::tool_after_escape(tool, drawing, false); + CHECK(tool == select_tool); +} From 0c01d660f64fbd1b75028f00eaf03cd816f27b9c Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:23:37 +0100 Subject: [PATCH 108/136] fix(editor): roads joined to a roundabout take only the room they need (#485) * fix(editor): a road joined to a roundabout takes only the room it needs A road led into the side of a roundabout gets a junction that cuts the ring on both sides of it. The cut was measured as on a straight road: where the edge of the road leaving meets the edge of the road it leaves, plus the corner, and with the value of the acute corner used on both sides. The ring bends away from a road leaving it to the outside, so the edges meet sooner, and a road leaving at a slant meets the ring much sooner on the side it leans away from. Each junction took too much of the ring, and the next road was refused with "Too close to a junction": with roads joined at a slant only two fitted on a roundabout of 12-15 m. On a roundabout the room on each side is now measured on the circle of the ring's outer edge, never more than before. In the editor, five roads at 45 degrees now join a roundabout of 15 m and four at 30 degrees one of 12 m (two before); roads joined straight out gain less: two instead of one on the smallest roundabout (8 m), four of six on one of 16 m instead of three. Saved roundabouts load as before; only junctions made from now on are laid out differently. Fixes #349 * fix(editor): junctions on a roundabout leave shorter pieces of the ring A junction cut into a road leaves at least 2 m of the piece it cuts. When less would be left, it takes the rest of the piece, so a junction next to the end of one of the ring's arcs grew by up to 2 m, and the next junction had to stay 2 m further away. On a roundabout of 8-10 m, where each road joined straight out takes about 14 m of the ring, that was the difference between two roads and three or four. The ring goes on round past such a piece, so on a roundabout the shortest piece is now 0.5 m (editor_ring::shortest_piece). Roads of their own keep the 2 m. In the editor, three roads joined straight out now fit on the smallest roundabout (8 m) and four on one of 9.6 m or more, wherever they join the ring; six fit on 15 and 16 m. Four roads on the 8 m one would take smaller corners, and are still refused. Saved roundabouts load as before. * fix(editor): the reaches of a junction on a roundabout in a std::array --- editor/editorRingRoom.hpp | 63 +++++++++++++++ editor/editorRoad.cpp | 44 ++++++++++- tests/unit/test_ring_room.cpp | 143 ++++++++++++++++++++++++++++++++++ 3 files changed, 248 insertions(+), 2 deletions(-) create mode 100644 editor/editorRingRoom.hpp create mode 100644 tests/unit/test_ring_room.cpp diff --git a/editor/editorRingRoom.hpp b/editor/editorRingRoom.hpp new file mode 100644 index 000000000..9051da616 --- /dev/null +++ b/editor/editorRingRoom.hpp @@ -0,0 +1,63 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include + +// the room a road leaving the side of a roundabout takes of the ring, seen from above. on a straight road the edge of the road +// leaving meets the edge of the road it leaves where the two straight lines cross; the ring bends away from the road leaving it +// to the outside, so there the edges meet sooner; and a road leaving at a slant meets the edge of the ring sooner on the side +// it leans away from than on the side it leans towards +namespace editor_ring +{ + +// the shortest piece of the ring a junction leaves before the next junction, or before the end of the arc it's cut from. +// the ring goes on past it, so it can be much shorter than a road of its own; a junction which would leave less takes +// the rest of the arc, and the shorter this is the less a junction grows next to the end of an arc +double constexpr shortest_piece{0.5}; + +// how far along the axis of the ring, from the point a road leaves it, the edge of that road meets the outer edge of the ring. +// Centre: of the ring, Radius: of its axis, Point: where the axis of the road leaving meets the axis of the ring, +// Direction: the way the road leaves, Along: the way along the ring the room is measured, Halfwidth: of the ring, +// Branchhalfwidth: of the road leaving. returns: the distance along the axis of the ring, 0 if the edges cross before they get +// past the point the road leaves, or a negative value if there's no such point: the road doesn't leave towards the outside, +// or it leans so far that the edge on that side stays outside the ring all along +inline double edge_room(glm::dvec2 const &Centre, double const Radius, glm::dvec2 const &Point, glm::dvec2 const &Direction, glm::dvec2 const &Along, double const Halfwidth, + double const Branchhalfwidth) +{ + if (Radius <= 0.0 || glm::length(Direction) < 1e-9 || glm::length(Point - Centre) < 1e-9) + return -1.0; + auto const direction{glm::normalize(Direction)}; + auto const outwards{glm::normalize(Point - Centre)}; + if (glm::dot(direction, outwards) < 1e-6) + return -1.0; + // the edge of the road leaving on the side the room is measured for + glm::dvec2 side{-direction.y, direction.x}; + if (glm::dot(side, Along) < 0.0) + side = -side; + auto const start{Point - Centre + side * Branchhalfwidth}; + auto const edge{Radius + Halfwidth}; + // start + direction * t on the circle of the outer edge, where the edge leaves it going out. a road wide enough, or leaning + // far enough, has the start of that edge outside the circle already: the edges crossed before it + auto const b{glm::dot(start, direction)}; + auto const discriminant{b * b + edge * edge - glm::dot(start, start)}; + if (discriminant < 0.0) + return -1.0; + auto const t{-b + std::sqrt(discriminant)}; + auto const meet{start + direction * t}; + // the angle from the point the road leaves to that point, around the centre and the way the room is measured, carried onto the axis + auto const turn{outwards.x * Along.y - outwards.y * Along.x < 0.0 ? -1.0 : 1.0}; + auto const angle{std::atan2(turn * (outwards.x * meet.y - outwards.y * meet.x), glm::dot(outwards, meet))}; + return std::max(0.0, Radius * angle); +} + +} // namespace editor_ring diff --git a/editor/editorRoad.cpp b/editor/editorRoad.cpp index 51aa495f3..b803416a8 100644 --- a/editor/editorRoad.cpp +++ b/editor/editorRoad.cpp @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "editor/editorRoad.hpp" #include "editor/editorFormat.hpp" +#include "editor/editorRingRoom.hpp" #include "editor/editorTrack.hpp" #include "world/Track.h" @@ -274,7 +275,9 @@ bool follow(road_node &Road, double const T, bool const Forward, double const Di auto const lengths{stations(state)}; auto const here{station_at(lengths, from)}; auto const available{forward ? lengths.back() - here : here}; - if (remaining <= 0.0 || available >= remaining + kShortestRoad) + // what's left of a piece of a roundabout carries on round, so it can be shorter than a road of its own + auto const shortest{state.roundabout ? editor_ring::shortest_piece : kShortestRoad}; + if (remaining <= 0.0 || available >= remaining + shortest) { // the cut is put here; with nothing left to go the piece is kept whole Cut.road = piece; @@ -339,6 +342,27 @@ double edge_reach(double const Halfwidth, double const Otherhalfwidth, double co return (Otherhalfwidth + Halfwidth * std::cos(Angle)) / std::sin(Angle); } +// the circle the axis of a piece bends along at specified value of its curve parameter, seen from above. returns: false if it's straight there +bool ring_circle(road_node::state const &State, double const T, glm::dvec2 &Centre, double &Radius) +{ + auto const points{curve_points(State.axis)}; + auto const u{1.0 - T}; + auto const first{3.0 * u * u * (points[1] - points[0]) + 6.0 * u * T * (points[2] - points[1]) + 3.0 * T * T * (points[3] - points[2])}; + auto const second{6.0 * u * (points[2] - 2.0 * points[1] + points[0]) + 6.0 * T * (points[3] - 2.0 * points[2] + points[1])}; + glm::dvec2 const velocity{first.x, first.z}; + auto const speed{glm::length(velocity)}; + if (speed < 1e-9) + return false; + auto const curvature{(velocity.x * second.z - velocity.y * second.x) / (speed * speed * speed)}; + if (std::abs(curvature) < 1e-5) + return false; + auto const point{curve_point(points, T)}; + auto const tangent{velocity / speed}; + Centre = glm::dvec2{point.x, point.z} + glm::dvec2{-tangent.y, tangent.x} / curvature; + Radius = 1.0 / std::abs(curvature); + return true; +} + // the look of a junction goes after the road it's made on void dress(junction_node::state &Junction, road_node::state const &Road) { @@ -1852,11 +1876,27 @@ bool editor_road::branch_from(road_node &Road, double const T, glm::dvec2 const auto const branchhalfwidth{0.5 * (Incoming + Outgoing) * Width}; auto const reach{edge_reach(halfwidth, branchhalfwidth, angle) + kCornerRoom}; auto const branchreach{edge_reach(branchhalfwidth, halfwidth, angle) + kCornerRoom}; + // how far the junction takes the road back along it and ahead of the centre + std::array reaches{reach, reach}; + glm::dvec2 ringcentre{0.0}; + double ringradius{0.0}; + if (layout.roundabout && ring_circle(layout, T, ringcentre, ringradius)) + { + // the ring bends away from a road leaving it to the outside, so their edges meet sooner than on a straight road; and a road + // leaving at a slant meets the edge of the ring sooner on the side it leans away from. the room of a straight road, measured + // on the side the road leans towards, is the most a side takes + for (int side = 0; side < 2; ++side) + { + auto const room{editor_ring::edge_room(ringcentre, ringradius, glm::dvec2{centre.x, centre.z}, direction, side == 0 ? -along : along, halfwidth, branchhalfwidth)}; + if (room >= 0.0) + reaches[side] = std::min(reach, room + kCornerRoom); + } + } // where the road is cut on both sides of the centre road_cut cuts[2]; std::vector consumed; - if (false == follow(Road, T, false, reach, cuts[0], consumed, Error) || false == follow(Road, T, true, reach, cuts[1], consumed, Error)) + if (false == follow(Road, T, false, reaches[0], cuts[0], consumed, Error) || false == follow(Road, T, true, reaches[1], cuts[1], consumed, Error)) return false; if (cuts[0].road == cuts[1].road && cuts[0].road != &Road) { diff --git a/tests/unit/test_ring_room.cpp b/tests/unit/test_ring_room.cpp new file mode 100644 index 000000000..835072f75 --- /dev/null +++ b/tests/unit/test_ring_room.cpp @@ -0,0 +1,143 @@ +#include "stdafx.h" +#include "doctest.h" +#include "editor/editorRingRoom.hpp" + +#include + +// the room a road leaving the side of a roundabout takes of the ring (eu07/maszyna GH#349): with the ring's bend +// counted, as many roads fit on a small roundabout as there's room for between their edges +namespace { + +double constexpr pi{3.14159265358979323846}; +// as the road editor has them: a junction takes the road it's made on past where the edges meet by the corner room, +// and between two junctions there's at least the shortest road left +double constexpr kCornerRoom{4.0}; +double constexpr kShortestRoad{2.0}; +// the roads the editor builds unless told otherwise: a lane each way, 3.5 m each, and a roundabout of a single lane +double constexpr kRoadHalfwidth{3.5}; +double constexpr kRingHalfwidth{1.75}; + +glm::dvec2 at(double const Radius, double const Angle) { return glm::dvec2{std::cos(Angle), std::sin(Angle)} * Radius; } +glm::dvec2 ahead(double const Angle) { return {-std::sin(Angle), std::cos(Angle)}; } + +// room of a road leaving the ring of the radius at the angle, turned from the way straight out by the slant (to the way ahead) +double room(double const Radius, double const Slant, bool const Ahead, double const Halfwidth = kRingHalfwidth, double const Branchhalfwidth = kRoadHalfwidth) { + double const angle{0.3}; + auto const outwards{at(1.0, angle)}; + auto const direction{outwards * std::cos(Slant) + ahead(angle) * std::sin(Slant)}; + return editor_ring::edge_room(glm::dvec2{0.0}, Radius, at(Radius, angle), direction, Ahead ? ahead(angle) : -ahead(angle), Halfwidth, Branchhalfwidth); +} + +// where the edges of two straight roads meet, measured along the first one, as the editor has it for a road leaving a straight road. +// Lean: the second one leans towards the side measured (the angle between them there is the acute one) +double straight_reach(double const Halfwidth, double const Branchhalfwidth, double const Angle, bool const Lean) { + return (Branchhalfwidth + (Lean ? 1.0 : -1.0) * Halfwidth * std::cos(Angle)) / std::sin(Angle); +} + +// whether the roads leaving straight out, evenly all around the ring, each get a junction: the junctions with what's left between them. +// Bend: the room measured on the ring, rather than as on a straight road; Shortest: the shortest piece left between two junctions. +// Arcs: a junction next to the end of an arc of the ring takes the rest of the arc when less than the shortest piece would be left +// of it, so in the worst case it grows by as much +bool fit(double const Radius, int const Roads, bool const Bend, double const Shortest, bool const Arcs) { + auto const side{Bend ? room(Radius, 0.0, true) : straight_reach(kRingHalfwidth, kRoadHalfwidth, pi / 2.0, true)}; + auto const junction{2.0 * (side + kCornerRoom)}; + return Roads * (junction + Shortest + (Arcs ? Shortest : 0.0)) <= 2.0 * pi * Radius; +} +bool fit(double const Radius, int const Roads, bool const Bend) { return fit(Radius, Roads, Bend, kShortestRoad, false); } +// as the editor has it now, wherever the roads join the ring +bool fits(double const Radius, int const Roads) { return fit(Radius, Roads, true, editor_ring::shortest_piece, true); } + +} // namespace + +TEST_CASE("ring room: on a very large ring the room is the one of a straight road") { + for (double const slant : {0.0, pi / 12.0, pi / 6.0, pi / 4.0, pi / 3.0}) { + CAPTURE(slant); + double const angle{pi / 2.0 - slant}; + CHECK(room(1.0e6, slant, true) == doctest::Approx(straight_reach(kRingHalfwidth, kRoadHalfwidth, angle, true)).epsilon(1e-4)); + CHECK(room(1.0e6, slant, false) == doctest::Approx(straight_reach(kRingHalfwidth, kRoadHalfwidth, angle, false)).epsilon(1e-4)); + } +} + +TEST_CASE("ring room: a road leaving straight out meets the outer edge where the circle reaches its edge") { + for (double const radius : {8.0, 15.0, 40.0}) { + CAPTURE(radius); + double const expected{radius * std::asin(kRoadHalfwidth / (radius + kRingHalfwidth))}; + CHECK(room(radius, 0.0, true) == doctest::Approx(expected)); + CHECK(room(radius, 0.0, false) == doctest::Approx(expected)); + // never more than on a straight road + CHECK(room(radius, 0.0, true) < kRoadHalfwidth); + } +} + +TEST_CASE("ring room: a slanted road takes less on the side it leans away from") { + for (double const radius : {8.0, 15.0, 50.0}) { + for (double const slant : {pi / 6.0, pi / 4.0}) { + CAPTURE(radius); + CAPTURE(slant); + auto const towards{room(radius, slant, true)}; + auto const away{room(radius, slant, false)}; + CHECK(away >= 0.0); + CHECK(away < towards); + // the editor took the room of the acute corner on both sides + CHECK(towards < straight_reach(kRingHalfwidth, kRoadHalfwidth, pi / 2.0 - slant, true)); + } + } + // on a straight road the obtuse corner takes less than the acute one too + CHECK(room(1.0e6, pi / 4.0, false) < room(1.0e6, pi / 4.0, true)); + // leaving the smallest ring as sharply as the editor allows, 30 degrees off it, the edge on the side the road leans away from + // is outside the ring all along: there's no point to measure to, and the editor keeps the room it took before + CHECK(room(8.0, pi / 3.0, false) < 0.0); + CHECK(room(8.0, pi / 3.0, true) > 0.0); + CHECK(room(15.0, pi / 3.0, false) >= 0.0); +} + +TEST_CASE("ring room: none for a road going inwards") { + CHECK(room(15.0, pi * 0.75, true) < 0.0); + CHECK(room(15.0, pi, true) < 0.0); + CHECK(editor_ring::edge_room(glm::dvec2{0.0}, 0.0, glm::dvec2{1.0, 0.0}, glm::dvec2{1.0, 0.0}, glm::dvec2{0.0, 1.0}, 1.0, 1.0) < 0.0); +} + +TEST_CASE("ring room: a road wider than the ring is round still meets its edge, sooner than on a straight road") { + // two lanes each way on the smallest roundabout: the edge of the road starts outside the ring + double const halfwidth{7.0}; + double const radius{8.0}; + double const expected{radius * std::atan2(halfwidth, std::sqrt((radius + kRingHalfwidth) * (radius + kRingHalfwidth) - halfwidth * halfwidth))}; + CHECK(room(radius, 0.0, true, kRingHalfwidth, halfwidth) == doctest::Approx(expected)); + CHECK(room(radius, 0.0, true, kRingHalfwidth, halfwidth) < halfwidth); +} + +TEST_CASE("ring room: roads joined to roundabouts of the radii the editor allows") { + // the smallest roundabout took two roads; three were too many for it + CHECK(fit(8.0, 2, false)); + CHECK_FALSE(fit(8.0, 3, false)); + CHECK(fit(8.0, 3, true)); + // four roads from 11 m + CHECK(fit(11.0, 4, true)); + CHECK(fit(15.0, 4, true)); + // six from 16 m, where they took 17 m before + CHECK_FALSE(fit(16.0, 6, false)); + CHECK(fit(16.0, 6, true)); + CHECK(fit(25.0, 6, true)); + // and more on the large ones + CHECK(fit(50.0, 8, true)); + CHECK(fit(200.0, 30, true)); +} + +TEST_CASE("ring room: a short piece of the ring is left between junctions, so small roundabouts take three or four roads") { + // the ring goes on past a piece of it, which can be much shorter than a road of its own + CHECK(editor_ring::shortest_piece < kShortestRoad); + CHECK(editor_ring::shortest_piece > 0.25); // further apart than ends taken for joined + // with the shortest road left between them, and a junction growing by as much next to the end of an arc, three roads + // didn't always fit on the smallest roundabout, nor four on one of 10 m + CHECK_FALSE(fit(8.0, 3, true, kShortestRoad, true)); + CHECK_FALSE(fit(10.0, 4, true, kShortestRoad, false)); + // they do now, wherever they join the ring + CHECK(fits(8.0, 3)); + CHECK(fits(10.0, 4)); + CHECK(fits(9.6, 4)); + // four on the smallest one would take smaller corners + CHECK_FALSE(fits(8.0, 4)); + // and the larger ones take more + CHECK(fits(15.0, 6)); + CHECK(fits(25.0, 8)); +} From 236a25eacbb41d287b51172e45bdc470468f92c7 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:23:53 +0100 Subject: [PATCH 109/136] Speed table: report a signal index that points past the end of the table (#489) * fix(ai): report a signal index past the end of the speed table TableTraceRoute() drops SemNextIndex / SemNextStopIndex when they point past the end of the speed table. This used to catch the indices TablePurger() and TableCheck() left behind; #178 fixed both, and nothing else shrinks the table without resetting them, so the check should never fire. It stays as a safety net, but now writes to errors.txt when it does fire (vehicle, index, table size, last track and its distance, scan range), so a new way of getting there is noticed instead of being hidden. Not seen in the scenario suite (37 cases) nor in two runs of the whole L053 poranek scenery with every train driven by AI (about 75 min of simulation each). * fix(ai): the stale index report captures what it uses and is built with std::format --- vehicle/Driver.cpp | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 086ff43ad..0c2568ad3 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -575,15 +575,21 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) } else { if( iTableDirection == 0 ) { return; } - // NOTE: belt and braces; TablePurger() used to leave these pointing past the end of the table - if( SemNextIndex != npos - && SemNextIndex >= sSpeedTable.size() ) { - SemNextIndex = npos; - } - if( SemNextStopIndex != npos - && SemNextStopIndex >= sSpeedTable.size() ) { - SemNextStopIndex = npos; - } + // NOTE: belt and braces; TablePurger() used to leave these pointing past the end of the table. + // nothing is known to do that any more, so say so when it happens + auto const dropstaleindex = [this, fDistance]( std::size_t &Index, std::string_view const Name ) { + if( Index == npos + || Index < sSpeedTable.size() ) { + return; + } + ErrorLog( std::format( + "Speed table for {}: {} {} points past the end of the table ({} records), last track {} at {:.1f} m, scan range {:.1f} m; reset", + OwnerName(), Name, Index, sSpeedTable.size(), + ( iLast >= 0 && sSpeedTable[ iLast ].trTrack != nullptr ? sSpeedTable[ iLast ].trTrack->name() : "none" ), + ( iLast >= 0 ? sSpeedTable[ iLast ].fDist : 0.0 ), fDistance ) ); + Index = npos; }; + dropstaleindex( SemNextIndex, "SemNextIndex" ); + dropstaleindex( SemNextStopIndex, "SemNextStopIndex" ); // kontynuacja skanowania od ostatnio sprawdzonego toru (w ostatniej pozycji zawsze jest tor) if( SemNextStopIndex != npos && sSpeedTable[SemNextStopIndex].fVelNext == 0.0 ) { From 781278463215b21300a9c72cc9c7d91cf7ea8903 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:24:12 +0100 Subject: [PATCH 110/136] fix(scripting): hold the Lua screen heap at each allocation on 64-bit Windows too (#490) * fix(scripting): hold the Lua screen heap at each allocation on 64-bit Windows too LuaJIT 2.0 on x64, the game's runtime on Windows, makes no state with an allocator of the game's, so a Lua screen's memory was checked only by the instruction hook every 1000 instructions. A loop doubling a string (s = s .. s, about 50 instructions) went on to LuaJIT's own heap limit: the unit test binary peaked at 1271 MB. The state is now made with luaL_newstate() and the screen's counting allocator is put in front of LuaJIT's own with lua_setallocf, which LuaJIT 2.0 has. LuaJIT's allocator still makes every block, so its heap stays where 2.0 on x64 needs it; the screen's allocator refuses a block that would take the screen over twice its limit during a script call, and LuaJIT raises "not enough memory" before the string is made. The same path now runs with every LuaJIT, so the lua_newstate probe is gone. LuaJIT's allocator is put back before lua_close, which frees its arena only then. The same loop now peaks at 310 MB with the game's 128 MB limit. The limit is read per screen, so the unit tests use 32 MB: a new test runs the doubling loop, and the one-concatenation test, skipped on Windows until now, runs everywhere. Follows up remark 4 of the review of #356. * fix(lua): the two memory globals behind functions, and the default order SonarCloud: the limit setting and the peak were mutable globals (S5421), the peak loop used relaxed order (S8417) and had an empty body (S108). They are function-local statics now, the loop uses the default order and says why it loops. --- script_screens_doc.md | 11 +- scripting/luaprogram.cpp | 162 ++++++++++++++----------- scripting/scriptscreenprogram.h | 14 +-- tests/unit/test_script_screen_host.cpp | 52 ++++++-- 4 files changed, 146 insertions(+), 93 deletions(-) diff --git a/script_screens_doc.md b/script_screens_doc.md index 723de28ea..3e9248d11 100644 --- a/script_screens_doc.md +++ b/script_screens_doc.md @@ -144,12 +144,11 @@ Besides the 200 million instructions of a call, a Lua screen is held to what run - memory: a screen holds at most 128 MB: its Lua heap and the pixels of its images, fonts and sprites (4 bytes a pixel of an image, 1 of a font or a sprite). An object that would take the screen over is refused (`memory limit exceeded`), and a screen found holding more stops with that error. Garbage doesn't count: the check collects it - first. Where LuaJIT takes an allocator of the game's (2.1 in its GC64 mode), anything over twice the limit is refused - as it is asked for (`not enough memory`); the game's LuaJIT 2.0 on 64-bit Windows takes none, and there the heap is - checked every thousand instructions and before the calls below, and whatever a script makes between two checks is - made whole first: every concatenation (`a .. b`) within one interval of a thousand instructions, so a loop doubling a - string (`for i = 1, 11 do s = s .. s end` on a 1 MB `s`) gets to LuaJIT's own heap limit of about 2 GB before the - check sees it; + first, every thousand instructions and before the calls below. Between the checks the screen's heap goes through a + counter of the game's, in front of LuaJIT's own allocator, which refuses a block that would take the screen over + twice the limit as it is asked for (`not enough memory`, an error the script may catch). So what one instruction + makes is held as well: a loop doubling a string (`for i = 1, 11 do s = s .. s end` on a 1 MB `s`) stops at the + concatenation that would go over 256 MB, not at LuaJIT's own heap limit of about 2 GB; - `string.rep` makes no string over 1 MB; `string.format`, `table.concat` and `string.gsub` (with a string or a table to replace with) refuse a result that may be over the memory of a screen, counted from the lengths of what they are given; diff --git a/scripting/luaprogram.cpp b/scripting/luaprogram.cpp index a490a9814..a79018a3d 100644 --- a/scripting/luaprogram.cpp +++ b/scripting/luaprogram.cpp @@ -32,7 +32,7 @@ http://mozilla.org/MPL/2.0/. #include #include -#include +#include #include #include #include @@ -57,22 +57,61 @@ constexpr char sprite_metatable[]{"eu07.sprite"}; // the address is the key of the program in the registry of its state constexpr char program_key{0}; -// the memory of a screen: what its Lua heap holds, when the allocator counts it, and the pixels of its images, fonts -// and sprites, which the objects keep outside the heap +// what set_lua_screen_memory_limit() set +std::atomic &memory_limit_setting() +{ + static std::atomic setting{max_screen_memory}; + return setting; +} + +// what lua_screen_memory_peak() gives +std::atomic &memory_peak() +{ + static std::atomic peak{0}; + return peak; +} + +// the memory of a screen: what its Lua heap holds and the pixels of its images, fonts and sprites, which the objects +// keep outside the heap struct screen_memory { + std::size_t limit{max_screen_memory}; // what the screen may hold, read when its state is made std::size_t heap{0}; std::size_t objects{0}; - bool counted{false}; // the state was made with limited_alloc + std::size_t peak{0}; // the most the screen held bool enforced{false}; // a call into the script is in progress: the allocator refuses what goes over the limit // what the screen holds when it is checked next (lua_program::over_memory) with a full collection std::size_t collect_at{max_screen_memory}; + // LuaJIT's own allocator of the state, which limited_alloc gives the blocks to + lua_Alloc base{nullptr}; + void *base_data{nullptr}; }; -// the allocator of a screen's state (lua_newstate), which refuses a block that would take the screen over twice -// max_screen_memory (what it holds, and its garbage between the collections) while a call into the script is in -// progress: LuaJIT raises "not enough memory" there, in the protected call. the game's own work between the calls isn't -// refused, as it isn't protected +// keeps the most the screen held +void note_peak(screen_memory &Memory) +{ + auto const held{Memory.heap + Memory.objects}; + if (held <= Memory.peak) + { + return; + } + Memory.peak = held; + auto &peak{memory_peak()}; + auto seen{peak.load()}; + while (held > seen && false == peak.compare_exchange_weak(seen, held)) + { + // a failed exchange put the value another screen stored in seen; try again while held is still more + } +} + +// the allocator of a screen's state, put in front of LuaJIT's own (lua_setallocf) once the state is made: LuaJIT 2.0 +// on x64 (the game's on Windows) and 2.1 on x64 without GC64 make no state with an allocator of the game's +// (lua_newstate gives nullptr), as their heap has to stay in the low addresses only their own allocator keeps to. so +// LuaJIT's allocator still makes every block; this one counts them, and refuses a block that would take the screen over +// twice its limit (what it holds, and its garbage between the collections) while a call into the script is in +// progress: LuaJIT raises "not enough memory" there, in the protected call, before the block is made. that holds what +// one instruction makes, which the instruction hook sees only once it is made (a concatenation, a .. b). the game's own +// work between the calls isn't refused, as it isn't protected void *limited_alloc(void *Data, void *Block, std::size_t Old, std::size_t New) { auto &memory{*static_cast(Data)}; @@ -80,20 +119,15 @@ void *limited_alloc(void *Data, void *Block, std::size_t Old, std::size_t New) { Old = 0; } - if (New == 0) - { - std::free(Block); - memory.heap -= Old; - return nullptr; - } - if (New > Old && memory.enforced && memory.heap - Old + New + memory.objects > 2 * max_screen_memory) + if (New > Old && memory.enforced && memory.heap - std::min(Old, memory.heap) + New + memory.objects > 2 * memory.limit) { return nullptr; } - auto *result{std::realloc(Block, New)}; - if (result != nullptr) + auto *result{memory.base(memory.base_data, Block, Old, New)}; + if (New == 0 || result != nullptr) { - memory.heap = memory.heap - Old + New; + memory.heap = memory.heap - std::min(Old, memory.heap) + New; + note_peak(memory); } return result; } @@ -111,6 +145,12 @@ class lua_program final : public program { // the finalizers lua_close runs aren't counted: the budget of the last call may be spent lua_sethook(m_state, nullptr, 0, 0); + // LuaJIT's own allocator back: lua_close frees the whole heap of its allocator only when the state has it, + // and otherwise leaves the heap's own bookkeeping behind + if (memory.base != nullptr) + { + lua_setallocf(m_state, memory.base, memory.base_data); + } lua_close(m_state); } } @@ -130,7 +170,7 @@ class lua_program final : public program char const *stopped{nullptr}; // why the call in progress is being stopped: the hook raises it at every instruction screen_memory memory; - // true when the screen would hold more than max_screen_memory with Adding bytes more. checked with a full collection + // true when the screen would hold more than its limit with Adding bytes more. checked with a full collection // once it has made a quarter of the limit since the last one, so a screen near its limit isn't collected over and // over bool over_memory(lua_State *L, std::size_t Adding); @@ -156,20 +196,15 @@ lua_program *program_of(lua_State *L) bool lua_program::over_memory(lua_State *L, std::size_t const Adding) { - auto const used{[this, L] { - auto const heap{memory.counted ? memory.heap - : static_cast(lua_gc(L, LUA_GCCOUNT, 0)) * 1024 + static_cast(lua_gc(L, LUA_GCCOUNTB, 0))}; - return heap + memory.objects; - }}; - if (used() + Adding <= memory.collect_at) + if (memory.heap + memory.objects + Adding <= memory.collect_at) { return false; } // what is garbage doesn't count lua_gc(L, LUA_GCCOLLECT, 0); - auto const held{used()}; - memory.collect_at = std::max(max_screen_memory, held + max_screen_memory / 4); - return held + Adding > max_screen_memory; + auto const held{memory.heap + memory.objects}; + memory.collect_at = std::max(memory.limit, held + memory.limit / 4); + return held + Adding > memory.limit; } void count_hook(lua_State *L, lua_Debug * /*Debug*/) @@ -188,7 +223,7 @@ void count_hook(lua_State *L, lua_Debug * /*Debug*/) } else if (self->over_memory(L, 0)) { - // what the allocator doesn't refuse (where the screen has none of its own) is caught here + // what the allocator lets through, up to twice the limit with the garbage, is caught here self->stopped = "memory limit exceeded"; } } @@ -208,10 +243,17 @@ void reserve_memory(lua_State *L, std::size_t const Bytes) { if (auto *self{program_of(L)}; self != nullptr && self->over_memory(L, Bytes)) { - luaL_error(L, "memory limit exceeded (%d MB)", static_cast(max_screen_memory / (1024 * 1024))); + luaL_error(L, "memory limit exceeded (%d MB)", static_cast(self->memory.limit / (1024 * 1024))); } } +// the memory the screen of the state may hold +std::size_t memory_limit(lua_State *L) +{ + auto const *self{program_of(L)}; + return self != nullptr ? self->memory.limit : max_screen_memory; +} + // objects of the api ------------------------------------------------------------------------------------------------- // where the userdata of an object keeps the bytes it counts in the screen's memory, after the object @@ -230,6 +272,7 @@ template std::remove_cvref_t *push_object(lua_State *L, if (auto *self{program_of(L)}; self != nullptr) { self->memory.objects += Bytes; + note_peak(self->memory); } luaL_getmetatable(L, Metatable); lua_setmetatable(L, -2); @@ -855,7 +898,7 @@ int api_repeat(lua_State *L) // the result may be over the memory of a screen. what they make otherwise is counted with the rest of the heap int too_large(lua_State *L, char const *Function) { - return luaL_error(L, "%s: the result may be over the memory of a screen (%d MB)", Function, static_cast(max_screen_memory / (1024 * 1024))); + return luaL_error(L, "%s: the result may be over the memory of a screen (%d MB)", Function, static_cast(memory_limit(L) / (1024 * 1024))); } // calls the library's own function, the upvalue, with the arguments, and returns what it returns @@ -878,7 +921,7 @@ int api_format(lua_State *L) { total += lua_type(L, idx) == LUA_TSTRING ? 4.0 * static_cast(lua_objlen(L, idx)) : 512.0; } - if (total > static_cast(max_screen_memory)) + if (total > static_cast(memory_limit(L))) { return too_large(L, "string.format"); } @@ -894,6 +937,7 @@ int api_concat(lua_State *L) luaL_optlstring(L, 2, "", &separator); auto const first{luaL_optinteger(L, 3, 1)}; auto const last{lua_isnoneornil(L, 4) ? static_cast(lua_objlen(L, 1)) : luaL_checkinteger(L, 4)}; + auto const limit{static_cast(memory_limit(L))}; auto total{0.0}; for (auto idx = first; idx <= last; ++idx) { @@ -906,7 +950,7 @@ int api_concat(lua_State *L) { break; } - if (total > static_cast(max_screen_memory)) + if (total > limit) { return too_large(L, "table.concat"); } @@ -978,7 +1022,7 @@ int api_pattern(lua_State *L) { auto const size{static_cast(subject)}; auto const matches{lua_isnumber(L, 4) ? std::clamp(static_cast(lua_tonumber(L, 4)), 0.0, size + 1.0) : size + 1.0}; - if (auto const replaced{replacement_length(L, 3, size, matches)}; replaced.has_value() && size + *replaced > static_cast(max_screen_memory)) + if (auto const replaced{replacement_length(L, 3, size, matches)}; replaced.has_value() && size + *replaced > static_cast(memory_limit(L))) { return too_large(L, name); } @@ -1195,46 +1239,20 @@ int call_render(lua_State *L) return 1; } -// true when a screen's state can be made with an allocator of its own: LuaJIT 2.0 on x64, and 2.1 on x64 without GC64, -// refuse one (lua_newstate gives nullptr, and writes so to stderr: 2.0 isn't asked) -bool custom_allocator_works() -{ -#if LUAJIT_VERSION_NUM < 20100 - if constexpr (sizeof(void *) == 8) - { - return false; - } -#endif - static bool const works{[] { - screen_memory probe; - auto *state{lua_newstate(limited_alloc, &probe)}; - if (state == nullptr) - { - return false; - } - lua_close(state); - return true; - }()}; - return works; -} - bool lua_program::start() { - // the screen's own allocator counts its memory, where LuaJIT takes one - if (custom_allocator_works()) - { - m_state = lua_newstate(limited_alloc, &memory); - memory.counted = m_state != nullptr; - } - if (m_state == nullptr) - { - m_state = luaL_newstate(); - } + m_state = luaL_newstate(); if (m_state == nullptr) { ErrorLog(std::format("Lua screen \"{}\": failed to create the state", script)); return false; } + // the screen's allocator in front of LuaJIT's own, counting from what the state holds already + memory.limit = memory_limit_setting().load(); + memory.collect_at = memory.limit; + memory.heap = static_cast(lua_gc(m_state, LUA_GCCOUNT, 0)) * 1024 + static_cast(lua_gc(m_state, LUA_GCCOUNTB, 0)); + memory.base = lua_getallocf(m_state, &memory.base_data); + lua_setallocf(m_state, limited_alloc, &memory); // no compiled code: LuaJIT calls no hooks in it, and the hook is what stops a script stuck in a loop luaJIT_setmode(m_state, 0, LUAJIT_MODE_ENGINE | LUAJIT_MODE_OFF); open_libraries(); @@ -1340,9 +1358,15 @@ class lua_runtime_host final : public runtime } // namespace -bool lua_screen_memory_allocator() +void set_lua_screen_memory_limit(std::size_t const Bytes) { - return custom_allocator_works(); + memory_limit_setting().store(Bytes); + memory_peak().store(0); +} + +std::size_t lua_screen_memory_peak() +{ + return memory_peak().load(); } std::unique_ptr make_lua_runtime() diff --git a/scripting/scriptscreenprogram.h b/scripting/scriptscreenprogram.h index 32fd493ef..10bed2124 100644 --- a/scripting/scriptscreenprogram.h +++ b/scripting/scriptscreenprogram.h @@ -39,16 +39,14 @@ constexpr std::size_t max_log_line{1024}; // bytes of the text, a longer one is // the largest file a screen reads: its script or module, a file below its folder constexpr std::uintmax_t max_screen_file{16 * 1024 * 1024}; // the memory a Lua screen may hold: its Lua heap, and the pixels of its images, fonts and sprites. checked with a full -// collection, so its garbage doesn't count; between the collections it may take the screen up to twice this +// collection, so its garbage doesn't count; between the collections it may take the screen up to twice this, which +// the screen's allocator refuses to go over as each block is asked for constexpr std::size_t max_screen_memory{128 * 1024 * 1024}; -// true when the Lua screens count their memory in an allocator of their own, which refuses what goes over -// max_screen_memory as it is asked for: LuaJIT 2.1 in its GC64 mode, a 32-bit build. LuaJIT 2.0 on x64 (the game's on -// Windows) and 2.1 on x64 without GC64 take no allocator; there the memory is checked by the instruction hook every -// so many instructions, and before what makes images and large strings in one call (string.rep, string.format, -// table.concat, string.gsub), but not at the concatenation operator: one concatenation of large strings is made -// whole, as far as LuaJIT's own heap goes (2 GB on x64), and the screen is stopped at the next check -bool lua_screen_memory_allocator(); +// for the unit tests, which fill the memory of a screen and stay small: the memory a Lua screen made from now on may +// hold in place of max_screen_memory, and the most any Lua screen held since it was set (its heap and its objects) +void set_lua_screen_memory_limit(std::size_t Bytes); +std::size_t lua_screen_memory_peak(); struct pending_command { diff --git a/tests/unit/test_script_screen_host.cpp b/tests/unit/test_script_screen_host.cpp index dc1cfa2f8..519e928de 100644 --- a/tests/unit/test_script_screen_host.cpp +++ b/tests/unit/test_script_screen_host.cpp @@ -1267,13 +1267,25 @@ for i = 1, 10000000 do kept[i] = ("x"):rep(1000) .. i end return { render = function(state) return eu07.image(1, 1, { 255, 255, 255 }) end } )"}; -// a concatenation of 320 MB in one operation, from a string of 64 MB: only an allocator of the screen's own refuses -// it as it is made +// the memory limit of the Lua screens made while it lives, in place of max_screen_memory: a test that fills the memory +// of a screen stays small +class screen_memory_limit { + public: + explicit screen_memory_limit(std::size_t const Bytes) { script_screens::set_lua_screen_memory_limit(Bytes); } + ~screen_memory_limit() { script_screens::set_lua_screen_memory_limit(script_screens::max_screen_memory); } + screen_memory_limit(screen_memory_limit const &) = delete; + screen_memory_limit &operator=(screen_memory_limit const &) = delete; +}; + +constexpr std::size_t small_screen_memory{32 * 1024 * 1024}; + +// with small_screen_memory: a concatenation of 80 MB in one operation, from a string of 8 MB, refused as it is made, in +// the pcall, as the instruction hook would see it only once it is made constexpr std::string_view one_concatenation_script{R"( local a = ("x"):rep(1024 * 1024) -for i = 1, 6 do a = a .. a end -local ok, message = pcall(function() return #(a .. a .. a .. a .. a) end) -local refused = #a == 64 * 1024 * 1024 and not ok and message:find("not enough memory", 1, true) ~= nil +for i = 1, 3 do a = a .. a end +local ok, message = pcall(function() return #(a .. a .. a .. a .. a .. a .. a .. a .. a .. a) end) +local refused = #a == 8 * 1024 * 1024 and not ok and message:find("not enough memory", 1, true) ~= nil a = nil return { render = function(state) @@ -1282,6 +1294,14 @@ return { } )"}; +// doubles a string to 2 GB, 64 times small_screen_memory, in some fifty instructions: fewer than the thousand after +// which the instruction hook looks at the heap +constexpr std::string_view doubling_script{R"( +local s = ("x"):rep(1024 * 1024) +for i = 1, 11 do s = s .. s end +return { render = function(state) return eu07.image(1, 1, { 255, 255, 255 }) end } +)"}; + // white when a coroutine yields across xpcall, and xpcall without a handler is an error constexpr std::string_view xpcall_yield_script{R"( local resume = coroutine.wrap(function() @@ -1390,13 +1410,25 @@ TEST_CASE("lua screens: a screen holding more than its memory is switched off") CHECK(log.lines_with("memory limit exceeded").size() + log.lines_with("not enough memory").size() > 0); } -TEST_CASE("lua screens: with an allocator of the screen's own, a string made over the memory in one operation is refused") { - if (false == script_screens::lua_screen_memory_allocator()) { - MESSAGE("LuaJIT takes no allocator of the game's here (2.0, or 2.1 without GC64 on x64): not tested"); - return; - } +TEST_CASE("lua screens: a string made over the memory in one operation is refused") { + screen_memory_limit const limit{small_screen_memory}; script_folder const folder{"lua_one_concatenation"}; CHECK(first_pixel(folder.write("concatenation.lua", one_concatenation_script), "concatenation") == 255); + CHECK(script_screens::lua_screen_memory_peak() <= 2 * small_screen_memory); +} + +TEST_CASE("lua screens: a string doubled in a loop stops at the memory of the screen, not at LuaJIT's own limit") { + log_capture const log; + screen_memory_limit const limit{small_screen_memory}; + script_folder const folder{"lua_doubling"}; + check_switched_off(folder, "doubling.lua", doubling_script); + CHECK(log.lines_with("not enough memory").size() + log.lines_with("memory limit exceeded").size() > 0); + // past the limit between two checks of the hook, but refused before twice the limit (its garbage included). with + // LuaJIT 2.0 on x64 and no allocator in front of LuaJIT's own, this went on to its own limit, over 1 GB + auto const peak{script_screens::lua_screen_memory_peak()}; + CAPTURE(peak); + CHECK(peak > small_screen_memory); + CHECK(peak <= 2 * small_screen_memory); } TEST_CASE("lua screens: a coroutine yields across xpcall") { From ee14cefcb5be898b37195aa9d01d20e32c06dfae Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:24:38 +0100 Subject: [PATCH 111/136] fix(parser): an include at the very end of a text leaves the end of the data to the included file (#492) A file which ends right after the end of an include directive, with no line break after it, had the parser report its end as soon as the directive was read: eof() looked only at the text being read, not at the included file it still had to go through. A reader which stops at the end of the data, like deserialize_map() (the sound overrides), then read only the first line of the included file. eof() now also waits for the included file to end. The tokens themselves don't change, and a file with a line break after the end of its last include reports the end as before. The .fiz files of the wagons which broke the change of #100 (pkp/yb_v1, the directive at the very end without a line break) are read through on staging already; a test now keeps them that way. --- tests/unit/test_parser.cpp | 64 ++++++++++++++++++++++++++++++++++++++ utilities/parser.h | 6 ++-- 2 files changed, 68 insertions(+), 2 deletions(-) diff --git a/tests/unit/test_parser.cpp b/tests/unit/test_parser.cpp index 2584218d0..ee82aca9a 100644 --- a/tests/unit/test_parser.cpp +++ b/tests/unit/test_parser.cpp @@ -696,6 +696,70 @@ TEST_CASE("parser: read line by line, a line starting with include is the direct CHECK(rest(word, false, "\n\r") == "one|two"); } +namespace { + +// the lines of a file, read the way the vehicle's .fiz is (TMoverParameters::LoadFIZ_Parse): line by line while the +// parser is ok +std::string fiz_lines(cParser &Parser) { + std::string joined; + while (Parser.ok()) { + auto const line{Parser.getToken(false, "\n\r")}; + if (line.empty()) { + continue; + } + if (false == joined.empty()) { + joined += '|'; + } + joined += line; + } + return joined; +} + +} // namespace + +TEST_CASE("parser: a file which ends right after the end of an include is read through, the included file too") { + // the shape of the .fiz files of the wagons (pkp/yb_v1/b84_pl_1.fiz): the directive, the file and its parameters + // each on a line of their own, and no line break after the end. the change of MaSzyna-EU07/maszyna#100 broke on these + test::scratch_folder const folder{"parser_include_at_end"}; + folder.write("yb.fiz.inc", "Mass=(p1)\r\nVmax=(p2)\r\nLength=20\r\n"); + folder.write("ended.fiz", "include\r\nyb.fiz.inc\r\n160\r\n80\r\nend"); + folder.write("newline.fiz", "include\r\nyb.fiz.inc\r\n160\r\n80\r\nend\r\n"); + + cParser ended("ended.fiz", cParser::buffer_FILE, folder.path()); + CHECK(fiz_lines(ended) == "Mass=160|Vmax=80|Length=20"); + cParser newline("newline.fiz", cParser::buffer_FILE, folder.path()); + CHECK(fiz_lines(newline) == "Mass=160|Vmax=80|Length=20"); + + SUBCASE("the end of the data shows once the included file is read through, not when its directive is") { + folder.write("pair.inc", "x y"); + cParser parser("include pair.inc end", cParser::buffer_TEXT, folder.path()); + CHECK(parser.getToken() == "x"); + CHECK_FALSE(parser.eof()); + CHECK(parser.getToken() == "y"); + CHECK(parser.eof()); + CHECK(parser.ok()); + CHECK(parser.getToken().empty()); + CHECK_FALSE(parser.ok()); + // the same as for a text with the included tokens in place of the directive + cParser same("x y", cParser::buffer_TEXT); + CHECK(same.getToken() == "x"); + CHECK_FALSE(same.eof()); + CHECK(same.getToken() == "y"); + CHECK(same.eof()); + } + SUBCASE("a reader which stops at the end of the data reads the whole included file") { + folder.write("map.inc", "alpha One\nbeta Two"); + for (auto const *const text : {"include map.inc end", "include map.inc end\n"}) { + CAPTURE(text); + cParser parser(text, cParser::buffer_TEXT, folder.path()); + std::map map; + deserialize_map(map, parser); + CHECK(map["alpha"] == "One"); + CHECK(map["beta"] == "Two"); + } + } +} + TEST_CASE("parser: an include can name several files to pick one from at random") { test::scratch_folder const folder{"parser_random_include"}; folder.write("only.inc", "chosen"); diff --git a/utilities/parser.h b/utilities/parser.h index 19fc34f18..fa4c2c597 100644 --- a/utilities/parser.h +++ b/utilities/parser.h @@ -62,10 +62,12 @@ class cParser //: public std::stringstream std::string out; readToken(out); return out == Value; }; + // the end of the data: of this text, and of the file included last in it, which an include directive at the very + // end of the text leaves to be read inline bool - eof() { - return mEofBit; }; + eof() const { + return mEofBit && ( mIncludeParser == nullptr || mIncludeParser->eof() ); }; inline bool ok() { From c65ba4f39aaeacb01cca47f298306375e830fb6c Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:24:45 +0100 Subject: [PATCH 112/136] fix(blackbox): a signal passed is told by its memory cell, not by the cell's position (#493) The record of a signal passed (0x32) took the number of the first signal of the map whose memory cell stands within a centimetre of the cell the train read. Two signals with their cells at one point (back to back, or a signal and a shunting signal on one post) both got the number of whichever came first on the map, so a pass of one could be written as a pass of the other. The number is now that of the signal with the very cell the event reads; basic_event::input_cell() gives it, for a getvalues event. The format doesn't change. A pass of a signal which isn't on the map is still written with 0xFFFFFFFF. --- simulation/blackboxrecorder.cpp | 7 ++++--- simulation/blackboxrecorder.h | 3 ++- world/Event.cpp | 12 ++++++++++++ world/Event.h | 3 +++ 4 files changed, 21 insertions(+), 4 deletions(-) diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index 5b224b666..345bae36c 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -722,8 +722,9 @@ std::uint32_t blackbox_recorder::known_id(TDynamicObject const *Vehicle) { return Vehicle != nullptr && Vehicle->bEnabled ? vehicle_id(Vehicle) : blackbox::no_vehicle; } -std::uint32_t blackbox_recorder::signal_at(glm::dvec3 const &Location) const { - auto const found{std::ranges::find_if(m_signals, [&Location](signal_entry const &Signal) { return glm::distance(Signal.location, Location) < 0.01; })}; +std::uint32_t blackbox_recorder::signal_of(TMemCell const *Cell) const { + // by the memory cell, not by its position: two signals can have their cells at one point + auto const found{std::ranges::find(m_signals, Cell, &signal_entry::cell)}; if (found == m_signals.end()) return blackbox::no_signal; return static_cast(std::distance(m_signals.begin(), found)); @@ -752,7 +753,7 @@ void blackbox_recorder::signal_passed(TDynamicObject const *Vehicle, basic_event if (m_writer == nullptr || Vehicle == nullptr) return; auto const location{Event.input_location()}; - m_writer->signal_passed({m_time, vehicle_id(Vehicle), signal_at(location), text_of(Event.name()), location, static_cast(Speed1), static_cast(Speed2), + m_writer->signal_passed({m_time, vehicle_id(Vehicle), signal_of(Event.input_cell()), text_of(Event.name()), location, static_cast(Speed1), static_cast(Speed2), static_cast(Trainspeed), static_cast(Overrun), Flags}); } diff --git a/simulation/blackboxrecorder.h b/simulation/blackboxrecorder.h index a3aaf5d0f..140503e39 100644 --- a/simulation/blackboxrecorder.h +++ b/simulation/blackboxrecorder.h @@ -106,7 +106,8 @@ private: std::uint32_t vehicle_id(TDynamicObject const *Vehicle); // the number of a vehicle still on the scenery, no_vehicle for none or one taken off it std::uint32_t known_id(TDynamicObject const *Vehicle); - std::uint32_t signal_at(glm::dvec3 const &Location) const; + // the number of the signal whose aspect the memory cell tells, no_signal for one which isn't on the map + std::uint32_t signal_of(TMemCell const *Cell) const; std::mutex m_mutex; std::array m_filebuffer{}; diff --git a/world/Event.cpp b/world/Event.cpp index c007b91dd..628e38ea7 100644 --- a/world/Event.cpp +++ b/world/Event.cpp @@ -440,6 +440,12 @@ basic_event::input_location() const { return glm::dvec3( 0, 0, 0 ); }; +TMemCell const * +basic_event::input_cell() const { + + return nullptr; +} + bool basic_event::is_keyword( std::string const &Token ) { // TODO: convert to array lookup if keyword list gets longer @@ -677,6 +683,12 @@ getvalues_event::input_location() const { return m_input.data_cell()->location(); // współrzędne podłączonej komórki pamięci } +TMemCell const * +getvalues_event::input_cell() const { + + return m_input.data_cell(); +} + // prepares event for use diff --git a/world/Event.h b/world/Event.h index 090d165d6..c86fb8275 100644 --- a/world/Event.h +++ b/world/Event.h @@ -85,6 +85,8 @@ public: virtual TCommandType input_command() const; virtual double input_value( int Index ) const; virtual glm::dvec3 input_location() const; + // the memory cell the data comes from, null if the event doesn't read one + virtual TMemCell const *input_cell() const; void group( scene::group_handle Group ); scene::group_handle group() const; std::string const &name() const { return m_name; } @@ -243,6 +245,7 @@ public: TCommandType input_command() const override; double input_value( int Index ) const override; glm::dvec3 input_location() const override; + TMemCell const *input_cell() const override; private: // methods From df95395dedea27147633a92d231ae7f99c47cc5d Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:24:58 +0100 Subject: [PATCH 113/136] docs/build: track_uneven_doc.md to docs/, the local ImGui changes listed, the audio license texts kept in ref/licenses (#495) * docs: track_uneven_doc.md from the root of the repository to docs/ (#237) The tool that grades the tracks points to its new place; directoryDescription.md names docs/. * docs: the local changes of the bundled ImGui (#236) docs/imgui_patches.md lists what imgui/ changes against upstream v1.91.9b-docking (io.ConfigViewportsNoAutoDetach, io.ConfigTooltipsWrapWidth, BufferingBar/Spinner, the glad loader, the main-window origin of the GLFW backend, the gamma of the OpenGL 3 backend) and in ImGuizmo, with the commits that brought them, so an update of ImGui carries them over. * build: the license texts of the audio DLLs from ref/licenses instead of downloads (#405) The Windows build downloaded 14 license texts on every run without a cache hit, from raw.githubusercontent.com, scm.orgis.org (mpg123) and sources.debian.org (LAME). They are now in ref/licenses, byte for byte as at the pinned URLs (-text in .gitattributes, so a checkout with CRLF doesn't change them), and the step copies them from there, still checked by their SHA-256. ref/licenses/README.md names the URL of each. The two release zips are still downloaded and cached as before. * docs: the ImAbs shim of ImGuizmo listed, stale comments of the DLL step, a plain docs/ row --- .gitattributes | 2 + .github/workflows/build_bin.yml | 63 +- directoryDescription.md | 1 + docs/imgui_patches.md | 52 ++ .../track_uneven_doc.md | 0 ref/licenses/README.md | 29 + ref/licenses/flac-COPYING.Xiph.txt | 29 + ref/licenses/lame-COPYING.txt | 481 +++++++++++ ref/licenses/libogg-COPYING.txt | 28 + ref/licenses/libsndfile-ALAC-LICENSE.txt | 170 ++++ ref/licenses/libsndfile-COPYING.txt | 503 ++++++++++++ ref/licenses/libsndfile-GSM610-COPYRIGHT.txt | 16 + ref/licenses/libvorbis-COPYING.txt | 28 + ref/licenses/mpg123-COPYING.txt | 772 ++++++++++++++++++ ref/licenses/openal-soft-BSD-3Clause.txt | 31 + ref/licenses/openal-soft-gsl-LICENSE.txt | 21 + .../openal-soft-mingw-w64-runtime.txt | 240 ++++++ ref/licenses/openal-soft-pffft-LICENSE.txt | 38 + .../openal-soft-winpthreads-COPYING.txt | 57 ++ ref/licenses/opus-COPYING.txt | 44 + tools/track_uneven_grade.py | 2 +- 21 files changed, 2570 insertions(+), 37 deletions(-) create mode 100644 docs/imgui_patches.md rename track_uneven_doc.md => docs/track_uneven_doc.md (100%) create mode 100644 ref/licenses/README.md create mode 100644 ref/licenses/flac-COPYING.Xiph.txt create mode 100644 ref/licenses/lame-COPYING.txt create mode 100644 ref/licenses/libogg-COPYING.txt create mode 100644 ref/licenses/libsndfile-ALAC-LICENSE.txt create mode 100644 ref/licenses/libsndfile-COPYING.txt create mode 100644 ref/licenses/libsndfile-GSM610-COPYRIGHT.txt create mode 100644 ref/licenses/libvorbis-COPYING.txt create mode 100644 ref/licenses/mpg123-COPYING.txt create mode 100644 ref/licenses/openal-soft-BSD-3Clause.txt create mode 100644 ref/licenses/openal-soft-gsl-LICENSE.txt create mode 100644 ref/licenses/openal-soft-mingw-w64-runtime.txt create mode 100644 ref/licenses/openal-soft-pffft-LICENSE.txt create mode 100644 ref/licenses/openal-soft-winpthreads-COPYING.txt create mode 100644 ref/licenses/opus-COPYING.txt diff --git a/.gitattributes b/.gitattributes index d2b789541..488a40d4b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4,3 +4,5 @@ text=auto *.h text README text LICENSE text +# the license texts the Windows build ships, checked by their SHA-256: byte for byte as upstream, LF on every checkout +ref/licenses/*.txt -text diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index 230e814cf..13f36b0c7 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -180,9 +180,9 @@ jobs: -Recurse ` -Force - # The downloads of the next step, kept between the runs: a release or raw.githubusercontent.com out of reach then - # doesn't fail the build. The key is this file, which pins them; a cache of an older one is taken too, as the next - # step checks every file by its SHA-256 and downloads only those it doesn't have. + # The downloads of the next step, kept between the runs: a release out of reach then doesn't fail the build. The + # key is this file, which pins them; a cache of an older one is taken too, as the next step checks every file by + # its SHA-256 and downloads only those it doesn't have. - name: Restore the audio library downloads uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: @@ -199,7 +199,8 @@ jobs: # go with both variants. The exe links them by name: soft_oal.dll is shipped as OpenAL32.dll (as its readme says, # without the router), sndfile.dll as libsndfile-1.dll. Both are LGPL, so their license texts go with them, in # licenses/, with those of what the DLLs have built in (below); the libsndfile zip has none, its COPYING is taken - # from the source tree of the same tag. + # from the source tree of the same tag. Those texts are kept in ref/licenses (with where each comes from), so the + # build doesn't depend on the servers they come from. - name: Add the OpenAL Soft and libsndfile DLLs shell: pwsh timeout-minutes: 10 @@ -214,7 +215,7 @@ jobs: $pinned = [System.Collections.Generic.List[string]]::new() # the file of the URL with the given SHA-256: the one kept by a run before, else downloaded. named by its - # SHA-256 and the last part of its path, without the query: several license texts are named the same + # SHA-256 and the last part of its path, without the query function Get-Pinned([string] $Url, [string] $Sha256) { $name = "$Sha256-$([uri]::new($Url).Segments[-1])" $pinned.Add($name) @@ -223,7 +224,6 @@ jobs: Write-Host "$Url kept by a run before" return $file } - # not a browser's user agent, which Debian's server answers with a challenge page Invoke-WebRequest -Uri $Url -OutFile $file -UserAgent 'ci-download' -MaximumRetryCount 3 -RetryIntervalSec 10 -TimeoutSec 120 $hash = (Get-FileHash -Algorithm SHA256 -Path $file).Hash.ToLowerInvariant() if ($hash -ne $Sha256) { @@ -262,39 +262,30 @@ jobs: # The versions in sndfile.dll: those it names (libopus 1.4, libFLAC 1.4.2, libVorbis 1.3.7), mpg123 1.31.3 by # the SHA-512 of its source archive in the build paths it keeps, and libogg 1.3.5 and LAME 3.100 of the vcpkg # ports of the time (mid 2023). LAME's from Debian's copy of the 3.100 source, the same file as in LAME's own - # repository on SourceForge, which may answer a script with a challenge page + # repository on SourceForge. The texts are in ref/licenses, whose README names the URL of each; each is + # checked by its SHA-256, so an edit or a line ending changed on the way doesn't go out unnoticed $texts = [ordered]@{ - 'libsndfile-COPYING.txt' = @('https://raw.githubusercontent.com/libsndfile/libsndfile/1.2.2/COPYING' - 'ad01ea5cd2755f6048383c8d54c88459cd6fcb17757c5c8892f8c5ea060f6140') - 'libsndfile-ALAC-LICENSE.txt' = @('https://raw.githubusercontent.com/libsndfile/libsndfile/1.2.2/src/ALAC/LICENSE' - '232efbd83786e157286b0b96c68ebb673541b69b33036287bf1e5ec5067a49d9') - 'libsndfile-GSM610-COPYRIGHT.txt' = @('https://raw.githubusercontent.com/libsndfile/libsndfile/1.2.2/src/GSM610/COPYRIGHT' - '1bbe7119b1bcd1489e0f36cb95b8902f7f0ceec9a2f3a67394bc9f4709a4e0a7') - 'libogg-COPYING.txt' = @('https://raw.githubusercontent.com/xiph/ogg/v1.3.5/COPYING' - 'd2ab5758336489da61c12cc5bb757da5339c4ae9001f9bb0562b4370249af814') - 'libvorbis-COPYING.txt' = @('https://raw.githubusercontent.com/xiph/vorbis/v1.3.7/COPYING' - 'ec1815db59fcd302846df949d7424876cb2e2dc5ed1606c5fb0b36787b1cf43a') - 'flac-COPYING.Xiph.txt' = @('https://raw.githubusercontent.com/xiph/flac/1.4.2/COPYING.Xiph' - '6e58d3036f05e2a0d58af854c12a505ddbe75011d71a598a2170987f3b15408d') - 'opus-COPYING.txt' = @('https://raw.githubusercontent.com/xiph/opus/v1.4/COPYING' - '8338ce8d922bb4416ce3dd1e5680173332435e3f0755007ac7801ccd674fe682') - 'mpg123-COPYING.txt' = @('https://scm.orgis.org/view/mpg123/tags/1.31.3/COPYING?view=co' - 'c22482728a634a8dfdb4ff72a96d4c1ed64cd8f3e79335c401751ac591609366') - 'lame-COPYING.txt' = @('https://sources.debian.org/data/main/l/lame/3.100-6/COPYING' - 'bfe4a52dc4645385f356a8e83cc54216a293e3b6f1cb4f79f5fc0277abf937fd') - 'openal-soft-pffft-LICENSE.txt' = @('https://raw.githubusercontent.com/kcat/openal-soft/1.25.2/LICENSE-pffft' - '64056328b3e7bc104e24ef96accc1a7abead156f0c02d1b87c97e3f3a28030de') - 'openal-soft-gsl-LICENSE.txt' = @('https://raw.githubusercontent.com/kcat/openal-soft/1.25.2/gsl/LICENSE' - '4c21dc82a1c7186ea754fd59d504c00947953a3401fe8e24eaa44109ef8e2555') - 'openal-soft-BSD-3Clause.txt' = @('https://raw.githubusercontent.com/kcat/openal-soft/1.25.2/BSD-3Clause' - 'b5a08cf98996dd83aa906a72c163600f6cb17a65ce546a553815a1267abd43ff') - 'openal-soft-winpthreads-COPYING.txt' = @('https://raw.githubusercontent.com/mingw-w64/mingw-w64/v13.0.0/mingw-w64-libraries/winpthreads/COPYING' - '63263614cdd29f2f93cba85e992f041b31f9fc7b4033692f31269489a8a1b177') - 'openal-soft-mingw-w64-runtime.txt' = @('https://raw.githubusercontent.com/mingw-w64/mingw-w64/v13.0.0/COPYING.MinGW-w64-runtime/COPYING.MinGW-w64-runtime.txt' - 'e9b2dc02451ea29092a1f25fa0f3c07207ed421f1807dffb0c4e6dce69dee7bd') + 'libsndfile-COPYING.txt' = 'ad01ea5cd2755f6048383c8d54c88459cd6fcb17757c5c8892f8c5ea060f6140' + 'libsndfile-ALAC-LICENSE.txt' = '232efbd83786e157286b0b96c68ebb673541b69b33036287bf1e5ec5067a49d9' + 'libsndfile-GSM610-COPYRIGHT.txt' = '1bbe7119b1bcd1489e0f36cb95b8902f7f0ceec9a2f3a67394bc9f4709a4e0a7' + 'libogg-COPYING.txt' = 'd2ab5758336489da61c12cc5bb757da5339c4ae9001f9bb0562b4370249af814' + 'libvorbis-COPYING.txt' = 'ec1815db59fcd302846df949d7424876cb2e2dc5ed1606c5fb0b36787b1cf43a' + 'flac-COPYING.Xiph.txt' = '6e58d3036f05e2a0d58af854c12a505ddbe75011d71a598a2170987f3b15408d' + 'opus-COPYING.txt' = '8338ce8d922bb4416ce3dd1e5680173332435e3f0755007ac7801ccd674fe682' + 'mpg123-COPYING.txt' = 'c22482728a634a8dfdb4ff72a96d4c1ed64cd8f3e79335c401751ac591609366' + 'lame-COPYING.txt' = 'bfe4a52dc4645385f356a8e83cc54216a293e3b6f1cb4f79f5fc0277abf937fd' + 'openal-soft-pffft-LICENSE.txt' = '64056328b3e7bc104e24ef96accc1a7abead156f0c02d1b87c97e3f3a28030de' + 'openal-soft-gsl-LICENSE.txt' = '4c21dc82a1c7186ea754fd59d504c00947953a3401fe8e24eaa44109ef8e2555' + 'openal-soft-BSD-3Clause.txt' = 'b5a08cf98996dd83aa906a72c163600f6cb17a65ce546a553815a1267abd43ff' + 'openal-soft-winpthreads-COPYING.txt' = '63263614cdd29f2f93cba85e992f041b31f9fc7b4033692f31269489a8a1b177' + 'openal-soft-mingw-w64-runtime.txt' = 'e9b2dc02451ea29092a1f25fa0f3c07207ed421f1807dffb0c4e6dce69dee7bd' } foreach ($text in $texts.GetEnumerator()) { - $file = Get-Pinned $text.Value[0] $text.Value[1] + $file = Join-Path 'ref/licenses' $text.Key + $hash = (Get-FileHash -Algorithm SHA256 -Path $file).Hash.ToLowerInvariant() + if ($hash -ne $text.Value) { + throw "${file}: SHA-256 $hash, expected $($text.Value)" + } Copy-Item -Path $file -Destination (Join-Path $licenses $text.Key) -Force } diff --git a/directoryDescription.md b/directoryDescription.md index eb943fb95..9db4a248f 100644 --- a/directoryDescription.md +++ b/directoryDescription.md @@ -21,3 +21,4 @@ | utilities/ | Logging, timing, parsing, math, globals, crash reporter | | world/ | Tracks, traction, events, memory cells, stations | | vehicle/ | Train, dynamic objects, driver, gauges, camera | +| docs/ | Documentation | diff --git a/docs/imgui_patches.md b/docs/imgui_patches.md new file mode 100644 index 000000000..3266158b5 --- /dev/null +++ b/docs/imgui_patches.md @@ -0,0 +1,52 @@ +# Local changes of the bundled ImGui + +`imgui/` holds Dear ImGui **v1.91.9b-docking** (`IMGUI_VERSION "1.91.9b"`, the docking branch: upstream tag +[`v1.91.9b-docking`](https://github.com/ocornut/imgui/tree/v1.91.9b-docking)), the GLFW, OpenGL 2 and OpenGL 3 backends +of the same tag, and ImGuizmo. The changes below are ours: an update of ImGui has to carry them over, or drop them on +purpose. Most of them are marked in the code with a `MaSzyna` comment (`grep -n MaSzyna imgui/*`), but not every +changed line is. + +Compared with the upstream tag, these files are unchanged: `imgui_demo.cpp`, `imgui_draw.cpp`, `imgui_internal.h`, +`imgui_tables.cpp`, `imstb_rectpack.h`, `imstb_textedit.h`, `imstb_truetype.h`, `LICENSE.txt` and the backend headers +(`imgui_impl_glfw.h`, `imgui_impl_opengl2.h`, `imgui_impl_opengl3.h`). The backends are in `backends/` upstream, here +next to the rest. + +## ImGui itself + +| Change | Files | Since | Used by | +|--------|-------|-------|---------| +| `io.ConfigViewportsNoAutoDetach` (default `false`): a floating window stays inside its host viewport. A resize stops at the viewport's edge, a window left past the edge or too big for it is moved back and shrunk, and it gets a viewport (an OS window) of its own only when dragged with the cursor outside the host viewport. Tooltips and popups over the main viewport, or begun outside any window, stay in the main viewport. Upstream has no such option ([#236](https://github.com/MaSzyna-EU07/maszyna/pull/236); the closest upstream report is [ocornut/imgui#9594](https://github.com/ocornut/imgui/issues/9594)) | `imgui.h` (`ImGuiIO` field), `imgui.cpp`: its default in `ImGuiIO::ImGuiIO()`; `WindowStaysInHostViewport()`, `IsWindowBeingMoved()`, `KeepWindowInsideRect()`; the resize limit in `UpdateWindowManualResize()`; two places in `Begin()` (no late viewport, window kept inside the work rect); the fallback and `ViewportAllowPlatformMonitorExtend` in `UpdateSelectWindowViewport()` | 5fa03304e (#236), be4000880, d0ca44cd6 | `application/uilayer.cpp`, with the viewports on | +| `io.ConfigTooltipsWrapWidth` (default `0`, no wrapping): the text of `SetTooltip()` / `SetItemTooltip()` wraps at that width. `BeginTooltip()` is not affected | `imgui.h` (`ImGuiIO` field), `imgui.cpp` (default, `SetTooltipV()`) | be4000880 | `application/uilayer.cpp` (40 font sizes) | +| `ImGui::BufferingBar()` and `ImGui::Spinner()`, by zfedoran from [ocornut/imgui#1901](https://github.com/ocornut/imgui/issues/1901) | `imgui.h`, end of `imgui_widgets.cpp` | ae3cecfa4 (2019, for the progress bar of the loading screen of the time), carried over in 344034ec7 | nothing at present: can be dropped | +| `#define IMGUI_IMPL_OPENGL_LOADER_CUSTOM`: the OpenGL 3 backend uses glad, loaded by the simulator, instead of its own loader | `imconfig.h` | 344034ec7 | the OpenGL 3 backend | + +## Backends + +| Change | File | Since | +|--------|------|-------| +| With multi-viewports, ImGui positions are relative to the simulator's main window instead of the desktop, so the main viewport stays at (0,0) and the overlays, picking and editor gizmo work in window coordinates as without viewports. `MainWindowOrigin` in the backend data, `ImGui_ImplGlfw_UpdateMainWindowOrigin()` called from `NewFrame()`; the origin is subtracted from the mouse position (callback and `UpdateMouseData()`), the monitors' `MainPos` / `WorkPos` and `GetWindowPos()`, and added back in `CreateWindow()` and `SetWindowPos()` | `imgui_impl_glfw.cpp` | 476f3bf1b | +| GL functions from glad (``) instead of the system's `GL/gl.h` | `imgui_impl_opengl2.cpp` | 344034ec7 | +| GL functions from glad, with `stdafx.h` and `utilities/Globals.h` included for the renderer's settings | `imgui_impl_opengl3.cpp` | 344034ec7 | +| `GlslVersionString` is 128 bytes instead of 32, for the longer GLES version string the simulator passes | `imgui_impl_opengl3.cpp` | 344034ec7 | +| Gamma of the UI follows the renderer: the vertex shaders linearise the vertex colour (`pow(Color.rgb, 2.2)`); each fragment shader's output goes through `FBOUT()`, which applies `1/2.2` when `Global.gfx_shadergamma` is set and passes it through otherwise; with desktop GL and no shader gamma `GL_FRAMEBUFFER_SRGB` is enabled while the UI is drawn and restored after | `imgui_impl_opengl3.cpp` (`RenderDrawData()`, the shader sources, `CreateDeviceObjects()`) | 344034ec7 | + +## ImGuizmo + +From [CedricGuillemet/ImGuizmo](https://github.com/CedricGuillemet/ImGuizmo), added in 5a39ed519; the upstream commit +it was taken from isn't recorded. Changed in 344034ec7 for the ImGui API of 1.91: + +- `IMGUI_DEFINE_MATH_OPERATORS` is defined before the first `#include "imgui.h"` (ImGui 1.86 and later want it so). +- `ImGui::CaptureMouseFromApp()` is replaced by `ImGui::SetNextFrameWantCaptureMouse(true)` (six places). + +And since 5a39ed519, for the ImGui of the time: + +- A compatibility shim, `#define ImAbs(X)` when `ImAbs` isn't a macro (`ImGuizmo.cpp:42-44`). ImGui 1.91 has `ImAbs` + as an inline function in `imgui_internal.h`, so the macro is always defined now and hides that function in + `ImGuizmo.cpp`. It can be dropped. + +## Checking an update + +Download the files of the new tag (`imgui*.cpp`, `imgui*.h`, `imstb_*.h`, `imconfig.h`, and from `backends/` +`imgui_impl_glfw.*`, `imgui_impl_opengl2.*`, `imgui_impl_opengl3.*`), diff the files here against the tag listed at the +top, and apply that diff to the new files. The diff of the files here against `v1.91.9b-docking` is exactly the list +above. diff --git a/track_uneven_doc.md b/docs/track_uneven_doc.md similarity index 100% rename from track_uneven_doc.md rename to docs/track_uneven_doc.md diff --git a/ref/licenses/README.md b/ref/licenses/README.md new file mode 100644 index 000000000..10ff550eb --- /dev/null +++ b/ref/licenses/README.md @@ -0,0 +1,29 @@ +# License texts of the Windows audio DLLs + +The Windows build ships `OpenAL32.dll` (OpenAL Soft 1.25.2) and `libsndfile-1.dll` (libsndfile 1.2.2), and in +`licenses/` next to them the texts of those libraries and of what they have built in. The DLLs and OpenAL Soft's own +`COPYING` come from the release zips, which CI downloads; the texts below are kept here, so a build doesn't depend on +the servers they come from. CI copies them into `licenses/` and checks each one by the SHA-256 in +`.github/workflows/build_bin.yml` (step "Add the OpenAL Soft and libsndfile DLLs"). `.gitattributes` keeps them byte +for byte as upstream (`-text`), whatever the line ending settings of a checkout. What each text covers is in +`audio-libraries.txt`, which that step writes. + +| File | Taken from | SHA-256 | +|------|------------|---------| +| `libsndfile-COPYING.txt` | https://raw.githubusercontent.com/libsndfile/libsndfile/1.2.2/COPYING | `ad01ea5cd2755f6048383c8d54c88459cd6fcb17757c5c8892f8c5ea060f6140` | +| `libsndfile-ALAC-LICENSE.txt` | https://raw.githubusercontent.com/libsndfile/libsndfile/1.2.2/src/ALAC/LICENSE | `232efbd83786e157286b0b96c68ebb673541b69b33036287bf1e5ec5067a49d9` | +| `libsndfile-GSM610-COPYRIGHT.txt` | https://raw.githubusercontent.com/libsndfile/libsndfile/1.2.2/src/GSM610/COPYRIGHT | `1bbe7119b1bcd1489e0f36cb95b8902f7f0ceec9a2f3a67394bc9f4709a4e0a7` | +| `libogg-COPYING.txt` | https://raw.githubusercontent.com/xiph/ogg/v1.3.5/COPYING | `d2ab5758336489da61c12cc5bb757da5339c4ae9001f9bb0562b4370249af814` | +| `libvorbis-COPYING.txt` | https://raw.githubusercontent.com/xiph/vorbis/v1.3.7/COPYING | `ec1815db59fcd302846df949d7424876cb2e2dc5ed1606c5fb0b36787b1cf43a` | +| `flac-COPYING.Xiph.txt` | https://raw.githubusercontent.com/xiph/flac/1.4.2/COPYING.Xiph | `6e58d3036f05e2a0d58af854c12a505ddbe75011d71a598a2170987f3b15408d` | +| `opus-COPYING.txt` | https://raw.githubusercontent.com/xiph/opus/v1.4/COPYING | `8338ce8d922bb4416ce3dd1e5680173332435e3f0755007ac7801ccd674fe682` | +| `mpg123-COPYING.txt` | https://scm.orgis.org/view/mpg123/tags/1.31.3/COPYING?view=co | `c22482728a634a8dfdb4ff72a96d4c1ed64cd8f3e79335c401751ac591609366` | +| `lame-COPYING.txt` | https://sources.debian.org/data/main/l/lame/3.100-6/COPYING (the same file as in LAME 3.100) | `bfe4a52dc4645385f356a8e83cc54216a293e3b6f1cb4f79f5fc0277abf937fd` | +| `openal-soft-pffft-LICENSE.txt` | https://raw.githubusercontent.com/kcat/openal-soft/1.25.2/LICENSE-pffft | `64056328b3e7bc104e24ef96accc1a7abead156f0c02d1b87c97e3f3a28030de` | +| `openal-soft-gsl-LICENSE.txt` | https://raw.githubusercontent.com/kcat/openal-soft/1.25.2/gsl/LICENSE | `4c21dc82a1c7186ea754fd59d504c00947953a3401fe8e24eaa44109ef8e2555` | +| `openal-soft-BSD-3Clause.txt` | https://raw.githubusercontent.com/kcat/openal-soft/1.25.2/BSD-3Clause | `b5a08cf98996dd83aa906a72c163600f6cb17a65ce546a553815a1267abd43ff` | +| `openal-soft-winpthreads-COPYING.txt` | https://raw.githubusercontent.com/mingw-w64/mingw-w64/v13.0.0/mingw-w64-libraries/winpthreads/COPYING | `63263614cdd29f2f93cba85e992f041b31f9fc7b4033692f31269489a8a1b177` | +| `openal-soft-mingw-w64-runtime.txt` | https://raw.githubusercontent.com/mingw-w64/mingw-w64/v13.0.0/COPYING.MinGW-w64-runtime/COPYING.MinGW-w64-runtime.txt | `e9b2dc02451ea29092a1f25fa0f3c07207ed421f1807dffb0c4e6dce69dee7bd` | + +When a DLL is updated to another version, its texts here are replaced by those of the new version's source tree, and +their SHA-256 in the workflow with them. diff --git a/ref/licenses/flac-COPYING.Xiph.txt b/ref/licenses/flac-COPYING.Xiph.txt new file mode 100644 index 000000000..edd24f719 --- /dev/null +++ b/ref/licenses/flac-COPYING.Xiph.txt @@ -0,0 +1,29 @@ +Copyright (C) 2000-2009 Josh Coalson +Copyright (C) 2011-2022 Xiph.Org Foundation + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of the Xiph.Org Foundation nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/ref/licenses/lame-COPYING.txt b/ref/licenses/lame-COPYING.txt new file mode 100644 index 000000000..f5030495b --- /dev/null +++ b/ref/licenses/lame-COPYING.txt @@ -0,0 +1,481 @@ + GNU LIBRARY GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the library GPL. It is + numbered 2 because it goes with version 2 of the ordinary GPL.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Library General Public License, applies to some +specially designated Free Software Foundation software, and to any +other libraries whose authors decide to use it. You can use it for +your libraries, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if +you distribute copies of the library, or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link a program with the library, you must provide +complete object files to the recipients so that they can relink them +with the library, after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + Our method of protecting your rights has two steps: (1) copyright +the library, and (2) offer you this license which gives you legal +permission to copy, distribute and/or modify the library. + + Also, for each distributor's protection, we want to make certain +that everyone understands that there is no warranty for this free +library. If the library is modified by someone else and passed on, we +want its recipients to know that what they have is not the original +version, so that any problems introduced by others will not reflect on +the original authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that companies distributing free +software will individually obtain patent licenses, thus in effect +transforming the program into proprietary software. To prevent this, +we have made it clear that any patent must be licensed for everyone's +free use or not licensed at all. + + Most GNU software, including some libraries, is covered by the ordinary +GNU General Public License, which was designed for utility programs. This +license, the GNU Library General Public License, applies to certain +designated libraries. This license is quite different from the ordinary +one; be sure to read it in full, and don't assume that anything in it is +the same as in the ordinary license. + + The reason we have a separate public license for some libraries is that +they blur the distinction we usually make between modifying or adding to a +program and simply using it. Linking a program with a library, without +changing the library, is in some sense simply using the library, and is +analogous to running a utility program or application program. However, in +a textual and legal sense, the linked executable is a combined work, a +derivative of the original library, and the ordinary General Public License +treats it as such. + + Because of this blurred distinction, using the ordinary General +Public License for libraries did not effectively promote software +sharing, because most developers did not use the libraries. We +concluded that weaker conditions might promote sharing better. + + However, unrestricted linking of non-free programs would deprive the +users of those programs of all benefit from the free status of the +libraries themselves. This Library General Public License is intended to +permit developers of non-free programs to use free libraries, while +preserving your freedom as a user of such programs to change the free +libraries that are incorporated in them. (We have not seen how to achieve +this as regards changes in header files, but we have achieved it as regards +changes in the actual functions of the Library.) The hope is that this +will lead to faster development of free libraries. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, while the latter only +works together with the library. + + Note that it is possible for a library to be covered by the ordinary +General Public License rather than by this special one. + + GNU LIBRARY GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library which +contains a notice placed by the copyright holder or other authorized +party saying it may be distributed under the terms of this Library +General Public License (also called "this License"). Each licensee is +addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also compile or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + c) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + d) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the source code distributed need not include anything that is normally +distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Library General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/ref/licenses/libogg-COPYING.txt b/ref/licenses/libogg-COPYING.txt new file mode 100644 index 000000000..6111c6c5a --- /dev/null +++ b/ref/licenses/libogg-COPYING.txt @@ -0,0 +1,28 @@ +Copyright (c) 2002, Xiph.org Foundation + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of the Xiph.org Foundation nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/ref/licenses/libsndfile-ALAC-LICENSE.txt b/ref/licenses/libsndfile-ALAC-LICENSE.txt new file mode 100644 index 000000000..7d8595490 --- /dev/null +++ b/ref/licenses/libsndfile-ALAC-LICENSE.txt @@ -0,0 +1,170 @@ +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the +copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other +entities that control, are controlled by, or are under common control +with that entity. For the purposes of this definition, "control" means +(i) the power, direct or indirect, to cause the direction or management +of such entity, whether by contract or otherwise, or (ii) ownership +of fifty percent (50%) or more of the outstanding shares, or (iii) +beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising +permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, +including but not limited to software source code, documentation source, +and configuration files. + +"Object" form shall mean any form resulting from mechanical +transformation or translation of a Source form, including but not +limited to compiled object code, generated documentation, and +conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object +form, made available under the License, as indicated by a copyright +notice that is included in or attached to the work (an example is +provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object +form, that is based on (or derived from) the Work and for which the +editorial revisions, annotations, elaborations, or other modifications +represent, as a whole, an original work of authorship. For the purposes +of this License, Derivative Works shall not include works that remain +separable from, or merely link (or bind by name) to the interfaces of, +the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original +version of the Work and any modifications or additions to that Work or +Derivative Works thereof, that is intentionally submitted to Licensor +for inclusion in the Work by the copyright owner or by an individual +or Legal Entity authorized to submit on behalf of the copyright owner. +For the purposes of this definition, "submitted" means any form of +electronic, verbal, or written communication sent to the Licensor +or its representatives, including but not limited to communication +on electronic mailing lists, source code control systems, and issue +tracking systems that are managed by, or on behalf of, the Licensor +for the purpose of discussing and improving the Work, but excluding +communication that is conspicuously marked or otherwise designated in +writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity +on behalf of whom a Contribution has been received by Licensor and +subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions +of this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +copyright license to reproduce, prepare Derivative Works of, publicly +display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except +as stated in this section) patent license to make, have made, use, +offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such +Contributor that are necessarily infringed by their Contribution(s) +alone or by combination of their Contribution(s) with the Work to which +such Contribution(s) was submitted. If You institute patent litigation +against any entity (including a cross-claim or counterclaim in a +lawsuit) alleging that the Work or a Contribution incorporated within +the Work constitutes direct or contributory patent infringement, then +any patent licenses granted to You under this License for that Work +shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the +Work or Derivative Works thereof in any medium, with or without +modifications, and in Source or Object form, provided that You meet the +following conditions: + +You must give any other recipients of the Work or Derivative Works a +copy of this License; and + +You must cause any modified files to carry prominent notices stating +that You changed the files; and + +You must retain, in the Source form of any Derivative Works that You +distribute, all copyright, patent, trademark, and attribution notices +from the Source form of the Work, excluding those notices that do not +pertain to any part of the Derivative Works; and + +If the Work includes a "NOTICE" text file as part of its distribution, +then any Derivative Works that You distribute must include a readable +copy of the attribution notices contained within such NOTICE file, +excluding those notices that do not pertain to any part of the +Derivative Works, in at least one of the following places: within a +NOTICE text file distributed as part of the Derivative Works; within +the Source form or documentation, if provided along with the Derivative +Works; or, within a display generated by the Derivative Works, if and +wherever such third-party notices normally appear. The contents of the +NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative +Works that You distribute, alongside or as an addendum to the NOTICE +text from the Work, provided that such additional attribution notices +cannot be construed as modifying the License. You may add Your own +copyright statement to Your modifications and may provide additional +or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as +a whole, provided Your use, reproduction, and distribution of the Work +otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, +any Contribution intentionally submitted for inclusion in the Work by +You to the Licensor shall be under the terms and conditions of this +License, without any additional terms or conditions. Notwithstanding +the above, nothing herein shall supersede or modify the terms of any +separate license agreement you may have executed with Licensor regarding +such Contributions. + +6. Trademarks. This License does not grant permission to use the trade +names, trademarks, service marks, or product names of the Licensor, +except as required for reasonable and customary use in describing the +origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed +to in writing, Licensor provides the Work (and each Contributor +provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied, including, without +limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, +MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your +exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, +whether in tort (including negligence), contract, or otherwise, unless +required by applicable law (such as deliberate and grossly negligent +acts) or agreed to in writing, shall any Contributor be liable to You +for damages, including any direct, indirect, special, incidental, or +consequential damages of any character arising as a result of this +License or out of the use or inability to use the Work (including but +not limited to damages for loss of goodwill, work stoppage, computer +failure or malfunction, or any and all other commercial damages or +losses), even if such Contributor has been advised of the possibility of +such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the +Work or Derivative Works thereof, You may choose to offer, and charge a +fee for, acceptance of support, warranty, indemnity, or other liability +obligations and/or rights consistent with this License. However, in +accepting such obligations, You may act only on Your own behalf and +on Your sole responsibility, not on behalf of any other Contributor, +and only if You agree to indemnify, defend, and hold each Contributor +harmless for any liability incurred by, or claims asserted against, such +Contributor by reason of your accepting any such warranty or additional +liability. diff --git a/ref/licenses/libsndfile-COPYING.txt b/ref/licenses/libsndfile-COPYING.txt new file mode 100644 index 000000000..c396169ee --- /dev/null +++ b/ref/licenses/libsndfile-COPYING.txt @@ -0,0 +1,503 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + diff --git a/ref/licenses/libsndfile-GSM610-COPYRIGHT.txt b/ref/licenses/libsndfile-GSM610-COPYRIGHT.txt new file mode 100644 index 000000000..eba0e523b --- /dev/null +++ b/ref/licenses/libsndfile-GSM610-COPYRIGHT.txt @@ -0,0 +1,16 @@ +Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann, +Technische Universitaet Berlin + +Any use of this software is permitted provided that this notice is not +removed and that neither the authors nor the Technische Universitaet Berlin +are deemed to have made any representations as to the suitability of this +software for any purpose nor are held responsible for any defects of +this software. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. + +As a matter of courtesy, the authors request to be informed about uses +this software has found, about bugs in this software, and about any +improvements that may be of general interest. + +Berlin, 28.11.1994 +Jutta Degener +Carsten Bormann diff --git a/ref/licenses/libvorbis-COPYING.txt b/ref/licenses/libvorbis-COPYING.txt new file mode 100644 index 000000000..fb456a87b --- /dev/null +++ b/ref/licenses/libvorbis-COPYING.txt @@ -0,0 +1,28 @@ +Copyright (c) 2002-2020 Xiph.org Foundation + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of the Xiph.org Foundation nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/ref/licenses/mpg123-COPYING.txt b/ref/licenses/mpg123-COPYING.txt new file mode 100644 index 000000000..14e14f01c --- /dev/null +++ b/ref/licenses/mpg123-COPYING.txt @@ -0,0 +1,772 @@ +This is the file that contains the terms of use, copying, etc. for the mpg123 distribution package. + +Main message, to include in "About ..." boxes, etc: + + Copyright (c) 1995-2020 by Michael Hipp and others, + free software under the terms of the LGPL v2.1 + +There is an attempt to cover the actual list of authors in the AUTHORS file. +Project maintainer since 2006 is Thomas Orgis and many people have contributed +since the Michael Hipp era, but he stays the initial source and it would +be impractical to count them all individually, so it's "and others". +Source files contain the phrase "the mpg123 project" to the same effect +in their license boilerplate; especially those that were added after +maintainership changed. The person mainly responsible for the first version +is usually named in the phrase "initially written by ...". + +All files in the distribution that don't carry a license note on their own are +licensed under the terms of the LGPL 2.1; exceptions may apply, especially to +files not in the official distribution but in the revision control repository. + +The formal license text follows. + +======================= +1. The LGPL version 2.1 +======================= + + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + +==================== +2. The GPL version 2 +==================== + + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS diff --git a/ref/licenses/openal-soft-BSD-3Clause.txt b/ref/licenses/openal-soft-BSD-3Clause.txt new file mode 100644 index 000000000..b1c2dbd76 --- /dev/null +++ b/ref/licenses/openal-soft-BSD-3Clause.txt @@ -0,0 +1,31 @@ +Portions of this software are licensed under the BSD 3-Clause license. + +Copyright (c) 2015, Archontis Politis +Copyright (c) 2019, Anis A. Hireche +Copyright (c) 2019, Christopher Robinson +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of Spherical-Harmonic-Transform nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/ref/licenses/openal-soft-gsl-LICENSE.txt b/ref/licenses/openal-soft-gsl-LICENSE.txt new file mode 100644 index 000000000..aa58667a3 --- /dev/null +++ b/ref/licenses/openal-soft-gsl-LICENSE.txt @@ -0,0 +1,21 @@ +Copyright (c) 2015 Microsoft Corporation. All rights reserved. + +This code is licensed under the MIT License (MIT). + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/ref/licenses/openal-soft-mingw-w64-runtime.txt b/ref/licenses/openal-soft-mingw-w64-runtime.txt new file mode 100644 index 000000000..ca6a077e2 --- /dev/null +++ b/ref/licenses/openal-soft-mingw-w64-runtime.txt @@ -0,0 +1,240 @@ +MinGW-w64 runtime licensing +*************************** + +This program or library was built using MinGW-w64 and statically +linked against the MinGW-w64 runtime. Some parts of the runtime +are under licenses which require that the copyright and license +notices are included when distributing the code in binary form. +These notices are listed below. + + +======================== +Overall copyright notice +======================== + +Copyright (c) 2009, 2010, 2011, 2012, 2013 by the mingw-w64 project + +This license has been certified as open source. It has also been designated +as GPL compatible by the Free Software Foundation (FSF). + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions in source code must retain the accompanying copyright + notice, this list of conditions, and the following disclaimer. + 2. Redistributions in binary form must reproduce the accompanying + copyright notice, this list of conditions, and the following disclaimer + in the documentation and/or other materials provided with the + distribution. + 3. Names of the copyright holders must not be used to endorse or promote + products derived from this software without prior written permission + from the copyright holders. + 4. The right to distribute this software or to use it for any purpose does + not give you the right to use Servicemarks (sm) or Trademarks (tm) of + the copyright holders. Use of them is covered by separate agreement + with the copyright holders. + 5. If any files are modified, you must cause the modified files to carry + prominent notices stating that you changed the files and the date of + any change. + +Disclaimer + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED +OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO +EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +======================================== +getopt, getopt_long, and getop_long_only +======================================== + +Copyright (c) 2002 Todd C. Miller + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +Sponsored in part by the Defense Advanced Research Projects +Agency (DARPA) and Air Force Research Laboratory, Air Force +Materiel Command, USAF, under agreement number F39502-99-1-0512. + + * * * * * * * + +Copyright (c) 2000 The NetBSD Foundation, Inc. +All rights reserved. + +This code is derived from software contributed to The NetBSD Foundation +by Dieter Baron and Thomas Klausner. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + + +=============================================================== +gdtoa: Converting between IEEE floating point numbers and ASCII +=============================================================== + +The author of this software is David M. Gay. + +Copyright (C) 1997, 1998, 1999, 2000, 2001 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + + * * * * * * * + +The author of this software is David M. Gay. + +Copyright (C) 2005 by David M. Gay +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that the copyright notice and this permission notice and warranty +disclaimer appear in supporting documentation, and that the name of +the author or any of his current or former employers not be used in +advertising or publicity pertaining to distribution of the software +without specific, written prior permission. + +THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN +NO EVENT SHALL THE AUTHOR OR ANY OF HIS CURRENT OR FORMER EMPLOYERS BE +LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY +DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS +SOFTWARE. + + * * * * * * * + +The author of this software is David M. Gay. + +Copyright (C) 2004 by David M. Gay. +All Rights Reserved +Based on material in the rest of /netlib/fp/gdota.tar.gz, +which is copyright (C) 1998, 2000 by Lucent Technologies. + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + + +========================= +Parts of the math library +========================= + +Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + +Developed at SunSoft, a Sun Microsystems, Inc. business. +Permission to use, copy, modify, and distribute this +software is freely granted, provided that this notice +is preserved. + + * * * * * * * + +Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + +Developed at SunPro, a Sun Microsystems, Inc. business. +Permission to use, copy, modify, and distribute this +software is freely granted, provided that this notice +is preserved. + + * * * * * * * + +FIXME: Cephes math lib +Copyright (C) 1984-1998 Stephen L. Moshier + +It sounds vague, but as to be found at +, it gives an +impression that the author could be willing to give an explicit +permission to distribute those files e.g. under a BSD style license. So +probably there is no problem here, although it could be good to get a +permission from the author and then add a license into the Cephes files +in MinGW runtime. At least on follow-up it is marked that debian sees the +version a-like BSD one. As MinGW.org (where those cephes parts are coming +from) distributes them now over 6 years, it should be fine. + +=================================== +Headers and IDLs imported from Wine +=================================== + +Some header and IDL files were imported from the Wine project. These files +are prominent maked in source. Their copyright belongs to contributors and +they are distributed under LGPL license. + +Disclaimer + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. diff --git a/ref/licenses/openal-soft-pffft-LICENSE.txt b/ref/licenses/openal-soft-pffft-LICENSE.txt new file mode 100644 index 000000000..5f1a8493f --- /dev/null +++ b/ref/licenses/openal-soft-pffft-LICENSE.txt @@ -0,0 +1,38 @@ +A modified PFFFT is included, with the following license. + +Copyright (c) 2023 Christopher Robinson + +Copyright (c) 2013 Julien Pommier ( pommier@modartt.com ) + +Copyright (c) 2004 the University Corporation for Atmospheric +Research ("UCAR"). All rights reserved. Developed by NCAR's +Computational and Information Systems Laboratory, UCAR, +www.cisl.ucar.edu. + +Redistribution and use of the Software in source and binary forms, +with or without modification, is permitted provided that the +following conditions are met: + +- Neither the names of NCAR's Computational and Information Systems +Laboratory, the University Corporation for Atmospheric Research, +nor the names of its sponsors or contributors may be used to +endorse or promote products derived from this Software without +specific prior written permission. + +- Redistributions of source code must retain the above copyright +notices, this list of conditions, and the disclaimer below. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions, and the disclaimer below in the +documentation and/or other materials provided with the +distribution. + +THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE +SOFTWARE. diff --git a/ref/licenses/openal-soft-winpthreads-COPYING.txt b/ref/licenses/openal-soft-winpthreads-COPYING.txt new file mode 100644 index 000000000..350770123 --- /dev/null +++ b/ref/licenses/openal-soft-winpthreads-COPYING.txt @@ -0,0 +1,57 @@ +Copyright (c) 2011 mingw-w64 project + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +/* + * Parts of this library are derived by: + * + * Posix Threads library for Microsoft Windows + * + * Use at own risk, there is no implied warranty to this code. + * It uses undocumented features of Microsoft Windows that can change + * at any time in the future. + * + * (C) 2010 Lockless Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of Lockless Inc. nor the names of its contributors may be + * used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AN + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + */ diff --git a/ref/licenses/opus-COPYING.txt b/ref/licenses/opus-COPYING.txt new file mode 100644 index 000000000..9c739c34a --- /dev/null +++ b/ref/licenses/opus-COPYING.txt @@ -0,0 +1,44 @@ +Copyright 2001-2011 Xiph.Org, Skype Limited, Octasic, + Jean-Marc Valin, Timothy B. Terriberry, + CSIRO, Gregory Maxwell, Mark Borgerding, + Erik de Castro Lopo + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of Internet Society, IETF or IETF Trust, nor the +names of specific contributors, may be used to endorse or promote +products derived from this software without specific prior written +permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Opus is subject to the royalty-free patent licenses which are +specified at: + +Xiph.Org Foundation: +https://datatracker.ietf.org/ipr/1524/ + +Microsoft Corporation: +https://datatracker.ietf.org/ipr/1914/ + +Broadcom Corporation: +https://datatracker.ietf.org/ipr/1526/ diff --git a/tools/track_uneven_grade.py b/tools/track_uneven_grade.py index ba60be900..889e0ad0f 100644 --- a/tools/track_uneven_grade.py +++ b/tools/track_uneven_grade.py @@ -7,7 +7,7 @@ curves, speed and road crossings. The originals stay as they are, graded copies python track_uneven_grade.py scenery/baltyk_skm1.scn --out graded --route -107,2300 -4120,2491 --straight tor0290,tor0906 python track_uneven_grade.py scenery/mytracks.scm --root scenery --out graded --gain 1.2 -With no --out it only reports. See track_uneven_doc.md for the attribute. Python 3.8 or later, no other packages. +With no --out it only reports. See docs/track_uneven_doc.md for the attribute. Python 3.8 or later, no other packages. """ import argparse import collections From 92bd7066d4521d6f427858ce44ff332a04b22fb0 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:41:39 +0100 Subject: [PATCH 114/136] ci: cache the apt packages of the Linux jobs, install only the X11 headers GLFW needs (#497) * ci: cache the apt packages of the Linux jobs, install only the X11 headers GLFW needs The "Install Linux dependencies" step timed out after 15 minutes in many runs: the runners' Ubuntu mirror delivered about 150 kB/s, with 30 s stalls on single files, and the step downloaded 136 packages (32.4 MB) every time. - a local action, .github/actions/apt-install, keeps the downloaded .deb files in the Actions cache, keyed by the runner image and the package list. With the same image and list it installs the cached files without apt-get update and without the mirror; otherwise it runs apt-get update and downloads only what the cache lacks - --no-install-recommends, and Acquire::Languages "none" for apt-get update - xorg-dev (about 45 packages nothing used) is replaced by the X11 headers GLFW 3.4 checks for: libx11-dev, libxcursor-dev, libxext-dev, libxi-dev, libxinerama-dev, libxrandr-dev; pkg-config is listed, as it is only a recommendation of libsndfile1-dev - Build, Build binaries and Coverage use it; Coverage gets the 15-minute step timeout and the apt retries too - Dependabot also updates the actions pinned in .github/actions * ci: a repaired apt cache is saved under a key of its own run, and the newest one is restored --- .github/actions/apt-install/action.yml | 137 +++++++++++++++++++++++++ .github/dependabot.yml | 10 +- .github/workflows/build.yml | 27 +++-- .github/workflows/build_bin.yml | 60 +++++------ .github/workflows/coverage.yml | 19 ++-- 5 files changed, 198 insertions(+), 55 deletions(-) create mode 100644 .github/actions/apt-install/action.yml diff --git a/.github/actions/apt-install/action.yml b/.github/actions/apt-install/action.yml new file mode 100644 index 000000000..0495b07ac --- /dev/null +++ b/.github/actions/apt-install/action.yml @@ -0,0 +1,137 @@ +# Installs Ubuntu packages, with the downloaded .deb files kept in the Actions cache. +# +# The Ubuntu mirror of the hosted runners has been slow: about 150 kB/s, with stalls of 30 s on single files, +# so 130 small packages took over 13 minutes to download. The .deb files of the last install are kept in the +# cache, under a key of the runner image and the package list: +# - the same image and list (the usual case): the cached files are installed as they are, without the mirror +# and without `apt-get update`; should that fail, the next way is taken +# - otherwise: `apt-get update`, then `apt-get install`, which takes the cached files of the same version +# (checked against the index) and downloads the rest; the files of this install are cached for the next run +# +# A cache entry can't be overwritten, so each one is saved under the key with the run appended, and the newest +# entry of a key is restored by its prefix. Cached files that failed to install are then replaced by the next +# save rather than restored again on every run of that image. +# +# Caches of a pull request are seen only by that pull request; the pushes to staging and master (Build binaries) +# fill the ones every pull request starts from. + +name: Install apt packages +description: apt-get install, with the downloaded packages kept in the Actions cache + +inputs: + packages: + description: The packages to install, separated by spaces or new lines + required: true + +runs: + using: composite + steps: + # the key: the runner image (its packages are what the cached files were resolved against) and the list, + # sorted, so neither its order nor its line breaks change it. Without ImageVersion (not a GitHub-hosted + # runner) the image isn't known, so the cached files are never installed as they are + - name: Cache key of the packages + id: key + shell: bash + env: + PACKAGES: ${{ inputs.packages }} + run: | + set -euo pipefail + printf '%s\n' "$PACKAGES" | tr -s '[:space:]' '\n' | sed '/^$/d' | sort -u > "$RUNNER_TEMP/apt-packages.txt" + os="${ImageOS:-$(. /etc/os-release && echo "${ID}${VERSION_ID}")}" + image="${ImageVersion:-unknown}" + prefix="apt-v2-${os}-$(dpkg --print-architecture)-" + list_hash="$(sha256sum < "$RUNNER_TEMP/apt-packages.txt" | cut -c1-16)" + { + echo "key=${prefix}${image}-${list_hash}" + echo "save-key=${prefix}${image}-${list_hash}-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + echo "image-prefix=${prefix}${image}-" + echo "prefix=${prefix}" + echo "known-image=$([ -n "${ImageVersion:-}" ] && echo true || echo false)" + } >> "$GITHUB_OUTPUT" + cat "$RUNNER_TEMP/apt-packages.txt" + + # no entry is saved under the key itself, so this restores the newest entry of the key (by its prefix), else + # a cache of another list (another workflow) or of an older image: the files apt finds there in the version + # it wants aren't downloaded again + - name: Restore the downloaded packages + id: restore + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: /tmp/apt-archives + key: ${{ steps.key.outputs.key }} + restore-keys: | + ${{ steps.key.outputs.image-prefix }} + ${{ steps.key.outputs.prefix }} + + # /tmp rather than the runner's temp folder: apt downloads as the user _apt, who has to reach the folder. + # Recommended packages are left out: the build needs the headers and libraries the packages depend on + - name: Install the packages + id: install + shell: bash + env: + EXACT_HIT: ${{ startsWith(steps.restore.outputs.cache-matched-key, format('{0}-', steps.key.outputs.key)) && steps.key.outputs.known-image == 'true' }} + run: | + set -euo pipefail + archives=/tmp/apt-archives + mkdir -p "$archives/partial" + + # a mirror that stops answering used to hold this step for over an hour: time out each download and + # retry it. The translations of the package descriptions aren't needed + printf '%s\n' \ + 'Acquire::Retries "3";' \ + 'Acquire::http::Timeout "60";' \ + 'Acquire::https::Timeout "60";' \ + 'Acquire::Languages "none";' \ + | sudo tee /etc/apt/apt.conf.d/80-ci-retries > /dev/null + + mapfile -t packages < "$RUNNER_TEMP/apt-packages.txt" + apt=(sudo apt-get -y --no-install-recommends -o "Dir::Cache::Archives=$archives/") + + all_installed() { + local package + for package in "${packages[@]}"; do + [[ "$(dpkg-query -W -f '${db:Status-Abbrev}' "$package" 2> /dev/null)" == ii* ]] || return 1 + done + } + + done=false + fix=() + if [ "$EXACT_HIT" = true ] && compgen -G "$archives/*.deb" > /dev/null; then + echo "::group::Install the $(ls "$archives"/*.deb | wc -l) cached packages" + if "${apt[@]}" install "$archives"/*.deb && all_installed; then + done=true + echo "from-cache=true" >> "$GITHUB_OUTPUT" + else + echo "::warning::The cached packages didn't install; installing from the mirror" + fix=(--fix-broken) + fi + echo "::endgroup::" + fi + + if [ "$done" != true ]; then + sudo apt-get update + "${apt[@]}" "${fix[@]}" install "${packages[@]}" + all_installed + fi + + # only the files of the packages now installed are kept, in the version installed: the cached files then + # are exactly this install, and the next run on this image can install them as they are + sudo rm -rf "$archives/partial" "$archives/lock" + sudo chown -R "$(id -u):$(id -g)" "$archives" + installed="$(dpkg-query -W -f '${db:Status-Abbrev}|${Package}|${Version}|${Architecture}\n' \ + | awk -F'|' '$1 ~ /^ii/ { print $2 "|" $3 "|" $4 }')" + for deb in "$archives"/*.deb; do + [ -e "$deb" ] || continue + id="$(dpkg-deb --show --showformat='${Package}|${Version}|${Architecture}' "$deb")" + grep -qxF -- "$id" <<< "$installed" || rm -f "$deb" + done + echo "Cached packages: $(find "$archives" -maxdepth 1 -name '*.deb' | wc -l), $(du -sh "$archives" | cut -f1)" + + # saved unless the cached files of this image and list installed as they are: after a miss, and after cached + # files that failed to install and were replaced from the mirror + - name: Save the downloaded packages + if: steps.install.outputs.from-cache != 'true' + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: /tmp/apt-archives + key: ${{ steps.key.outputs.save-key }} diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 0a520876d..23c5f7c9d 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,10 +1,12 @@ -# Keeps the GitHub Actions used by the workflows up to date. The actions are pinned by commit hash, with the -# version in a comment; Dependabot updates both. One pull request a week for all of them, so the workflows -# stay on the same versions. +# Keeps the GitHub Actions used by the workflows and by the local actions (.github/actions) up to date. The actions +# are pinned by commit hash, with the version in a comment; Dependabot updates both. One pull request a week for all +# of them, so the workflows stay on the same versions. version: 2 updates: - package-ecosystem: github-actions - directory: / + directories: + - / + - /.github/actions/* schedule: interval: weekly groups: diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 7eaf891fe..3b279bbb0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -41,23 +41,20 @@ jobs: with: python-version: '3.14' - # A mirror that stops answering used to hold this step for over an hour. - # Time out each download, retry it, and give up on the whole step early. + # The packages are kept in the Actions cache (.github/actions/apt-install): the mirror of the + # runners has been too slow to download them every time. The timeout is a safety net. + # The X11 packages are the ones GLFW (ref/glfw, 3.4) looks for; xorg-dev brought ~45 more. - name: Install build dependencies timeout-minutes: 15 - run: | - printf '%s\n' \ - 'Acquire::Retries "3";' \ - 'Acquire::http::Timeout "60";' \ - 'Acquire::https::Timeout "60";' \ - | sudo tee /etc/apt/apt.conf.d/80-ci-retries > /dev/null - sudo apt-get update -y - sudo apt-get install -y \ - build-essential \ - libgl1-mesa-dev libglew-dev libglfw3-dev \ - libpng-dev libopenal-dev libluajit-5.1-dev \ - libserialport-dev libsndfile1-dev \ - xorg-dev libxkbcommon-dev libwayland-dev wayland-protocols + uses: ./.github/actions/apt-install + with: + packages: >- + build-essential pkg-config + libgl1-mesa-dev libglew-dev libglfw3-dev + libpng-dev libopenal-dev libluajit-5.1-dev + libserialport-dev libsndfile1-dev + libx11-dev libxcursor-dev libxext-dev libxi-dev libxinerama-dev libxrandr-dev + libxkbcommon-dev libwayland-dev wayland-protocols - name: Build current OpenAL Soft run: | diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index 13f36b0c7..91ad66978 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -400,37 +400,39 @@ jobs: with: python-version: "3.14" - # A mirror that stops answering used to hold this step for over an hour. - # Time out each download, retry it, and give up on the whole step early. + # The packages are kept in the Actions cache (.github/actions/apt-install): the mirror of the runners has been + # too slow to download them every time. The timeout is a safety net. + # libasound2-dev, libpulse-dev and libpipewire-0.3-dev: the headers of OpenAL Soft's audio backends (built below). + # Without them it builds with OSS only, which modern distributions and the Steam Linux Runtime don't have: no sound. + # The X11 packages are the ones GLFW (ref/glfw, 3.4) looks for; xorg-dev brought ~45 more. The game loads the + # X11 and Wayland libraries of the system, none of them is bundled (CMake_modules/bundle_runtime_libs.cmake). - name: Install Linux dependencies timeout-minutes: 15 - run: | - printf '%s\n' \ - 'Acquire::Retries "3";' \ - 'Acquire::http::Timeout "60";' \ - 'Acquire::https::Timeout "60";' \ - | sudo tee /etc/apt/apt.conf.d/80-ci-retries > /dev/null - sudo apt-get update - - # libasound2-dev, libpulse-dev and libpipewire-0.3-dev: the headers of OpenAL Soft's audio backends (built below). - # Without them it builds with OSS only, which modern distributions and the Steam Linux Runtime don't have: no sound. - sudo apt-get install -y \ - build-essential \ - libasound2-dev \ - libpulse-dev \ - libpipewire-0.3-dev \ - libgl1-mesa-dev \ - libglew-dev \ - libglfw3-dev \ - libpng-dev \ - libopenal-dev \ - libluajit-5.1-dev \ - libserialport-dev \ - libsndfile1-dev \ - libcurl4-openssl-dev \ - xorg-dev \ - libxkbcommon-dev \ - libwayland-dev \ + uses: ./.github/actions/apt-install + with: + packages: >- + build-essential + pkg-config + libasound2-dev + libpulse-dev + libpipewire-0.3-dev + libgl1-mesa-dev + libglew-dev + libglfw3-dev + libpng-dev + libopenal-dev + libluajit-5.1-dev + libserialport-dev + libsndfile1-dev + libcurl4-openssl-dev + libx11-dev + libxcursor-dev + libxext-dev + libxi-dev + libxinerama-dev + libxrandr-dev + libxkbcommon-dev + libwayland-dev wayland-protocols # diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index d2f00bccd..27fa64bc2 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -47,14 +47,19 @@ jobs: # the same packages as the Build workflow: the game is configured as a whole, # though only the unit tests and the core library they link are built - name: Install build dependencies + timeout-minutes: 15 + uses: ./.github/actions/apt-install + with: + packages: >- + build-essential pkg-config + libgl1-mesa-dev libglew-dev libglfw3-dev + libpng-dev libopenal-dev libluajit-5.1-dev + libserialport-dev libsndfile1-dev + libx11-dev libxcursor-dev libxext-dev libxi-dev libxinerama-dev libxrandr-dev + libxkbcommon-dev libwayland-dev wayland-protocols + + - name: Install gcovr run: | - sudo apt-get update -y - sudo apt-get install -y \ - build-essential \ - libgl1-mesa-dev libglew-dev libglfw3-dev \ - libpng-dev libopenal-dev libluajit-5.1-dev \ - libserialport-dev libsndfile1-dev \ - xorg-dev libxkbcommon-dev libwayland-dev wayland-protocols python3 -m pip install --no-cache-dir --only-binary :all: gcovr==8.3 - name: Build current OpenAL Soft From be28108b9132795ca2dc83bf52261952f6682084 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:41:50 +0100 Subject: [PATCH 115/136] fix(events): write memcompareex conditions back in the order they are read (#498) The editor wrote a memory cell comparison as memcompareex , without the pass word and with each value before its operator. The parser and the sceneries use memcompareex . A saved scenery read its conditions shifted by one token, and the last value took the next word of the event. The writer now puts out the pass and the operator before each value. The >= operator was written as >; it is written as >= now. The text side of the conditions moves unchanged to the core file world/eventconditions.cpp, so a unit test can check that what is written reads back the same. --- CMakeLists.txt | 1 + tests/unit/test_event_conditions.cpp | 130 +++++++++++++++++++++++++++ utilities/comparison.h | 14 ++- world/Event.cpp | 112 ----------------------- world/eventconditions.cpp | 129 ++++++++++++++++++++++++++ 5 files changed, 273 insertions(+), 113 deletions(-) create mode 100644 tests/unit/test_event_conditions.cpp create mode 100644 world/eventconditions.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 200adcf30..12a5ca1ad 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -584,6 +584,7 @@ set(CORE_SOURCES "world/timetableflags.cpp" "world/timetablereader.cpp" "world/stationnames.cpp" +"world/eventconditions.cpp" ) add_library(eu07_core STATIC ${CORE_SOURCES}) target_link_libraries(eu07_core PUBLIC eu07_settings) diff --git a/tests/unit/test_event_conditions.cpp b/tests/unit/test_event_conditions.cpp new file mode 100644 index 000000000..81a55201b --- /dev/null +++ b/tests/unit/test_event_conditions.cpp @@ -0,0 +1,130 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "utilities/comparison.h" +#include "utilities/parser.h" +#include "world/Event.h" + +#include + +// the condition block of the multiple and updatevalues events (world/eventconditions.cpp): the scenery editor writes +// the conditions of the events back with export_as_text(), and what it writes has to read back as the same conditions + +namespace { + +// the conditions are a part of the event, open to its kinds only +struct event_kind : basic_event { + using basic_event::event_conditions; +}; +using conditions = event_kind::event_conditions; + +// the conditions of an event text, read the way the events read them: the parser stands on the word 'condition' +conditions read(std::string const &Text) { + cParser parser(Text, cParser::buffer_TEXT); + parser.getTokens(); + REQUIRE(parser.peek() == "condition"); + conditions result; + result.deserialize(parser); + // the reading stops at the next keyword of the event and leaves it for the event + CHECK(parser.peek() == "endevent"); + return result; +} + +std::string write(conditions const &Conditions) { + std::ostringstream output; + Conditions.export_as_text(output); + return output.str(); +} + +// the conditions written and read again +conditions write_and_read(conditions const &Conditions) { + return read(write(Conditions) + "endevent"); +} + +void check_same(conditions const &Read, conditions const &Expected) { + CHECK(Read.flags == Expected.flags); + CHECK(Read.probability == Expected.probability); + CHECK(Read.memcompare_pass == Expected.memcompare_pass); + CHECK(Read.memcompare_text == Expected.memcompare_text); + CHECK(Read.memcompare_text_operator == Expected.memcompare_text_operator); + CHECK(Read.memcompare_value1 == Expected.memcompare_value1); + CHECK(Read.memcompare_value1_operator == Expected.memcompare_value1_operator); + CHECK(Read.memcompare_value2 == Expected.memcompare_value2); + CHECK(Read.memcompare_value2_operator == Expected.memcompare_value2_operator); +} + +comparison_operator const operators[]{comparison_operator::equal, comparison_operator::not_equal, comparison_operator::lt, + comparison_operator::gt, comparison_operator::lt_eq, comparison_operator::gt_eq}; +comparison_pass const passes[]{comparison_pass::all, comparison_pass::any, comparison_pass::none}; + +} // namespace + +TEST_CASE("event conditions: each comparison operator and pass is written as the word that reads back as it") { + for (auto const op : operators) { + CAPTURE(to_string(op)); + CHECK(comparison_operator_from_string(to_string(op)) == op); + } + CHECK(to_string(comparison_operator::gt_eq) == ">="); + for (auto const pass : passes) { + CAPTURE(to_string(pass)); + CHECK(comparison_pass_from_string(to_string(pass)) == pass); + } +} + +TEST_CASE("event conditions: memcompareex is written as the pass, then the operator before each compared value") { + auto const conditions{read("condition memcompareex any != Blokada >= 1 < 2.5 endevent")}; + CHECK(conditions.memcompare_pass == comparison_pass::any); + CHECK(conditions.memcompare_text == "Blokada"); + CHECK(conditions.memcompare_text_operator == comparison_operator::not_equal); + CHECK(conditions.memcompare_value1_operator == comparison_operator::gt_eq); + CHECK(conditions.memcompare_value2_operator == comparison_operator::lt); + CHECK(write(conditions) == "condition memcompareex any != Blokada >= 1.000000 < 2.500000 "); + check_same(write_and_read(conditions), conditions); +} + +TEST_CASE("event conditions: memcompareex reads back the same for every pass, operator and left out value") { + for (auto const pass : passes) { + for (auto const op : operators) { + for (unsigned int used{0}; used < 8; ++used) { + std::string text{"condition memcompareex " + to_string(pass)}; + text += (used & 1) ? " " + to_string(op) + " Zajety_tor" : std::string{" *"}; + text += (used & 2) ? " " + to_string(op) + " -3.25" : std::string{" *"}; + text += (used & 4) ? " " + to_string(op) + " 1250" : std::string{" *"}; + text += " endevent"; + CAPTURE(text); + auto const conditions{read(text)}; + CHECK(conditions.flags == used); + if (used == 0) { + // nothing compared is no condition, and no condition is written + CHECK(write(conditions).empty()); + continue; + } + check_same(write_and_read(conditions), conditions); + } + } + } +} + +TEST_CASE("event conditions: the old memcompare is written as memcompareex all with == and reads back the same") { + auto const conditions{read("condition memcompare Wolny * 3 endevent")}; + CHECK(write(conditions) == "condition memcompareex all == Wolny * == 3.000000 "); + check_same(write_and_read(conditions), conditions); + + auto const all{read("condition memcompare Wolny 1 0 endevent")}; + check_same(write_and_read(all), all); +} + +TEST_CASE("event conditions: the track and probability conditions read back along with the comparison") { + auto const conditions{read("condition trackoccupied trackfree probability 0.25 memcompareex none <= 3 * > -1.5 endevent")}; + CHECK(conditions.flags == (basic_event::flags::track_busy | basic_event::flags::track_free | basic_event::flags::probability | + basic_event::flags::text | basic_event::flags::value2)); + check_same(write_and_read(conditions), conditions); + + auto const probability{read("condition probability 0.5 endevent")}; + CHECK(write(probability) == "condition probability 0.5 "); + check_same(write_and_read(probability), probability); +} + +TEST_CASE("event conditions: an event without conditions writes none") { + CHECK(write(conditions{}).empty()); +} diff --git a/utilities/comparison.h b/utilities/comparison.h index f0fc5d0af..1345e690b 100644 --- a/utilities/comparison.h +++ b/utilities/comparison.h @@ -48,11 +48,23 @@ to_string( comparison_operator const Operator ) { case lt: { return "<"; } case gt: { return ">"; } case lt_eq: { return "<="; } - case gt_eq: { return ">"; } + case gt_eq: { return ">="; } default: { return "??"; } } } +inline +std::string +to_string( comparison_pass const Pass ) { + switch( Pass ) { + using enum comparison_pass; + case all: { return "all"; } + case any: { return "any"; } + case none: { return "none"; } + default: { return "all"; } + } +} + inline comparison_pass comparison_pass_from_string( std::string const &Input ) { diff --git a/world/Event.cpp b/world/Event.cpp index 628e38ea7..814cd9918 100644 --- a/world/Event.cpp +++ b/world/Event.cpp @@ -178,110 +178,6 @@ basic_event::event_conditions::test() const { return true; } -void -basic_event::event_conditions::deserialize( cParser &Input ) { - // przetwarzanie warunków, wspólne dla Multiple i UpdateValues - - std::string token; - while( true == Input.getTokens() - && false == (token = Input.peek()).empty() - && false == basic_event::is_keyword(token) ) { - - if( token == "trackoccupied" ) { - flags |= flags::track_busy; - } - else if( token == "trackfree" ) { - flags |= flags::track_free; - } - else if( token == "propability" || token == "probability") { //remove propability in few years after changing old scenery scripts 01.2021 - flags |= flags::probability; - Input.getTokens(); - Input >> probability; - } - else if( token == "memcompare" ) { - Input.getTokens( 1, false ); // case sensitive - if( Input.peek() != "*" ) //"*" - nie brac command pod uwage - { // zapamiętanie łańcucha do porównania - Input >> memcompare_text; - flags |= flags::text; - } - Input.getTokens(); - if( Input.peek() != "*" ) //"*" - nie brac val1 pod uwage - { - Input >> memcompare_value1; - flags |= flags::value1; - } - Input.getTokens(); - if( Input.peek() != "*" ) //"*" - nie brac val2 pod uwage - { - Input >> memcompare_value2; - flags |= flags::value2; - } - } - else if( token == "memcompareex" ) { - memcompare_pass = comparison_pass_from_string( Input.getToken() ); - Input.getTokens(); - if( Input.peek() != "*" ) //"*" - nie brac pod uwage - { // two tokens, operator followed by comparison value - std::string operatorstring; - Input >> operatorstring; - memcompare_text_operator = comparison_operator_from_string( operatorstring ); - Input.getTokens( 1, false ); // case sensitive - Input >> memcompare_text; - flags |= flags::text; - } - Input.getTokens(); - if( Input.peek() != "*" ) //"*" - nie brac pod uwage - { // two tokens, operator followed by comparison value - std::string operatorstring; - Input >> operatorstring; - memcompare_value1_operator = comparison_operator_from_string( operatorstring ); - Input.getTokens(); - Input >> memcompare_value1; - flags |= flags::value1; - } - Input.getTokens(); - if( Input.peek() != "*" ) //"*" - nie brac pod uwage - { // two tokens, operator followed by comparison value - std::string operatorstring; - Input >> operatorstring; - memcompare_value2_operator = comparison_operator_from_string( operatorstring ); - Input.getTokens(); - Input >> memcompare_value2; - flags |= flags::value2; - } - } - } -} - -// sends basic content of the class in legacy (text) format to provided stream -void -basic_event::event_conditions::export_as_text( std::ostream &Output ) const { - - if( flags != 0 ) { - Output << "condition "; - if( ( flags & flags::track_busy ) != 0 ) { - Output << "trackoccupied "; - } - if( ( flags & flags::track_free ) != 0 ) { - Output << "trackfree "; - } - if( ( flags & flags::probability ) != 0 ) { - Output - << "probability " - << probability << ' '; - } - if( ( flags & ( flags::text | flags::value1 | flags::value2 ) ) != 0 ) { - // NOTE: export doesn't preserve original memcompare condition, these are all upgraded to memcompareex format for simplicity - Output - << "memcompareex " - << ( ( flags & flags::text ) == 0 ? "*" : memcompare_text + ' ' + to_string( memcompare_text_operator ) ) << ' ' - << ( ( flags & flags::value1 ) == 0 ? "*" : std::to_string( memcompare_value1 ) + ' ' + to_string( memcompare_value1_operator ) ) << ' ' - << ( ( flags & flags::value2 ) == 0 ? "*" : std::to_string( memcompare_value2 ) + ' ' + to_string( memcompare_value2_operator ) ) << ' '; - } - } -} - basic_event::~basic_event() { m_sibling = nullptr; // nie usuwać podczepionych tutaj @@ -446,14 +342,6 @@ basic_event::input_cell() const { return nullptr; } -bool -basic_event::is_keyword( std::string const &Token ) { - // TODO: convert to array lookup if keyword list gets longer - return Token == "endevent" - || Token == "randomdelay" - || Token == "departuredelay"; -} - TMemCell const * diff --git a/world/eventconditions.cpp b/world/eventconditions.cpp new file mode 100644 index 000000000..a091746e6 --- /dev/null +++ b/world/eventconditions.cpp @@ -0,0 +1,129 @@ +/* +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/. +*/ + +// the text of the event conditions: read from the scenery and written back by the editor. kept apart from +// Event.cpp so the unit tests can check that what is written reads back the same + +#include "stdafx.h" +#include "world/Event.h" + +bool +basic_event::is_keyword( std::string const &Token ) { + // TODO: convert to array lookup if keyword list gets longer + return Token == "endevent" + || Token == "randomdelay" + || Token == "departuredelay"; +} + +void +basic_event::event_conditions::deserialize( cParser &Input ) { + // przetwarzanie warunków, wspólne dla Multiple i UpdateValues + + std::string token; + while( true == Input.getTokens() + && false == (token = Input.peek()).empty() + && false == basic_event::is_keyword(token) ) { + + if( token == "trackoccupied" ) { + flags |= flags::track_busy; + } + else if( token == "trackfree" ) { + flags |= flags::track_free; + } + else if( token == "propability" || token == "probability") { //remove propability in few years after changing old scenery scripts 01.2021 + flags |= flags::probability; + Input.getTokens(); + Input >> probability; + } + else if( token == "memcompare" ) { + Input.getTokens( 1, false ); // case sensitive + if( Input.peek() != "*" ) //"*" - nie brac command pod uwage + { // zapamiętanie łańcucha do porównania + Input >> memcompare_text; + flags |= flags::text; + } + Input.getTokens(); + if( Input.peek() != "*" ) //"*" - nie brac val1 pod uwage + { + Input >> memcompare_value1; + flags |= flags::value1; + } + Input.getTokens(); + if( Input.peek() != "*" ) //"*" - nie brac val2 pod uwage + { + Input >> memcompare_value2; + flags |= flags::value2; + } + } + else if( token == "memcompareex" ) { + memcompare_pass = comparison_pass_from_string( Input.getToken() ); + Input.getTokens(); + if( Input.peek() != "*" ) //"*" - nie brac pod uwage + { // two tokens, operator followed by comparison value + std::string operatorstring; + Input >> operatorstring; + memcompare_text_operator = comparison_operator_from_string( operatorstring ); + Input.getTokens( 1, false ); // case sensitive + Input >> memcompare_text; + flags |= flags::text; + } + Input.getTokens(); + if( Input.peek() != "*" ) //"*" - nie brac pod uwage + { // two tokens, operator followed by comparison value + std::string operatorstring; + Input >> operatorstring; + memcompare_value1_operator = comparison_operator_from_string( operatorstring ); + Input.getTokens(); + Input >> memcompare_value1; + flags |= flags::value1; + } + Input.getTokens(); + if( Input.peek() != "*" ) //"*" - nie brac pod uwage + { // two tokens, operator followed by comparison value + std::string operatorstring; + Input >> operatorstring; + memcompare_value2_operator = comparison_operator_from_string( operatorstring ); + Input.getTokens(); + Input >> memcompare_value2; + flags |= flags::value2; + } + } + } +} + +// sends basic content of the class in legacy (text) format to provided stream +void +basic_event::event_conditions::export_as_text( std::ostream &Output ) const { + + if( flags != 0 ) { + Output << "condition "; + if( ( flags & flags::track_busy ) != 0 ) { + Output << "trackoccupied "; + } + if( ( flags & flags::track_free ) != 0 ) { + Output << "trackfree "; + } + if( ( flags & flags::probability ) != 0 ) { + Output + << "probability " + << probability << ' '; + } + if( ( flags & ( flags::text | flags::value1 | flags::value2 ) ) != 0 ) { + // NOTE: export doesn't preserve original memcompare condition, these are all upgraded to memcompareex format for simplicity + // memcompareex then for the text and both values either * or the operator followed by the compared value, + // the order deserialize() reads them in. a legacy memcompare is the same as memcompareex all with all operators == + Output + << "memcompareex " + << to_string( memcompare_pass ) << ' ' + << ( ( flags & flags::text ) == 0 ? "*" : to_string( memcompare_text_operator ) + ' ' + memcompare_text ) << ' ' + << ( ( flags & flags::value1 ) == 0 ? "*" : to_string( memcompare_value1_operator ) + ' ' + std::to_string( memcompare_value1 ) ) << ' ' + << ( ( flags & flags::value2 ) == 0 ? "*" : to_string( memcompare_value2_operator ) + ' ' + std::to_string( memcompare_value2 ) ) << ' '; + } + } +} From 5551a5308e98770c798cfbc7e4133447a5245f79 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 05:57:38 +0100 Subject: [PATCH 116/136] perf(models): read the .e3d file with one unbuffered fread instead of a file stream (#499) * perf(models): read the .e3d file with one unbuffered fread The model loader read the whole .e3d file with std::ifstream::read. With MSVC that reads a file not in the system cache from a hard disk at about 24 MB/s, against about 38 MB/s for one unbuffered fread, and a cached file at less than half the speed. The new core helper read_whole_file() opens the file without a stream buffer and reads it with one fread. The loader parses the same bytes from memory as before; a missing, empty or short file gives the same result as with the file stream. * perf(models): the comment of read_whole_file quotes the measured read speeds --- CMakeLists.txt | 1 + model/Model3d.cpp | 17 ++-------- tests/unit/test_whole_file.cpp | 59 ++++++++++++++++++++++++++++++++++ utilities/wholefile.cpp | 43 +++++++++++++++++++++++++ utilities/wholefile.h | 26 +++++++++++++++ 5 files changed, 132 insertions(+), 14 deletions(-) create mode 100644 tests/unit/test_whole_file.cpp create mode 100644 utilities/wholefile.cpp create mode 100644 utilities/wholefile.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 12a5ca1ad..9097a57c9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -585,6 +585,7 @@ set(CORE_SOURCES "world/timetablereader.cpp" "world/stationnames.cpp" "world/eventconditions.cpp" +"utilities/wholefile.cpp" ) add_library(eu07_core STATIC ${CORE_SOURCES}) target_link_libraries(eu07_core PUBLIC eu07_settings) diff --git a/model/Model3d.cpp b/model/Model3d.cpp index e3507e216..f836d7177 100644 --- a/model/Model3d.cpp +++ b/model/Model3d.cpp @@ -24,6 +24,7 @@ Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others #include "simulation/simulationtime.h" #include "world/mtable.h" #include "scene/sn_utils.h" +#include "utilities/wholefile.h" #include @@ -2653,20 +2654,8 @@ void TModel3d::LoadFromBinFile(std::string const &FileName, bool dynamic) WriteLog("Loading binary format 3d model data from \"" + FileName + "\"...", logtype::model); // the file is read whole in one go and parsed from memory - std::unique_ptr filedata; - std::size_t filesize{0}; - { - std::ifstream input(FileName, std::ios::binary | std::ios::ate); - auto const length{input.tellg()}; - if (length > 0) - { - filedata.reset(new char[static_cast(length)]); - input.seekg(0); - input.read(filedata.get(), length); - filesize = static_cast(input.gcount()); - } - } - e3d_memorybuffer buffer(filedata.get(), filedata.get() + filesize); + auto const filedata{read_whole_file(FileName)}; + e3d_memorybuffer buffer(filedata.data.get(), filedata.data.get() + filedata.size); std::istream file(&buffer); uint32_t type = sn_utils::ld_uint32(file); diff --git a/tests/unit/test_whole_file.cpp b/tests/unit/test_whole_file.cpp new file mode 100644 index 000000000..f1cd98b5c --- /dev/null +++ b/tests/unit/test_whole_file.cpp @@ -0,0 +1,59 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scratch.h" + +#include "utilities/wholefile.h" + +#include +#include + +// the read of a whole file in one go (utilities/wholefile.cpp), which the loader of the binary models (.e3d) parses +// from memory: the bytes come as they are in the file, whatever they are + +using namespace std::string_view_literals; + +namespace { + +std::string_view content(whole_file const &File) { + return {File.data.get(), File.size}; +} + +} // namespace + +TEST_CASE("whole file: the bytes come as they are in the file, the line ends and the text end marks too") { + test::scratch_folder const folder{"whole_file"}; + // all the byte values, then a size which isn't a multiple of any buffer, so the end of the file is read as well + std::string bytes; + for (int i{0}; i < 256; ++i) { + bytes += static_cast(i); + } + bytes += "\r\n\n\r\x1a\x00\xff"sv; + std::string text; + while (text.size() < 70000) { + text += bytes; + } + text += "end"; + auto const path{folder.write("model.e3d", text)}; + + auto const file{read_whole_file(path)}; + REQUIRE(file.size == text.size()); + CHECK(content(file) == text); +} + +TEST_CASE("whole file: a small file is read whole") { + test::scratch_folder const folder{"whole_file_small"}; + auto const path{folder.write("e3d0.e3d", "E3D0")}; + auto const file{read_whole_file(path)}; + CHECK(content(file) == "E3D0"); +} + +TEST_CASE("whole file: an empty file and a file which isn't there give no data") { + test::scratch_folder const folder{"whole_file_none"}; + auto const empty{read_whole_file(folder.write("empty.e3d", ""))}; + CHECK(empty.size == 0); + CHECK(empty.data == nullptr); + + auto const missing{read_whole_file(folder.path("missing.e3d"))}; + CHECK(missing.size == 0); + CHECK(missing.data == nullptr); +} diff --git a/utilities/wholefile.cpp b/utilities/wholefile.cpp new file mode 100644 index 000000000..573f0f1ab --- /dev/null +++ b/utilities/wholefile.cpp @@ -0,0 +1,43 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "utilities/wholefile.h" + +#include + +whole_file read_whole_file(std::string const &Path) +{ + whole_file result; + + auto *const file{std::fopen(Path.c_str(), "rb")}; + if (file == nullptr) + { + return result; + } + // without a buffer of its own the stream hands the read to the system in one piece, straight into the memory + std::setvbuf(file, nullptr, _IONBF, 0); +#ifdef _WIN32 + _fseeki64(file, 0, SEEK_END); + auto const length{_ftelli64(file)}; + _fseeki64(file, 0, SEEK_SET); +#else + fseeko(file, 0, SEEK_END); + auto const length{ftello(file)}; + fseeko(file, 0, SEEK_SET); +#endif + if (length > 0) + { + result.data.reset(new char[static_cast(length)]); + result.size = std::fread(result.data.get(), 1, static_cast(length), file); + } + std::fclose(file); + + return result; +} diff --git a/utilities/wholefile.h b/utilities/wholefile.h new file mode 100644 index 000000000..992ea8086 --- /dev/null +++ b/utilities/wholefile.h @@ -0,0 +1,26 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include + +// the content of a whole file, kept in memory +struct whole_file +{ + std::unique_ptr data; + std::size_t size{0}; +}; + +// reads the whole file with one large read. a file stream reads a file which isn't in the system's cache yet from a +// hard disk in small pieces, slower (2026-11, .e3d files of a scenario: about 24 MB/s against 38 MB/s for one read). +// a file which can't be opened or is empty gives no data; a read which stops early gives what was read +whole_file read_whole_file(std::string const &Path); From cd60d0abc1f8ade5afa29ef4642efafdcedfd8aa Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 06:14:11 +0100 Subject: [PATCH 117/136] fix(cab): the converter switches follow a change made by the AI (#480) * fix(cab): the converter switches follow a change made by the AI The converter switch (converter_sw) and the local converter switch (converterlocal_sw) were set from the vehicle only when the cab was entered (set_cab_controls()). When the AI driver switched the converter on or off, or the local converter back on (since #276), the lever in the cab stayed where it was until the cab was loaded again. Each frame the two switches now take the state of the vehicle, the way the cab activation switch and the shunt mode lever already do. The main switch follows only where it is a two-state switch (not "impulse") and the converter is started by hand, so a converter started by the line breaker or the reverser does not drag the lever along. The state is read from the occupied vehicle, the one the switch commands of the cab change. * fix(cab): the converter switches are set on entering the cab from the occupied vehicle too --- vehicle/Train.cpp | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 3f2cbebae..f28f11d3b 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -10004,7 +10004,17 @@ bool TTrain::Update(double const Deltatime) ggDimHeadlightsButton.Update(); ggDimHeadlightsButton.Update(); //------------ + // the converter switches follow the vehicle when something else flips them (the AI driver, the other cab, + // the pressure switch of an EMU), not only when the cab is entered (set_cab_controls()) + if (ggConverterButton.SubModel != nullptr && mvOccupied->ConvSwitchType != "impulse" && mvOccupied->ConverterStart == start_t::manual) + { + ggConverterButton.UpdateValue(mvOccupied->ConverterAllow ? 1.f : 0.f, dsbSwitch); + } ggConverterButton.Update(); + if (ggConverterLocalButton.SubModel != nullptr) + { + ggConverterLocalButton.UpdateValue(mvOccupied->ConverterAllowLocal ? 1.f : 0.f, dsbSwitch); + } ggConverterLocalButton.Update(); ggConverterOffButton.Update(); ggTrainHeatingButton.Update(); @@ -11905,9 +11915,9 @@ void TTrain::set_cab_controls(int const Cab) // converter if (mvOccupied->ConvSwitchType != "impulse") { - ggConverterButton.PutValue(mvControlled->ConverterAllow ? 1.f : 0.f); + ggConverterButton.PutValue(mvOccupied->ConverterAllow ? 1.f : 0.f); } - ggConverterLocalButton.PutValue(mvControlled->ConverterAllowLocal ? 1.f : 0.f); + ggConverterLocalButton.PutValue(mvOccupied->ConverterAllowLocal ? 1.f : 0.f); // compressor ggCompressorButton.PutValue(mvControlled->CompressorAllow ? 1.f : 0.f); ggCompressorLocalButton.PutValue(mvControlled->CompressorAllowLocal ? 1.f : 0.f); From 8c8d5ff5cccce5266aa96d40b85d6427cb9181ca Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 06:14:43 +0100 Subject: [PATCH 118/136] Keep the shared log.txt and errors.txt when the run writes its own logs (multiplelogs) (#341) * fix: keep the shared log.txt and errors.txt when the run writes multiplelogs Every start deleted log.txt and errors.txt in the game folder before the settings were read, so a run with multiplelogs (each scenario test) wiped the logs of the player's last ordinary game although it writes its own files in logs/. The shared files are now deleted after the settings, and only without multiplelogs, where the run is about to write them (an errors.txt of an earlier run must still not stay behind a run without errors). The log service keeps what is logged until then, so an early message can't open and empty log.txt before multiplelogs is known. The file names come from one place (utilities/logfiles), covered by unit tests. * refactor(log): the wait for the log file names without Sonar issues The log service skips a pass with an early continue instead of wrapping the writing in an if, so the writing keeps its nesting. No change in behaviour. * fix(log): the node bank preview tool opens its log files after the settings The log service holds every message until OpenLogFiles() is called, and only the game called it. The preview tool kept its whole log in memory and wrote it only at the end, so a crash or a killed run lost it. --- CMakeLists.txt | 1 + application/application.cpp | 18 ++++++++++------ nodebank_previews_standalone.cpp | 2 ++ tests/unit/test_log_files.cpp | 35 ++++++++++++++++++++++++++++++++ utilities/Logs.cpp | 24 +++++++++++++++++++--- utilities/Logs.h | 3 +++ utilities/logfiles.cpp | 26 ++++++++++++++++++++++++ utilities/logfiles.h | 29 ++++++++++++++++++++++++++ 8 files changed, 129 insertions(+), 9 deletions(-) create mode 100644 tests/unit/test_log_files.cpp create mode 100644 utilities/logfiles.cpp create mode 100644 utilities/logfiles.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 9097a57c9..a6504301f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -552,6 +552,7 @@ set(CORE_SOURCES "world/TrackCheck.cpp" "world/SleeperPack.cpp" "McZapkie/Oerlikon_ESt.cpp" +"utilities/logfiles.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" "scene/sn_utils.cpp" diff --git a/application/application.cpp b/application/application.cpp index bc4b7dc1d..25f620766 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -25,6 +25,7 @@ http://mozilla.org/MPL/2.0/. #include "rendering/renderer.h" #include "application/uilayer.h" #include "utilities/Logs.h" +#include "utilities/logfiles.h" #include "world/SleeperWorker.h" #include "rendering/screenshot.h" #include "utilities/translation.h" @@ -403,8 +404,10 @@ int eu07_application::init(int Argc, char *Argv[]) Global.threads.emplace("LogService", std::move(sLoggingService)); init_debug(); + result = init_settings(Argc, Argv); + // the log files are named by the settings (multiplelogs), so they are cleared and opened once those are read init_files(); - if ((result = init_settings(Argc, Argv)) != 0) + if (result != 0) { ErrorLog("Failed to initialize settings! Maybe you're missing eu07.ini file?"); return result; @@ -1262,16 +1265,19 @@ void eu07_application::init_console() void eu07_application::init_files() { - + // without multiplelogs the run writes the shared log.txt / errors.txt, and those of the run before go. with it the + // run writes files of its own in logs/, and the shared ones are left to whoever ran the game last without it + for (auto const &file : stale_log_files(Global.MultipleLogs)) + { + std::error_code error; // not there is fine + std::filesystem::remove(file, error); + } #ifdef _WIN32 - DeleteFile("log.txt"); - DeleteFile("errors.txt"); CreateDirectory("logs", nullptr); #elif __unix__ - unlink("log.txt"); - unlink("errors.txt"); mkdir("logs", 0750); #endif + OpenLogFiles(); } namespace fs = std::filesystem; diff --git a/nodebank_previews_standalone.cpp b/nodebank_previews_standalone.cpp index 65c5e07f3..93fc39732 100644 --- a/nodebank_previews_standalone.cpp +++ b/nodebank_previews_standalone.cpp @@ -287,6 +287,8 @@ int generate_nodebank_previews(int Argc, char *Argv[]) { Global.LoadIniFile("eu07.ini"); } + // the settings are read, so the log service writes as it goes instead of holding everything until it stops + OpenLogFiles(); // the progress goes to the console, the log keeps the details Global.iWriteLogEnabled &= ~2; std::thread logservice(LogService); diff --git a/tests/unit/test_log_files.cpp b/tests/unit/test_log_files.cpp new file mode 100644 index 000000000..8a0aac6f3 --- /dev/null +++ b/tests/unit/test_log_files.cpp @@ -0,0 +1,35 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "utilities/logfiles.h" + +#include + +// the files the log is written to, and which of them a run deletes when it starts + +TEST_CASE("log files: without multiplelogs the run writes the shared log.txt and errors.txt") +{ + CHECK(log_file_name(log_file::log, false, "td", "20261112_1200123") == "log.txt"); + CHECK(log_file_name(log_file::errors, false, "td", "20261112_1200123") == "errors.txt"); +} + +TEST_CASE("log files: with multiplelogs the run writes its own in logs/, named after the scenery and the time") +{ + CHECK(log_file_name(log_file::log, true, "autotest_case", "20261112_1200123") == "logs/log (autotest_case) 20261112_1200123.txt"); + CHECK(log_file_name(log_file::errors, true, "autotest_case", "20261112_1200123") == "logs/errors (autotest_case) 20261112_1200123.txt"); +} + +TEST_CASE("log files: without multiplelogs the start deletes the shared files it is going to write") +{ + // errors.txt is made at the first error only: one of the run before must not stay behind a run without errors + auto const stale{stale_log_files(false)}; + CHECK(stale.size() == 2); + for (auto const kind : {log_file::log, log_file::errors}) + CHECK(std::ranges::count(stale, log_file_name(kind, false, "td", "20261112_1200123")) == 1); +} + +TEST_CASE("log files: with multiplelogs the start keeps the shared log.txt and errors.txt of the last ordinary run") +{ + // the scenario tests run with multiplelogs; the logs of the player's last game in the game folder stay + CHECK(stale_log_files(true).empty()); +} diff --git a/utilities/Logs.cpp b/utilities/Logs.cpp index f4032d808..1b122535d 100644 --- a/utilities/Logs.cpp +++ b/utilities/Logs.cpp @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "utilities/Logs.h" +#include "utilities/logfiles.h" #include "utilities/crashsignals.h" #include @@ -82,6 +83,12 @@ std::atomic &log_stopped() static std::atomic stopped{false}; return stopped; } +// set once the settings are read: the files are named by them (multiplelogs, the scenery) +std::atomic &log_files_open() +{ + static std::atomic open{false}; + return open; +} } // namespace void StopLogService() @@ -89,6 +96,11 @@ void StopLogService() log_stopped() = true; } +void OpenLogFiles() +{ + log_files_open() = true; +} + void LogService() { @@ -96,6 +108,13 @@ void LogService() for (bool last{false}; false == last;) { last = log_stopped(); + // what is logged before the settings are read waits for them, or it would open (and empty) the shared log.txt + // of a run that writes its own files in logs/. a start that stops before that writes it anyway + if (false == log_files_open() && false == last) + { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + continue; + } { // --- Obsługa InfoStack --- while (!InfoStack.empty()) @@ -114,7 +133,7 @@ void LogService() { if (!output.is_open()) { - std::string filename = Global.MultipleLogs ? "logs/log (" + filename_scenery() + ") " + filename_date() + ".txt" : "log.txt"; + std::string const filename { log_file_name(log_file::log, Global.MultipleLogs, filename_scenery(), filename_date()) }; output.open(filename, std::ios::trunc); // the stack of a crash on Linux goes to the end of this file crash_signals::set_log_path(filename); @@ -153,8 +172,7 @@ void LogService() if (!errors.is_open()) { - std::string filename = Global.MultipleLogs ? "logs/errors (" + filename_scenery() + ") " + filename_date() + ".txt" : "errors.txt"; - errors.open(filename, std::ios::trunc); + errors.open(log_file_name(log_file::errors, Global.MultipleLogs, filename_scenery(), filename_date()), std::ios::trunc); errors << "EU07.EXE " + Global.asVersion << "\n"; } diff --git a/utilities/Logs.h b/utilities/Logs.h index 63727de9c..5fd5d4a56 100644 --- a/utilities/Logs.h +++ b/utilities/Logs.h @@ -26,6 +26,9 @@ enum class logtype : unsigned int { // writes the log until StopLogService(), and all of it that came before void LogService(); void StopLogService(); +// the settings are read: the log files can be named and written from now on; until then the log service keeps what +// is logged +void OpenLogFiles(); void WriteLog( const char *str, logtype const Type = logtype::generic, bool isError = false ); void Error( const std::string &asMessage, bool box = false ); void Error( const char* &asMessage, bool box = false ); diff --git a/utilities/logfiles.cpp b/utilities/logfiles.cpp new file mode 100644 index 000000000..7dd9a6745 --- /dev/null +++ b/utilities/logfiles.cpp @@ -0,0 +1,26 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "utilities/logfiles.h" + +#include + +std::string log_file_name(log_file const Kind, bool const MultipleLogs, std::string_view const Scenery, std::string_view const Date) +{ + std::string_view const name{Kind == log_file::errors ? "errors" : "log"}; + return MultipleLogs ? std::format("logs/{} ({}) {}.txt", name, Scenery, Date) : std::format("{}.txt", name); +} + +std::vector stale_log_files(bool const MultipleLogs) +{ + if (MultipleLogs) + return {}; + return {log_file_name(log_file::log, false, {}, {}), log_file_name(log_file::errors, false, {}, {})}; +} diff --git a/utilities/logfiles.h b/utilities/logfiles.h new file mode 100644 index 000000000..7c88ea436 --- /dev/null +++ b/utilities/logfiles.h @@ -0,0 +1,29 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include + +// the files the log is written to, and which of them a run clears when it starts. kept apart from the log service so +// the unit tests can check them + +// the log of everything, and the list of the errors (made at the first error) +enum class log_file { log, errors }; + +// the name of a log file: the shared one in the game folder, or with multiplelogs the run's own in logs/, named after +// the scenery and the time +std::string log_file_name(log_file Kind, bool MultipleLogs, std::string_view Scenery, std::string_view Date); + +// the shared log files a run deletes when it starts: the ones it writes itself, that is without multiplelogs, so an +// errors.txt of an earlier run doesn't stay behind when this one logs no error. with multiplelogs the run writes files +// of its own in logs/, and the log.txt / errors.txt of the last ordinary run are kept +std::vector stale_log_files(bool MultipleLogs); From 4d12693376be848fbc65d230aced581a7258112d Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 06:15:09 +0100 Subject: [PATCH 119/136] AI: say so when standing with the pantographs up and no voltage (#344) * fix(ai): the driver tells of standing with its pantographs up and no voltage An AI driver of an electric vehicle standing past the end of the overhead wire, or under a wire switched off, never gets out of Prepare_engine: the voltage PrepareEngine() waits for doesn't come. It waited without a word (eu07/maszyna#421, L053 poranek with an ET21 on TME222158). Now it says so in the log, once per episode, with the vehicle's name and position, telling a missing wire (no raised pantograph found one) from a wire without voltage. It keeps trying, so towed back under the wire or with the power switched on the vehicle still gets prepared. The decision is ai_power (vehicle/aipower), in the core library with unit tests; scenario case et21_td_no_wire_reports puts an ET21 on a track of its own with no wire next to td.scn. * refactor(ai): the power stall report without Sonar issues stall::none becomes stall::not_stalled (none shadowed a global enumerator), using enum in check(), and an explicit cast of the pantograph count. No change in behaviour. * fix(ai): the power stall report is a traction log line It went out as a generic error, so a scenery that keeps its wire off on purpose couldn't mute it with logs.filter like the other traction lines. --- CMakeLists.txt | 1 + tests/scenarios/README.md | 6 + .../cases/et21_td_no_wire_reports.json | 27 +++++ tests/scenarios/cases/td_no_wire.scn | 18 +++ tests/unit/test_ai_power.cpp | 105 ++++++++++++++++++ vehicle/Driver.cpp | 48 +++++++- vehicle/Driver.h | 4 + vehicle/aipower.cpp | 56 ++++++++++ vehicle/aipower.h | 61 ++++++++++ 9 files changed, 320 insertions(+), 6 deletions(-) create mode 100644 tests/scenarios/cases/et21_td_no_wire_reports.json create mode 100644 tests/scenarios/cases/td_no_wire.scn create mode 100644 tests/unit/test_ai_power.cpp create mode 100644 vehicle/aipower.cpp create mode 100644 vehicle/aipower.h diff --git a/CMakeLists.txt b/CMakeLists.txt index a6504301f..ff27c20e6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -564,6 +564,7 @@ set(CORE_SOURCES "scripting/scriptscreenkernels.cpp" "scripting/scriptscreendrawing.cpp" "simulation/simulationtestrules.cpp" +"vehicle/aipower.cpp" "vehicle/aiwire.cpp" "vehicle/blackbox.cpp" "utilities/physicslog.cpp" diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index 5ddc77dca..d85bd15e9 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -301,6 +301,12 @@ couple and neither shows up: the black box has to have the last car of the stand writes nothing to the log when couplers catch). Nothing reports a result, so both end on the 60 s test timeout. +`et21_td_no_wire_reports` (issue #421, fragment `td_no_wire.scn`) adds a 200 m track of its own, +with no overhead wire, 400 m off the line of td.scn (every track of td.scn is under the wire), with +an ET21 and its AI driver on it. The pantographs go up and find no wire, so the locomotive can't +start: the driver has to say so in the log, once, naming the locomotive and where it stands, and +not mistake it for a wire without voltage. It ends on the standstill. + `eu07_td_cold_connect` (fragment `td_cold_connect.scn`) has an EU07 with a hand brake (`4E-ZEZ_GREY`; the plain `4e` has none) standing cold on track 1 of Stacja1 (trainset velocity 0, so it starts with the hand brake on) and two coaches standing 45 m ahead of it. Its driver sleeps diff --git a/tests/scenarios/cases/et21_td_no_wire_reports.json b/tests/scenarios/cases/et21_td_no_wire_reports.json new file mode 100644 index 000000000..3aeaeecde --- /dev/null +++ b/tests/scenarios/cases/et21_td_no_wire_reports.json @@ -0,0 +1,27 @@ +{ + "description": "ET21 with an AI driver on a track of td.scn's own with no overhead wire: it raises the pantographs, finds no wire and can't start; the driver tells of it in the log, once, and keeps waiting for the voltage (eu07/maszyna#421). The test ends on the standstill.", + "base_scenery": "td.scn", + "fragment": "td_no_wire.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\et21_v2 ET21-367 3e2 0 headdriver 0 0 enddynamic" + }, + "test_config": [ + "test.standstill 300" + ], + "expect": "standstill", + "timeout": 900, + "checks": [ + { + "type": "log_contains", + "pattern": "AI \\[autotest_et21_td_no_wire_reports\\]: can't start, no overhead wire above its raised pantographs \\(at -?[\\d.]+, -?[\\d.]+, -?[\\d.]+\\)" + }, + { + "type": "log_lacks", + "pattern": "no voltage in the overhead wire at its raised pantographs" + }, + { + "type": "distance", + "max": 1 + } + ] +} diff --git a/tests/scenarios/cases/td_no_wire.scn b/tests/scenarios/cases/td_no_wire.scn new file mode 100644 index 000000000..edca73c0b --- /dev/null +++ b/tests/scenarios/cases/td_no_wire.scn @@ -0,0 +1,18 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a piece of track of its own, 200 m long and with no overhead wire above it, 400 m off the line of td.scn +// (all of whose tracks are under the wire), and an electric locomotive with an AI driver standing on it. +// the driver raises the pantographs, which find no wire, and waits in Prepare_engine for the voltage for good +// (eu07/maszyna#421); it tells of it in the log once. +node -1 0 autotest_no_wire track normal 200.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-400.0 0.2 0.0 0.0 //point 1 +0.0 0.0 0.0 //control vector 1 +0.0 0.0 0.0 //control vector 2 +-400.0 0.2 200.0 0.0 //point 2 +0 +endtrack + +// no timetable: the driver goes shunting; 0.01 km/h has it prepare the vehicle and wait for a signal (at 0 it sleeps) +trainset none autotest_no_wire 100.0 0.01 +{{consist}} +endtrainset diff --git a/tests/unit/test_ai_power.cpp b/tests/unit/test_ai_power.cpp new file mode 100644 index 000000000..330f09e0a --- /dev/null +++ b/tests/unit/test_ai_power.cpp @@ -0,0 +1,105 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/aipower.h" + +// the AI driver of an electric vehicle standing with its pantographs up and no voltage at them: what it makes of +// it, and when it tells of it in the log (eu07/maszyna#421) + +namespace { + +using ai_power::stall; + +// standing with the pantographs up, past the end of the overhead wire +ai_power::state past_the_wire() { + ai_power::state state; + state.collector = true; + state.power = false; + state.standing = true; + state.pantographs_up = true; + state.wire = false; + return state; +} + +} // namespace + +TEST_CASE("ai power: standing with the pantographs up and no wire above them is a stall") { + CHECK(ai_power::check(past_the_wire()) == stall::no_wire); +} + +TEST_CASE("ai power: a wire above the raised pantographs which carries no voltage is told apart") { + auto state{past_the_wire()}; + state.wire = true; + + CHECK(ai_power::check(state) == stall::no_voltage); +} + +TEST_CASE("ai power: with the voltage there, or without a pantograph to take it, there is nothing to tell") { + auto powered{past_the_wire()}; + powered.power = true; // at the pantographs, or from the rest of the train through its high voltage cable + auto diesel{past_the_wire()}; + diesel.collector = false; + + CHECK(ai_power::check(powered) == stall::not_stalled); + CHECK(ai_power::check(diesel) == stall::not_stalled); +} + +TEST_CASE("ai power: moving, or the pantographs not up yet, it only waits") { + auto moving{past_the_wire()}; + moving.standing = false; // coasting through a gap of the wire, say + auto rising{past_the_wire()}; + rising.pantographs_up = false; // the air for the pantographs still being pumped up + + CHECK(ai_power::check(moving) == stall::waiting); + CHECK(ai_power::check(rising) == stall::waiting); +} + +TEST_CASE("ai power: a stall is reported once it lasted report_delay, and only once") { + ai_power::reporter reporter; + + CHECK_FALSE(reporter.update(stall::no_wire, 100.0).has_value()); + CHECK_FALSE(reporter.update(stall::no_wire, 100.0 + ai_power::report_delay - 0.5).has_value()); + auto const report{reporter.update(stall::no_wire, 100.0 + ai_power::report_delay)}; + REQUIRE(report.has_value()); + CHECK(*report == stall::no_wire); + // the driver keeps trying to prepare the vehicle, without telling of it again + CHECK_FALSE(reporter.update(stall::no_wire, 100.0 + ai_power::report_delay + 1.0).has_value()); + CHECK_FALSE(reporter.update(stall::no_wire, 1000.0).has_value()); +} + +TEST_CASE("ai power: the voltage coming back ends the stall, the next one is reported again") { + ai_power::reporter reporter; + reporter.update(stall::no_wire, 0.0); + REQUIRE(reporter.update(stall::no_wire, ai_power::report_delay).has_value()); + + // towed back under the wire: the vehicle gets prepared + CHECK_FALSE(reporter.update(stall::not_stalled, 100.0).has_value()); + // and later stands without voltage again, under a wire switched off this time + CHECK_FALSE(reporter.update(stall::no_voltage, 200.0).has_value()); + auto const report{reporter.update(stall::no_voltage, 200.0 + ai_power::report_delay)}; + REQUIRE(report.has_value()); + CHECK(*report == stall::no_voltage); +} + +TEST_CASE("ai power: moving or lowering the pantographs restarts the count but doesn't end a reported stall") { + ai_power::reporter reporter; + reporter.update(stall::no_wire, 0.0); + // the vehicle moves before the stall is reported: the count starts again once it stands + CHECK_FALSE(reporter.update(stall::waiting, 20.0).has_value()); + CHECK_FALSE(reporter.update(stall::no_wire, 25.0).has_value()); + CHECK_FALSE(reporter.update(stall::no_wire, 25.0 + ai_power::report_delay - 1.0).has_value()); + REQUIRE(reporter.update(stall::no_wire, 25.0 + ai_power::report_delay).has_value()); + // still with no voltage, the vehicle moved (pushed a bit) and stands again: no second report + CHECK_FALSE(reporter.update(stall::waiting, 100.0).has_value()); + CHECK_FALSE(reporter.update(stall::no_wire, 110.0).has_value()); + CHECK_FALSE(reporter.update(stall::no_wire, 110.0 + 2.0 * ai_power::report_delay).has_value()); +} + +TEST_CASE("ai power: the report names the vehicle, where it stands and why") { + auto const nowire{ai_power::message(stall::no_wire, "et21-367", {1817.4, 0.38, 4785.94})}; + auto const novoltage{ai_power::message(stall::no_voltage, "et21-367", {1817.4, 0.38, 4785.94})}; + + CHECK(nowire == "AI [et21-367]: can't start, no overhead wire above its raised pantographs (at 1817.40, 0.38, 4785.94); it waits for the voltage"); + CHECK(novoltage.find("no voltage in the overhead wire") != std::string::npos); + CHECK(novoltage.find("et21-367") != std::string::npos); +} diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 0c2568ad3..cba35b68a 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -3248,15 +3248,15 @@ bool TController::PrepareEngine() close_line_breaker(); } + auto const sufficientpantographpressure { ( + is_emu() ? + 2.5 : // Ra 2013-12: Niebugocław mówi, że w EZT podnoszą się przy 2.5 + 3.5 ) + + 0.1 }; // leeway margin + if( mvPantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector && mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 0 ) { // if our pantograph unit isn't a pantograph-devoid fallback - auto const sufficientpantographpressure { ( - is_emu() ? - 2.5 : // Ra 2013-12: Niebugocław mówi, że w EZT podnoszą się przy 2.5 - 3.5 ) - + 0.1 }; // leeway margin - if (mvPantographUnit->PantPress < sufficientpantographpressure) { // załączenie małej sprężarki if( false == mvPantographUnit->PantAutoValve ) { @@ -3286,6 +3286,9 @@ bool TController::PrepareEngine() auto const ispoweravailable = mvControlling->EnginePowerSource.SourceType != TPowerSource::CurrentCollector || std::max(mvControlling->GetTrainsetHighVoltage(), mvControlling->PantographVoltage) > mvControlling->EnginePowerSource.CollectorParameters.MinV; + // standing with the pantographs up and no voltage, nothing the driver does starts the vehicle. it says so, and keeps + // trying: towed back under the wire, or with the power switched on, the vehicle gets prepared after all + report_power_stall( ispoweravailable, sufficientpantographpressure ); bool isready = false; @@ -3372,6 +3375,39 @@ bool TController::PrepareEngine() return iEngineActive; } +// tells in the log, once, of standing with the pantographs up and no voltage at them, past the end of the overhead +// wire or under a wire switched off (eu07/maszyna#421). Poweravailable is what PrepareEngine() found, Pantographpressure +// the air the pantographs need to rise +void +TController::report_power_stall( bool const Poweravailable, double const Pantographpressure ) { + + ai_power::state state; + state.collector = mvControlling->EnginePowerSource.SourceType == TPowerSource::CurrentCollector; + state.power = Poweravailable; + state.standing = mvOccupied->Vel < EU07_AI_NOMOVEMENT; + if( mvPantographUnit->PantPress >= Pantographpressure ) { + state.pantographs_up = + mvPantographUnit->Pantographs[ end::front ].is_active + || mvPantographUnit->Pantographs[ end::rear ].is_active; + } + // the pantographs of the vehicle carrying them hold the wire they found above them + if( auto const *carrier { pVehicle->FindPantographCarrier() }; + carrier != nullptr && carrier->MoverParameters == mvPantographUnit ) { + auto const pantographcount { std::min( carrier->iAnimType[ ANIM_PANTS ], static_cast( carrier->MoverParameters->Pantographs.size() ) ) }; + for( auto index { 0 }; index < pantographcount; ++index ) { + if( true == carrier->MoverParameters->Pantographs[ index ].is_active + && carrier->pants[ index ].fParamPants->hvPowerWire != nullptr ) { + state.wire = true; + } + } + } + // a user driving the vehicle sees the voltmeters for themselves + if( auto const stall { m_powerstall.update( AIControllFlag ? ai_power::check( state ) : ai_power::stall::waiting, ElapsedTime ) }; + stall.has_value() ) { + ErrorLog( ai_power::message( *stall, pVehicle->asName, pVehicle->GetPosition() ), logtype::traction ); + } +} + // wyłączanie silnika (test wyłączenia, a część wykonawcza tylko jeśli steruje komputer) bool TController::ReleaseEngine() { /* diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 87dccd030..b8eb4ec94 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -20,6 +20,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/translation.h" #include "application/driverhints.h" #include "vehicle/blackbox.h" +#include "vehicle/aipower.h" auto const EU07_AI_ACCELERATION = 0.05; auto const EU07_AI_NOACCELERATION = -0.05; @@ -683,6 +684,9 @@ public: bool CheckVehicles( TOrders user = Wait_for_orders ); private: bool PrepareEngine(); + // tells in the log, once, of standing with the pantographs up and no voltage (eu07/maszyna#421) + void report_power_stall( bool const Poweravailable, double const Pantographpressure ); + ai_power::reporter m_powerstall; // the reports of report_power_stall() void close_line_breaker(); bool ReleaseEngine(); void Doors( bool const Open, int const Side = 0 ); diff --git a/vehicle/aipower.cpp b/vehicle/aipower.cpp new file mode 100644 index 000000000..8418d5fe1 --- /dev/null +++ b/vehicle/aipower.cpp @@ -0,0 +1,56 @@ +/* +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/aipower.h" + +#include + +namespace ai_power { + +stall check(state const &State) { + using enum stall; + if (false == State.collector || true == State.power) { + return not_stalled; + } + if (false == State.standing || false == State.pantographs_up) { + return waiting; + } + return State.wire ? no_voltage : no_wire; +} + +std::optional reporter::update(stall const Stall, double const Now) { + if (Stall == stall::not_stalled) { + m_since.reset(); + m_reported = false; + return std::nullopt; + } + if (Stall == stall::waiting) { + m_since.reset(); + return std::nullopt; + } + if (false == m_since.has_value()) { + m_since = Now; + } + if (true == m_reported || Now - *m_since < report_delay) { + return std::nullopt; + } + m_reported = true; + return Stall; +} + +std::string message(stall const Stall, std::string const &Name, glm::dvec3 const &Position) { + auto const reason{ + Stall == stall::no_wire ? + "no overhead wire above its raised pantographs" : + "no voltage in the overhead wire at its raised pantographs"}; + return std::format("AI [{}]: can't start, {} (at {:.2f}, {:.2f}, {:.2f}); it waits for the voltage", Name, reason, Position.x, Position.y, Position.z); +} + +} // namespace ai_power diff --git a/vehicle/aipower.h b/vehicle/aipower.h new file mode 100644 index 000000000..4d822980a --- /dev/null +++ b/vehicle/aipower.h @@ -0,0 +1,61 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include + +#include + +// an AI driver of an electric vehicle standing with its pantographs up and no voltage at them: past the end of the +// overhead wire, or under a wire which is switched off. no driver can start such a vehicle, it waits in +// TController::PrepareEngine() until the voltage comes, towed back under the wire or the power switched on. the +// driver tells of it in the log, once, instead of waiting without a word (eu07/maszyna#421) +namespace ai_power { + +// what the driver knows of the power of the vehicle when it prepares it +struct state { + bool collector{false}; // the vehicle takes its power from the overhead wire + bool power{false}; // there is the voltage the vehicle needs, at its pantographs or from the rest of the train + bool standing{false}; // the vehicle stands + bool pantographs_up{false}; // a pantograph is raised, with the air to hold it up + bool wire{false}; // a raised pantograph found a wire above it +}; + +enum class stall { + not_stalled, // the voltage is there, or the vehicle doesn't take it from the wire + waiting, // no voltage, but nothing to tell yet: the vehicle moves, or its pantographs aren't up + no_wire, // standing with the pantographs up and no wire above them + no_voltage // standing with a pantograph up at a wire which carries no voltage +}; + +stall check(state const &State); + +// how long [s] the vehicle stands with its pantographs up and no voltage before the driver tells of it. the +// pantographs need a few seconds to rise and the voltage a moment to come, a gap under a section insulator is +// shorter still +inline constexpr double report_delay{30.0}; + +// tells of a stall once: one report while it lasts. the voltage coming back ends it, and the next one is reported +// again; moving, or the pantographs going down, only restarts the count of report_delay +class reporter { +public: + // one look at the vehicle at the time Now [s]: the stall to report now, if any + std::optional update(stall Stall, double Now); + +private: + std::optional m_since; // when the vehicle began to stand with the pantographs up and no voltage + bool m_reported{false}; // the stall has been reported +}; + +// the line of the log telling of the stall of the vehicle Name standing at Position +std::string message(stall Stall, std::string const &Name, glm::dvec3 const &Position); + +} // namespace ai_power From dadc3905bac9865040c695c0e8cdf8c47e7d86d7 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 06:15:33 +0100 Subject: [PATCH 120/136] feat(log): the cpu, the memory and the GPUs at startup, with a warning for an integrated GPU (#389) * feat: log the cpu, the memory and the GPUs at startup Bug reports can't tell from log.txt whether the game ran on the integrated GPU of a laptop instead of the dedicated one: it names only GL_RENDERER, GL_VENDOR and the GL version. The exe asks for the dedicated GPU (NvOptimusEnablement, AmdPowerXpressRequestHighPerformance), but the Windows graphics settings, the driver panel or the socket the monitor is plugged into can override that. At startup the log now gets, every line starting with "hardware: ": - the cpu (cpuid brand string, the registry on Windows as a fallback, /proc/cpuinfo on Linux), its cores and threads, and AVX2 support (with a warning when the build needs AVX2 and the cpu has none) - the total and the available memory - on Windows every adapter DXGI lists (description, vendor and device id, dedicated and shared memory, monitors connected, integrated or discrete), the software adapter left out; dxgi.dll is loaded with LoadLibrary, so the game gets no new link dependency - right after the OpenGL context is made, the GPU it runs on and its memory where the driver tells it (GL_NVX_gpu_memory_info, GL_ATI_meminfo) - a warning when OpenGL runs on an integrated GPU while the system has a discrete one, or draws on the cpu (GDI Generic, llvmpipe) Integrated or discrete is told from the vendor and the name, and only when sure (utilities/hardwareinfo.h): NVIDIA is discrete; Intel is integrated except the Arc cards and Iris Xe MAX; AMD is discrete for RX/Pro/VII/FirePro, integrated for the APU names ending in "Graphics", unknown otherwise. An unknown GPU never raises the warning. The rules and the text are in utilities/hardwareinfo.cpp (core library, unit tested); the probing in utilities/hardwareprobe.cpp, called from application.cpp. No renderer file is touched. README.md: the minimum cpu now matches the package readme, 4 cores with AVX2 (Core i5-4430 / Ryzen 3 1200), instead of 2 cores (Core i3-2100, which has no AVX2 the release needs). * refactor(log): the hardware info without Sonar issues using enum for gpu_kind, the ranges algorithms, a reader struct for /proc/cpuinfo instead of a long lambda, explicit captures, cpuid returning a std::array, the adapter list behind a function rather than a mutable global, and uppercase literal suffixes in the test. No change in behaviour. * fix(log): load dxgi.dll from System32 only, cap the GL error drain LoadLibraryW searched the game folder first, so a proxy dxgi.dll left there by ReShade or ENB was loaded at every start just to list the adapters. The loop that clears the GL errors after the memory queries could spin forever on a lost context that keeps reporting one; it now stops after 32. A comment says when the AVX2 warning can be reached. * fix(log): Raven Ridge RX Vega and Panther Lake Arc B3xx are integrated "Radeon RX Vega 11 Graphics" (Ryzen 2400G) and "RX Vega 10 Graphics" (2700U) hit the "rx" card rule before the "ends with Graphics" APU one, and "Arc B390 GPU" / "B370" of Panther Lake looked like an Arc card by the letter and number. Both came out discrete, so the integrated-GPU warning never showed on such a machine. An RX Vega with a number and "Graphics" is now an APU (RX Vega 56 and Vega M of Kaby Lake G stay discrete), and Arc B3xx is integrated (A310, A380, B570, B580 stay cards). --- CMakeLists.txt | 2 + README.md | 2 +- application/application.cpp | 7 + tests/unit/test_hardware_info.cpp | 236 ++++++++++++++++ utilities/hardwareinfo.cpp | 441 ++++++++++++++++++++++++++++++ utilities/hardwareinfo.h | 114 ++++++++ utilities/hardwareprobe.cpp | 336 +++++++++++++++++++++++ utilities/hardwareprobe.h | 22 ++ 8 files changed, 1159 insertions(+), 1 deletion(-) create mode 100644 tests/unit/test_hardware_info.cpp create mode 100644 utilities/hardwareinfo.cpp create mode 100644 utilities/hardwareinfo.h create mode 100644 utilities/hardwareprobe.cpp create mode 100644 utilities/hardwareprobe.h diff --git a/CMakeLists.txt b/CMakeLists.txt index ff27c20e6..3627ef518 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -289,6 +289,7 @@ set(SOURCES "utilities/dictionary.cpp" "rendering/particles.cpp" "utilities/headtrack.cpp" +"utilities/hardwareprobe.cpp" "rendering/geometrybank.cpp" "rendering/openglcolor.cpp" "simulation/simulationsounds.cpp" @@ -555,6 +556,7 @@ set(CORE_SOURCES "utilities/logfiles.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" +"utilities/hardwareinfo.cpp" "scene/sn_utils.cpp" "scene/regionfile.cpp" "utilities/inionlysettings.cpp" diff --git a/README.md b/README.md index f0c7ac3cd..9f607f704 100644 --- a/README.md +++ b/README.md @@ -231,7 +231,7 @@ If detection still fails, padding the file (with comments) up to ~1 MB may hel ## Minimum requirements - OS: **Windows 10 64-bit** -- Processor: **2 core at least 2 GHz (e.g. Intel Core i3-2100 / AMD Athlon II X2)** +- Processor: **4 cores with AVX2 support (e.g. Intel Core i5-4430 / AMD Ryzen 3 1200)** - RAM: **6 GB RAM** - Graphics Card: **supporting OpenGL 3.3 with at least 1GB VRAM** - **150 GB of free disk space** diff --git a/application/application.cpp b/application/application.cpp index 25f620766..0ac02c4fe 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -32,6 +32,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Train.h" #include "utilities/Timer.h" #include "utilities/framepacer.h" +#include "utilities/hardwareprobe.h" #include "utilities/dictionary.h" #include "version_info.h" #include "simulation/simulationtest.h" @@ -448,6 +449,9 @@ int eu07_application::init(int Argc, char *Argv[]) if (Global.NvRenderer) Global.python_threadedupload = false; + // the cpu, the memory and the graphics adapters, for the bug reports + hardware::log_system(); + WriteLog("// startup"); if ((result = init_glfw()) != 0) @@ -1632,6 +1636,9 @@ int eu07_application::init_ogl() } } + // which of the GPUs the context runs on, and its memory + hardware::log_gl_context(); + return 0; } diff --git a/tests/unit/test_hardware_info.cpp b/tests/unit/test_hardware_info.cpp new file mode 100644 index 000000000..73023ca23 --- /dev/null +++ b/tests/unit/test_hardware_info.cpp @@ -0,0 +1,236 @@ +#include "stdafx.h" +#include "doctest.h" +#include "utilities/hardwareinfo.h" + +// what the log says of the machine at startup (utilities/hardwareinfo.h): the names of real GPUs, as DXGI and the +// OpenGL drivers give them, and the text of /proc on Linux +using namespace hardware; + +TEST_CASE("hardware info: NVIDIA GPUs are discrete") +{ + CHECK(classify_gpu(vendor_nvidia, "NVIDIA GeForce RTX 3060") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_nvidia, "NVIDIA GeForce MX150") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_nvidia, "NVIDIA RTX A2000 Laptop GPU") == gpu_kind::discrete); +} + +TEST_CASE("hardware info: Intel GPUs are integrated, except the Arc cards and Iris Xe MAX") +{ + CHECK(classify_gpu(vendor_intel, "Intel(R) UHD Graphics 630") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_intel, "Intel(R) HD Graphics 4600") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_intel, "Intel(R) Iris(R) Xe Graphics") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) Graphics") == gpu_kind::integrated); // Meteor Lake + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) 140V GPU (16GB)") == gpu_kind::integrated); // Lunar Lake + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) B390 GPU") == gpu_kind::integrated); // Panther Lake + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) B370 GPU") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) A310 Graphics") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) A380 Graphics") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) A370M Graphics") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) B570 Graphics") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) A770 Graphics") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) B580 Graphics") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) Pro A60 Graphics") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_intel, "Intel(R) Iris(R) Xe MAX Graphics") == gpu_kind::discrete); +} + +TEST_CASE("hardware info: AMD cards are discrete, the APUs integrated, the rest unknown") +{ + CHECK(classify_gpu(vendor_amd, "AMD Radeon RX 6600") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_amd, "Radeon RX 580 Series") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_amd, "AMD Radeon Pro W6600") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_amd, "AMD Radeon VII") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_amd, "AMD FirePro W5100") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_amd, "AMD Radeon(TM) Graphics") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_amd, "AMD Radeon(TM) Vega 8 Graphics") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_amd, "AMD Radeon 780M Graphics") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_amd, "AMD Radeon(TM) R7 Graphics") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_amd, "AMD Radeon(TM) RX Vega 11 Graphics") == gpu_kind::integrated); // Raven Ridge + CHECK(classify_gpu(vendor_amd, "AMD Radeon(TM) RX Vega 10 Graphics") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_amd, "Radeon RX Vega") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_amd, "AMD Radeon RX Vega 56") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_amd, "Radeon RX Vega M GH Graphics") == gpu_kind::discrete); // Kaby Lake G, own memory + CHECK(classify_gpu(vendor_amd, "AMD Radeon R7 370") == gpu_kind::unknown); + CHECK(classify_gpu(vendor_amd, "AMD Radeon HD 7850") == gpu_kind::unknown); + CHECK(classify_gpu(vendor_amd_alt, "AMD Radeon(TM) Graphics") == gpu_kind::integrated); +} + +TEST_CASE("hardware info: other vendors are unknown, software renderers software") +{ + CHECK(classify_gpu(0x15ad, "VMware SVGA 3D") == gpu_kind::unknown); + CHECK(classify_gpu(0x5143, "Qualcomm(R) Adreno(TM) X1-85 GPU") == gpu_kind::unknown); + CHECK(classify_gpu(vendor_microsoft, "Microsoft Basic Render Driver") == gpu_kind::software); +} + +TEST_CASE("hardware info: the OpenGL vendor and renderer strings") +{ + // Windows drivers + CHECK(vendor_from_gl("NVIDIA Corporation", "NVIDIA GeForce RTX 3060/PCIe/SSE2") == vendor_nvidia); + CHECK(vendor_from_gl("ATI Technologies Inc.", "AMD Radeon RX 6600") == vendor_amd); + CHECK(vendor_from_gl("Intel", "Intel(R) UHD Graphics 630") == vendor_intel); + // Mesa names the maker in the renderer + CHECK(vendor_from_gl("Mesa", "Mesa Intel(R) UHD Graphics 620 (KBL GT2)") == vendor_intel); + CHECK(vendor_from_gl("X.Org", "AMD Radeon Graphics (radeonsi, renoir, LLVM 15.0.7, DRM 3.49)") == vendor_amd); + CHECK(vendor_from_gl("Mesa", "llvmpipe (LLVM 15.0.7, 256 bits)") == 0); + + CHECK(classify_gl("NVIDIA Corporation", "NVIDIA GeForce RTX 3060/PCIe/SSE2") == gpu_kind::discrete); + CHECK(classify_gl("Intel", "Intel(R) UHD Graphics 630") == gpu_kind::integrated); + CHECK(classify_gl("ATI Technologies Inc.", "AMD Radeon(TM) Graphics") == gpu_kind::integrated); + CHECK(classify_gl("X.Org", "AMD Radeon Graphics (radeonsi, renoir, LLVM 15.0.7, DRM 3.49)") == gpu_kind::integrated); + CHECK(classify_gl("AMD", "AMD Radeon RX 6600 (radeonsi, navi23, LLVM 17.0.6, DRM 3.57)") == gpu_kind::discrete); + CHECK(classify_gl("Intel", "Mesa Intel(R) Arc(tm) A770 Graphics (DG2)") == gpu_kind::discrete); + CHECK(classify_gl("Mesa", "llvmpipe (LLVM 15.0.7, 256 bits)") == gpu_kind::software); + CHECK(classify_gl("Microsoft Corporation", "GDI Generic") == gpu_kind::software); + CHECK(classify_gl("nouveau", "NV138") == gpu_kind::unknown); +} + +namespace { +gpu_adapter adapter(std::string Description, std::uint32_t const VendorId, bool const Software = false) +{ + gpu_adapter result; + result.description = std::move(Description); + result.vendor_id = VendorId; + result.software = Software; + return result; +} +} // namespace + +TEST_CASE("hardware info: a warning when OpenGL runs on the integrated GPU beside a dedicated one") +{ + std::vector const laptop{adapter("Intel(R) UHD Graphics 630", vendor_intel), adapter("NVIDIA GeForce GTX 1650", vendor_nvidia)}; + + auto const warnings{gl_warnings(laptop, "Intel", "Intel(R) UHD Graphics 630")}; + REQUIRE(warnings.size() == 1); + CHECK(warnings.front().starts_with("hardware: warning: ")); + CHECK(warnings.front().find("Intel(R) UHD Graphics 630") != std::string::npos); + CHECK(warnings.front().find("NVIDIA GeForce GTX 1650") != std::string::npos); + + // on the dedicated one all is well + CHECK(gl_warnings(laptop, "NVIDIA Corporation", "NVIDIA GeForce GTX 1650/PCIe/SSE2").empty()); + // a desktop with the integrated GPU only, or a GPU that can't be told, says nothing + CHECK(gl_warnings({adapter("Intel(R) UHD Graphics 630", vendor_intel)}, "Intel", "Intel(R) UHD Graphics 630").empty()); + CHECK(gl_warnings({adapter("AMD Radeon HD 7850", vendor_amd), adapter("Intel(R) HD Graphics 4600", vendor_intel)}, "Intel", "Intel(R) HD Graphics 4600").empty()); + // Linux lists no adapters + CHECK(gl_warnings({}, "Intel", "Mesa Intel(R) UHD Graphics 620 (KBL GT2)").empty()); + // an AMD APU beside an AMD card + CHECK(gl_warnings({adapter("AMD Radeon(TM) Graphics", vendor_amd), adapter("AMD Radeon RX 6600M", vendor_amd)}, "ATI Technologies Inc.", "AMD Radeon(TM) Graphics").size() == 1); + // a Ryzen 2400G with the monitor on the motherboard beside a GeForce, a Panther Lake laptop running GL on the B390 + CHECK(gl_warnings({adapter("AMD Radeon(TM) RX Vega 11 Graphics", vendor_amd), adapter("NVIDIA GeForce GTX 1650", vendor_nvidia)}, "ATI Technologies Inc.", "AMD Radeon(TM) RX Vega 11 Graphics").size() == 1); + CHECK(gl_warnings({adapter("Intel(R) Arc(TM) B390 GPU", vendor_intel), adapter("NVIDIA GeForce RTX 5060 Laptop GPU", vendor_nvidia)}, "Intel", "Intel(R) Arc(TM) B390 GPU").size() == 1); +} + +TEST_CASE("hardware info: a warning when OpenGL draws on the cpu") +{ + auto const warnings{gl_warnings({adapter("NVIDIA GeForce GTX 1650", vendor_nvidia)}, "Microsoft Corporation", "GDI Generic")}; + REQUIRE(warnings.size() == 1); + CHECK(warnings.front().find("GDI Generic") != std::string::npos); +} + +TEST_CASE("hardware info: a warning for a cpu without AVX2 only when the build needs it") +{ + cpu_info cpu; + cpu.avx2 = 0; + CHECK(cpu_warnings(cpu, true).size() == 1); + CHECK(cpu_warnings(cpu, false).empty()); + cpu.avx2 = 1; + CHECK(cpu_warnings(cpu, true).empty()); + cpu.avx2 = -1; // can't tell: no warning + CHECK(cpu_warnings(cpu, true).empty()); +} + +TEST_CASE("hardware info: sizes") +{ + CHECK(format_size(0) == "0 MiB"); + CHECK(format_size(128ULL * 1024 * 1024) == "128 MiB"); + CHECK(format_size(1023ULL * 1024 * 1024) == "1023 MiB"); + CHECK(format_size(1024ULL * 1024 * 1024) == "1.0 GiB"); + CHECK(format_size(12ULL * 1024 * 1024 * 1024) == "12.0 GiB"); + CHECK(format_size(17'058'000'000ULL) == "15.9 GiB"); +} + +TEST_CASE("hardware info: names") +{ + CHECK(tidy_name(" Intel(R) Core(TM) i5-4430 CPU @ 3.00GHz") == "Intel(R) Core(TM) i5-4430 CPU @ 3.00GHz"); + CHECK(tidy_name("AMD Ryzen 5 5600X 6-Core Processor ") == "AMD Ryzen 5 5600X 6-Core Processor"); + CHECK(tidy_name("") == ""); +} + +TEST_CASE("hardware info: /proc/cpuinfo") +{ + // two cores with two threads each, one package; the flags of the first processor count + auto const cpu{parse_cpuinfo("processor\t: 0\n" + "model name\t: Intel(R) Core(TM) i3-7100U CPU @ 2.40GHz\n" + "physical id\t: 0\n" + "core id\t\t: 0\n" + "cpu cores\t: 2\n" + "flags\t\t: fpu vme sse sse2 avx avx2 bmi2\n" + "\n" + "processor\t: 1\n" + "model name\t: Intel(R) Core(TM) i3-7100U CPU @ 2.40GHz\n" + "physical id\t: 0\n" + "core id\t\t: 1\n" + "\n" + "processor\t: 2\n" + "physical id\t: 0\n" + "core id\t\t: 0\n" + "\n" + "processor\t: 3\n" + "physical id\t: 0\n" + "core id\t\t: 1\n")}; + CHECK(cpu.model == "Intel(R) Core(TM) i3-7100U CPU @ 2.40GHz"); + CHECK(cpu.logical_cores == 4); + CHECK(cpu.physical_cores == 2); + CHECK(cpu.avx2 == 1); + + // no core ids (some virtual machines): the cores of the package; no avx2 in the flags + auto const vm{parse_cpuinfo("processor : 0\nmodel name : Some CPU\ncpu cores : 4\nflags : sse sse2 avx\n")}; + CHECK(vm.physical_cores == 4); + CHECK(vm.avx2 == 0); + + // nothing known + auto const empty{parse_cpuinfo("")}; + CHECK(empty.model.empty()); + CHECK(empty.logical_cores == 0); + CHECK(empty.physical_cores == 0); + CHECK(empty.avx2 == -1); +} + +TEST_CASE("hardware info: /proc/meminfo") +{ + auto const memory{parse_meminfo("MemTotal: 16303064 kB\nMemFree: 1234567 kB\nMemAvailable: 8151532 kB\n")}; + CHECK(memory.total == 16303064ULL * 1024); + CHECK(memory.available == 8151532ULL * 1024); + CHECK(parse_meminfo("").total == 0); +} + +TEST_CASE("hardware info: the lines of the log") +{ + cpu_info cpu; + cpu.model = "AMD Ryzen 5 5600X 6-Core Processor"; + cpu.physical_cores = 6; + cpu.logical_cores = 12; + cpu.avx2 = 1; + CHECK(format_cpu(cpu) == "hardware: cpu: AMD Ryzen 5 5600X 6-Core Processor, 6 cores, 12 threads, avx2 yes"); + CHECK(format_cpu(cpu_info{}) == "hardware: cpu: unknown, avx2 unknown"); + + memory_info memory; + memory.total = 16ULL * 1024 * 1024 * 1024; + memory.available = 7ULL * 1024 * 1024 * 1024; + CHECK(format_memory(memory) == "hardware: ram: 16.0 GiB total, 7.0 GiB available"); + CHECK(format_memory(memory_info{}) == "hardware: ram: unknown total"); + + gpu_adapter gpu{adapter("NVIDIA GeForce GTX 1650", vendor_nvidia)}; + gpu.device_id = 0x1f82; + gpu.dedicated_video_memory = 4ULL * 1024 * 1024 * 1024; + gpu.shared_system_memory = 8ULL * 1024 * 1024 * 1024; + gpu.outputs = 1; + CHECK(format_adapter(1, gpu) == "hardware: gpu 1: NVIDIA GeForce GTX 1650 (vendor 0x10de, device 0x1f82), 4.0 GiB dedicated, 8.0 GiB shared, 1 outputs, discrete"); + + CHECK(format_gl("Intel", "Intel(R) UHD Graphics 630") == "hardware: opengl gpu: Intel(R) UHD Graphics 630 (Intel), integrated"); + + gl_memory_info gl; + gl.dedicated = 4ULL * 1024 * 1024 * 1024; + gl.available = 3ULL * 1024 * 1024 * 1024; + CHECK(format_gl_memory(gl) == "hardware: opengl gpu memory: 4.0 GiB dedicated, 3.0 GiB free"); + gl.dedicated = 0; + CHECK(format_gl_memory(gl) == "hardware: opengl gpu memory: 3.0 GiB free"); + CHECK(format_gl_memory(gl_memory_info{}) == "hardware: opengl gpu memory: unknown"); +} diff --git a/utilities/hardwareinfo.cpp b/utilities/hardwareinfo.cpp new file mode 100644 index 000000000..3124307ba --- /dev/null +++ b/utilities/hardwareinfo.cpp @@ -0,0 +1,441 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "utilities/hardwareinfo.h" + +#include +#include +#include +#include +#include + +namespace hardware { + +namespace { + +std::string lowercase(std::string_view Text) +{ + std::string result{Text}; + for (auto &c : result) + c = static_cast(std::tolower(static_cast(c))); + return result; +} + +bool contains(std::string_view Text, std::string_view What) +{ + return Text.find(What) != std::string_view::npos; +} + +void erase_all(std::string &Text, std::string_view What) +{ + auto at = Text.find(What); + while (at != std::string::npos) + { + Text.erase(at, What.size()); + at = Text.find(What, at); + } +} + +// the words of a GPU name, lowercase: without the (TM) and (R) marks, and without what follows them in parentheses +// (Mesa adds the driver and the chip: "AMD Radeon Graphics (radeonsi, renoir, LLVM 15.0.7)") +std::vector name_words(std::string_view Name) +{ + auto name{lowercase(Name)}; + erase_all(name, "(tm)"); + erase_all(name, "(r)"); + if (auto const parenthesis = name.find('('); parenthesis != std::string::npos) + name.erase(parenthesis); + std::vector words; + std::string word; + for (auto const c : name) + { + if (std::isalnum(static_cast(c))) + { + word += c; + } + else if (!word.empty()) + { + words.push_back(std::move(word)); + word.clear(); + } + } + if (!word.empty()) + words.push_back(std::move(word)); + return words; +} + +// whether the words hold First directly followed by Second +bool has_pair(std::vector const &Words, std::string_view First, std::string_view Second) +{ + for (std::size_t i = 0; i + 1 < Words.size(); ++i) + if (Words[i] == First && Words[i + 1] == Second) + return true; + return false; +} + +bool has_word(std::vector const &Words, std::string_view What) +{ + return std::ranges::find(Words, What) != Words.end(); +} + +bool is_number(std::string_view Word) +{ + return !Word.empty() && std::ranges::all_of(Word, [](char const c) { return std::isdigit(static_cast(c)) != 0; }); +} + +bool is_software_name(std::string_view Name) +{ + constexpr std::array markers{"llvmpipe", "softpipe", "swiftshader", "gdi generic", "software rasterizer", "basic render driver"}; + auto const name{lowercase(Name)}; + return std::ranges::any_of(markers, [&name](std::string_view const Marker) { return contains(name, Marker); }); +} + +gpu_kind classify_intel(std::vector const &Words) +{ + using enum gpu_kind; + // Iris Xe MAX (DG1) is a laptop card + for (std::size_t i = 0; i + 2 < Words.size(); ++i) + if (Words[i] == "iris" && Words[i + 1] == "xe" && Words[i + 2] == "max") + return discrete; + // the Arc cards have a letter and a number after "Arc" (A310, A770, B580) or are the Pro ones; the integrated Arc + // are "Arc Graphics" (Meteor Lake), "Arc 140V" (Lunar Lake) and "Arc B370", "Arc B390" (Panther Lake), the B3xx + // range, below the B570 and B580 cards + for (std::size_t i = 0; i + 1 < Words.size(); ++i) + { + if (Words[i] != "arc") + continue; + auto const &model{Words[i + 1]}; + if (model == "pro") + return discrete; + if (model.size() >= 2 && model[0] == 'b' && model[1] == '3') + return integrated; + if (model.size() >= 2 && std::isalpha(static_cast(model[0])) && std::isdigit(static_cast(model[1]))) + return discrete; + } + return integrated; +} + +// Raven Ridge and Picasso APUs: "Radeon RX Vega 11 Graphics", "Radeon RX Vega 10 Graphics". the RX Vega cards have +// no "Graphics" ("Radeon RX Vega 56"), and Kaby Lake G's own-memory chip has a letter ("Radeon RX Vega M GH Graphics") +bool is_rx_vega_apu(std::vector const &Words) +{ + if (Words.empty() || Words.back() != "graphics") + return false; + for (std::size_t i = 0; i + 2 < Words.size(); ++i) + if (Words[i] == "rx" && Words[i + 1] == "vega" && is_number(Words[i + 2])) + return true; + return false; +} + +gpu_kind classify_amd(std::vector const &Words) +{ + using enum gpu_kind; + if (is_rx_vega_apu(Words)) + return integrated; + if (has_word(Words, "rx") || has_word(Words, "firepro") || has_word(Words, "instinct") || has_pair(Words, "radeon", "pro") || has_pair(Words, "radeon", "vii")) + return discrete; + // the APUs are "Radeon Graphics", "Radeon Vega 8 Graphics", "Radeon R7 Graphics", "Radeon 780M Graphics"; the + // cards are named by their model ("Radeon RX 580 Series", "Radeon R7 370") + if (!Words.empty() && Words.back() == "graphics") + return integrated; + return unknown; +} + +std::string_view yes_no(int const Value) +{ + if (Value > 0) + return "yes"; + if (Value == 0) + return "no"; + return "unknown"; +} + +// "Key: value" of /proc/cpuinfo and /proc/meminfo +std::pair split_entry(std::string_view Line) +{ + auto const colon = Line.find(':'); + if (colon == std::string_view::npos) + return {}; + auto key{Line.substr(0, colon)}; + auto value{Line.substr(colon + 1)}; + while (!key.empty() && std::isspace(static_cast(key.back()))) + key.remove_suffix(1); + while (!value.empty() && std::isspace(static_cast(value.front()))) + value.remove_prefix(1); + while (!value.empty() && std::isspace(static_cast(value.back()))) + value.remove_suffix(1); + return {key, value}; +} + +template void for_each_line(std::string_view Text, Function &&Each) +{ + while (!Text.empty()) + { + auto const end = Text.find('\n'); + Each(Text.substr(0, end)); + if (end == std::string_view::npos) + break; + Text.remove_prefix(end + 1); + } +} + +std::uint64_t to_number(std::string_view Text) +{ + std::uint64_t result{0}; + for (auto const c : Text) + { + if (!std::isdigit(static_cast(c))) + break; + result = result * 10 + static_cast(c - '0'); + } + return result; +} + +// the state of reading /proc/cpuinfo, line by line +struct cpuinfo_reader +{ + cpu_info cpu; + std::set> cores; // (physical id, core id) + std::set> packages; + int cores_per_package{0}; + std::string package; + + void read(std::string_view Line); +}; + +void cpuinfo_reader::read(std::string_view const Line) +{ + auto const [key, value] = split_entry(Line); + if (key == "processor") + { + ++cpu.logical_cores; + package.clear(); + } + else if ((key == "model name" || key == "Model") && cpu.model.empty()) + { + cpu.model = tidy_name(value); + } + else if (key == "physical id") + { + package = value; + packages.emplace(value); + } + else if (key == "core id") + { + cores.emplace(package, value); + } + else if (key == "cpu cores" && cores_per_package == 0) + { + cores_per_package = static_cast(to_number(value)); + } + else if (key == "flags" && cpu.avx2 < 0) + { + auto const flags{name_words(value)}; + cpu.avx2 = has_word(flags, "avx2") ? 1 : 0; + } +} + +} // namespace + +std::string_view to_string(gpu_kind const Kind) +{ + using enum gpu_kind; + switch (Kind) + { + case integrated: + return "integrated"; + case discrete: + return "discrete"; + case software: + return "software"; + default: + return "unknown"; + } +} + +gpu_kind classify_gpu(std::uint32_t const VendorId, std::string_view const Name) +{ + using enum gpu_kind; + if (is_software_name(Name)) + return software; + auto const words{name_words(Name)}; + switch (VendorId) + { + case vendor_nvidia: + return discrete; + case vendor_intel: + return classify_intel(words); + case vendor_amd: + case vendor_amd_alt: + return classify_amd(words); + default: + return unknown; + } +} + +std::uint32_t vendor_from_gl(std::string_view const GlVendor, std::string_view const GlRenderer) +{ + // the vendor first; Mesa ("Mesa", "X.Org", "Collabora Ltd") and the D3D12 layer ("Microsoft Corporation") name + // the maker of the chip in the renderer + for (auto const &text : {lowercase(GlVendor), lowercase(GlRenderer)}) + { + if (contains(text, "nvidia") || contains(text, "geforce") || contains(text, "quadro")) + return vendor_nvidia; + if (contains(text, "ati technologies") || contains(text, "advanced micro devices") || contains(text, "radeon") || has_word(name_words(text), "amd")) + return vendor_amd; + if (contains(text, "intel")) + return vendor_intel; + } + return 0; +} + +bool is_software_gl(std::string_view const GlVendor, std::string_view const GlRenderer) +{ + return is_software_name(GlRenderer) || is_software_name(GlVendor); +} + +gpu_kind classify_gl(std::string_view const GlVendor, std::string_view const GlRenderer) +{ + if (is_software_gl(GlVendor, GlRenderer)) + return gpu_kind::software; + return classify_gpu(vendor_from_gl(GlVendor, GlRenderer), GlRenderer); +} + +std::string format_size(std::uint64_t const Bytes) +{ + constexpr std::uint64_t mebibyte{1024 * 1024}; + constexpr std::uint64_t gibibyte{1024 * mebibyte}; + if (Bytes < gibibyte) + return std::format("{} MiB", (Bytes + mebibyte / 2) / mebibyte); + return std::format("{:.1f} GiB", static_cast(Bytes) / static_cast(gibibyte)); +} + +std::string tidy_name(std::string_view const Name) +{ + std::string result; + for (auto const c : Name) + { + if (c == '\0') + break; + if (std::isspace(static_cast(c))) + { + if (!result.empty() && result.back() != ' ') + result += ' '; + continue; + } + result += c; + } + if (!result.empty() && result.back() == ' ') + result.pop_back(); + return result; +} + +cpu_info parse_cpuinfo(std::string_view const Text) +{ + cpuinfo_reader reader; + for_each_line(Text, [&reader](std::string_view const Line) { reader.read(Line); }); + auto cpu{std::move(reader.cpu)}; + if (!reader.cores.empty()) + cpu.physical_cores = static_cast(reader.cores.size()); + else if (reader.cores_per_package > 0) + cpu.physical_cores = reader.cores_per_package * static_cast(std::max(reader.packages.size(), 1)); + return cpu; +} + +memory_info parse_meminfo(std::string_view const Text) +{ + memory_info memory; + for_each_line(Text, [&memory](std::string_view const Line) { + auto const [key, value] = split_entry(Line); + // the values are in kB (kibibytes, whatever the unit says) + if (key == "MemTotal") + memory.total = to_number(value) * 1024; + else if (key == "MemAvailable") + memory.available = to_number(value) * 1024; + }); + return memory; +} + +std::string format_cpu(cpu_info const &Cpu) +{ + auto line{std::format("hardware: cpu: {}", Cpu.model.empty() ? std::string{"unknown"} : Cpu.model)}; + if (Cpu.physical_cores > 0) + line += std::format(", {} cores", Cpu.physical_cores); + if (Cpu.logical_cores > 0) + line += std::format(", {} threads", Cpu.logical_cores); + line += std::format(", avx2 {}", yes_no(Cpu.avx2)); + return line; +} + +std::string format_memory(memory_info const &Memory) +{ + auto line{std::format("hardware: ram: {} total", Memory.total > 0 ? format_size(Memory.total) : std::string{"unknown"})}; + if (Memory.available > 0) + line += std::format(", {} available", format_size(Memory.available)); + return line; +} + +std::string format_adapter(int const Index, gpu_adapter const &Adapter) +{ + return std::format("hardware: gpu {}: {} (vendor 0x{:04x}, device 0x{:04x}), {} dedicated, {} shared, {} outputs, {}", Index, Adapter.description, Adapter.vendor_id, Adapter.device_id, + format_size(Adapter.dedicated_video_memory), format_size(Adapter.shared_system_memory), Adapter.outputs, + Adapter.software ? to_string(gpu_kind::software) : to_string(classify_gpu(Adapter.vendor_id, Adapter.description))); +} + +std::string format_gl(std::string_view const GlVendor, std::string_view const GlRenderer) +{ + return std::format("hardware: opengl gpu: {} ({}), {}", GlRenderer, GlVendor, to_string(classify_gl(GlVendor, GlRenderer))); +} + +std::string format_gl_memory(gl_memory_info const &Memory) +{ + std::string line{"hardware: opengl gpu memory:"}; + if (Memory.dedicated > 0) + line += std::format(" {} dedicated", format_size(Memory.dedicated)); + if (Memory.available > 0) + line += std::format("{} {} free", Memory.dedicated > 0 ? "," : "", format_size(Memory.available)); + if (Memory.dedicated == 0 && Memory.available == 0) + line += " unknown"; + return line; +} + +std::vector gl_warnings(std::vector const &Adapters, std::string_view const GlVendor, std::string_view const GlRenderer) +{ + std::vector warnings; + auto const kind{classify_gl(GlVendor, GlRenderer)}; + if (kind == gpu_kind::software) + { + warnings.push_back(std::format("hardware: warning: OpenGL draws on the cpu ({}), the graphics driver is missing or not used", GlRenderer)); + return warnings; + } + if (kind != gpu_kind::integrated) + return warnings; + if (auto const discrete = std::ranges::find_if(Adapters, [](gpu_adapter const &Adapter) { + return !Adapter.software && classify_gpu(Adapter.vendor_id, Adapter.description) == gpu_kind::discrete; + }); + discrete != Adapters.end()) + { + warnings.push_back(std::format("hardware: warning: OpenGL runs on the integrated GPU ({}) though there is a dedicated one ({}); " + "choose High performance for the game in the Windows graphics settings or the GPU control panel, " + "and connect the monitor to the dedicated GPU", + GlRenderer, discrete->description)); + } + return warnings; +} + +std::vector cpu_warnings(cpu_info const &Cpu, bool const BuildNeedsAvx2) +{ + std::vector warnings; + if (BuildNeedsAvx2 && Cpu.avx2 == 0) + warnings.emplace_back("hardware: warning: the cpu has no AVX2, which this build of the game needs"); + return warnings; +} + +} // namespace hardware diff --git a/utilities/hardwareinfo.h b/utilities/hardwareinfo.h new file mode 100644 index 000000000..54fdbd02d --- /dev/null +++ b/utilities/hardwareinfo.h @@ -0,0 +1,114 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include +#include + +// what the log says about the machine at startup: the cpu, the memory, the graphics adapters and the one OpenGL runs +// on. a bug report then shows whether the game ran on the integrated GPU of a laptop instead of the dedicated one. +// this part holds the rules and the text, which need nothing of the machine; the probing is in hardwareprobe.cpp +namespace hardware { + +// the PCI vendor ids of the graphics adapters +constexpr std::uint32_t vendor_nvidia{0x10de}; +constexpr std::uint32_t vendor_amd{0x1002}; +constexpr std::uint32_t vendor_amd_alt{0x1022}; // AMD's cpu id, shown by some APUs +constexpr std::uint32_t vendor_intel{0x8086}; +constexpr std::uint32_t vendor_microsoft{0x1414}; // Microsoft Basic Render Driver, the software adapter + +enum class gpu_kind { + unknown, // can't tell from the name; never taken for either of the other two + integrated, // part of the cpu, shares the system memory + discrete, // a card (or a chip) with its own memory + software, // drawn by the cpu (Microsoft Basic Render Driver, GDI Generic, llvmpipe) +}; + +std::string_view to_string(gpu_kind Kind); + +// whether a GPU is integrated or discrete, from its vendor and its name (the DXGI description or GL_RENDERER). +// conservative, by the names the vendors give their chips: +// - NVIDIA: discrete (PC NVIDIA graphics have been cards or laptop chips with their own memory since the nForce days) +// - Intel: discrete only for the Arc cards (Arc A380/A770/B580, Arc Pro A60) and Iris Xe MAX; the rest (HD, UHD, +// Iris, Arc Graphics, Arc 140V and Arc B370/B390 of Meteor/Lunar/Panther Lake) is integrated +// - AMD: discrete for Radeon RX/Pro/VII, FirePro and Instinct; integrated for the APU names, which have no model +// number before "Graphics" (Radeon(TM) Graphics, Radeon Vega 8 Graphics, Radeon 780M Graphics, Radeon 8060S +// Graphics), and Radeon RX Vega 11 Graphics of Raven Ridge; anything else (an old Radeon HD, R7 ...) is unknown, as +// both cards and APUs were named so +// - software renderers are software; any other vendor (virtual machines, Qualcomm) is unknown +gpu_kind classify_gpu(std::uint32_t VendorId, std::string_view Name); + +// the PCI vendor id behind the GL_VENDOR and GL_RENDERER strings (Mesa names the vendor in the renderer); 0 if none +std::uint32_t vendor_from_gl(std::string_view GlVendor, std::string_view GlRenderer); + +// whether GL_VENDOR and GL_RENDERER name a renderer that draws on the cpu +bool is_software_gl(std::string_view GlVendor, std::string_view GlRenderer); + +// the kind of the GPU an OpenGL context runs on +gpu_kind classify_gl(std::string_view GlVendor, std::string_view GlRenderer); + +// a graphics adapter of the system (on Windows, as DXGI lists it) +struct gpu_adapter { + std::string description; + std::uint32_t vendor_id{0}; + std::uint32_t device_id{0}; + std::uint64_t dedicated_video_memory{0}; // bytes + std::uint64_t shared_system_memory{0}; // bytes + int outputs{0}; // the monitors connected to it + bool software{false}; +}; + +struct cpu_info { + std::string model; + int logical_cores{0}; // 0: unknown + int physical_cores{0}; // 0: unknown + int avx2{-1}; // 1 yes, 0 no, -1 unknown +}; + +struct memory_info { + std::uint64_t total{0}; // bytes, 0: unknown + std::uint64_t available{0}; // bytes, 0: unknown +}; + +// what the context's driver says of its memory (GL_NVX_gpu_memory_info, GL_ATI_meminfo), in bytes, 0: not told +struct gl_memory_info { + std::uint64_t dedicated{0}; + std::uint64_t available{0}; +}; + +// a size for a person to read: "512 MiB", "7.9 GiB" +std::string format_size(std::uint64_t Bytes); + +// trims the padding cpuid and the registry leave in the cpu brand string, squeezes the runs of spaces +std::string tidy_name(std::string_view Name); + +// what /proc/cpuinfo says of the cpu: the model name, the processors (logical cores) and the distinct cores +cpu_info parse_cpuinfo(std::string_view Text); + +// what /proc/meminfo says of the memory: MemTotal and MemAvailable +memory_info parse_meminfo(std::string_view Text); + +// the lines of the log, every one starting with "hardware: " so a single grep finds them all +std::string format_cpu(cpu_info const &Cpu); +std::string format_memory(memory_info const &Memory); +std::string format_adapter(int Index, gpu_adapter const &Adapter); +std::string format_gl(std::string_view GlVendor, std::string_view GlRenderer); +std::string format_gl_memory(gl_memory_info const &Memory); + +// the warnings of the log about the GPU OpenGL runs on: on the cpu, or on an integrated GPU while the system has a +// discrete one (Adapters: as the system lists them; the software ones are passed over). nothing if all is well +std::vector gl_warnings(std::vector const &Adapters, std::string_view GlVendor, std::string_view GlRenderer); + +// the warning of the log about a cpu without AVX2 when the build needs it. nothing if all is well +std::vector cpu_warnings(cpu_info const &Cpu, bool BuildNeedsAvx2); + +} // namespace hardware diff --git a/utilities/hardwareprobe.cpp b/utilities/hardwareprobe.cpp new file mode 100644 index 000000000..b7574281b --- /dev/null +++ b/utilities/hardwareprobe.cpp @@ -0,0 +1,336 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "utilities/hardwareprobe.h" + +#include "utilities/hardwareinfo.h" +#include "utilities/Logs.h" + +#include +#include + +#if defined(_M_X64) || defined(_M_IX86) || defined(__x86_64__) || defined(__i386__) +#define EU07_HARDWARE_X86 1 +#ifdef _MSC_VER +#include +#else +#include +#endif +#endif + +#ifdef _WIN32 +#include +#endif + +namespace hardware { + +namespace { + +// the adapters log_system() found, for the warning of log_gl_context() +std::vector &system_adapters() +{ + static std::vector adapters; + return adapters; +} + +#ifdef EU07_HARDWARE_X86 +// the eax, ebx, ecx and edx the cpuid instruction gives for the provided leaf and subleaf +std::array cpuid(unsigned int const Leaf, unsigned int const Subleaf) +{ + std::array result{}; +#ifdef _MSC_VER + std::array registers{}; + __cpuidex(registers.data(), static_cast(Leaf), static_cast(Subleaf)); + for (std::size_t i = 0; i < result.size(); ++i) + result[i] = static_cast(registers[i]); +#else + __cpuid_count(Leaf, Subleaf, result[0], result[1], result[2], result[3]); +#endif + return result; +} + +// the brand string of the cpu ("AMD Ryzen 5 5600X 6-Core Processor"); empty if the cpu has none +std::string cpu_brand() +{ + if (cpuid(0x80000000u, 0)[0] < 0x80000004u) + return {}; + std::array brand{}; + for (unsigned int leaf = 0; leaf < 3; ++leaf) + { + auto const registers{cpuid(0x80000002u + leaf, 0)}; + std::memcpy(brand.data() + leaf * 16, registers.data(), 16); + } + return tidy_name(brand.data()); +} + +// whether the cpu has AVX2 and the system saves the AVX registers +int cpu_avx2() +{ +#ifdef _MSC_VER + if (cpuid(0, 0)[0] < 7) + return 0; + auto const features{cpuid(1, 0)}; + auto const osxsave{(features[2] & (1u << 27)) != 0}; + auto const avx{(features[2] & (1u << 28)) != 0}; + if (!osxsave || !avx) + return 0; + if ((_xgetbv(0) & 0x6) != 0x6) // the system saves xmm and ymm + return 0; + return (cpuid(7, 0)[1] & (1u << 5)) != 0 ? 1 : 0; +#else + // checks the system's support as well + __builtin_cpu_init(); + return __builtin_cpu_supports("avx2") ? 1 : 0; +#endif +} +#endif + +#ifdef _WIN32 +std::string narrow(wchar_t const *Text) +{ + auto const length{WideCharToMultiByte(CP_UTF8, 0, Text, -1, nullptr, 0, nullptr, nullptr)}; + if (length <= 1) + return {}; + std::string result(static_cast(length - 1), '\0'); + WideCharToMultiByte(CP_UTF8, 0, Text, -1, result.data(), length, nullptr, nullptr); + return result; +} + +std::string registry_cpu_name() +{ + char name[256]{}; + DWORD size{sizeof(name)}; + if (RegGetValueA(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", "ProcessorNameString", RRF_RT_REG_SZ, nullptr, name, &size) != ERROR_SUCCESS) + return {}; + return tidy_name(name); +} + +int physical_cores() +{ + DWORD length{0}; + GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &length); + if (length == 0) + return 0; + std::vector buffer(length); + auto *records{reinterpret_cast(buffer.data())}; + if (!GetLogicalProcessorInformationEx(RelationProcessorCore, records, &length)) + return 0; + int cores{0}; + for (DWORD offset = 0; offset < length;) + { + auto const *record{reinterpret_cast(buffer.data() + offset)}; + if (record->Size == 0) + break; + ++cores; + offset += record->Size; + } + return cores; +} + +cpu_info probe_cpu() +{ + cpu_info cpu; +#ifdef EU07_HARDWARE_X86 + cpu.model = cpu_brand(); + cpu.avx2 = cpu_avx2(); +#endif + if (cpu.model.empty()) + cpu.model = registry_cpu_name(); + cpu.logical_cores = static_cast(GetActiveProcessorCount(ALL_PROCESSOR_GROUPS)); + cpu.physical_cores = physical_cores(); + return cpu; +} + +memory_info probe_memory() +{ + memory_info memory; + MEMORYSTATUSEX status{}; + status.dwLength = sizeof(status); + if (GlobalMemoryStatusEx(&status)) + { + memory.total = status.ullTotalPhys; + memory.available = status.ullAvailPhys; + } + return memory; +} + +// the adapters DXGI lists, the software one left out. dxgi.dll is loaded only for this, so the game doesn't link it; +// from System32 only, so a proxy dxgi.dll left in the game folder (ReShade, ENB) isn't loaded with it +std::vector probe_adapters() +{ + std::vector adapters; + auto *library{LoadLibraryExW(L"dxgi.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32)}; + if (library == nullptr) + { + WriteLog("hardware: gpus: dxgi.dll not found"); + return adapters; + } + using create_factory = HRESULT(WINAPI *)(REFIID, void **); + auto const create{reinterpret_cast(reinterpret_cast(GetProcAddress(library, "CreateDXGIFactory1")))}; + IDXGIFactory1 *factory{nullptr}; + if (create == nullptr || FAILED(create(__uuidof(IDXGIFactory1), reinterpret_cast(&factory))) || factory == nullptr) + { + WriteLog("hardware: gpus: can't create a DXGI factory"); + FreeLibrary(library); + return adapters; + } + IDXGIAdapter1 *adapter{nullptr}; + for (UINT index = 0; SUCCEEDED(factory->EnumAdapters1(index, &adapter)); ++index) + { + DXGI_ADAPTER_DESC1 description{}; + if (SUCCEEDED(adapter->GetDesc1(&description))) + { + gpu_adapter entry; + entry.description = tidy_name(narrow(description.Description)); + entry.vendor_id = description.VendorId; + entry.device_id = description.DeviceId; + entry.dedicated_video_memory = description.DedicatedVideoMemory; + entry.shared_system_memory = description.SharedSystemMemory; + entry.software = (description.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) != 0 || description.VendorId == vendor_microsoft; + IDXGIOutput *output{nullptr}; + while (SUCCEEDED(adapter->EnumOutputs(static_cast(entry.outputs), &output))) + { + output->Release(); + ++entry.outputs; + } + if (!entry.software) + adapters.push_back(std::move(entry)); + } + adapter->Release(); + } + factory->Release(); + FreeLibrary(library); + return adapters; +} +#else +std::string read_file(char const *Path) +{ + std::ifstream file{Path}; + if (!file) + return {}; + std::stringstream text; + text << file.rdbuf(); + return text.str(); +} + +cpu_info probe_cpu() +{ + auto cpu{parse_cpuinfo(read_file("/proc/cpuinfo"))}; +#ifdef EU07_HARDWARE_X86 + if (cpu.model.empty()) + cpu.model = cpu_brand(); + cpu.avx2 = cpu_avx2(); +#endif + if (cpu.logical_cores == 0) + cpu.logical_cores = static_cast(std::thread::hardware_concurrency()); + return cpu; +} + +memory_info probe_memory() +{ + return parse_meminfo(read_file("/proc/meminfo")); +} +#endif + +std::string gl_string(GLenum const Name) +{ + auto const *text{reinterpret_cast(glGetString(Name))}; + return text != nullptr ? std::string{text} : std::string{"unknown"}; +} + +bool has_gl_extension(std::string_view const Name) +{ + if (glGetStringi != nullptr) + { + GLint count{0}; + glGetIntegerv(GL_NUM_EXTENSIONS, &count); + for (GLint i = 0; i < count; ++i) + { + auto const *extension{reinterpret_cast(glGetStringi(GL_EXTENSIONS, static_cast(i)))}; + if (extension != nullptr && Name == extension) + return true; + } + return false; + } + // OpenGL ES 2: one string of them all + auto const *extensions{reinterpret_cast(glGetString(GL_EXTENSIONS))}; + return extensions != nullptr && std::string_view{extensions}.find(Name) != std::string_view::npos; +} + +gl_memory_info probe_gl_memory() +{ + // GL_NVX_gpu_memory_info and GL_ATI_meminfo tokens, in kilobytes + constexpr GLenum gpu_memory_info_dedicated_vidmem_nvx{0x9047}; + constexpr GLenum gpu_memory_info_current_available_vidmem_nvx{0x9049}; + constexpr GLenum texture_free_memory_ati{0x87fc}; + + gl_memory_info memory; + if (has_gl_extension("GL_NVX_gpu_memory_info")) + { + GLint kilobytes{0}; + glGetIntegerv(gpu_memory_info_dedicated_vidmem_nvx, &kilobytes); + memory.dedicated = static_cast(std::max(kilobytes, 0)) * 1024; + kilobytes = 0; + glGetIntegerv(gpu_memory_info_current_available_vidmem_nvx, &kilobytes); + memory.available = static_cast(std::max(kilobytes, 0)) * 1024; + } + else if (has_gl_extension("GL_ATI_meminfo")) + { + // the free memory of the texture pool, the largest free block, and the same of the auxiliary memory + std::array kilobytes{}; + glGetIntegerv(texture_free_memory_ati, kilobytes.data()); + memory.available = static_cast(std::max(kilobytes[0], 0)) * 1024; + } + // a driver that takes the queries amiss leaves an error the renderer would report as its own. each call takes one + // error off; a lost context may keep reporting one, hence the limit + constexpr int max_errors{32}; + for (int i = 0; i < max_errors && glGetError() != GL_NO_ERROR; ++i) + { + // nothing else to do + } + return memory; +} + +} // namespace + +void log_system() +{ + auto const cpu{probe_cpu()}; + WriteLog(format_cpu(cpu)); + // an AVX2 build on a cpu without it may die on an illegal instruction before this line; when it gets here (the + // start so far ran without an AVX2 or FMA instruction), the line names the cause of the crash that comes later +#ifdef __AVX2__ + constexpr bool build_needs_avx2{true}; +#else + constexpr bool build_needs_avx2{false}; +#endif + for (auto const &warning : cpu_warnings(cpu, build_needs_avx2)) + WriteLog(warning); + WriteLog(format_memory(probe_memory())); +#ifdef _WIN32 + auto &adapters{system_adapters()}; + adapters = probe_adapters(); + for (std::size_t index = 0; index < adapters.size(); ++index) + WriteLog(format_adapter(static_cast(index), adapters[index])); +#endif +} + +void log_gl_context() +{ + auto const vendor{gl_string(GL_VENDOR)}; + auto const renderer{gl_string(GL_RENDERER)}; + WriteLog(format_gl(vendor, renderer)); + if (auto const memory{probe_gl_memory()}; memory.dedicated > 0 || memory.available > 0) + WriteLog(format_gl_memory(memory)); + for (auto const &warning : gl_warnings(system_adapters(), vendor, renderer)) + WriteLog(warning); +} + +} // namespace hardware diff --git a/utilities/hardwareprobe.h b/utilities/hardwareprobe.h new file mode 100644 index 000000000..75cb1e405 --- /dev/null +++ b/utilities/hardwareprobe.h @@ -0,0 +1,22 @@ +/* +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 + +// writes the machine to the log at startup, every line starting with "hardware: " (see hardwareinfo.h) +namespace hardware { + +// the cpu, the memory and, on Windows, the graphics adapters DXGI lists +void log_system(); + +// the GPU the current OpenGL context runs on, its memory where the driver tells it, and a warning when it's the +// integrated GPU while the system has a dedicated one. after log_system(), with the context current +void log_gl_context(); + +} // namespace hardware From dc9e1b2ebd1c54f93cb3131b349b6a27ddebc655 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 06:16:08 +0100 Subject: [PATCH 121/136] test(scenarios): AI through a section without voltage and with interlocked line contactors (#272, #276) (#467) * test(scenarios): AI through a section without voltage and with interlocked line contactors Scenario cases for the parts of #272 (line breaker ahead of the pantographs, PantRequiresMain) and #276 (line contactors interlocked with the vehicle's own converter, LineContactorsInterlock) that had not been run in the simulator before. They all run the AI on the timetable run of td.scn. - ep05_td_dead_section: an EP05 runs under power into a 61 m span of overhead wire that has no voltage. Its line breaker stays closed, the traction force drops to 0, and behind the span the AI takes power again and stops at Przystanek. eu07_td_dead_section is the same run with an EU07, as a reference for the old behaviour: its line breaker opens after 0.2 s and the AI closes it again. - ep05_td_neutral_section: the same span, with the track under it marked overhead 0. The AI coasts from before the dead wire. - ep05_td_section_insulator: a 1 m section insulator, run under power. The 0.2 s voltage hold keeps the traction force up past it. - et42_td_converter_interlock(_cold): an ET42 with the interlock starts up and runs its timetable. - ep05_td_interlock_dead_section_cold: both keys on one EP05, starting cold, with the dead span on its way. - ep05_td_timetable: the plain timetable run of the EP05, as a reference. The runner gets vehicle_variants, a vehicle of the case's own made from one of the game's with .fiz replacements. The game's ET42 data doesn't have the interlock key yet. The runner also gets two new checks: traction (the traction force between two distances travelled) and master_controller. The local converter switch of #276 can't be covered: only the cab can set it, and in test mode nobody sits in a cab. * test(scenarios): the ET42 interlock case that fails without the interlock The ET42 interlock cases checked only that the AI gets the train going, which a plain ET42 does too. A case with a converter that starts 60 s after it is switched on shows the interlock taking effect: the train reaches 20 km/h at 80.0 s with it and at 73.8 s without it, and the starts check gets an optional lower bound, after, to fail the early one. The runner also checks the case's expect and --watch before it writes anything into the game folder, and builds the scenery inside the try that removes the case's files, so an exit or Ctrl+C there leaves none. --- tests/scenarios/README.md | 62 ++++++++- .../scenarios/cases/ep05_td_dead_section.json | 22 +++ .../ep05_td_interlock_dead_section_cold.json | 28 ++++ .../cases/ep05_td_neutral_section.json | 26 ++++ .../cases/ep05_td_section_insulator.json | 21 +++ tests/scenarios/cases/ep05_td_timetable.json | 17 +++ .../cases/et42_td_converter_interlock.json | 24 ++++ .../et42_td_converter_interlock_cold.json | 27 ++++ ...td_converter_interlock_slow_converter.json | 27 ++++ .../scenarios/cases/eu07_td_dead_section.json | 22 +++ tests/scenarios/run.py | 129 +++++++++++++++--- 11 files changed, 388 insertions(+), 17 deletions(-) create mode 100644 tests/scenarios/cases/ep05_td_dead_section.json create mode 100644 tests/scenarios/cases/ep05_td_interlock_dead_section_cold.json create mode 100644 tests/scenarios/cases/ep05_td_neutral_section.json create mode 100644 tests/scenarios/cases/ep05_td_section_insulator.json create mode 100644 tests/scenarios/cases/ep05_td_timetable.json create mode 100644 tests/scenarios/cases/et42_td_converter_interlock.json create mode 100644 tests/scenarios/cases/et42_td_converter_interlock_cold.json create mode 100644 tests/scenarios/cases/et42_td_converter_interlock_slow_converter.json create mode 100644 tests/scenarios/cases/eu07_td_dead_section.json diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index d85bd15e9..e021bb398 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -215,6 +215,7 @@ to `logs/`. | `fragment` | `.scn` file in `cases/` added to the scenery: trainsets after `FirstInit` (before it they derail on unlinked track), the rest before it (launchers read after it never fire). Optional when the case keeps the scenery's trainsets | | `vars` | values for `{{name}}` in the fragment; a list becomes one line per item | | `timetable` | a timetable file in `cases/` for a trainset of the fragment, for a train whose timetable no scenery of the game has: copied to the game's `scenery/` dir as `autotest_.txt` for the run and removed after it; the fragment names it `{{timetable}}` | +| `vehicle_variants` | vehicles of the case's own, made from those of the game, e.g. with a `.fiz` key the game's data doesn't have yet: a list of `{ "name": ..., "from": "/", "replace": [[old, new], ...] }`. For the run the vehicle's `.fiz`, with the literal replacements (an `old` it doesn't have is an error), and its `.mmd` are copied beside it in the game's `dynamic/` dir as `autotest__` and removed after it; the fragment names the type `{{variant_}}`, e.g. `dynamic pkp/et42_v2 112e-014-a {{variant_a}} ...`. The copy of the `.mmd` has the name of the vehicle it is made from in place of `(p2)`, the type name the simulator hands it, which some pass on to the include that names the model | | `expect` | the result the test mode should end with: `pass`, `fail`, `signal_passed_at_danger`, `timeout`, `standstill` or `error`, or `wall_timeout` for the timeout of the real time watchdog (the timeout code with a verdict saying it was the real time; a case expecting `timeout` fails on it). Default `timeout` for a case with `duration`, else `pass` | | `duration` | seconds of simulation to record: the test timeout of the run (`--test-timeout`) | | `timeout` | wall-clock seconds before giving up, loading included: the simulator's `--test-wall-timeout` (default 600) | @@ -396,6 +397,57 @@ working it stops at 0.57 m/s², 99 m: that is `eu07_td_reinspect_brakes_legacy_i of the earlier releases (`ai.brakesetting.cw1 no`), which cuts no brake out, and also what a build whose `reinspect_brakes()` does nothing gives for the first case, which then fails. The test passes 150 s after the driver goes. +The `*_section*` and `*_converter_interlock*` cases are about the line breaker closed ahead of the pantographs +(`PantRequiresMain=Yes` in `Cntrl.`, MaSzyna-EU07/maszyna#272) and the line contactors that wait for the +converter of their own vehicle (`LineContactorsInterlock=Converter`, #276), driven by the AI on the timetable +run of td.scn. The overhead wire of td.scn is changed with `replace`: one span of it, 61 m some 400 m from +the start (`0.7764 5.845 1561.2417` onwards, over the way out of Stacja1, which the train runs under power at +50-55 km/h), gets no supply and 0 V (`traction none 0`), and in `ep05_td_section_insulator` the span before +it is split around a section insulator 1 m long (`traction * 0`, as sceneries hang insulators). The EP05 has +`PantRequiresMain=Yes` in the game's data; the ET42 has no `LineContactorsInterlock` yet (SVN data of #276), +so those cases run variants of the vehicles made for the run (`vehicle_variants`). + +- `ep05_td_timetable`: the EP05 on the plain timetable run, the reference: 20 km/h after 73 s, the stop + after 205 s and 1400 m. +- `ep05_td_dead_section`: the EP05 runs into the span without voltage under power, nothing on the track + telling its driver to coast. The traction force drops to nothing at once and the AI puts the master + controller to 0; the line breaker stays closed (the log + says the vehicle lost power for 4.05 s, which it says only while the line breaker is closed). Behind the + section the AI takes power again (535 m, 36 kN by 595 m) and stops at Przystanek (1399 m). +- `ep05_td_neutral_section`: the same with the track under that span, `koniec`, marked as one to coast + through (`overhead 0`, which `track_events` adds as it adds events): the AI puts the master controller to + 0 as the locomotive runs onto it, 25 m ahead of the dead wire, and takes power again behind it. +- `eu07_td_dead_section`: the old behaviour for reference, an EU07 (pantographs first) into the same span: + its line breaker opens after 0.2 s (`lost power for 0.21 sec`, no longer), and behind the section the AI + closes it again and takes power (493 m). +- `ep05_td_section_insulator`: the EP05 runs under the insulator under power at 50 km/h. The pantograph is + without voltage for some 0.07 s, which the vehicle bridges by holding the last voltage for 0.2 s + (`TDynamicObject::Update`): the traction force stays between 50 and 58 kN past it and nothing is logged. + Without the hold the undervoltage relay of a `PantRequiresMain` vehicle would open the line contactors, + which close again only with the master controller back at its first position. With the insulator 15 m long + instead (a trial run) the vehicle does lose power there (logged, the force drops to 0), which shows the + pantograph runs under the piece of wire. +- `et42_td_converter_interlock_cold`: an ET42 with `LineContactorsInterlock=Converter` in both sections + stands cold (`td_cold_timetable.scn`) and is ordered to run the timetable: the AI starts the converters, + leaves (20 km/h after 74 s) and stops at Przystanek (1393 m). It and `et42_td_converter_interlock`, the + same from the timetable start, check that the AI gets such a train going; a plain ET42 passes them too. +- `et42_td_converter_interlock_slow_converter`: the check that the interlock takes effect. The same cold ET42 + with a converter that starts 60 s after it is switched on (`ConverterStartDelay=60`): the line contactors + wait for it, and the train reaches 20 km/h at 80.0 s; `starts` with `after: 77` fails it earlier. With the + same converter and no interlock it gets there at 73.8 s, as fast as without the slow converter (a copy of + the case without the key, run once, not kept). +- `ep05_td_interlock_dead_section_cold`: #272 and #276 together, an EP05 with `LineContactorsInterlock=Converter` + added, standing cold, with the span without voltage on its way: the pantographs can go up only through the + closed line breaker, so the AI has to close it first, then start the converter; it leaves (20 km/h after + 77 s). Under the dead wire the converter stops with the main circuit, behind it the converter starts again + and the AI takes power (573 m, 4 s later than the EP05 without the interlock) and stops at Przystanek + (1393 m). + +What these can't reach: the local converter switch of the ET42 (`converterlocal_sw:`), which the AI has to put +back on (`LineContactorsHeldByLocalConverterSwitch()`, the part of #276 in `determine_consist_state()` and +the `converteron` hint), is in the cab only: no command of a scenery or of the train's cables sets +`ConverterAllowLocal`, and nobody sits in a cab in the test mode, so the switch is always on in a case. + ### Cases on a mission of a scenery The cases made from players' reports (eu07/maszyna#421, #506, #524, #525) run a whole mission @@ -450,7 +502,8 @@ the physicslog Velocity column, which is the wheel speed: it stays at 0 while th locked in a skid. The ones marked *vehicle speed* use the vehicle speed column at the end of the row instead, logged by builds from this branch on. -- `starts` `min_speed`, `within`: reaches `min_speed` within `within` seconds. +- `starts` `min_speed`, `within` (`after`): reaches `min_speed` within `within` seconds (and not before `after` seconds, + when given). - `max_speed` `limit`, `tolerance`: never goes faster than `limit + tolerance`. - `brakes` `min_pressure`: after moving off, brake cylinder pressure reaches `min_pressure` bar (physicslog pressures are in bar whatever its header says; the brake pipe runs at 5.0). @@ -497,6 +550,13 @@ the row instead, logged by builds from this branch on. cut out stops slower. - `moves` `vehicle`, `min_speed`, optional `direction` (`front`, or `rear`): the black box has the vehicle reach `min_speed` with that end leading (the physicslog speed has no direction). +- `traction` `from_distance`, `to_distance`, and one or more of `reaches`, `at_most`, `at_least`: the + traction force in kN (the physicslog has it in N, whatever its header says) while the vehicle runs between + the two distances (metres travelled, as in `distance`): its highest there reaches `reaches`, e.g. the power + taken again behind a section without voltage; it stays at or below `at_most`, e.g. none under a dead wire; + it stays at or above `at_least`, e.g. no power lost under an insulator. +- `master_controller` `from_distance`, `to_distance`, `at_most`: the master controller stays at or below the + position between the two distances, e.g. at 0 where the scenery tells the driver to coast. 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 diff --git a/tests/scenarios/cases/ep05_td_dead_section.json b/tests/scenarios/cases/ep05_td_dead_section.json new file mode 100644 index 000000000..d6bfe2c49 --- /dev/null +++ b/tests/scenarios/cases/ep05_td_dead_section.json @@ -0,0 +1,22 @@ +{ + "description": "#272: an EP05 (PantRequiresMain=Yes: its line breaker closes ahead of the pantographs and holds without voltage) runs the td/rozklad timetable of td.scn with one span of the overhead wire on its way, 61 m some 400 m from the start, left without voltage, and nothing on the track to tell the driver to coast. The AI runs into it under power: the line breaker stays closed (the log keeps saying the vehicle lost power, which it says only while the line breaker is closed), the traction force drops to nothing and the AI puts the master controller to 0; behind the section the AI takes power again and stops at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/ep05_v2 ep05-23 ep05 0 headdriver 0 0 enddynamic" + }, + "replace": [ + ["node -1 0 none traction pwr01 3500 4500 0.01 cu 3.0 1\r\n0.7764 5.845 1561.2417", "node -1 0 none traction none 0 4500 0.01 cu 3.0 1\r\n0.7764 5.845 1561.2417"] + ], + "duration": 240, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "traction", "from_distance": 420, "to_distance": 455, "at_most": 1}, + {"type": "traction", "from_distance": 460, "to_distance": 620, "reaches": 25}, + {"type": "log_contains", "pattern": "lost power for [3-9]\\.\\d\\d sec"}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/ep05_td_interlock_dead_section_cold.json b/tests/scenarios/cases/ep05_td_interlock_dead_section_cold.json new file mode 100644 index 000000000..4cccc94f5 --- /dev/null +++ b/tests/scenarios/cases/ep05_td_interlock_dead_section_cold.json @@ -0,0 +1,28 @@ +{ + "description": "#272 with #276: an EP05 whose line breaker closes ahead of the pantographs (PantRequiresMain=Yes) and whose line contactors close only with its own converter running (LineContactorsInterlock=Converter, a variant of the .fiz made for the run) stands cold on track 1 of Stacja1 and gets the order to run the td/rozklad timetable, with the span without voltage of ep05_td_dead_section on its way. The pantographs go up only through the closed line breaker, so the AI has to close it first, then start the converter, and leave; under the dead wire the main circuit, and with it the converter, has no voltage; behind it the AI takes power again and stops at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_cold_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/ep05_v2 ep05-23 {{variant_ep05}} 0 headdriver 0 0 enddynamic" + }, + "vehicle_variants": [ + {"name": "ep05", "from": "pkp/ep05_v2/ep05", "replace": [["Camshaft=Yes PantRequiresMain=Yes", "Camshaft=Yes PantRequiresMain=Yes LineContactorsInterlock=Converter"]]} + ], + "replace": [ + ["node -1 0 none traction pwr01 3500 4500 0.01 cu 3.0 1\r\n0.7764 5.845 1561.2417", "node -1 0 none traction none 0 4500 0.01 cu 3.0 1\r\n0.7764 5.845 1561.2417"] + ], + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "duration": 300, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "traction", "from_distance": 420, "to_distance": 455, "at_most": 1}, + {"type": "traction", "from_distance": 460, "to_distance": 620, "reaches": 25}, + {"type": "log_contains", "pattern": "lost power for [3-9]\\.\\d\\d sec"}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/ep05_td_neutral_section.json b/tests/scenarios/cases/ep05_td_neutral_section.json new file mode 100644 index 000000000..ea261b0b7 --- /dev/null +++ b/tests/scenarios/cases/ep05_td_neutral_section.json @@ -0,0 +1,26 @@ +{ + "description": "#272: as ep05_td_dead_section, with the track under the span without voltage (koniec, 371-466 m) marked as a section to coast through (overhead 0), as a scenery marks a neutral section: the AI puts the master controller to zero when the locomotive runs onto that track, coasts under the dead wire with the line breaker closed, and takes power again behind it.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/ep05_v2 ep05-23 ep05 0 headdriver 0 0 enddynamic" + }, + "replace": [ + ["node -1 0 none traction pwr01 3500 4500 0.01 cu 3.0 1\r\n0.7764 5.845 1561.2417", "node -1 0 none traction none 0 4500 0.01 cu 3.0 1\r\n0.7764 5.845 1561.2417"] + ], + "track_events": { + "koniec": "overhead 0" + }, + "duration": 240, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "master_controller", "from_distance": 395, "to_distance": 455, "at_most": 0}, + {"type": "traction", "from_distance": 415, "to_distance": 455, "at_most": 1}, + {"type": "traction", "from_distance": 470, "to_distance": 640, "reaches": 25}, + {"type": "log_contains", "pattern": "lost power for [3-9]\\.\\d\\d sec"}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/ep05_td_section_insulator.json b/tests/scenarios/cases/ep05_td_section_insulator.json new file mode 100644 index 000000000..2490bcf9b --- /dev/null +++ b/tests/scenarios/cases/ep05_td_section_insulator.json @@ -0,0 +1,21 @@ +{ + "description": "#272: the EP05 of ep05_td_timetable runs under power under a section insulator: a piece of the overhead wire 1 m long with no supply (\"*\", 0 V), some 375 m from the start. The pantograph is without voltage for a few hundredths of a second, which the vehicle bridges by holding the last voltage for 0.2 s (TDynamicObject::Update). Without the hold the undervoltage relay would open the line contactors, which on a PantRequiresMain vehicle close again only with the master controller back at its first position: the traction force stays up all the way past the insulator.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/ep05_v2 ep05-23 ep05 0 headdriver 0 0 enddynamic" + }, + "replace": [ + ["node -1 0 none traction pwr01 3500 4500 0.01 cu 3.0 1\r\n0.687223 5.8 1500.25\r\n0.7764 5.845 1561.2417\r\n0.687223 7.5 1500.25\r\n0.7764 7.545 1561.2417\r\n0.4 4.0 3 0.04 vis\r\nendtraction", "node -1 0 none traction pwr01 3500 4500 0.01 cu 3.0 1\r\n0.687223 5.8 1500.25\r\n0.7457 5.8295 1540.2499\r\n0.687223 7.5 1500.25\r\n0.7457 7.5295 1540.2499\r\n0.4 4.0 3 0.04 vis\r\nendtraction\r\nnode -1 0 none traction * 0 4500 0.01 cu 3.0 1\r\n0.7457 5.8295 1540.2499\r\n0.7472 5.8302 1541.2499\r\n0.7457 7.5295 1540.2499\r\n0.7472 7.5302 1541.2499\r\n0.4 4.0 3 0.04 vis\r\nendtraction\r\nnode -1 0 none traction pwr01 3500 4500 0.01 cu 3.0 1\r\n0.7472 5.8302 1541.2499\r\n0.7764 5.845 1561.2417\r\n0.7472 7.5302 1541.2499\r\n0.7764 7.545 1561.2417\r\n0.4 4.0 3 0.04 vis\r\nendtraction"] + ], + "duration": 240, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "traction", "from_distance": 345, "to_distance": 395, "at_least": 30}, + {"type": "log_lacks", "pattern": "lost power"}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/ep05_td_timetable.json b/tests/scenarios/cases/ep05_td_timetable.json new file mode 100644 index 000000000..4291cdb72 --- /dev/null +++ b/tests/scenarios/cases/ep05_td_timetable.json @@ -0,0 +1,17 @@ +{ + "description": "EP05 (PantRequiresMain=Yes) on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek. The reference run of the ep05_td_*_section cases, with the overhead wire live all the way.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/ep05_v2 ep05-23 ep05 0 headdriver 0 0 enddynamic" + }, + "duration": 240, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "brakes", "min_pressure": 0.5}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/et42_td_converter_interlock.json b/tests/scenarios/cases/et42_td_converter_interlock.json new file mode 100644 index 000000000..35d78a4f4 --- /dev/null +++ b/tests/scenarios/cases/et42_td_converter_interlock.json @@ -0,0 +1,24 @@ +{ + "description": "#276: as et42_td_converter_interlock_cold, from the timetable start (trainset velocity 0.1, the locomotive ready to go).", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp/et42_v2 112e-014-a {{variant_a}} 0 headdriver 255 0 enddynamic", + "node -1 0 {{vehicle}}_b dynamic pkp/et42_v2 112e-014-b {{variant_b}} 0 nobody 3 0 enddynamic" + ] + }, + "vehicle_variants": [ + {"name": "a", "from": "pkp/et42_v2/112e-a", "replace": [["IniCDelay=0.5 SCDelay=0.1", "IniCDelay=0.5 SCDelay=0.1 LineContactorsInterlock=Converter"]]}, + {"name": "b", "from": "pkp/et42_v2/112e-b", "replace": [["IniCDelay=0.5 SCDelay=0.1", "IniCDelay=0.5 SCDelay=0.1 LineContactorsInterlock=Converter"]]} + ], + "duration": 240, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "brakes", "min_pressure": 0.5}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/et42_td_converter_interlock_cold.json b/tests/scenarios/cases/et42_td_converter_interlock_cold.json new file mode 100644 index 000000000..f8dfdff56 --- /dev/null +++ b/tests/scenarios/cases/et42_td_converter_interlock_cold.json @@ -0,0 +1,27 @@ +{ + "description": "#276: an ET42 whose sections take power only with their own converter running (LineContactorsInterlock=Converter in Cntrl., the .fiz key the shipped et42_v2 doesn't have yet: a variant of both sections made for the run) stands cold on track 1 of Stacja1 on td.scn and gets the order to run the td/rozklad timetable. The AI has to start the converters before the line contactors close: it leaves, keeps to the speed limit and stops at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_cold_timetable.scn", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp/et42_v2 112e-014-a {{variant_a}} 0 headdriver 255 0 enddynamic", + "node -1 0 {{vehicle}}_b dynamic pkp/et42_v2 112e-014-b {{variant_b}} 0 nobody 3 0 enddynamic" + ] + }, + "vehicle_variants": [ + {"name": "a", "from": "pkp/et42_v2/112e-a", "replace": [["IniCDelay=0.5 SCDelay=0.1", "IniCDelay=0.5 SCDelay=0.1 LineContactorsInterlock=Converter"]]}, + {"name": "b", "from": "pkp/et42_v2/112e-b", "replace": [["IniCDelay=0.5 SCDelay=0.1", "IniCDelay=0.5 SCDelay=0.1 LineContactorsInterlock=Converter"]]} + ], + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "duration": 300, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "brakes", "min_pressure": 0.5}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/et42_td_converter_interlock_slow_converter.json b/tests/scenarios/cases/et42_td_converter_interlock_slow_converter.json new file mode 100644 index 000000000..d492aa671 --- /dev/null +++ b/tests/scenarios/cases/et42_td_converter_interlock_slow_converter.json @@ -0,0 +1,27 @@ +{ + "description": "#276, the check that the interlock takes effect: the ET42 of et42_td_converter_interlock_cold, with ConverterStartDelay=60 added to both sections, so the converters need a minute to start. With LineContactorsInterlock=Converter the line contactors wait for them and the train leaves later than it does with the same converter delay and no interlock (20 km/h at 80.0 s with it, at 73.8 s without it, measured with this case and a copy without the interlock key). Then it runs the timetable to Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_cold_timetable.scn", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp/et42_v2 112e-014-a {{variant_a}} 0 headdriver 255 0 enddynamic", + "node -1 0 {{vehicle}}_b dynamic pkp/et42_v2 112e-014-b {{variant_b}} 0 nobody 3 0 enddynamic" + ] + }, + "vehicle_variants": [ + {"name": "a", "from": "pkp/et42_v2/112e-a", "replace": [["IniCDelay=0.5 SCDelay=0.1", "IniCDelay=0.5 SCDelay=0.1 LineContactorsInterlock=Converter ConverterStartDelay=60"]]}, + {"name": "b", "from": "pkp/et42_v2/112e-b", "replace": [["IniCDelay=0.5 SCDelay=0.1", "IniCDelay=0.5 SCDelay=0.1 LineContactorsInterlock=Converter ConverterStartDelay=60"]]} + ], + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "duration": 300, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "after": 77, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "brakes", "min_pressure": 0.5}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/eu07_td_dead_section.json b/tests/scenarios/cases/eu07_td_dead_section.json new file mode 100644 index 000000000..44c4c38f5 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_dead_section.json @@ -0,0 +1,22 @@ +{ + "description": "The reference of ep05_td_dead_section: an EU07, whose pantographs come first and whose line breaker opens without voltage (no PantRequiresMain), runs into the same span without voltage under power. Its line breaker opens 0.2 s into the section (the log says it lost power for 0.2x s, no longer: it says so only while the line breaker is closed), and behind it the AI closes the line breaker again, takes power and stops at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "replace": [ + ["node -1 0 none traction pwr01 3500 4500 0.01 cu 3.0 1\r\n0.7764 5.845 1561.2417", "node -1 0 none traction none 0 4500 0.01 cu 3.0 1\r\n0.7764 5.845 1561.2417"] + ], + "duration": 240, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "log_contains", "pattern": "lost power for 0\\.2\\d sec"}, + {"type": "log_lacks", "pattern": "lost power for (0\\.[3-9]|[1-9])"}, + {"type": "traction", "from_distance": 460, "to_distance": 700, "reaches": 25}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py index 2dcec6f0d..fef87c4f3 100644 --- a/tests/scenarios/run.py +++ b/tests/scenarios/run.py @@ -49,7 +49,9 @@ OUT_DIR = HERE / "out" # Velocity is in km/h and pressures in bar, despite the header saying m/s and MPa. COL_TIME = 0 COL_VELOCITY = 1 # wheel speed: stays at 0 while the wheels are locked in a skid +COL_TRACTION_FORCE = 5 # N, despite the header saying kN COL_BRAKE_PRESS = 8 +COL_MASTER_CONTROLLER = 11 # the position of the master controller COL_COMMAND = 16 # text, read as None COL_WHEELSLIP = 20 COL_VEHICLE_VELOCITY = 25 # signed vehicle speed, km/h; only in builds which log it @@ -155,6 +157,46 @@ def timetable_path(game_dir: Path, case_name: str) -> Path: return game_dir / "scenery" / f"{timetable_name(case_name)}.txt" +def variant_name(case_name: str, name: str) -> str: + """A vehicle variant of the case as a trainset names it: {{variant_}} in the fragment.""" + return f"autotest_{case_name}_{name}" + + +def variant_paths(game_dir: Path, case_name: str, variant: dict) -> list[Path]: + """The .fiz and .mmd of a vehicle variant of the case, beside those of the vehicle it is made from.""" + folder = (game_dir / "dynamic" / variant["from"]).parent + return [folder / f"{variant_name(case_name, variant['name'])}{suffix}" for suffix in (".fiz", ".mmd")] + + +def write_vehicle_variants(case: dict, game_dir: Path, case_name: str) -> None: + """Writes the case's vehicle variants into the game's dynamic/ dir: a copy of a vehicle's .fiz with the + case's replacements, e.g. a .fiz key the shipped data doesn't have yet, and a copy of its .mmd. The + simulator hands the .mmd its type name as (p2), which some pass on to the include that names the + model (et42_v2: `include 112e-a.mmd.inc (p2) end`, `models: (p1).t3d`), so the copy has the name of + the vehicle it is made from in place of (p2) and looks and loads as that one does.""" + files = {} + for variant in case.get("vehicle_variants", []): + source = game_dir / "dynamic" / variant["from"] + # .fiz files are cp1250 like the sceneries; latin-1 round-trips every byte + fiz = source.with_name(source.name + ".fiz").read_bytes().decode("latin-1") + for old, new in variant.get("replace", []): + if old not in fiz: + sys.exit(f"vehicle_variants: {variant['from']}.fiz has no {old!r}") + fiz = fiz.replace(old, new) + mmd = source.with_name(source.name + ".mmd").read_bytes().decode("latin-1").replace("(p2)", source.name) + fiz_path, mmd_path = variant_paths(game_dir, case_name, variant) + files[fiz_path], files[mmd_path] = fiz, mmd + # written once every variant is made, so a case with a wrong replacement leaves nothing in the game dir + for path, text in files.items(): + path.write_bytes(text.encode("latin-1")) + + +def remove_vehicle_variants(case: dict, game_dir: Path, case_name: str) -> None: + for variant in case.get("vehicle_variants", []): + for path in variant_paths(game_dir, case_name, variant): + path.unlink(missing_ok=True) + + def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> str: """Writes the case scenery into the game's scenery dir and returns its file name.""" scenery_dir = game_dir / "scenery" @@ -175,8 +217,9 @@ def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> s # a case on a mission of the base scenery may have nothing to add but its test_config fragment = (CASES_DIR / case["fragment"]).read_bytes().decode("latin-1") if "fragment" in case else "" # vars first: {{vehicle}} and {{timetable}} inside a var's value get filled in the second pass - fragment = fill_vars(fragment, case.get("vars", {}), keep={"vehicle", "timetable"}) - fragment = fill_vars(fragment, {"vehicle": vehicle, "timetable": timetable_name(case_name)}) + variants = {f"variant_{v['name']}": variant_name(case_name, v["name"]) for v in case.get("vehicle_variants", [])} + fragment = fill_vars(fragment, case.get("vars", {}), keep={"vehicle", "timetable", *variants}) + fragment = fill_vars(fragment, {"vehicle": vehicle, "timetable": timetable_name(case_name), **variants}) # FirstInit binds event launchers to their events and links the tracks. so launchers and # events of the case go in before it (read after it they never fire), trainsets after it # (placed before it they stand on unlinked track and derail at once) @@ -192,6 +235,8 @@ def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> s else: text += header + before + "\n" text += header + trainsets + "\n" + # vehicles of the case's own, made from those of the game + write_vehicle_variants(case, game_dir, case_name) name = f"autotest_{case_name}.scn" (scenery_dir / name).write_bytes(text.encode("latin-1")) # a timetable of the case's own, for a train whose timetable the sceneries of the game have none like @@ -442,11 +487,14 @@ def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog # ---------------------------------------------------------------- checks -def check_starts(rows, min_speed, within): +def check_starts(rows, min_speed, within, after=None): for r in rows: if r[COL_TIME] > within: break if r[COL_VELOCITY] >= min_speed: + # a case can also say the train mustn't leave before something it waits for (a converter starting) + if after is not None and r[COL_TIME] < after: + return False, f"reached {min_speed} km/h at t={r[COL_TIME]:.1f}s, before {after}s" return True, f"reached {min_speed} km/h at t={r[COL_TIME]:.1f}s" top = max((r[COL_VELOCITY] for r in rows if r[COL_TIME] <= within), default=0.0) return False, f"top speed in the first {within}s was {top:.1f} km/h, wanted {min_speed}" @@ -602,7 +650,51 @@ def check_slip_clears(rows, moving_speed, stop_speed, within): return True, f"stopped at t={rows[stop][COL_TIME]:.1f}s, no slipping after t={deadline:.1f}s" +def check_traction(rows, from_distance, to_distance, reaches=None, at_most=None, at_least=None): + """The traction force of the vehicle in kN (the physicslog has it in N, whatever its header says) while it + runs between two points of its way, in metres travelled as in `distance`: the highest there `reaches` a + force, e.g. the power taken again behind a section without voltage; it stays `at_most` a force, e.g. none + taken where there is no voltage; it stays `at_least` a force, e.g. no power lost under an insulator.""" + dist = _distances(rows) + window = [(d, r) for d, r in zip(dist, rows) if from_distance <= d <= to_distance] + if not window: + return False, f"never got between {from_distance} and {to_distance} m (travelled {dist[-1] if dist else 0:.0f} m)" + + def describe(item): + d, r = item + return f"{r[COL_TRACTION_FORCE] / 1000:.1f} kN at {d:.0f} m, t={r[COL_TIME]:.1f}s, v={r[COL_VELOCITY]:.1f} km/h" + + top = max(window, key=lambda item: item[1][COL_TRACTION_FORCE]) + low = min(window, key=lambda item: item[1][COL_TRACTION_FORCE]) + detail = (f"between {from_distance} and {to_distance} m (t={window[0][1][COL_TIME]:.1f}-{window[-1][1][COL_TIME]:.1f}s) " + f"the traction force was {describe(low)} at its lowest, {describe(top)} at its highest") + if reaches is not None and top[1][COL_TRACTION_FORCE] / 1000 < reaches: + return False, f"{detail}; wanted it to reach {reaches} kN" + if at_most is not None and top[1][COL_TRACTION_FORCE] / 1000 > at_most: + return False, f"{detail}; wanted at most {at_most} kN" + if at_least is not None and low[1][COL_TRACTION_FORCE] / 1000 < at_least: + return False, f"{detail}; wanted at least {at_least} kN" + return True, detail + + +def check_master_controller(rows, from_distance, to_distance, at_most): + """The master controller of the vehicle stays at or below a position while it runs between two points of its + way (metres travelled, as in `distance`), e.g. at 0 where the scenery tells the driver to coast.""" + dist = _distances(rows) + window = [(d, r) for d, r in zip(dist, rows) if from_distance <= d <= to_distance] + if not window: + return False, f"never got between {from_distance} and {to_distance} m (travelled {dist[-1] if dist else 0:.0f} m)" + d, top = max(window, key=lambda item: item[1][COL_MASTER_CONTROLLER]) + detail = (f"between {from_distance} and {to_distance} m (t={window[0][1][COL_TIME]:.1f}-{window[-1][1][COL_TIME]:.1f}s) " + f"the master controller was at {top[COL_MASTER_CONTROLLER]:.0f} at most, at {d:.0f} m, t={top[COL_TIME]:.1f}s") + if top[COL_MASTER_CONTROLLER] > at_most: + return False, f"{detail}; wanted at most {at_most}" + return True, detail + + CHECKS = { + "master_controller": check_master_controller, + "traction": check_traction, "slips": check_slips, "slip_clears": check_slip_clears, "holds_still": check_holds_still, @@ -856,15 +948,6 @@ def _run_case(name: str, case: dict, exe: Path, game_dir: Path, timespeed: float if not with_physicslog and (watch or needs_physicslog): sys.exit(f"{name}: with physicslog off a case can have log checks only ({', '.join(LOG_CHECKS)}), " "and can't run with --watch") - scenery = build_scenery(case, game_dir, name, vehicle) - ini = out / "autotest.ini" - # the case's own settings go last, over the common ones; then the seed of this run of the suite, if any - settings = [*case.get("ini", []), *([f"randomseed {seed}"] if seed else [])] - ini.write_text(TEST_INI.format(timespeed=timespeed, physicslog="yes" if with_physicslog else "no") - + "".join(line + "\n" for line in settings), encoding="ascii") - physicslog = game_dir / "physicslog" / f"{vehicle}.dat" - started = time.time() - 1 - duration = float(case["duration"]) if "duration" in case else None # a case that only records `duration` seconds ends on the test timeout; one that says # how the test ends (a pass event, a signal passed at danger...) expects that result @@ -873,10 +956,24 @@ def _run_case(name: str, case: dict, exe: Path, game_dir: Path, timespeed: float sys.exit(f"{name}: expect must be one of {', '.join(RESULTS)}") if watch and duration is None: sys.exit(f"{name}: --watch needs a case with duration") - result = run_simulator(exe, game_dir, scenery, ini, physicslog, - duration, float(case.get("timeout", 600)), watch, say, - expect_rows=with_physicslog and not own_vehicle) - timetable_path(game_dir, name).unlink(missing_ok=True) + + ini = out / "autotest.ini" + # the case's own settings go last, over the common ones; then the seed of this run of the suite, if any + settings = [*case.get("ini", []), *([f"randomseed {seed}"] if seed else [])] + ini.write_text(TEST_INI.format(timespeed=timespeed, physicslog="yes" if with_physicslog else "no") + + "".join(line + "\n" for line in settings), encoding="ascii") + physicslog = game_dir / "physicslog" / f"{vehicle}.dat" + started = time.time() - 1 + # from here on the case has files of its own in the game dir (the vehicle variants, the timetable) + try: + scenery = build_scenery(case, game_dir, name, vehicle) + result = run_simulator(exe, game_dir, scenery, ini, physicslog, + duration, float(case.get("timeout", 600)), watch, say, + expect_rows=with_physicslog and not own_vehicle) + finally: + # the case's own files go from the game dir also when the run is broken off (ctrl+c) + timetable_path(game_dir, name).unlink(missing_ok=True) + remove_vehicle_variants(case, game_dir, name) # a case that asked for no geometry cache (file.binary.terrain no) leaves none of an earlier run behind if any(line.split()[:2] == ["file.binary.terrain", "no"] for line in case.get("ini", [])): scenery_cache(game_dir, name).unlink(missing_ok=True) From 2d16657c2e313e2aad0e69a5fe0f521161f266db Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 06:16:59 +0100 Subject: [PATCH 122/136] fix(ai): keep the locomotive released while it pushes the buffers in to uncouple (#482) * test(scenarios): the L053 poranek cases now fail on the station's SM42 #409 fixed what both l053_poranek_tme222158_debica cases were marked xfail for: the EP07 on Tm4 stops at the checkpoint, and the ET21 no longer stands off the wire at Debica Towarowa. Run on staging f15ea405, neither passes yet: TME222158 gets to Debica and reports there, but the station's SM42-1096, ordered to uncouple at step 10 of deb_sm42_stat, pushes its cut past debica_k_sem_info at danger and never gets the coupler off, so the station never gives TME222158 step 1 and both runs end as a standstill (4347 s and 4576 s of simulation time). The xfail marks stay, with that reason. * fix(ai): keep the locomotive released while it pushes the buffers in to uncouple Stage 3 of uncoupling (TController::UpdateDisconnect) ends only when the locomotive has pushed the buffers together: a screw coupler is let go with the buffers under 0.01 m apart (or over 0.2 m). Nothing else ends the stage. The consist brakes applied in stage 2 hold the locomotive as well, and only its brake releaser lets it go. The AI worked the releaser in that stage only while it wanted to speed up (AccDesired above -0.05), together with the start-off rules of control_releaser. When the cut stands across a signal at stop for the direction the locomotive pushes in, the driver counts the signal as passed at its first move after the direction change, VelSignalLast becomes 0 and AccDesired stays at -0.05 or -0.85. The releaser then went off, the brake cylinder filled again from the brake pipe, the pressure switch cut the power, and the locomotive stood for good with the buffers 0.018 m apart. The station's SM42-1096 at Debica on L053 poranek did that at step 10 of deb_sm42_stat and logged "actuating and compressing buffers..." for the rest of the run (a temporary log line showed the brake cylinder going from 1.25 to 3.69 bar with the releaser off, and the gap staying at 0.0184 m). In stage 3 the releaser now stays on while the locomotive's brake cylinder holds more than 0.1 bar, whatever AccDesired is. The push asks for 2 km/h at most and the cut stays braked, so this changes nothing else. Everything else, including the rest of the uncoupling (the direction changes before and after it) and coupling, keeps the old rule. The overcharge guard (pipe above 5.2 bar) still turns the releaser off. The decision moves into vehicle/brakereleaser.{h,cpp} so it is unit tested; control_releaser does the same cues in the same order as before. On L053 poranek the SM42 now uncouples at step 10 in 0.2 s (gap 0.021 -> 0.0096 m) and the mission goes on. * test(scenarios): a shunter uncouples with its wagons standing across a signal at stop sm42_td_uncouple_past_signal (fragment td_uncouple_past_signal.scn) rebuilds the uncoupling of the SM42 at Debica on L053 poranek on td.scn. An SM42 pulls three loaded wagons back along tor1k, stops in front of a closed track with the far end of the last wagon 2 m past the exit signal stacja1_j at stop, and gets Shunt 0 0 at once. The pull leaves the screw coupler 0.019 m apart at the buffers. Before the fix of the releaser the locomotive stayed braked and the case ran into its timeout with no "uncoupled" in the log; now it uncouples within a second. * test(scenarios): the L053 poranek cases pass again With the station's SM42-1096 uncoupling at step 10 of deb_sm42_stat again (the releaser fix before this commit), both l053_poranek_tme222158_debica cases pass: TME222158 gets its exit signal at Debica after 4086.2 s of simulation, and with the ET21 after 4131.6 s. The xfail marks go, so that the runner doesn't fail on XPASS, and the README rows say so. --- CMakeLists.txt | 1 + tests/scenarios/README.md | 19 ++- .../cases/l053_poranek_tme222158_debica.json | 1 - .../l053_poranek_tme222158_debica_et21.json | 1 - .../cases/sm42_td_uncouple_past_signal.json | 25 ++++ .../cases/td_uncouple_past_signal.scn | 31 +++++ tests/unit/test_brake_releaser.cpp | 114 ++++++++++++++++++ vehicle/Driver.cpp | 50 +++----- vehicle/brakereleaser.cpp | 60 +++++++++ vehicle/brakereleaser.h | 39 ++++++ 10 files changed, 306 insertions(+), 35 deletions(-) create mode 100644 tests/scenarios/cases/sm42_td_uncouple_past_signal.json create mode 100644 tests/scenarios/cases/td_uncouple_past_signal.scn create mode 100644 tests/unit/test_brake_releaser.cpp create mode 100644 vehicle/brakereleaser.cpp create mode 100644 vehicle/brakereleaser.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 3627ef518..34be53811 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -576,6 +576,7 @@ set(CORE_SOURCES "vehicle/drivingaid.cpp" "vehicle/brakingcurve.cpp" "vehicle/signalpassing.cpp" +"vehicle/brakereleaser.cpp" "vehicle/handover.cpp" "vehicle/crew.cpp" "vehicle/horn.cpp" diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index e021bb398..6d6317bd7 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -326,6 +326,21 @@ Przystanek whatever the buckle. With 600 mm over a main lobe of 8 m the locomoti the buckle at 46 km/h, 1036 m from the start (`Bad driving: ... derailed on buckled track`); with 30 mm it keeps on the rails and stops at Przystanek after 1400 m. +`sm42_td_uncouple_past_signal` (fragment `td_uncouple_past_signal.scn`) is the uncoupling of the SM42 at Debica on +L053 poranek (step 10 of `deb_sm42_stat`) on td.scn. An SM42 with no timetable stands turned at the far end of `tor1k`, +three wagons loaded with gravel (51 m of train) behind it towards the exit signal `stacja1_j`, which stays at stop (no +route). `tdo_n1734`, the track behind `tor1k`, is closed (`trackvel 0`) from the start. `event0` of `tor1k` gives the +driver `Shunt -1 0`: it pulls the wagons back for 47 m and stops in front of the closed track, with the far end of the +last wagon 2 m past the signal's memory cell (the `distance` check keeps it 0-4 m past). The pull leaves the screw +coupler stretched, 0.019 m apart at the buffers, and a screw coupler is let go only with the buffers pressed together +(under 0.01 m). At the first stand `event0` gives `Shunt 0 0`: brake the wagons, change direction, push the buffers in, +uncouple. After the direction change the driver counts `stacja1_j` as passed at its first move, so its speed is capped +at 0. The driver used to work the brake releaser only while it wanted to speed up, so the locomotive stayed braked by +the wagons' brake application and never closed the gap: no `uncoupled` in the log, and the case ran into its timeout. +Now the locomotive is released, eases into the wagons and uncouples within a second. The wagons are loaded so that the +stop leaves the gap above 0.01 m: with a coach and an empty wagon the buffers came to rest 0.009 m apart and the +coupler let go at once. + The `*_td_crew_*` cases (eu07/maszyna#510, fragment `td_crew.scn`) are about the crew command of a `putvalues` event, `Crew: `: cab 1 or -1 puts an AI driver in cab A or B of the vehicle named, 0 takes its AI driver off. The vehicle is named in the text, so the events are @@ -485,8 +500,8 @@ staging f15ea405 of 2026-11-23): | `wrzosy_pxe336080_couples` | #524 | passes: ordered to, the locomotive couples to the rake (`couples`, 262 s) and takes it out of the depot (696 s). The scenery itself gives no such order | | `baltyk_skm1_roj55324_shunting_signal` | #525 | passes, with four seeds: the unit on the siding is let into the platforms 4 minutes after the start, once the shunter beside it has done its first moves, and leaves at 10:42 | | `baltyk_skm1_roj55321_departure` | #525 | passes, with three seeds: the unit in the platform leaves at 10:34 | -| `l053_poranek_tme222158_debica` | #421 | `xfail`: on master of 2026-11-11 the station jammed 4 minutes after the start, the AI of EP07-338'16 passed the shunting signal Tm4 at stop at 29 km/h. Since #409 (staging f15ea405, 2026-11-23) the EP07 stops at the checkpoint and TME222158 gets to Debica, but the station's SM42-1096 jams it: ordered to uncouple at step 10 of `deb_sm42_stat` it pushes its cut past `debica_k_sem_info` at danger and never gets the coupler off, so the station never sends TME222158 on | -| `l053_poranek_tme222158_debica_et21` | #421 | `xfail`: on master of 2026-11-11, with an ET21 as in the report, the locomotive stopped for good at Debica Towarowa, on the headshunt 20 m past the end of the overhead wire, and its driver never got out of `Prepare_engine`. Since #409 (staging f15ea405) the ET21 gets through Debica Towarowa (steps 1-5 of `dt_tme222158_stat`) to Debica, then fails on the SM42 as `l053_poranek_tme222158_debica` does | +| `l053_poranek_tme222158_debica` | #421 | passes: TME222158 gets the exit signal to Sandomierz (step 6 of `deb_tme222158_stat`) after 4086.2 s. On master of 2026-11-11 the station jammed 4 minutes after the start, the AI of EP07-338'16 passed the shunting signal Tm4 at stop at 29 km/h; #409 fixed that. On staging f15ea405 (2026-11-23) the station's SM42-1096 jammed it next: ordered to uncouple at step 10 of `deb_sm42_stat`, with its cut standing across `debica_k_sem_info` at stop, it stayed braked and never got the coupler off (standstill after 4347 s), until the AI kept the locomotive released while it pushes the buffers in to uncouple (`sm42_td_uncouple_past_signal`) | +| `l053_poranek_tme222158_debica_et21` | #421 | passes after 4131.6 s. On master of 2026-11-11, with an ET21 as in the report, the locomotive stopped for good at Debica Towarowa, on the headshunt 20 m past the end of the overhead wire, and its driver never got out of `Prepare_engine`. Since #409 the ET21 gets through Debica Towarowa (steps 1-5 of `dt_tme222158_stat`) to Debica; there it waited for the SM42 as `l053_poranek_tme222158_debica` did, until the same fix | | `l053_poludnie_roj32134_debica` | #506 | passes: both trains run and the unit ends at Debica after 6134 s; no train in its way | In the L053 sceneries the test mode logs a signal passed at danger for several shunting diff --git a/tests/scenarios/cases/l053_poranek_tme222158_debica.json b/tests/scenarios/cases/l053_poranek_tme222158_debica.json index cba4a9830..dde90e86a 100644 --- a/tests/scenarios/cases/l053_poranek_tme222158_debica.json +++ b/tests/scenarios/cases/l053_poranek_tme222158_debica.json @@ -10,7 +10,6 @@ "reason": "tme222158_got_the_exit_signal_at_debica" }, "slow": true, - "xfail": "eu07/maszyna#421 is not reached, the station's SM42 jams Debica: since #409 EP07-338'16 stops at the checkpoint before Tm4 (tor1834:event0) and TME222158 is let in and reports at Debica (deb_tme222158_stat c 0), but SM42-1096, ordered to uncouple at step 10 of deb_sm42_stat, pushes its cut past debica_k_sem_info at danger and never gets the coupler off (\"Uncoupling [sm42-1096]: actuating and compressing buffers... from front\" for the rest of the run), so it never does step 11 and the station never gives TME222158 step 1: standstill after 4347 s", "physicslog": false, "ini": [ "file.binary.terrain no" diff --git a/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json b/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json index 62785a518..7ad5a1a78 100644 --- a/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json +++ b/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json @@ -16,7 +16,6 @@ "reason": "tme222158_got_the_exit_signal_at_debica" }, "slow": true, - "xfail": "eu07/maszyna#421 is not reached, the station's SM42 jams Debica, as in l053_poranek_tme222158_debica: since #409 the ET21 no longer stands off the wire at Debica Towarowa, it gets through steps 1-5 of dt_tme222158_stat, takes the wagons to Debica and reports there (deb_tme222158_stat c 0), but SM42-1096, ordered to uncouple at step 10 of deb_sm42_stat, pushes its cut past debica_k_sem_info at danger and never gets the coupler off (\"Uncoupling [sm42-1096]: actuating and compressing buffers... from front\" for the rest of the run), so it never does step 11 and the station never gives TME222158 step 1: standstill after 4576 s", "physicslog": false, "ini": [ "file.binary.terrain no" diff --git a/tests/scenarios/cases/sm42_td_uncouple_past_signal.json b/tests/scenarios/cases/sm42_td_uncouple_past_signal.json new file mode 100644 index 000000000..f1ae7b835 --- /dev/null +++ b/tests/scenarios/cases/sm42_td_uncouple_past_signal.json @@ -0,0 +1,25 @@ +{ + "description": "SM42 shunter on td.scn pulls three loaded wagons back along tor1k and stops with the far end of the last one a few metres past the exit signal stacja1_j at stop, then gets Shunt 0 0 (uncouple): after the direction change the signal lies at stop over that wagon, behind the new head, and the AI has to push the buffers in all the same and let the coupler go.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_uncouple_past_signal.scn", + "vars": { + "wagons": [ + "node -1 0 {{vehicle}}_w3 dynamic pkp\\401z_v2 82515940087-8 401zp_2 0 nobody 3 60 gravel enddynamic", + "node -1 0 {{vehicle}}_w2 dynamic pkp\\401z_v2 82515942691-5 401zp_1 0 nobody 3 60 gravel enddynamic", + "node -1 0 {{vehicle}}_w1 dynamic pkp\\401z_v2 82515993043-7 401zl_2 0 nobody 3 60 gravel enddynamic" + ] + }, + "track_events": { + "tor1k": "event0 autotest_wake" + }, + "test_config": [ + "test.fail_if_stop_overran no" + ], + "duration": 180, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Uncoupling \\[autotest_sm42_td_uncouple_past_signal\\]: uncoupled" }, + { "type": "distance", "min": 45, "max": 49 } + ] +} diff --git a/tests/scenarios/cases/td_uncouple_past_signal.scn b/tests/scenarios/cases/td_uncouple_past_signal.scn new file mode 100644 index 000000000..98ab9033e --- /dev/null +++ b/tests/scenarios/cases/td_uncouple_past_signal.scn @@ -0,0 +1,31 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a shunter with no timetable stands at the far end of tor1k (point 2), turned (offset -1) to face back towards +// track 1 of Stacja1, with its wagons (vars.wagons) behind it, towards the exit signal stacja1_j (at stop, no route; +// its memory cell is 51 m into tor1k). the trainset's velocity is negative, so its driver takes the direction of the +// locomotive's cab and pulls. tdo_n1734, the track behind tor1k, is closed (speed 0) from the start, so the shunter +// pulls the wagons back along tor1k and stops in front of it, with the far end of the last wagon a few metres past +// the signal: the signal stands at stop over that wagon for the direction the shunter pushes in when it uncouples. +// the pull leaves the screw coupler stretched, as at a real stop. +trainset none tor1k 100.0 -0.1 +{{wagons}} +node -1 0 {{vehicle}} dynamic pkp\sm42_v1 6DA-1096 6da -1 headdriver 0 0 enddynamic +endtrainset + +node -1 0 autotest_closed eventlauncher 0 0 0 -1 none 1034 autotest_close end +event autotest_close trackvel 0 tdo_n1734 0 endevent + +// a standing shunter waits for the scenery's orders. event0 of tor1k (the case's track_events) runs while it stands +// there. the first time it gives the order to go (Shunt -1 0). 25 s later the shunter is on its way, and the first +// time it stands again, in front of tdo_n1734, it gets the order a scenery gives to leave the wagons: Shunt 0 0, +// uncouple everything behind the locomotive and stay. it brakes the wagons, changes direction, pushes the buffers in +// and lets the coupler go. the order comes at once: standing for long, the wagons' brakes release and the coupler +// draws the buffers together, which leaves nothing to push +node -1 0 autotest_ordered memcell 0 0 0 ordered 0 0 none endmemcell +event autotest_wake multiple 0 none autotest_go autotest_uncouple endevent +event autotest_go multiple 0 autotest_ordered autotest_go_order autotest_go_given autotest_go_done condition memcompare * 0 * endevent +event autotest_go_order PutValues 0 none 0 0 0 Shunt -1 0 endevent +event autotest_go_given UpdateValues 0 autotest_ordered * 1 * endevent +event autotest_go_done UpdateValues 25 autotest_ordered * 2 * endevent +event autotest_uncouple multiple 0 autotest_ordered autotest_uncouple_order autotest_uncouple_given condition memcompare * 2 * endevent +event autotest_uncouple_order PutValues 0 none 0 0 0 Shunt 0 0 endevent +event autotest_uncouple_given UpdateValues 0 autotest_ordered * 3 * endevent diff --git a/tests/unit/test_brake_releaser.cpp b/tests/unit/test_brake_releaser.cpp new file mode 100644 index 000000000..0e32552b3 --- /dev/null +++ b/tests/unit/test_brake_releaser.cpp @@ -0,0 +1,114 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/brakereleaser.h" + +// when the AI works the brake releaser of its locomotive (TController::control_releaser). in stage 3 of uncoupling +// the locomotive pushes towards the cut it leaves, until the screw coupler slackens enough to be let go +// (TController::UpdateDisconnect). the consist brakes applied in stage 2 hold the locomotive too, and only the +// releaser lets it go. the releaser was worked only while the driver wanted to speed up (AccDesired above +// -0.05), so a signal at stop the cut stood across after the direction change, which caps the speed at 0, left the +// locomotive braked and the uncoupling went on for good (SM42 at Debica on L053). + +namespace { + +// a locomotive standing in stage 3 of uncoupling, braked by the consist's brake application of stage 2 +brake_releaser::conditions compressing_buffers(double const Acceleration) { + brake_releaser::conditions state; + state.acceleration_desired = Acceleration; + state.pipe_pressure = 3.8; + state.cylinder_pressure = 1.5; + state.control_pressure = 5.0; + state.velocity = 0.0; + state.pressing = true; + state.compressing_buffers = true; + return state; +} + +// a locomotive standing braked at the head of a train with a charged brake pipe, about to start off +brake_releaser::conditions standing_braked(double const Acceleration) { + brake_releaser::conditions state; + state.acceleration_desired = Acceleration; + state.pipe_pressure = 5.0; + state.cylinder_pressure = 1.0; + state.control_pressure = 5.0; + state.velocity = 0.0; + return state; +} + +} // namespace + +TEST_CASE("brake releaser: stage 3 of uncoupling releases the locomotive whatever the driver's acceleration") { + for (auto const acceleration : {0.3, 0.0, -0.05, -0.2, -0.9}) { + CAPTURE(acceleration); + auto const wanted{brake_releaser::decide(compressing_buffers(acceleration))}; + CHECK(wanted.actuate); + CHECK_FALSE(wanted.fill_pipe); + } +} + +TEST_CASE("brake releaser: stage 3 of uncoupling leaves a released locomotive alone") { + for (auto const acceleration : {0.3, -0.9}) { + CAPTURE(acceleration); + auto state{compressing_buffers(acceleration)}; + state.cylinder_pressure = 0.05; + CHECK_FALSE(brake_releaser::decide(state).actuate); + } +} + +TEST_CASE("brake releaser: pressing outside stage 3 still needs the driver to want to speed up") { + // the direction changes of stages 2 and 4, and coupling, are as before: the releaser goes on only with + // AccDesired above -0.05 + auto state{compressing_buffers(0.3)}; + state.compressing_buffers = false; + CHECK(brake_releaser::decide(state).actuate); + state.acceleration_desired = -0.05; + CHECK_FALSE(brake_releaser::decide(state).actuate); + state.acceleration_desired = -0.9; + CHECK_FALSE(brake_releaser::decide(state).actuate); +} + +TEST_CASE("brake releaser: starting off releases a braked locomotive below 1 km/h") { + CHECK(brake_releaser::decide(standing_braked(0.3)).actuate); + CHECK_FALSE(brake_releaser::decide(standing_braked(-0.05)).actuate); + + auto moving{standing_braked(0.3)}; + moving.velocity = 1.0; + CHECK_FALSE(brake_releaser::decide(moving).actuate); + + auto lightly{standing_braked(0.3)}; + lightly.cylinder_pressure = 0.4; + CHECK_FALSE(brake_releaser::decide(lightly).actuate); + + // the control reservoir not charged: releasing would vent it + auto uncharged{standing_braked(0.3)}; + uncharged.control_pressure = 4.9; + CHECK_FALSE(brake_releaser::decide(uncharged).actuate); + // unless the train brake is held on purpose to start uphill + uncharged.uphill_start = true; + CHECK(brake_releaser::decide(uncharged).actuate); +} + +TEST_CASE("brake releaser: an empty brake pipe is filled up when the driver wants to speed up") { + auto state{standing_braked(0.3)}; + state.pipe_pressure = 2.9; + state.cylinder_pressure = 0.0; + auto const wanted{brake_releaser::decide(state)}; + CHECK(wanted.actuate); + CHECK(wanted.fill_pipe); + + state.acceleration_desired = -0.2; + auto const braking{brake_releaser::decide(state)}; + CHECK_FALSE(braking.actuate); + CHECK_FALSE(braking.fill_pipe); +} + +TEST_CASE("brake releaser: an overcharged brake pipe turns the releaser off, in stage 3 of uncoupling too") { + auto starting{standing_braked(0.3)}; + starting.pipe_pressure = 5.3; + CHECK_FALSE(brake_releaser::decide(starting).actuate); + + auto uncoupling{compressing_buffers(-0.9)}; + uncoupling.pipe_pressure = 5.3; + CHECK_FALSE(brake_releaser::decide(uncoupling).actuate); +} diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index cba35b68a..675c1ef8e 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -20,6 +20,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/physicslog.h" #include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" #include "vehicle/brakesetting.h" #include "vehicle/brakingcurve.h" #include "vehicle/handover.h" @@ -9117,39 +9118,26 @@ void TController::control_releaser() { if( false == hasreleaser ) { return; } - auto actuate { false }; + brake_releaser::conditions state; + state.acceleration_desired = AccDesired; + state.pipe_pressure = mvOccupied->PipePress; + state.cylinder_pressure = mvOccupied->BrakePress; + state.control_pressure = mvOccupied->Hamulec->GetCRP(); + state.velocity = mvOccupied->Vel; + state.uphill_start = bUphillStart; + state.pressing = TestFlag( iDrivigFlags, movePress ); + // stage 3 of uncoupling (UpdateDisconnect), from the direction change until the coupler lets go + state.compressing_buffers = + state.pressing && ( OrderCurrentGet() & Disconnect ) != 0 && iVehicleCount >= 0 && iDirection == iDirectionOrder; + auto const wanted { brake_releaser::decide( state ) }; + auto const actuate { wanted.actuate }; auto isbrakehandleinrightposition { true }; - if( AccDesired > EU07_AI_NOACCELERATION ) { - // fill up brake pipe if needed - if( mvOccupied->PipePress < 3.0 ) { - actuate = true; - // some vehicles require brake handle to be moved to specific position - if( mvOccupied->HandleUnlock != -3 ) { - cue_action( driver_hint::trainbrakesetpipeunlock ); - isbrakehandleinrightposition &= BrakeCtrlPosition == mvOccupied->HandleUnlock; - } - } - // wyluzuj lokomotywę, to szybciej ruszymy - // this rule is for starting off, so only below 1 km/h: at speed, just after an application, it would vent - // the control reservoir of a locomotive that may have to brake again before the pipe has refilled it - if( mvOccupied->BrakePress > 0.4 - && ( mvOccupied->Hamulec->GetCRP() > 4.9 - // starting uphill the train brake stays applied on purpose, and the locomotive's own share of it has to go - // for the power to come on (asynchronous drives and the pressure switch cut the power while it is applied) - || bUphillStart ) - && mvOccupied->Vel < 1.0 ) { - actuate = true; - } - // keep engine brakes released during coupling/uncoupling - if( true == TestFlag(iDrivigFlags, movePress) - && mvOccupied->BrakePress > 0.1 ) { - actuate = true; - } - } - // don't overcharge train brake pipe - if( mvOccupied->PipePress > 5.2 ) { - actuate = false; + // some vehicles require brake handle to be moved to specific position to fill up the brake pipe + if( wanted.fill_pipe + && mvOccupied->HandleUnlock != -3 ) { + cue_action( driver_hint::trainbrakesetpipeunlock ); + isbrakehandleinrightposition = ( BrakeCtrlPosition == mvOccupied->HandleUnlock ); } if( actuate ) { diff --git a/vehicle/brakereleaser.cpp b/vehicle/brakereleaser.cpp new file mode 100644 index 000000000..0a51c9a62 --- /dev/null +++ b/vehicle/brakereleaser.cpp @@ -0,0 +1,60 @@ +/* +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/brakereleaser.h" + +namespace brake_releaser { + +namespace { + +// the rules for a driver that wants to speed up +bool wanted_to_start(conditions const &State) { + // fill up the brake pipe if needed + if (State.pipe_pressure < 3.0) { + return true; + } + // wyluzuj lokomotywę, to szybciej ruszymy + // this rule is for starting off, so only below 1 km/h: at speed, just after an application, it would vent + // the control reservoir of a locomotive that may have to brake again before the pipe has refilled it + if (State.cylinder_pressure > 0.4 + && (State.control_pressure > 4.9 + // starting uphill the train brake stays applied on purpose, and the locomotive's own share of it has to go + // for the power to come on (asynchronous drives and the pressure switch cut the power while it is applied) + || State.uphill_start) + && State.velocity < 1.0) { + return true; + } + // keep engine brakes released during coupling/uncoupling + return State.pressing && State.cylinder_pressure > 0.1; +} + +} // namespace + +decision decide(conditions const &State) { + decision result; + if (State.acceleration_desired > no_acceleration) { + result.fill_pipe = State.pipe_pressure < 3.0; + result.actuate = wanted_to_start(State); + } + // uncoupling, stage 3: the locomotive has to push the slack of the coupler out whatever its speed table says. + // the consist stays held by its own brakes, applied in stage 2, and the push asks for 2 km/h at most. a signal + // at stop that the consist stands across after the direction change caps the speed at 0 and so AccDesired + // below no_acceleration, and a locomotive left braked by the consist's brake application never closes the gap + if (State.compressing_buffers && State.cylinder_pressure > 0.1) { + result.actuate = true; + } + // don't overcharge train brake pipe + if (State.pipe_pressure > 5.2) { + result.actuate = false; + } + return result; +} + +} // namespace brake_releaser diff --git a/vehicle/brakereleaser.h b/vehicle/brakereleaser.h new file mode 100644 index 000000000..62bc2e7c1 --- /dev/null +++ b/vehicle/brakereleaser.h @@ -0,0 +1,39 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +// when the AI driver works the brake releaser of its locomotive (TController::control_releaser): it vents the +// locomotive's own train brake cylinders, to start off sooner, to fill up an empty brake pipe, and to let the +// locomotive press the buffers while it (un)couples +namespace brake_releaser { + +// the state of the locomotive and of its driver the decision depends on +struct conditions { + double acceleration_desired{0.0}; // AccDesired of the driver [m/s2]; above no_acceleration it wants to speed up + double pipe_pressure{0.0}; // brake pipe [bar] + double cylinder_pressure{0.0}; // the locomotive's brake cylinders [bar] + double control_pressure{0.0}; // the control reservoir of the locomotive's distributor [bar] + double velocity{0.0}; // [km/h] + bool uphill_start{false}; // starting uphill with the train brake held on purpose + bool pressing{false}; // (un)coupling: the driver presses the buffers (movePress) + bool compressing_buffers{false}; // uncoupling, stage 3: pushing towards the cut to slacken the coupler +}; + +struct decision { + bool actuate{false}; // the releaser goes on (else off) + bool fill_pipe{false}; // the brake pipe is to be filled up: the brake handle goes to its unlock position +}; + +// AccDesired at or below this asks for no speeding up (EU07_AI_NOACCELERATION of Driver.h) +inline constexpr double no_acceleration{-0.05}; + +decision decide(conditions const &State); + +} // namespace brake_releaser From e2abe0384fc5f223224e0c7d1bdaf9eb5c56c4ac Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 06:17:22 +0100 Subject: [PATCH 123/136] fix(ai): a heavy train starting on poor rails keeps sanding and takes the power down a step at a time (#494) * test(scenarios): heavy trains on gradients, the limits #187, #199, #263 and #265 left Cases on lines of their own beside td.scn, built the way the downgrade fragment of #479 is (x = -3000, a substation of their own, signals that are a memory cell with SetVelocity 0 0), with level track long enough for a whole heavy consist at the start: - et41_coal_td_downgrade_restriction: ET41 + 25 coal wagons (1670 t) down 20 per mille into a 20 km/h restriction. Staging: 10.5 km/h at the lowest, stops at the signal. #263 saw it stop before the restriction; it no longer does. - et22_764_td_downgrade_restriction: ET22 + 20 loaded 764 (2650 t) on the same line. xfail: it dips to 8.5 km/h in the restriction, as the AI applies and releases the train brake in turn and the release of a G train takes 10-15 s. - st43_steel_td_downgrade12_long: ST43 + 45 425S, 6.5 km down 12 per mille at 40 km/h (#199): 35-37.5 km/h all the way. - et41_coal_td_upgrade_start: the ET41 train stops at a signal on 10 per mille and starts when it clears (#265): moves off 4.7 s later, rolls back 0.04 m. - eu07a_coaches_td_upgrade_long: EU07A + 8 coaches up 10 per mille at 80 km/h (#187): never below 73.8 km/h. run.py gets two checks: keeps_moving (the lowest vehicle speed between two distances) and starts_again (a start from a signal that clears at a given time, with the rollback). The README lists the cases and what the AI still does with heavy trains. * fix(ai): a heavy train starting on poor rails keeps sanding and takes the power down a step at a time An ET41 with 25 loaded coal wagons (2170 t) starting on level track with friction 0.3 (#187: heavy trains often don't get going on such rails) moved 75 m in 1500 s, never above 1 km/h, with 395 slips. Each slip made control_wheelslip() take the power down on every update while the wheels spun (DecSpeed(), two notches each: 3 to 0 within half a second) and press the anti-slip brake (1.1 bar on the locomotive), which braked the train, just moving, to a stand. Once the wheels gripped, the sand went off at once, as it stays on ahead of a slip only at a high motor current, and the start began anew from notch 1. A slip under power below 15 km/h now makes the start a sanded one until the train is at 15 km/h, or stands with no speed asked for: the sand stays on while there is power, a slip takes the power down one step at most once a second, and the anti-slip brake isn't used. A slip at speed, or one without power, is handled as before. The same train now gets going and stops at the signal 1000 m ahead (392 s, 85 slips). New case et41_coal_td_slippery_start (td_level_signal.scn); it fails on staging. * fix(ai): a sanded start only on a vehicle with sand --- tests/scenarios/README.md | 42 + .../et22_764_td_downgrade_restriction.json | 62 ++ .../et41_coal_td_downgrade_restriction.json | 67 ++ .../cases/et41_coal_td_slippery_start.json | 66 ++ .../cases/et41_coal_td_upgrade_start.json | 73 ++ .../cases/eu07a_coaches_td_upgrade_long.json | 50 + .../cases/st43_steel_td_downgrade12_long.json | 86 ++ tests/scenarios/cases/td_downgrade12_long.scn | 608 ++++++++++++ .../cases/td_downgrade_restriction.scn | 638 ++++++++++++ .../scenarios/cases/td_freight_downgrade.txt | 17 + .../cases/td_freight_downgrade12.txt | 17 + tests/scenarios/cases/td_level_signal.scn | 333 +++++++ .../scenarios/cases/td_passenger_upgrade.txt | 17 + tests/scenarios/cases/td_upgrade_long.scn | 934 ++++++++++++++++++ .../cases/td_upgrade_signal_start.scn | 492 +++++++++ tests/scenarios/run.py | 54 + vehicle/Driver.cpp | 29 +- vehicle/Driver.h | 3 + 18 files changed, 3585 insertions(+), 3 deletions(-) create mode 100644 tests/scenarios/cases/et22_764_td_downgrade_restriction.json create mode 100644 tests/scenarios/cases/et41_coal_td_downgrade_restriction.json create mode 100644 tests/scenarios/cases/et41_coal_td_slippery_start.json create mode 100644 tests/scenarios/cases/et41_coal_td_upgrade_start.json create mode 100644 tests/scenarios/cases/eu07a_coaches_td_upgrade_long.json create mode 100644 tests/scenarios/cases/st43_steel_td_downgrade12_long.json create mode 100644 tests/scenarios/cases/td_downgrade12_long.scn create mode 100644 tests/scenarios/cases/td_downgrade_restriction.scn create mode 100644 tests/scenarios/cases/td_freight_downgrade.txt create mode 100644 tests/scenarios/cases/td_freight_downgrade12.txt create mode 100644 tests/scenarios/cases/td_level_signal.scn create mode 100644 tests/scenarios/cases/td_passenger_upgrade.txt create mode 100644 tests/scenarios/cases/td_upgrade_long.scn create mode 100644 tests/scenarios/cases/td_upgrade_signal_start.scn diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index 6d6317bd7..2af439ed5 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -275,6 +275,42 @@ starts on the level at the W4 of Gora, stops at the W4 of Dol 1500 m down the gr model), about 1590 m and 2690 m from the start. The three trains are the light EU07, the SN61 alone and the EU07 with three coaches. +### Heavy trains + +The heavy train cases (#187, #199, #263, #265) run on lines of their own beside the tracks of td.scn, at x = -3000, as +the `*_td_downgrade_w4_signal` cases of #479 do: 100 m tracks, an overhead wire fed by a substation of its own (none for +the diesel case) and signals at stop that are a memory cell with `SetVelocity 0 0` and the event that reads it, with no +model. Each train starts on a level stretch long enough for the whole consist, with its head 10 m before the W4 of Gora, +which is where the distances in the checks start from. A freight train leaves a station of its timetable as soon as it +stands there (`IsCargoTrain` in `TController`), so the freight trains leave Gora at once, not at 10:35. The checks that +look for a train that comes to a stand use the vehicle speed (`keeps_moving`), as the wheels of a heavy train starting +on poor rails spin while it stands; `starts_again` checks a start from a signal that clears at a given time, and how far +the train rolls back meanwhile. + +| case | fragment | train | what it shows | +| --- | --- | --- | --- | +| `et41_coal_td_downgrade_restriction` | `td_downgrade_restriction.scn`: 600 m level, 3500 m down 20 per mille, 20 km/h from 1500 to 1900 m down, the signal 3000 m down | ET41, 25 coal wagons 412W with 40 t each, G (about 1670 t) | passes: through the restriction at 10.5 km/h at the lowest, stops at the signal (3078 m) | +| `et22_764_td_downgrade_restriction` | the same | ET22, 20 heavy wagons 764 with 84 t each (about 2650 t) | `xfail`: dips to 8.5 km/h in the 20 km/h restriction (below the 10 km/h #263 counts as a defect); it doesn't stop | +| `st43_steel_td_downgrade12_long` | `td_downgrade12_long.scn`: 900 m level, 6500 m down 12 per mille, no wire, the signal 6000 m down | ST43, 45 coil wagons 425S, G | passes: holds 35-37.5 km/h of the 40 all the way down, never below 20 km/h, stops at the signal | +| `et41_coal_td_upgrade_start` | `td_upgrade_signal_start.scn`: 600 m level, 2500 m up 10 per mille, a signal 1000 m up that clears at 10:42, another 2300 m up | the ET41 with 25 coal wagons | passes: stops at the first signal with the whole train on the gradient, moves off 4.7 s after it clears, 10 km/h after 52 s, rolls back 0.04 m | +| `eu07a_coaches_td_upgrade_long` | `td_upgrade_long.scn`: 600 m level, 5500 m up 10 per mille, the signal 5300 m up | EU07A (303E), 8 coaches (about 360 t), passenger timetable at 80 km/h | passes: 80 km/h at 1430 m, never below 73.8 km/h on the climb | +| `et41_coal_td_slippery_start` | `td_level_signal.scn`: 2100 m level, the signal 1000 m ahead | ET41, 25 coal wagons with 60 t each (about 2170 t), `friction 0.3` | passes with the fix of this branch: gets going and stops at the signal (1082 m, at 392 s); before it, 395 slips in 1500 s and 75 m | + +What the AI still does with heavy trains, without a case that fails on it: + +- On a steep descent into a restriction a heavy G train holds the speed by applying and releasing the train brake in + turn. Its brake takes 10-15 s to release, so it falls well below the limit before the brake lets go: 10.5-12 km/h + for the ET41 with coal wagons, 8.5 km/h for the ET22 with the 764 wagons (the `xfail` above), in a 20 km/h + restriction. #263 reported this train stopping before the restriction in 10 of 12 runs; on staging it no longer + does, also with `friction 0.5` and with the wagons fully loaded. +- Starting uphill, a heavy train pulls against its train brake while the brake releases (#265): in + `et41_coal_td_upgrade_start` about 13 s at about 200 kN with the head moving by the slack of the couplers alone. It + starts at full power, without taking up the slack first. +- The AI doesn't know the adhesion of the rails: it plans braking with `Global.FrictionWeatherFactor` alone, and the + result of its running brake test (`adjust_desired_speed_for_braking_test`) is shown in the debug panel only. It sands + ahead of a slip only at a high motor current, and, since the fix of `et41_coal_td_slippery_start`, through the rest of + a start that has slipped (`control_wheelslip()`); not before a hard brake, nor before the first slip of a start. + The `test_mode_*` cases show the ends of the test mode: `test_mode_pass` (exit 0, the pass event), `test_mode_signal_passed_at_danger` (exit 11), `test_mode_timeout` (exit 12, from `test.timeout`), `test_mode_standstill` (exit 13, from `test.standstill`) and @@ -540,6 +576,12 @@ the row instead, logged by builds from this branch on. after moving off, moves no more than `max_distance` metres, e.g. no creeping on locked wheels. - `ends_moving` `min_speed`: the last row of the physicslog is at `min_speed` or faster, e.g. the test ended without waiting for the train to stop. +- `keeps_moving` `moving_speed`, `min_speed`, `until_distance`, optional `from_distance` (*vehicle speed*): once at + `moving_speed`, the speed stays at or above `min_speed` between the two distances (metres travelled, from the vehicle + speed), e.g. a heavy train doesn't come to a stand on a descent before a restriction. Reports the lowest speed. +- `starts_again` `after`, `min_speed`, `within`, optional `max_rollback` (*vehicle speed* for the rollback): standing + at the time `after` (a signal that clears then), the train reaches `min_speed` within `within` seconds, and rolls back + no more than `max_rollback` metres meanwhile. - `log_contains` `pattern`: a line of the run's `log.txt` matches the regex, e.g. the `Bad driving: ... collided` message of a collision. - `log_lacks` `pattern`: no line of the run's `log.txt` matches the regex. diff --git a/tests/scenarios/cases/et22_764_td_downgrade_restriction.json b/tests/scenarios/cases/et22_764_td_downgrade_restriction.json new file mode 100644 index 000000000..b53a23411 --- /dev/null +++ b/tests/scenarios/cases/et22_764_td_downgrade_restriction.json @@ -0,0 +1,62 @@ +{ + "description": "An ET22 with 20 loaded heavy wagons 764 (Uaai, 84 t of machinery each, KE, G; about 2650 t) on the line of et41_coal_td_downgrade_restriction: down 20 per mille into a 20 km/h restriction 400 m long, then to the signal at stop. The train is to keep above 10 km/h through the restriction (#187: it almost stops).", + "xfail": "#187, #263: down 20 per mille the AI holds the 20 km/h restriction by applying and releasing the train brake in turn (handle 0, then 1.25-2.75, then 0 again); the release of this G train takes 10-15 s, so each one comes late and the train dips to 8.5 km/h, below the 10 km/h #263 counts as a defect. It doesn't stop. Known limitation of the AI, not fixed here", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_downgrade_restriction.scn", + "timetable": "td_freight_downgrade.txt", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\et22_v3 201E-1150 201E 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_w01 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w02 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w03 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w04 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w05 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w06 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w07 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w08 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w09 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w10 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w11 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w12 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w13 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w14 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w15 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w16 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w17 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w18 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w19 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w20 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic" + ] + }, + "expect": "standstill", + "duration": 1200, + "timeout": 1500, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 300 + }, + { + "type": "max_speed", + "limit": 60, + "tolerance": 5 + }, + { + "type": "keeps_moving", + "moving_speed": 20, + "min_speed": 10, + "until_distance": 2450 + }, + { + "type": "stops", + "moving_speed": 15, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 2950, + "max_distance": 3110 + } + ] +} diff --git a/tests/scenarios/cases/et41_coal_td_downgrade_restriction.json b/tests/scenarios/cases/et41_coal_td_downgrade_restriction.json new file mode 100644 index 000000000..966c6b0a8 --- /dev/null +++ b/tests/scenarios/cases/et41_coal_td_downgrade_restriction.json @@ -0,0 +1,67 @@ +{ + "description": "An ET41 with 25 loaded coal wagons (412W, 60 t each, cast-iron blocks, G; about 1670 t) on a line of its own beside td.scn: from the level down a gradient of 20 per mille at the 60 km/h of its timetable, into a 20 km/h restriction 400 m long 1500 m down the gradient, then to the signal at stop 3000 m down. The train is to pass through the restriction without coming to a stand, and stop at the signal (#263, #187).", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_downgrade_restriction.scn", + "timetable": "td_freight_downgrade.txt", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\et41_v2 41-045-a 203e-a 0 headdriver 55 0 enddynamic", + "node -1 0 {{vehicle}}_b dynamic pkp\\et41_v2 41-045-b 203e-b 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w01 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w02 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w03 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w04 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w05 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w06 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w07 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w08 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w09 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w10 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w11 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w12 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w13 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w14 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w15 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w16 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w17 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w18 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w19 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w20 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w21 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w22 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w23 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w24 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w25 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic" + ] + }, + "expect": "standstill", + "duration": 1200, + "timeout": 1500, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 300 + }, + { + "type": "max_speed", + "limit": 60, + "tolerance": 5 + }, + { + "type": "keeps_moving", + "moving_speed": 20, + "min_speed": 10, + "until_distance": 2400 + }, + { + "type": "stops", + "moving_speed": 15, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 2950, + "max_distance": 3110 + } + ] +} diff --git a/tests/scenarios/cases/et41_coal_td_slippery_start.json b/tests/scenarios/cases/et41_coal_td_slippery_start.json new file mode 100644 index 000000000..34696d422 --- /dev/null +++ b/tests/scenarios/cases/et41_coal_td_slippery_start.json @@ -0,0 +1,66 @@ +{ + "description": "An ET41 with 25 fully loaded coal wagons (412W, 80 t each, G; about 2170 t) starts on level track with the rail friction at 0.3 of its normal (eu07.ini friction 0.3, as on wet leaves), and runs to the signal at stop 1000 m ahead. The train is to get going, keep moving and stop at the signal (#187: heavy trains slip, grip and snatch over and over and often don't get going).", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_level_signal.scn", + "timetable": "td_freight_downgrade.txt", + "ini": [ + "friction 0.3" + ], + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\et41_v2 41-045-a 203e-a 0 headdriver 55 0 enddynamic", + "node -1 0 {{vehicle}}_b dynamic pkp\\et41_v2 41-045-b 203e-b 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w01 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w02 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w03 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w04 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w05 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w06 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w07 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w08 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w09 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w10 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w11 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w12 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w13 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w14 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w15 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w16 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w17 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w18 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w19 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w20 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w21 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w22 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w23 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w24 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w25 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic" + ] + }, + "expect": "standstill", + "duration": 1500, + "timeout": 1800, + "checks": [ + { + "type": "moves", + "vehicle": "{{vehicle}}", + "min_speed": 10 + }, + { + "type": "keeps_moving", + "moving_speed": 5, + "min_speed": 3, + "from_distance": 100, + "until_distance": 900 + }, + { + "type": "stops", + "moving_speed": 10, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 1040, + "max_distance": 1150 + } + ] +} diff --git a/tests/scenarios/cases/et41_coal_td_upgrade_start.json b/tests/scenarios/cases/et41_coal_td_upgrade_start.json new file mode 100644 index 000000000..05d005919 --- /dev/null +++ b/tests/scenarios/cases/et41_coal_td_upgrade_start.json @@ -0,0 +1,73 @@ +{ + "description": "An ET41 with 25 loaded coal wagons (412W, 60 t each, G; about 1670 t) on a line of its own beside td.scn: up a gradient of 10 per mille to the signal hu_sem1 1000 m up, at stop until 10:42, where it stops with the whole train on the gradient; when the signal clears, it is to start without rolling back and get away, to the signal at stop 2300 m up (#265, #187).", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_upgrade_signal_start.scn", + "timetable": "td_freight_downgrade.txt", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\et41_v2 41-045-a 203e-a 0 headdriver 55 0 enddynamic", + "node -1 0 {{vehicle}}_b dynamic pkp\\et41_v2 41-045-b 203e-b 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w01 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w02 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w03 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w04 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w05 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w06 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w07 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w08 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w09 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w10 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w11 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w12 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w13 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w14 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w15 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w16 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w17 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w18 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w19 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w20 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w21 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w22 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w23 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w24 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w25 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic" + ] + }, + "expect": "standstill", + "duration": 1500, + "timeout": 1800, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 300 + }, + { + "type": "max_speed", + "limit": 60, + "tolerance": 5 + }, + { + "type": "stops", + "moving_speed": 15, + "stop_speed": 1.0, + "hold": 60, + "min_distance": 1040, + "max_distance": 1110 + }, + { + "type": "starts_again", + "after": 480, + "min_speed": 10, + "within": 120, + "max_rollback": 1.0 + }, + { + "type": "distance", + "min": 2340, + "max": 2410 + } + ] +} diff --git a/tests/scenarios/cases/eu07a_coaches_td_upgrade_long.json b/tests/scenarios/cases/eu07a_coaches_td_upgrade_long.json new file mode 100644 index 000000000..aa6fb0f86 --- /dev/null +++ b/tests/scenarios/cases/eu07a_coaches_td_upgrade_long.json @@ -0,0 +1,50 @@ +{ + "description": "An EU07A (303E) with 8 coaches (about 360 t) on a line of its own beside td.scn: up a gradient of 10 per mille, 5.5 km long, at the 80 km/h of its timetable, to the signal at stop 5300 m up. The train is to keep above 70 km/h on the climb (#187: an EU07A hung at 55-58 km/h on 10 per mille).", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_upgrade_long.scn", + "timetable": "td_passenger_upgrade.txt", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\303e_v1 303E-336'20 303E 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c4 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c5 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c6 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c7 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c8 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic" + ] + }, + "expect": "standstill", + "duration": 1200, + "timeout": 1500, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 150 + }, + { + "type": "max_speed", + "limit": 80, + "tolerance": 3 + }, + { + "type": "keeps_moving", + "moving_speed": 20, + "min_speed": 70, + "from_distance": 2500, + "until_distance": 4800 + }, + { + "type": "stops", + "moving_speed": 15, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 5330, + "max_distance": 5410 + } + ] +} diff --git a/tests/scenarios/cases/st43_steel_td_downgrade12_long.json b/tests/scenarios/cases/st43_steel_td_downgrade12_long.json new file mode 100644 index 000000000..371faa23c --- /dev/null +++ b/tests/scenarios/cases/st43_steel_td_downgrade12_long.json @@ -0,0 +1,86 @@ +{ + "description": "An ST43 with 45 loaded steel coil wagons (425S, G) on a line of its own beside td.scn: from the level down a gradient of 12 per mille, 6 km long, at the 40 km/h of its timetable, to the signal at stop 6000 m down. The train is not to come to a stand on the way down (#199).", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_downgrade12_long.scn", + "timetable": "td_freight_downgrade12.txt", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\st43_v1 st43-195 060Da 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_w01 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w02 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w03 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w04 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w05 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w06 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w07 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w08 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w09 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w10 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w11 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w12 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w13 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w14 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w15 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w16 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w17 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w18 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w19 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w20 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w21 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w22 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w23 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w24 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w25 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w26 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w27 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w28 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w29 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w30 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w31 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w32 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w33 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w34 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w35 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w36 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w37 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w38 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w39 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w40 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w41 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w42 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w43 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w44 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w45 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic" + ] + }, + "expect": "standstill", + "duration": 1500, + "timeout": 1800, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 400 + }, + { + "type": "max_speed", + "limit": 40, + "tolerance": 5 + }, + { + "type": "keeps_moving", + "moving_speed": 20, + "min_speed": 5, + "until_distance": 5800 + }, + { + "type": "stops", + "moving_speed": 15, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 5950, + "max_distance": 6110 + } + ] +} diff --git a/tests/scenarios/cases/td_downgrade12_long.scn b/tests/scenarios/cases/td_downgrade12_long.scn new file mode 100644 index 000000000..37cf1eff3 --- /dev/null +++ b/tests/scenarios/cases/td_downgrade12_long.scn @@ -0,0 +1,608 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a line of its own, away from the tracks of td.scn: 900 m level, then 6500 m down a gradient of 12 per mille, +// with no overhead wire (diesel trains). the train starts on the level with its head 10 m before the W4 of Gora and runs on +// the timetable {{timetable}} (no stop; a freight train leaves Gora at once) at its line limit, down to the signal hl_sem +// at stop 6000 m down the gradient. the line goes on 500 m past the signal +node -1 0 hl_00 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -800.0 0.0 +0 +endtrack +node -1 0 hl_01 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -700.0 0.0 +0 +endtrack +node -1 0 hl_02 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -600.0 0.0 +0 +endtrack +node -1 0 hl_03 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -500.0 0.0 +0 +endtrack +node -1 0 hl_04 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -400.0 0.0 +0 +endtrack +node -1 0 hl_05 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -300.0 0.0 +0 +endtrack +node -1 0 hl_06 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -200.0 0.0 +0 +endtrack +node -1 0 hl_07 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -100.0 0.0 +0 +endtrack +node -1 0 hl_08 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 0.0 0.0 +0 +event2 gora#1_stopinfo +endtrack +node -1 0 hl_09 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 0.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 58.80 100.0 0.0 +0 +endtrack +node -1 0 hl_10 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 58.80 100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 57.60 200.0 0.0 +0 +endtrack +node -1 0 hl_11 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 57.60 200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 56.40 300.0 0.0 +0 +endtrack +node -1 0 hl_12 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 56.40 300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 55.20 400.0 0.0 +0 +endtrack +node -1 0 hl_13 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 55.20 400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 54.00 500.0 0.0 +0 +endtrack +node -1 0 hl_14 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 54.00 500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 52.80 600.0 0.0 +0 +endtrack +node -1 0 hl_15 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 52.80 600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 51.60 700.0 0.0 +0 +endtrack +node -1 0 hl_16 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 51.60 700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 50.40 800.0 0.0 +0 +endtrack +node -1 0 hl_17 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 50.40 800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 49.20 900.0 0.0 +0 +endtrack +node -1 0 hl_18 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 49.20 900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 48.00 1000.0 0.0 +0 +endtrack +node -1 0 hl_19 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 48.00 1000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 46.80 1100.0 0.0 +0 +endtrack +node -1 0 hl_20 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 46.80 1100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 45.60 1200.0 0.0 +0 +endtrack +node -1 0 hl_21 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 45.60 1200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 44.40 1300.0 0.0 +0 +endtrack +node -1 0 hl_22 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 44.40 1300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 43.20 1400.0 0.0 +0 +endtrack +node -1 0 hl_23 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 43.20 1400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 42.00 1500.0 0.0 +0 +endtrack +node -1 0 hl_24 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 42.00 1500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 40.80 1600.0 0.0 +0 +endtrack +node -1 0 hl_25 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 40.80 1600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 39.60 1700.0 0.0 +0 +endtrack +node -1 0 hl_26 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 39.60 1700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 38.40 1800.0 0.0 +0 +endtrack +node -1 0 hl_27 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 38.40 1800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 37.20 1900.0 0.0 +0 +endtrack +node -1 0 hl_28 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 37.20 1900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 36.00 2000.0 0.0 +0 +endtrack +node -1 0 hl_29 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 36.00 2000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 34.80 2100.0 0.0 +0 +endtrack +node -1 0 hl_30 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 34.80 2100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 33.60 2200.0 0.0 +0 +endtrack +node -1 0 hl_31 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 33.60 2200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 32.40 2300.0 0.0 +0 +endtrack +node -1 0 hl_32 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 32.40 2300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 31.20 2400.0 0.0 +0 +endtrack +node -1 0 hl_33 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 31.20 2400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 30.00 2500.0 0.0 +0 +endtrack +node -1 0 hl_34 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 30.00 2500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 28.80 2600.0 0.0 +0 +endtrack +node -1 0 hl_35 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 28.80 2600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 27.60 2700.0 0.0 +0 +endtrack +node -1 0 hl_36 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 27.60 2700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 26.40 2800.0 0.0 +0 +endtrack +node -1 0 hl_37 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 26.40 2800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 25.20 2900.0 0.0 +0 +endtrack +node -1 0 hl_38 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 25.20 2900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 24.00 3000.0 0.0 +0 +endtrack +node -1 0 hl_39 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 24.00 3000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 22.80 3100.0 0.0 +0 +endtrack +node -1 0 hl_40 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 22.80 3100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 21.60 3200.0 0.0 +0 +endtrack +node -1 0 hl_41 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 21.60 3200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 20.40 3300.0 0.0 +0 +endtrack +node -1 0 hl_42 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 20.40 3300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 19.20 3400.0 0.0 +0 +endtrack +node -1 0 hl_43 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 19.20 3400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 18.00 3500.0 0.0 +0 +endtrack +node -1 0 hl_44 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 18.00 3500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 16.80 3600.0 0.0 +0 +endtrack +node -1 0 hl_45 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 16.80 3600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 15.60 3700.0 0.0 +0 +endtrack +node -1 0 hl_46 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 15.60 3700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 14.40 3800.0 0.0 +0 +endtrack +node -1 0 hl_47 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 14.40 3800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 13.20 3900.0 0.0 +0 +endtrack +node -1 0 hl_48 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 13.20 3900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 12.00 4000.0 0.0 +0 +endtrack +node -1 0 hl_49 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 12.00 4000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 10.80 4100.0 0.0 +0 +endtrack +node -1 0 hl_50 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 10.80 4100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 9.60 4200.0 0.0 +0 +endtrack +node -1 0 hl_51 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 9.60 4200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 8.40 4300.0 0.0 +0 +endtrack +node -1 0 hl_52 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 8.40 4300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 7.20 4400.0 0.0 +0 +endtrack +node -1 0 hl_53 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 7.20 4400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 6.00 4500.0 0.0 +0 +endtrack +node -1 0 hl_54 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 6.00 4500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 4.80 4600.0 0.0 +0 +endtrack +node -1 0 hl_55 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 4.80 4600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 3.60 4700.0 0.0 +0 +endtrack +node -1 0 hl_56 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 3.60 4700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 2.40 4800.0 0.0 +0 +endtrack +node -1 0 hl_57 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 2.40 4800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 1.20 4900.0 0.0 +0 +endtrack +node -1 0 hl_58 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 1.20 4900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -0.00 5000.0 0.0 +0 +endtrack +node -1 0 hl_59 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -0.00 5000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -1.20 5100.0 0.0 +0 +endtrack +node -1 0 hl_60 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -1.20 5100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -2.40 5200.0 0.0 +0 +endtrack +node -1 0 hl_61 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -2.40 5200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -3.60 5300.0 0.0 +0 +endtrack +node -1 0 hl_62 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -3.60 5300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -4.80 5400.0 0.0 +0 +endtrack +node -1 0 hl_63 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -4.80 5400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -6.00 5500.0 0.0 +0 +endtrack +node -1 0 hl_64 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -6.00 5500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -7.20 5600.0 0.0 +0 +endtrack +node -1 0 hl_65 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -7.20 5600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -8.40 5700.0 0.0 +0 +endtrack +node -1 0 hl_66 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -8.40 5700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -9.60 5800.0 0.0 +0 +endtrack +node -1 0 hl_67 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -9.60 5800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -10.80 5900.0 0.0 +0 +endtrack +node -1 0 hl_68 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -10.80 5900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -12.00 6000.0 0.0 +0 +event2 hl_sem_info +endtrack +node -1 0 hl_69 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -12.00 6000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -13.20 6100.0 0.0 +0 +endtrack +node -1 0 hl_70 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -13.20 6100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -14.40 6200.0 0.0 +0 +endtrack +node -1 0 hl_71 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -14.40 6200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -15.60 6300.0 0.0 +0 +endtrack +node -1 0 hl_72 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -15.60 6300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -16.80 6400.0 0.0 +0 +endtrack +node -1 0 hl_73 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -16.80 6400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -18.00 6500.0 0.0 +0 +endtrack +// the W4 of the stations of the timetable +include ip/pkp/w4n.inc gora#1 -2997.3 60.00 -90.0 180 0 0 -10 202 end +// a signal at stop: what the AI reads of one, a memory cell with SetVelocity 0 0 and the event that reads it +node -1 0 hl_sem_mem memcell -2997.3 -4.00 6000.0 SetVelocity 0.0 0.0 none endmemcell +event hl_sem_info getvalues 5.0 hl_sem_mem endevent + +trainset {{timetable}} hl_08 0.0 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_downgrade_restriction.scn b/tests/scenarios/cases/td_downgrade_restriction.scn new file mode 100644 index 000000000..42c7cf775 --- /dev/null +++ b/tests/scenarios/cases/td_downgrade_restriction.scn @@ -0,0 +1,638 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a line of its own, away from the tracks of td.scn: 600 m level, then 3500 m down a gradient of 20 per mille, +// under an overhead wire. the train starts on the level with its head 10 m before the W4 of Gora and runs on the timetable +// {{timetable}} (no stop; a freight train leaves Gora at once): its line limit, a 20 km/h restriction from 1500 to 1900 m +// down the gradient, then the signal hr_sem at stop 3000 m down the gradient. the line goes on 500 m past the signal +node -1 0 hr_00 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -500.0 0.0 +0 +endtrack +node -1 0 hr_01 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -400.0 0.0 +0 +endtrack +node -1 0 hr_02 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -300.0 0.0 +0 +endtrack +node -1 0 hr_03 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -200.0 0.0 +0 +endtrack +node -1 0 hr_04 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -100.0 0.0 +0 +endtrack +node -1 0 hr_05 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 0.0 0.0 +0 +event2 gora#1_stopinfo +endtrack +node -1 0 hr_06 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 0.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 58.00 100.0 0.0 +0 +endtrack +node -1 0 hr_07 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 58.00 100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 56.00 200.0 0.0 +0 +endtrack +node -1 0 hr_08 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 56.00 200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 54.00 300.0 0.0 +0 +endtrack +node -1 0 hr_09 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 54.00 300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 52.00 400.0 0.0 +0 +endtrack +node -1 0 hr_10 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 52.00 400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 50.00 500.0 0.0 +0 +endtrack +node -1 0 hr_11 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 50.00 500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 48.00 600.0 0.0 +0 +endtrack +node -1 0 hr_12 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 48.00 600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 46.00 700.0 0.0 +0 +endtrack +node -1 0 hr_13 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 46.00 700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 44.00 800.0 0.0 +0 +endtrack +node -1 0 hr_14 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 44.00 800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 42.00 900.0 0.0 +0 +endtrack +node -1 0 hr_15 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 42.00 900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 40.00 1000.0 0.0 +0 +endtrack +node -1 0 hr_16 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 40.00 1000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 38.00 1100.0 0.0 +0 +endtrack +node -1 0 hr_17 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 38.00 1100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 36.00 1200.0 0.0 +0 +endtrack +node -1 0 hr_18 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 36.00 1200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 34.00 1300.0 0.0 +0 +endtrack +node -1 0 hr_19 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 34.00 1300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 32.00 1400.0 0.0 +0 +endtrack +node -1 0 hr_20 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 32.00 1400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 30.00 1500.0 0.0 +0 +endtrack +node -1 0 hr_21 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 30.00 1500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 28.00 1600.0 0.0 +0 +velocity 20 +endtrack +node -1 0 hr_22 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 28.00 1600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 26.00 1700.0 0.0 +0 +velocity 20 +endtrack +node -1 0 hr_23 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 26.00 1700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 24.00 1800.0 0.0 +0 +velocity 20 +endtrack +node -1 0 hr_24 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 24.00 1800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 22.00 1900.0 0.0 +0 +velocity 20 +endtrack +node -1 0 hr_25 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 22.00 1900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 20.00 2000.0 0.0 +0 +endtrack +node -1 0 hr_26 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 20.00 2000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 18.00 2100.0 0.0 +0 +endtrack +node -1 0 hr_27 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 18.00 2100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 16.00 2200.0 0.0 +0 +endtrack +node -1 0 hr_28 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 16.00 2200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 14.00 2300.0 0.0 +0 +endtrack +node -1 0 hr_29 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 14.00 2300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 12.00 2400.0 0.0 +0 +endtrack +node -1 0 hr_30 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 12.00 2400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 10.00 2500.0 0.0 +0 +endtrack +node -1 0 hr_31 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 10.00 2500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 8.00 2600.0 0.0 +0 +endtrack +node -1 0 hr_32 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 8.00 2600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 6.00 2700.0 0.0 +0 +endtrack +node -1 0 hr_33 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 6.00 2700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 4.00 2800.0 0.0 +0 +endtrack +node -1 0 hr_34 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 4.00 2800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 2.00 2900.0 0.0 +0 +endtrack +node -1 0 hr_35 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 2.00 2900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 0.00 3000.0 0.0 +0 +event2 hr_sem_info +endtrack +node -1 0 hr_36 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 0.00 3000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -2.00 3100.0 0.0 +0 +endtrack +node -1 0 hr_37 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -2.00 3100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -4.00 3200.0 0.0 +0 +endtrack +node -1 0 hr_38 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -4.00 3200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -6.00 3300.0 0.0 +0 +endtrack +node -1 0 hr_39 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -6.00 3300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -8.00 3400.0 0.0 +0 +endtrack +node -1 0 hr_40 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -8.00 3400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -10.00 3500.0 0.0 +0 +endtrack +// the overhead wire along the whole line, as td.scn has it: 5.6 m above the rail, the carrier 1.7 m higher, fed by +// a substation of its own +node -1 0 hr_pwr tractionpowersource -3000.0 60.00 0.0 3400 0 0.01 2000 1.0 3 60.0 end +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -600.0 +-3000.0 65.60 -500.0 +-3000.0 67.30 -600.0 +-3000.0 67.30 -500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -500.0 +-3000.0 65.60 -400.0 +-3000.0 67.30 -500.0 +-3000.0 67.30 -400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -400.0 +-3000.0 65.60 -300.0 +-3000.0 67.30 -400.0 +-3000.0 67.30 -300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -300.0 +-3000.0 65.60 -200.0 +-3000.0 67.30 -300.0 +-3000.0 67.30 -200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -200.0 +-3000.0 65.60 -100.0 +-3000.0 67.30 -200.0 +-3000.0 67.30 -100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -100.0 +-3000.0 65.60 0.0 +-3000.0 67.30 -100.0 +-3000.0 67.30 0.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 0.0 +-3000.0 63.60 100.0 +-3000.0 67.30 0.0 +-3000.0 65.30 100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 63.60 100.0 +-3000.0 61.60 200.0 +-3000.0 65.30 100.0 +-3000.0 63.30 200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 61.60 200.0 +-3000.0 59.60 300.0 +-3000.0 63.30 200.0 +-3000.0 61.30 300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 59.60 300.0 +-3000.0 57.60 400.0 +-3000.0 61.30 300.0 +-3000.0 59.30 400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 57.60 400.0 +-3000.0 55.60 500.0 +-3000.0 59.30 400.0 +-3000.0 57.30 500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 55.60 500.0 +-3000.0 53.60 600.0 +-3000.0 57.30 500.0 +-3000.0 55.30 600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 53.60 600.0 +-3000.0 51.60 700.0 +-3000.0 55.30 600.0 +-3000.0 53.30 700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 51.60 700.0 +-3000.0 49.60 800.0 +-3000.0 53.30 700.0 +-3000.0 51.30 800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 49.60 800.0 +-3000.0 47.60 900.0 +-3000.0 51.30 800.0 +-3000.0 49.30 900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 47.60 900.0 +-3000.0 45.60 1000.0 +-3000.0 49.30 900.0 +-3000.0 47.30 1000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 45.60 1000.0 +-3000.0 43.60 1100.0 +-3000.0 47.30 1000.0 +-3000.0 45.30 1100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 43.60 1100.0 +-3000.0 41.60 1200.0 +-3000.0 45.30 1100.0 +-3000.0 43.30 1200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 41.60 1200.0 +-3000.0 39.60 1300.0 +-3000.0 43.30 1200.0 +-3000.0 41.30 1300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 39.60 1300.0 +-3000.0 37.60 1400.0 +-3000.0 41.30 1300.0 +-3000.0 39.30 1400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 37.60 1400.0 +-3000.0 35.60 1500.0 +-3000.0 39.30 1400.0 +-3000.0 37.30 1500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 35.60 1500.0 +-3000.0 33.60 1600.0 +-3000.0 37.30 1500.0 +-3000.0 35.30 1600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 33.60 1600.0 +-3000.0 31.60 1700.0 +-3000.0 35.30 1600.0 +-3000.0 33.30 1700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 31.60 1700.0 +-3000.0 29.60 1800.0 +-3000.0 33.30 1700.0 +-3000.0 31.30 1800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 29.60 1800.0 +-3000.0 27.60 1900.0 +-3000.0 31.30 1800.0 +-3000.0 29.30 1900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 27.60 1900.0 +-3000.0 25.60 2000.0 +-3000.0 29.30 1900.0 +-3000.0 27.30 2000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 25.60 2000.0 +-3000.0 23.60 2100.0 +-3000.0 27.30 2000.0 +-3000.0 25.30 2100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 23.60 2100.0 +-3000.0 21.60 2200.0 +-3000.0 25.30 2100.0 +-3000.0 23.30 2200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 21.60 2200.0 +-3000.0 19.60 2300.0 +-3000.0 23.30 2200.0 +-3000.0 21.30 2300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 19.60 2300.0 +-3000.0 17.60 2400.0 +-3000.0 21.30 2300.0 +-3000.0 19.30 2400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 17.60 2400.0 +-3000.0 15.60 2500.0 +-3000.0 19.30 2400.0 +-3000.0 17.30 2500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 15.60 2500.0 +-3000.0 13.60 2600.0 +-3000.0 17.30 2500.0 +-3000.0 15.30 2600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 13.60 2600.0 +-3000.0 11.60 2700.0 +-3000.0 15.30 2600.0 +-3000.0 13.30 2700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 11.60 2700.0 +-3000.0 9.60 2800.0 +-3000.0 13.30 2700.0 +-3000.0 11.30 2800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 9.60 2800.0 +-3000.0 7.60 2900.0 +-3000.0 11.30 2800.0 +-3000.0 9.30 2900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 7.60 2900.0 +-3000.0 5.60 3000.0 +-3000.0 9.30 2900.0 +-3000.0 7.30 3000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 5.60 3000.0 +-3000.0 3.60 3100.0 +-3000.0 7.30 3000.0 +-3000.0 5.30 3100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 3.60 3100.0 +-3000.0 1.60 3200.0 +-3000.0 5.30 3100.0 +-3000.0 3.30 3200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 1.60 3200.0 +-3000.0 -0.40 3300.0 +-3000.0 3.30 3200.0 +-3000.0 1.30 3300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 -0.40 3300.0 +-3000.0 -2.40 3400.0 +-3000.0 1.30 3300.0 +-3000.0 -0.70 3400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 -2.40 3400.0 +-3000.0 -4.40 3500.0 +-3000.0 -0.70 3400.0 +-3000.0 -2.70 3500.0 +0.4 4.0 3 0.04 vis +endtraction +// the W4 of the stations of the timetable +include ip/pkp/w4n.inc gora#1 -2997.3 60.00 -90.0 180 0 0 -10 202 end +// a signal at stop: what the AI reads of one, a memory cell with SetVelocity 0 0 and the event that reads it +node -1 0 hr_sem_mem memcell -2997.3 8.00 3000.0 SetVelocity 0.0 0.0 none endmemcell +event hr_sem_info getvalues 5.0 hr_sem_mem endevent + +trainset {{timetable}} hr_05 0.0 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_freight_downgrade.txt b/tests/scenarios/cases/td_freight_downgrade.txt new file mode 100644 index 000000000..1fd01f911 --- /dev/null +++ b/tests/scenarios/cases/td_freight_downgrade.txt @@ -0,0 +1,17 @@ +________________________________________________________________ +[ Rodzaj i numer pociagu | TEST44 ] +[ Kategoria | TME ] +[________________________________________________|______________] +[ | Gora ] +[ Relacja pociagu | Koniec ] +[________________________________________________|______________] +[ Wymagany % ciezaru hamujacego | 50% ] +[________________________________________________|______________] +[ Seria i obciazenie lokomotywy | ET41 1700 ] +[________________________________________________|______________] +[ | | Gora 2 | | ] +[ | 60 | R1,L,H,RT,PP 2 10.35 | ] +[ | |----------------------------------1----------|---] +[ | | Koniec 1 10.55 | 20] +[ | | R1 1 10.56 | ] +[_______|_____|__________________________________1__________|___] diff --git a/tests/scenarios/cases/td_freight_downgrade12.txt b/tests/scenarios/cases/td_freight_downgrade12.txt new file mode 100644 index 000000000..1fc503342 --- /dev/null +++ b/tests/scenarios/cases/td_freight_downgrade12.txt @@ -0,0 +1,17 @@ +________________________________________________________________ +[ Rodzaj i numer pociagu | TEST45 ] +[ Kategoria | TME ] +[________________________________________________|______________] +[ | Gora ] +[ Relacja pociagu | Koniec ] +[________________________________________________|______________] +[ Wymagany % ciezaru hamujacego | 50% ] +[________________________________________________|______________] +[ Seria i obciazenie lokomotywy | ST43 3000 ] +[________________________________________________|______________] +[ | | Gora 2 | | ] +[ | 40 | R1,L,H,RT,PP 2 10.35 | ] +[ | |----------------------------------1----------|---] +[ | | Koniec 1 11.10 | 35] +[ | | R1 1 11.11 | ] +[_______|_____|__________________________________1__________|___] diff --git a/tests/scenarios/cases/td_level_signal.scn b/tests/scenarios/cases/td_level_signal.scn new file mode 100644 index 000000000..c3d13eb87 --- /dev/null +++ b/tests/scenarios/cases/td_level_signal.scn @@ -0,0 +1,333 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a line of its own, away from the tracks of td.scn: 2100 m level, under an overhead wire. the train starts with +// its head 10 m before the W4 of Gora and runs on the timetable {{timetable}} (no stop; a freight train leaves Gora at once) to the signal +// lv_sem at stop 1000 m ahead. the line goes on 500 m past it +node -1 0 lv_00 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -500.0 0.0 +0 +endtrack +node -1 0 lv_01 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -400.0 0.0 +0 +endtrack +node -1 0 lv_02 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -300.0 0.0 +0 +endtrack +node -1 0 lv_03 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -200.0 0.0 +0 +endtrack +node -1 0 lv_04 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -100.0 0.0 +0 +endtrack +node -1 0 lv_05 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 0.0 0.0 +0 +event2 gora#1_stopinfo +endtrack +node -1 0 lv_06 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 0.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 100.0 0.0 +0 +endtrack +node -1 0 lv_07 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 200.0 0.0 +0 +endtrack +node -1 0 lv_08 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 300.0 0.0 +0 +endtrack +node -1 0 lv_09 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 400.0 0.0 +0 +endtrack +node -1 0 lv_10 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 500.0 0.0 +0 +endtrack +node -1 0 lv_11 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 600.0 0.0 +0 +endtrack +node -1 0 lv_12 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 700.0 0.0 +0 +endtrack +node -1 0 lv_13 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 800.0 0.0 +0 +endtrack +node -1 0 lv_14 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 900.0 0.0 +0 +endtrack +node -1 0 lv_15 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 1000.0 0.0 +0 +event2 lv_sem_info +endtrack +node -1 0 lv_16 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 1000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 1100.0 0.0 +0 +endtrack +node -1 0 lv_17 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 1100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 1200.0 0.0 +0 +endtrack +node -1 0 lv_18 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 1200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 1300.0 0.0 +0 +endtrack +node -1 0 lv_19 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 1300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 1400.0 0.0 +0 +endtrack +node -1 0 lv_20 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 1400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 1500.0 0.0 +0 +endtrack +// the overhead wire along the whole line, as td.scn has it: 5.6 m above the rail, the carrier 1.7 m higher, fed by +// a substation of its own +node -1 0 lv_pwr tractionpowersource -3000.0 60.00 0.0 3400 0 0.01 2000 1.0 3 60.0 end +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -600.0 +-3000.0 65.60 -500.0 +-3000.0 67.30 -600.0 +-3000.0 67.30 -500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -500.0 +-3000.0 65.60 -400.0 +-3000.0 67.30 -500.0 +-3000.0 67.30 -400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -400.0 +-3000.0 65.60 -300.0 +-3000.0 67.30 -400.0 +-3000.0 67.30 -300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -300.0 +-3000.0 65.60 -200.0 +-3000.0 67.30 -300.0 +-3000.0 67.30 -200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -200.0 +-3000.0 65.60 -100.0 +-3000.0 67.30 -200.0 +-3000.0 67.30 -100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -100.0 +-3000.0 65.60 0.0 +-3000.0 67.30 -100.0 +-3000.0 67.30 0.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 0.0 +-3000.0 65.60 100.0 +-3000.0 67.30 0.0 +-3000.0 67.30 100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 100.0 +-3000.0 65.60 200.0 +-3000.0 67.30 100.0 +-3000.0 67.30 200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 200.0 +-3000.0 65.60 300.0 +-3000.0 67.30 200.0 +-3000.0 67.30 300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 300.0 +-3000.0 65.60 400.0 +-3000.0 67.30 300.0 +-3000.0 67.30 400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 400.0 +-3000.0 65.60 500.0 +-3000.0 67.30 400.0 +-3000.0 67.30 500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 500.0 +-3000.0 65.60 600.0 +-3000.0 67.30 500.0 +-3000.0 67.30 600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 600.0 +-3000.0 65.60 700.0 +-3000.0 67.30 600.0 +-3000.0 67.30 700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 700.0 +-3000.0 65.60 800.0 +-3000.0 67.30 700.0 +-3000.0 67.30 800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 800.0 +-3000.0 65.60 900.0 +-3000.0 67.30 800.0 +-3000.0 67.30 900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 900.0 +-3000.0 65.60 1000.0 +-3000.0 67.30 900.0 +-3000.0 67.30 1000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 1000.0 +-3000.0 65.60 1100.0 +-3000.0 67.30 1000.0 +-3000.0 67.30 1100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 1100.0 +-3000.0 65.60 1200.0 +-3000.0 67.30 1100.0 +-3000.0 67.30 1200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 1200.0 +-3000.0 65.60 1300.0 +-3000.0 67.30 1200.0 +-3000.0 67.30 1300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 1300.0 +-3000.0 65.60 1400.0 +-3000.0 67.30 1300.0 +-3000.0 67.30 1400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 1400.0 +-3000.0 65.60 1500.0 +-3000.0 67.30 1400.0 +-3000.0 67.30 1500.0 +0.4 4.0 3 0.04 vis +endtraction +// the W4 of the stations of the timetable +include ip/pkp/w4n.inc gora#1 -2997.3 60.00 -90.0 180 0 0 -10 202 end +// a signal at stop: what the AI reads of one, a memory cell with SetVelocity 0 0 and the event that reads it +node -1 0 lv_sem_mem memcell -2997.3 68.00 1000.0 SetVelocity 0.0 0.0 none endmemcell +event lv_sem_info getvalues 5.0 lv_sem_mem endevent + +trainset {{timetable}} lv_05 0.0 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_passenger_upgrade.txt b/tests/scenarios/cases/td_passenger_upgrade.txt new file mode 100644 index 000000000..bc8e12087 --- /dev/null +++ b/tests/scenarios/cases/td_passenger_upgrade.txt @@ -0,0 +1,17 @@ +________________________________________________________________ +[ Rodzaj i numer pociagu | TEST28 ] +[ Kategoria | RO ] +[________________________________________________|______________] +[ | Gora ] +[ Relacja pociagu | Koniec ] +[________________________________________________|______________] +[ Wymagany % ciezaru hamujacego | 88% ] +[________________________________________________|______________] +[ Seria i obciazenie lokomotywy | EU07 400 ] +[________________________________________________|______________] +[ | | Gora 2 | | ] +[ | 80 | R1,L,H,RT,PP 2 10.35 | ] +[ | |----------------------------------1----------|---] +[ | | Koniec 1 10.45 | 10] +[ | | R1 1 10.46 | ] +[_______|_____|__________________________________1__________|___] diff --git a/tests/scenarios/cases/td_upgrade_long.scn b/tests/scenarios/cases/td_upgrade_long.scn new file mode 100644 index 000000000..12ff5c713 --- /dev/null +++ b/tests/scenarios/cases/td_upgrade_long.scn @@ -0,0 +1,934 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a line of its own, away from the tracks of td.scn: 600 m level, then 5500 m up a gradient of 10 per mille, +// under an overhead wire. the train starts on the level with its head 10 m before the W4 of Gora and runs on the +// timetable {{timetable}} (leaves Gora at 10:35, no other stop) at the line limit of the timetable, up to the signal ul_sem +// at stop 5300 m up the gradient. the line goes on 200 m past it +node -1 0 ul_00 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -500.0 0.0 +0 +endtrack +node -1 0 ul_01 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -400.0 0.0 +0 +endtrack +node -1 0 ul_02 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -300.0 0.0 +0 +endtrack +node -1 0 ul_03 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -200.0 0.0 +0 +endtrack +node -1 0 ul_04 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -100.0 0.0 +0 +endtrack +node -1 0 ul_05 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 0.0 0.0 +0 +event2 gora#1_stopinfo +endtrack +node -1 0 ul_06 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 0.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 61.00 100.0 0.0 +0 +endtrack +node -1 0 ul_07 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 61.00 100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 62.00 200.0 0.0 +0 +endtrack +node -1 0 ul_08 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 62.00 200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 63.00 300.0 0.0 +0 +endtrack +node -1 0 ul_09 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 63.00 300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 64.00 400.0 0.0 +0 +endtrack +node -1 0 ul_10 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 64.00 400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 65.00 500.0 0.0 +0 +endtrack +node -1 0 ul_11 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 65.00 500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 66.00 600.0 0.0 +0 +endtrack +node -1 0 ul_12 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 66.00 600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 67.00 700.0 0.0 +0 +endtrack +node -1 0 ul_13 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 67.00 700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 68.00 800.0 0.0 +0 +endtrack +node -1 0 ul_14 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 68.00 800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 69.00 900.0 0.0 +0 +endtrack +node -1 0 ul_15 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 69.00 900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 70.00 1000.0 0.0 +0 +endtrack +node -1 0 ul_16 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 70.00 1000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 71.00 1100.0 0.0 +0 +endtrack +node -1 0 ul_17 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 71.00 1100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 72.00 1200.0 0.0 +0 +endtrack +node -1 0 ul_18 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 72.00 1200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 73.00 1300.0 0.0 +0 +endtrack +node -1 0 ul_19 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 73.00 1300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 74.00 1400.0 0.0 +0 +endtrack +node -1 0 ul_20 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 74.00 1400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 75.00 1500.0 0.0 +0 +endtrack +node -1 0 ul_21 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 75.00 1500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 76.00 1600.0 0.0 +0 +endtrack +node -1 0 ul_22 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 76.00 1600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 77.00 1700.0 0.0 +0 +endtrack +node -1 0 ul_23 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 77.00 1700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 78.00 1800.0 0.0 +0 +endtrack +node -1 0 ul_24 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 78.00 1800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 79.00 1900.0 0.0 +0 +endtrack +node -1 0 ul_25 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 79.00 1900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 80.00 2000.0 0.0 +0 +endtrack +node -1 0 ul_26 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 80.00 2000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 81.00 2100.0 0.0 +0 +endtrack +node -1 0 ul_27 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 81.00 2100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 82.00 2200.0 0.0 +0 +endtrack +node -1 0 ul_28 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 82.00 2200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 83.00 2300.0 0.0 +0 +endtrack +node -1 0 ul_29 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 83.00 2300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 84.00 2400.0 0.0 +0 +endtrack +node -1 0 ul_30 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 84.00 2400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 85.00 2500.0 0.0 +0 +endtrack +node -1 0 ul_31 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 85.00 2500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 86.00 2600.0 0.0 +0 +endtrack +node -1 0 ul_32 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 86.00 2600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 87.00 2700.0 0.0 +0 +endtrack +node -1 0 ul_33 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 87.00 2700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 88.00 2800.0 0.0 +0 +endtrack +node -1 0 ul_34 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 88.00 2800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 89.00 2900.0 0.0 +0 +endtrack +node -1 0 ul_35 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 89.00 2900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 90.00 3000.0 0.0 +0 +endtrack +node -1 0 ul_36 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 90.00 3000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 91.00 3100.0 0.0 +0 +endtrack +node -1 0 ul_37 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 91.00 3100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 92.00 3200.0 0.0 +0 +endtrack +node -1 0 ul_38 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 92.00 3200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 93.00 3300.0 0.0 +0 +endtrack +node -1 0 ul_39 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 93.00 3300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 94.00 3400.0 0.0 +0 +endtrack +node -1 0 ul_40 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 94.00 3400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 95.00 3500.0 0.0 +0 +endtrack +node -1 0 ul_41 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 95.00 3500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 96.00 3600.0 0.0 +0 +endtrack +node -1 0 ul_42 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 96.00 3600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 97.00 3700.0 0.0 +0 +endtrack +node -1 0 ul_43 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 97.00 3700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 98.00 3800.0 0.0 +0 +endtrack +node -1 0 ul_44 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 98.00 3800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 99.00 3900.0 0.0 +0 +endtrack +node -1 0 ul_45 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 99.00 3900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 100.00 4000.0 0.0 +0 +endtrack +node -1 0 ul_46 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 100.00 4000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 101.00 4100.0 0.0 +0 +endtrack +node -1 0 ul_47 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 101.00 4100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 102.00 4200.0 0.0 +0 +endtrack +node -1 0 ul_48 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 102.00 4200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 103.00 4300.0 0.0 +0 +endtrack +node -1 0 ul_49 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 103.00 4300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 104.00 4400.0 0.0 +0 +endtrack +node -1 0 ul_50 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 104.00 4400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 105.00 4500.0 0.0 +0 +endtrack +node -1 0 ul_51 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 105.00 4500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 106.00 4600.0 0.0 +0 +endtrack +node -1 0 ul_52 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 106.00 4600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 107.00 4700.0 0.0 +0 +endtrack +node -1 0 ul_53 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 107.00 4700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 108.00 4800.0 0.0 +0 +endtrack +node -1 0 ul_54 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 108.00 4800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 109.00 4900.0 0.0 +0 +endtrack +node -1 0 ul_55 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 109.00 4900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 110.00 5000.0 0.0 +0 +endtrack +node -1 0 ul_56 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 110.00 5000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 111.00 5100.0 0.0 +0 +endtrack +node -1 0 ul_57 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 111.00 5100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 112.00 5200.0 0.0 +0 +endtrack +node -1 0 ul_58 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 112.00 5200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 113.00 5300.0 0.0 +0 +event2 ul_sem_info +endtrack +node -1 0 ul_59 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 113.00 5300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 114.00 5400.0 0.0 +0 +endtrack +node -1 0 ul_60 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 114.00 5400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 115.00 5500.0 0.0 +0 +endtrack +// the overhead wire along the whole line, as td.scn has it: 5.6 m above the rail, the carrier 1.7 m higher, fed by +// a substation of its own +node -1 0 ul_pwr tractionpowersource -3000.0 60.00 0.0 3400 0 0.01 2000 1.0 3 60.0 end +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -600.0 +-3000.0 65.60 -500.0 +-3000.0 67.30 -600.0 +-3000.0 67.30 -500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -500.0 +-3000.0 65.60 -400.0 +-3000.0 67.30 -500.0 +-3000.0 67.30 -400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -400.0 +-3000.0 65.60 -300.0 +-3000.0 67.30 -400.0 +-3000.0 67.30 -300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -300.0 +-3000.0 65.60 -200.0 +-3000.0 67.30 -300.0 +-3000.0 67.30 -200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -200.0 +-3000.0 65.60 -100.0 +-3000.0 67.30 -200.0 +-3000.0 67.30 -100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -100.0 +-3000.0 65.60 0.0 +-3000.0 67.30 -100.0 +-3000.0 67.30 0.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 0.0 +-3000.0 66.60 100.0 +-3000.0 67.30 0.0 +-3000.0 68.30 100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 66.60 100.0 +-3000.0 67.60 200.0 +-3000.0 68.30 100.0 +-3000.0 69.30 200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 67.60 200.0 +-3000.0 68.60 300.0 +-3000.0 69.30 200.0 +-3000.0 70.30 300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 68.60 300.0 +-3000.0 69.60 400.0 +-3000.0 70.30 300.0 +-3000.0 71.30 400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 69.60 400.0 +-3000.0 70.60 500.0 +-3000.0 71.30 400.0 +-3000.0 72.30 500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 70.60 500.0 +-3000.0 71.60 600.0 +-3000.0 72.30 500.0 +-3000.0 73.30 600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 71.60 600.0 +-3000.0 72.60 700.0 +-3000.0 73.30 600.0 +-3000.0 74.30 700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 72.60 700.0 +-3000.0 73.60 800.0 +-3000.0 74.30 700.0 +-3000.0 75.30 800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 73.60 800.0 +-3000.0 74.60 900.0 +-3000.0 75.30 800.0 +-3000.0 76.30 900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 74.60 900.0 +-3000.0 75.60 1000.0 +-3000.0 76.30 900.0 +-3000.0 77.30 1000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 75.60 1000.0 +-3000.0 76.60 1100.0 +-3000.0 77.30 1000.0 +-3000.0 78.30 1100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 76.60 1100.0 +-3000.0 77.60 1200.0 +-3000.0 78.30 1100.0 +-3000.0 79.30 1200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 77.60 1200.0 +-3000.0 78.60 1300.0 +-3000.0 79.30 1200.0 +-3000.0 80.30 1300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 78.60 1300.0 +-3000.0 79.60 1400.0 +-3000.0 80.30 1300.0 +-3000.0 81.30 1400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 79.60 1400.0 +-3000.0 80.60 1500.0 +-3000.0 81.30 1400.0 +-3000.0 82.30 1500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 80.60 1500.0 +-3000.0 81.60 1600.0 +-3000.0 82.30 1500.0 +-3000.0 83.30 1600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 81.60 1600.0 +-3000.0 82.60 1700.0 +-3000.0 83.30 1600.0 +-3000.0 84.30 1700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 82.60 1700.0 +-3000.0 83.60 1800.0 +-3000.0 84.30 1700.0 +-3000.0 85.30 1800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 83.60 1800.0 +-3000.0 84.60 1900.0 +-3000.0 85.30 1800.0 +-3000.0 86.30 1900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 84.60 1900.0 +-3000.0 85.60 2000.0 +-3000.0 86.30 1900.0 +-3000.0 87.30 2000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 85.60 2000.0 +-3000.0 86.60 2100.0 +-3000.0 87.30 2000.0 +-3000.0 88.30 2100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 86.60 2100.0 +-3000.0 87.60 2200.0 +-3000.0 88.30 2100.0 +-3000.0 89.30 2200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 87.60 2200.0 +-3000.0 88.60 2300.0 +-3000.0 89.30 2200.0 +-3000.0 90.30 2300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 88.60 2300.0 +-3000.0 89.60 2400.0 +-3000.0 90.30 2300.0 +-3000.0 91.30 2400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 89.60 2400.0 +-3000.0 90.60 2500.0 +-3000.0 91.30 2400.0 +-3000.0 92.30 2500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 90.60 2500.0 +-3000.0 91.60 2600.0 +-3000.0 92.30 2500.0 +-3000.0 93.30 2600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 91.60 2600.0 +-3000.0 92.60 2700.0 +-3000.0 93.30 2600.0 +-3000.0 94.30 2700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 92.60 2700.0 +-3000.0 93.60 2800.0 +-3000.0 94.30 2700.0 +-3000.0 95.30 2800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 93.60 2800.0 +-3000.0 94.60 2900.0 +-3000.0 95.30 2800.0 +-3000.0 96.30 2900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 94.60 2900.0 +-3000.0 95.60 3000.0 +-3000.0 96.30 2900.0 +-3000.0 97.30 3000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 95.60 3000.0 +-3000.0 96.60 3100.0 +-3000.0 97.30 3000.0 +-3000.0 98.30 3100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 96.60 3100.0 +-3000.0 97.60 3200.0 +-3000.0 98.30 3100.0 +-3000.0 99.30 3200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 97.60 3200.0 +-3000.0 98.60 3300.0 +-3000.0 99.30 3200.0 +-3000.0 100.30 3300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 98.60 3300.0 +-3000.0 99.60 3400.0 +-3000.0 100.30 3300.0 +-3000.0 101.30 3400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 99.60 3400.0 +-3000.0 100.60 3500.0 +-3000.0 101.30 3400.0 +-3000.0 102.30 3500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 100.60 3500.0 +-3000.0 101.60 3600.0 +-3000.0 102.30 3500.0 +-3000.0 103.30 3600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 101.60 3600.0 +-3000.0 102.60 3700.0 +-3000.0 103.30 3600.0 +-3000.0 104.30 3700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 102.60 3700.0 +-3000.0 103.60 3800.0 +-3000.0 104.30 3700.0 +-3000.0 105.30 3800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 103.60 3800.0 +-3000.0 104.60 3900.0 +-3000.0 105.30 3800.0 +-3000.0 106.30 3900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 104.60 3900.0 +-3000.0 105.60 4000.0 +-3000.0 106.30 3900.0 +-3000.0 107.30 4000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 105.60 4000.0 +-3000.0 106.60 4100.0 +-3000.0 107.30 4000.0 +-3000.0 108.30 4100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 106.60 4100.0 +-3000.0 107.60 4200.0 +-3000.0 108.30 4100.0 +-3000.0 109.30 4200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 107.60 4200.0 +-3000.0 108.60 4300.0 +-3000.0 109.30 4200.0 +-3000.0 110.30 4300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 108.60 4300.0 +-3000.0 109.60 4400.0 +-3000.0 110.30 4300.0 +-3000.0 111.30 4400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 109.60 4400.0 +-3000.0 110.60 4500.0 +-3000.0 111.30 4400.0 +-3000.0 112.30 4500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 110.60 4500.0 +-3000.0 111.60 4600.0 +-3000.0 112.30 4500.0 +-3000.0 113.30 4600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 111.60 4600.0 +-3000.0 112.60 4700.0 +-3000.0 113.30 4600.0 +-3000.0 114.30 4700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 112.60 4700.0 +-3000.0 113.60 4800.0 +-3000.0 114.30 4700.0 +-3000.0 115.30 4800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 113.60 4800.0 +-3000.0 114.60 4900.0 +-3000.0 115.30 4800.0 +-3000.0 116.30 4900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 114.60 4900.0 +-3000.0 115.60 5000.0 +-3000.0 116.30 4900.0 +-3000.0 117.30 5000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 115.60 5000.0 +-3000.0 116.60 5100.0 +-3000.0 117.30 5000.0 +-3000.0 118.30 5100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 116.60 5100.0 +-3000.0 117.60 5200.0 +-3000.0 118.30 5100.0 +-3000.0 119.30 5200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 117.60 5200.0 +-3000.0 118.60 5300.0 +-3000.0 119.30 5200.0 +-3000.0 120.30 5300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 118.60 5300.0 +-3000.0 119.60 5400.0 +-3000.0 120.30 5300.0 +-3000.0 121.30 5400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 119.60 5400.0 +-3000.0 120.60 5500.0 +-3000.0 121.30 5400.0 +-3000.0 122.30 5500.0 +0.4 4.0 3 0.04 vis +endtraction +// the W4 of the stations of the timetable +include ip/pkp/w4n.inc gora#1 -2997.3 60.00 -90.0 180 0 0 -10 202 end +// a signal at stop: what the AI reads of one, a memory cell with SetVelocity 0 0 and the event that reads it +node -1 0 ul_sem_mem memcell -2997.3 121.00 5300.0 SetVelocity 0.0 0.0 none endmemcell +event ul_sem_info getvalues 5.0 ul_sem_mem endevent + +trainset {{timetable}} ul_05 0.0 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_upgrade_signal_start.scn b/tests/scenarios/cases/td_upgrade_signal_start.scn new file mode 100644 index 000000000..3995d3a96 --- /dev/null +++ b/tests/scenarios/cases/td_upgrade_signal_start.scn @@ -0,0 +1,492 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a line of its own, away from the tracks of td.scn: 600 m level, then 2500 m up a gradient of 10 per mille, +// under an overhead wire. the train starts on the level with its head 10 m before the W4 of Gora and runs on the +// timetable {{timetable}} (no stop; a freight train leaves Gora at once) up to the signal hu_sem1 1000 m up the gradient, at stop until 10:42, +// where it stops with the whole train on the gradient, then on to the signal hu_sem2 at stop 2300 m up the +// gradient. the line goes on 200 m past it +node -1 0 hu_00 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -500.0 0.0 +0 +endtrack +node -1 0 hu_01 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -400.0 0.0 +0 +endtrack +node -1 0 hu_02 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -300.0 0.0 +0 +endtrack +node -1 0 hu_03 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -200.0 0.0 +0 +endtrack +node -1 0 hu_04 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -100.0 0.0 +0 +endtrack +node -1 0 hu_05 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 0.0 0.0 +0 +event2 gora#1_stopinfo +endtrack +node -1 0 hu_06 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 0.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 61.00 100.0 0.0 +0 +endtrack +node -1 0 hu_07 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 61.00 100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 62.00 200.0 0.0 +0 +endtrack +node -1 0 hu_08 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 62.00 200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 63.00 300.0 0.0 +0 +endtrack +node -1 0 hu_09 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 63.00 300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 64.00 400.0 0.0 +0 +endtrack +node -1 0 hu_10 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 64.00 400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 65.00 500.0 0.0 +0 +endtrack +node -1 0 hu_11 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 65.00 500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 66.00 600.0 0.0 +0 +endtrack +node -1 0 hu_12 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 66.00 600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 67.00 700.0 0.0 +0 +endtrack +node -1 0 hu_13 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 67.00 700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 68.00 800.0 0.0 +0 +endtrack +node -1 0 hu_14 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 68.00 800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 69.00 900.0 0.0 +0 +endtrack +node -1 0 hu_15 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 69.00 900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 70.00 1000.0 0.0 +0 +event2 hu_sem1_info +endtrack +node -1 0 hu_16 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 70.00 1000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 71.00 1100.0 0.0 +0 +endtrack +node -1 0 hu_17 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 71.00 1100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 72.00 1200.0 0.0 +0 +endtrack +node -1 0 hu_18 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 72.00 1200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 73.00 1300.0 0.0 +0 +endtrack +node -1 0 hu_19 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 73.00 1300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 74.00 1400.0 0.0 +0 +endtrack +node -1 0 hu_20 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 74.00 1400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 75.00 1500.0 0.0 +0 +endtrack +node -1 0 hu_21 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 75.00 1500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 76.00 1600.0 0.0 +0 +endtrack +node -1 0 hu_22 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 76.00 1600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 77.00 1700.0 0.0 +0 +endtrack +node -1 0 hu_23 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 77.00 1700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 78.00 1800.0 0.0 +0 +endtrack +node -1 0 hu_24 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 78.00 1800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 79.00 1900.0 0.0 +0 +endtrack +node -1 0 hu_25 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 79.00 1900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 80.00 2000.0 0.0 +0 +endtrack +node -1 0 hu_26 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 80.00 2000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 81.00 2100.0 0.0 +0 +endtrack +node -1 0 hu_27 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 81.00 2100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 82.00 2200.0 0.0 +0 +endtrack +node -1 0 hu_28 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 82.00 2200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 83.00 2300.0 0.0 +0 +event2 hu_sem2_info +endtrack +node -1 0 hu_29 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 83.00 2300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 84.00 2400.0 0.0 +0 +endtrack +node -1 0 hu_30 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 84.00 2400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 85.00 2500.0 0.0 +0 +endtrack +// the overhead wire along the whole line, as td.scn has it: 5.6 m above the rail, the carrier 1.7 m higher, fed by +// a substation of its own +node -1 0 hu_pwr tractionpowersource -3000.0 60.00 0.0 3400 0 0.01 2000 1.0 3 60.0 end +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -600.0 +-3000.0 65.60 -500.0 +-3000.0 67.30 -600.0 +-3000.0 67.30 -500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -500.0 +-3000.0 65.60 -400.0 +-3000.0 67.30 -500.0 +-3000.0 67.30 -400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -400.0 +-3000.0 65.60 -300.0 +-3000.0 67.30 -400.0 +-3000.0 67.30 -300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -300.0 +-3000.0 65.60 -200.0 +-3000.0 67.30 -300.0 +-3000.0 67.30 -200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -200.0 +-3000.0 65.60 -100.0 +-3000.0 67.30 -200.0 +-3000.0 67.30 -100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -100.0 +-3000.0 65.60 0.0 +-3000.0 67.30 -100.0 +-3000.0 67.30 0.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 0.0 +-3000.0 66.60 100.0 +-3000.0 67.30 0.0 +-3000.0 68.30 100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 66.60 100.0 +-3000.0 67.60 200.0 +-3000.0 68.30 100.0 +-3000.0 69.30 200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 67.60 200.0 +-3000.0 68.60 300.0 +-3000.0 69.30 200.0 +-3000.0 70.30 300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 68.60 300.0 +-3000.0 69.60 400.0 +-3000.0 70.30 300.0 +-3000.0 71.30 400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 69.60 400.0 +-3000.0 70.60 500.0 +-3000.0 71.30 400.0 +-3000.0 72.30 500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 70.60 500.0 +-3000.0 71.60 600.0 +-3000.0 72.30 500.0 +-3000.0 73.30 600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 71.60 600.0 +-3000.0 72.60 700.0 +-3000.0 73.30 600.0 +-3000.0 74.30 700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 72.60 700.0 +-3000.0 73.60 800.0 +-3000.0 74.30 700.0 +-3000.0 75.30 800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 73.60 800.0 +-3000.0 74.60 900.0 +-3000.0 75.30 800.0 +-3000.0 76.30 900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 74.60 900.0 +-3000.0 75.60 1000.0 +-3000.0 76.30 900.0 +-3000.0 77.30 1000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 75.60 1000.0 +-3000.0 76.60 1100.0 +-3000.0 77.30 1000.0 +-3000.0 78.30 1100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 76.60 1100.0 +-3000.0 77.60 1200.0 +-3000.0 78.30 1100.0 +-3000.0 79.30 1200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 77.60 1200.0 +-3000.0 78.60 1300.0 +-3000.0 79.30 1200.0 +-3000.0 80.30 1300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 78.60 1300.0 +-3000.0 79.60 1400.0 +-3000.0 80.30 1300.0 +-3000.0 81.30 1400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 79.60 1400.0 +-3000.0 80.60 1500.0 +-3000.0 81.30 1400.0 +-3000.0 82.30 1500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 80.60 1500.0 +-3000.0 81.60 1600.0 +-3000.0 82.30 1500.0 +-3000.0 83.30 1600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 81.60 1600.0 +-3000.0 82.60 1700.0 +-3000.0 83.30 1600.0 +-3000.0 84.30 1700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 82.60 1700.0 +-3000.0 83.60 1800.0 +-3000.0 84.30 1700.0 +-3000.0 85.30 1800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 83.60 1800.0 +-3000.0 84.60 1900.0 +-3000.0 85.30 1800.0 +-3000.0 86.30 1900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 84.60 1900.0 +-3000.0 85.60 2000.0 +-3000.0 86.30 1900.0 +-3000.0 87.30 2000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 85.60 2000.0 +-3000.0 86.60 2100.0 +-3000.0 87.30 2000.0 +-3000.0 88.30 2100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 86.60 2100.0 +-3000.0 87.60 2200.0 +-3000.0 88.30 2100.0 +-3000.0 89.30 2200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 87.60 2200.0 +-3000.0 88.60 2300.0 +-3000.0 89.30 2200.0 +-3000.0 90.30 2300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 88.60 2300.0 +-3000.0 89.60 2400.0 +-3000.0 90.30 2300.0 +-3000.0 91.30 2400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 89.60 2400.0 +-3000.0 90.60 2500.0 +-3000.0 91.30 2400.0 +-3000.0 92.30 2500.0 +0.4 4.0 3 0.04 vis +endtraction +// the W4 of the stations of the timetable +include ip/pkp/w4n.inc gora#1 -2997.3 60.00 -90.0 180 0 0 -10 202 end +// a signal at stop: what the AI reads of one, a memory cell with SetVelocity 0 0 and the event that reads it +node -1 0 hu_sem1_mem memcell -2997.3 78.00 1000.0 SetVelocity 0.0 0.0 none endmemcell +event hu_sem1_info getvalues 5.0 hu_sem1_mem endevent +// cleared at 10:42: the memory cell lets the train go at the line speed +event hu_sem1_go updatevalues 0.0 hu_sem1_mem SetVelocity 100 100 endevent +node -1 0 hu_sem1_launcher eventlauncher 0 0 0 -1 none 1042 hu_sem1_go end +// a signal at stop: what the AI reads of one, a memory cell with SetVelocity 0 0 and the event that reads it +node -1 0 hu_sem2_mem memcell -2997.3 91.00 2300.0 SetVelocity 0.0 0.0 none endmemcell +event hu_sem2_info getvalues 5.0 hu_sem2_mem endevent + +trainset {{timetable}} hu_05 0.0 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py index fef87c4f3..fc5ab3397 100644 --- a/tests/scenarios/run.py +++ b/tests/scenarios/run.py @@ -632,6 +632,58 @@ def check_ends_moving(rows, min_speed): return ok, f"last row t={last[COL_TIME]:.1f}s, v={last[COL_VELOCITY]:.1f} km/h (wanted >= {min_speed})" +def check_keeps_moving(rows, moving_speed, min_speed, until_distance, from_distance=0.0): + """(*vehicle speed*) Once at moving_speed, the speed stays at or above min_speed between the two distances (metres + travelled, from the vehicle speed), e.g. a train doesn't come to a stand on a gradient before a restriction or in + it. The vehicle speed, as wheels slipping at the start would count as moving off.""" + if not rows or len(rows[0]) <= COL_VEHICLE_VELOCITY or rows[0][COL_VEHICLE_VELOCITY] is None: + return False, "the physicslog has no vehicle speed column, the build is too old" + speed = [abs(r[COL_VEHICLE_VELOCITY]) for r in rows] + start = next((i for i, v in enumerate(speed) if v >= moving_speed), None) + if start is None: + return False, f"never reached {moving_speed} km/h" + dist, d = [0.0], 0.0 + for i in range(1, len(rows)): + d += (speed[i - 1] + speed[i]) / 2 / 3.6 * (rows[i][COL_TIME] - rows[i - 1][COL_TIME]) + dist.append(d) + span = [i for i in range(start, len(rows)) if from_distance <= dist[i] <= until_distance] + if not span or dist[-1] < until_distance: + return False, f"travelled {dist[-1]:.0f} m only, wanted {until_distance} m" + low = min(span, key=lambda i: speed[i]) + r = rows[low] + detail = (f"lowest speed {speed[low]:.1f} km/h at t={r[COL_TIME]:.1f}s after {dist[low]:.0f} m " + f"(brake cylinder {r[COL_BRAKE_PRESS]:.2f} bar), wanted >= {min_speed} between {from_distance:.0f} and {until_distance} m") + return speed[low] >= min_speed, detail + + +def check_starts_again(rows, after, min_speed, within, max_rollback=None): + """Standing at the time `after` (e.g. at a signal that clears then), the vehicle reaches min_speed within `within` + seconds; with max_rollback (*vehicle speed*), it rolls back no more than that many metres meanwhile.""" + first = next((i for i, r in enumerate(rows) if r[COL_TIME] >= after), None) + if first is None: + return False, f"the physicslog ends before t={after}s" + if rows[first][COL_VELOCITY] > 1.0: + return False, f"moving at {rows[first][COL_VELOCITY]:.1f} km/h at t={after}s, wanted standing" + moved = next((r[COL_TIME] for r in rows[first:] if r[COL_VELOCITY] > 1.0), None) + reached = next((r[COL_TIME] for r in rows[first:] if r[COL_VELOCITY] >= min_speed), None) + rollback, back = 0.0, 0.0 + if max_rollback is not None: + if len(rows[0]) <= COL_VEHICLE_VELOCITY or rows[0][COL_VEHICLE_VELOCITY] is None: + return False, "the physicslog has no vehicle speed column, the build is too old" + end = reached if reached is not None else after + within + for a, b in zip(rows[first:], rows[first + 1:]): + if b[COL_TIME] > end: + break + back += (a[COL_VEHICLE_VELOCITY] + b[COL_VEHICLE_VELOCITY]) / 2 / 3.6 * (b[COL_TIME] - a[COL_TIME]) + rollback = max(rollback, -back) + detail = (f"moved off (1 km/h) {moved - after:.1f}s after t={after}s" if moved is not None else f"didn't move off after t={after}s") + detail += f", {min_speed} km/h after {reached - after:.1f}s" if reached is not None else f", never reached {min_speed} km/h" + if max_rollback is not None: + detail += f", rolled back {rollback:.2f} m (wanted <= {max_rollback})" + ok = reached is not None and reached - after <= within and (max_rollback is None or rollback <= max_rollback) + return ok, detail + f" (wanted {min_speed} km/h within {within}s)" + + def check_slip_clears(rows, moving_speed, stop_speed, within): """Once the vehicle has stopped after moving off, its wheels stop slipping within `within` seconds (a vehicle left skidding on locked wheels keeps its brakes capped by the sliding adhesion).""" @@ -705,6 +757,8 @@ CHECKS = { "stays_stopped": check_stays_stopped, "distance": check_distance, "ends_moving": check_ends_moving, + "keeps_moving": check_keeps_moving, + "starts_again": check_starts_again, } diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 675c1ef8e..dfe4ed1c6 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -6781,15 +6781,38 @@ TController::determine_consist_state() { void TController::control_wheelslip() { + // a start that has slipped once keeps the sand on until the train is under way. with the sand off as soon as the + // wheels grip again, the next notch slips again, and a heavy train on poor rails slips, grips and snatches over + // and over, and may never get going (#187). a vehicle without sand starts as before + auto const velocity { std::abs( mvOccupied->Vel ) }; + if( mvControlling->SlippingWheels + && velocity < EU07_AI_SANDEDSTARTVELOCITY + && false == mvControlling->IsMainCtrlNoPowerPos() + && mvControlling->Sand > 0.0 ) { + bSandedStart = true; + } + else if( velocity >= EU07_AI_SANDEDSTARTVELOCITY + || ( velocity < EU07_AI_NOMOVEMENT && VelDesired == 0.0 ) ) { + bSandedStart = false; + } // wheel slip if( mvControlling->SlippingWheels ) { cue_action( driver_hint::sandingon ); // piasku! - cue_action( driver_hint::tractiveforcedecrease ); + if( false == bSandedStart ) { + cue_action( driver_hint::tractiveforcedecrease ); + cue_action( driver_hint::antislip ); + } + else if( ElapsedTime - fSandedStartDecreaseTime >= 1.0 ) { + // starting, a step down at a time, and no anti-slip brake: taking the power off at once and braking the + // locomotive brings a heavy train that has just got moving to a stand again, and the start begins anew + cue_action( driver_hint::tractiveforcedecrease ); + fSandedStartDecreaseTime = ElapsedTime; + } cue_action( driver_hint::brakingforcedecrease ); - cue_action( driver_hint::antislip ); ++iDriverFailCount; } - else if( std::fabs( mvControlling->Im ) > 0.75 * mvControlling->ImaxHi ) { + else if( ( std::fabs( mvControlling->Im ) > 0.75 * mvControlling->ImaxHi ) + || ( bSandedStart && false == mvControlling->IsMainCtrlNoPowerPos() ) ) { cue_action( driver_hint::sandingon ); // piaskujemy tory, coby się nie ślizgać } else { diff --git a/vehicle/Driver.h b/vehicle/Driver.h index b8eb4ec94..a00a3935f 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -29,6 +29,7 @@ auto const EU07_AI_NOMOVEMENT = 0.05; // standstill velocity threshold auto const EU07_AI_MOVEMENT = 1.0; // deliberate movement velocity threshold auto const EU07_AI_UPHILLGRAVITY = -0.025; // [m/s2] about 2.5 per mille up: the gradient that rolls a standing train back auto const EU07_AI_SPEEDLIMITEXTENDSBEYONDSCANRANGE = 10000.0; +auto const EU07_AI_SANDEDSTARTVELOCITY = 15.0; // [km/h] a start that slipped keeps the sand on up to this speed enum TOrders { // rozkazy dla AI @@ -442,6 +443,8 @@ private: double fShortfallTime = 0.0; // when that was checked int iShortfallGrowth = 0; // how many checks in a row the shortfall has grown bool bUphillStart = false; // starting uphill: the train brake holds the train until the power does + bool bSandedStart = false; // the wheels slipped while starting: sand while under power until the train is under way + double fSandedStartDecreaseTime = -1.0; // when the power was last taken down a step for a slip while starting double fUphillStartTime = 0.0; // when the uphill start began double fAccDesiredGravity = 0.0; // część AccDesired odjęta na spadku jako kompensacja pochylenia; AbsAccS zawiera ją już sam double VelforDriver = -1.0; // prędkość, używana przy zmianie kierunku (ograniczenie przy nieznajmości szlaku?) From 5a24a10481f2c35a2f7e7437e9917d6537bd54c1 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 22:12:27 +0100 Subject: [PATCH 124/136] test(scenarios): a switch thrown under a train, standing, facing and trailing (#472) * test(scenarios): on_track check of the black box The runner reads the map of the tracks from the black box (the track records, one for each way of a switch). The new on_track check takes the vehicles of the case and, in every state the black box has of them, wants the middle of each within max_offset (0.5 m) of the line of a track, and two coupled vehicles no more than max_detour (5 m) farther apart along the tracks than in a straight line. A vehicle thrown sideways, or with its bogies on two tracks that part, is off the line; a coach running beside the locomotive it is coupled to, on the next track, is hundreds of metres away from it along the tracks. * test(scenarios): a switch thrown under a train, standing, facing and trailing Six cases on td.scn for the review of #289, point 2b: a switch of Stacja1 thrown by an event under an EU07 with three coaches. The train has to keep to the rails (on_track) and the AI to the route it is really on (a signal at stop of the case on track 1). On staging an axle on a switch keeps the way it ran onto but leaves the switch by the way it is set to now, and the AI does not scan its route again for a switch that changed behind the head of the train. Trailing through the switch (standing, or running) is fine: the first wheels from the frog end push the switch back. Facing, three cases fail and are marked xfail: - thrown with the locomotive on the switch: it jumps sideways at the end of the switch, the train goes to track 1, and the AI, still on the route of track 2, runs past the signal of track 1 at 40 km/h; - thrown just behind the locomotive: the locomotive runs on along track 2 and the coaches coupled to it along track 1, for 900 m; - thrown under the standing train, which then leaves: a coach runs with a bogie on each track, 2.3 m off both, and the AI reads the signals of track 1 while running on track 2. Nothing derails, with physics.derailment monitor or new. There is no small fix: the axle keeping to its way was in the stack and taken out before the merge (c268673c), and an interlocking of switches under trains would change what sceneries can do. * test(scenarios): the trailing case passes only once the switch was thrown, on_track allows a coach's chord on a curve by default --- tests/scenarios/README.md | 41 ++++ .../cases/eu07_td_switch_facing_control.json | 52 +++++ .../eu07_td_switch_thrown_facing_behind.json | 50 +++++ .../eu07_td_switch_thrown_facing_head.json | 57 +++++ ...eu07_td_switch_thrown_standing_facing.json | 49 +++++ ...07_td_switch_thrown_standing_trailing.json | 52 +++++ .../cases/eu07_td_switch_thrown_trailing.json | 56 +++++ tests/scenarios/cases/td_switch_thrown.scn | 45 ++++ tests/scenarios/run.py | 201 +++++++++++++++++- 9 files changed, 592 insertions(+), 11 deletions(-) create mode 100644 tests/scenarios/cases/eu07_td_switch_facing_control.json create mode 100644 tests/scenarios/cases/eu07_td_switch_thrown_facing_behind.json create mode 100644 tests/scenarios/cases/eu07_td_switch_thrown_facing_head.json create mode 100644 tests/scenarios/cases/eu07_td_switch_thrown_standing_facing.json create mode 100644 tests/scenarios/cases/eu07_td_switch_thrown_standing_trailing.json create mode 100644 tests/scenarios/cases/eu07_td_switch_thrown_trailing.json create mode 100644 tests/scenarios/cases/td_switch_thrown.scn diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index 2af439ed5..cfd959343 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -499,6 +499,34 @@ back on (`LineContactorsHeldByLocalConverterSwitch()`, the part of #276 in `dete the `converteron` hint), is in the cab only: no command of a scenery or of the train's cables sets `ConverterAllowLocal`, and nobody sits in a cab in the test mode, so the switch is always on in a case. +The `eu07_td_switch_*` cases (fragment `td_switch_thrown.scn`, the review of #289, point 2b) throw a switch of +Stacja1 by an event under an EU07 with three coaches and check that the train keeps to the rails (`on_track`) and that +the AI keeps to the route it is really on. Both switches of the station have their points towards the line and the +way to track 2 straight (position 0), to track 1 curved (position 1); the ends of the two ways are 1.9 m apart, the +tracks 4.6 m. `zwr01` at the west end is run through facing by a train running into the station, `zwr02` at the east +end trailing by one leaving it. The throw is an event set off once, by the rear axle of the locomotive running onto a +track (`event1`/`event2` of it, which only the vehicle with the driver sets off) or by a launcher 5 s after the start; +a driver that stands cold gets its order (`vars.order`) from `event0` of its track, after the throw where the train +stands over the switch. On track 1 a signal at stop of the case's own stands at z 1100: the train has to stop before +it (`event0` of `tdo_n1725` passes the test, running onto `tdo_n1734` fails it); on track 2 the exit signal `stacja1_k` +at stop. What they showed on `staging` of 2026-11-22 (f15ea405), where an axle on a switch keeps the way it ran onto +(the segment it took when it got onto the switch) but leaves the switch by the way it is set to now, and the AI does +not scan its route again for a switch that changed behind the head of the train: + +| case | throw | result | +| --- | --- | --- | +| `eu07_td_switch_facing_control` | none, set to track 1 from the start | passes: stops before the signal of track 1 | +| `eu07_td_switch_thrown_facing_head` | `zwr01` to track 1 with the locomotive on the switch | `xfail`: the locomotive jumps sideways at the end of the switch (0.78 m off the track in the black box), the whole train goes to track 1, and the AI, still on the route of track 2, runs past the signal of track 1 at 40 km/h | +| `eu07_td_switch_thrown_facing_behind` | `zwr01` to track 1 with the locomotive just past it | `xfail`: the locomotive runs on along track 2 and the coaches coupled to it along track 1, side by side, for 900 m | +| `eu07_td_switch_thrown_standing_facing` | `zwr01` to track 1 under the standing train, which then leaves facing | `xfail`: the second coach runs with a bogie on each track, its body 2.3 m off both; the AI, which scans from the last vehicle, reads the signals of track 1 while it runs on track 2 (a signal passed at danger, `stacja1_j`) | +| `eu07_td_switch_thrown_standing_trailing` | `zwr02` to track 1 under the standing train, which then leaves trailing | passes: the first wheels coming from track 2 push the switch back (as through any switch set against them from the frog end) | +| `eu07_td_switch_thrown_trailing` | `zwr02` to track 2 under the coaches of the timetable train leaving track 1 | passes: the switch is pushed back, the train stops at Przystanek after 1402 m | + +Nothing derails in any of them with `physics.derailment monitor` (the default; the monitor reported nothing either), +and the three `xfail` cases run with `physics.derailment new` came out the same to the metre: the criteria of +derailment look at the curve, the cant and the speed of a vehicle, not at its bogies being on two tracks. Nor does the +coupler between a locomotive and a coach 4.6 m beside it break. + ### Cases on a mission of a scenery The cases made from players' reports (eu07/maszyna#421, #506, #524, #525) run a whole mission @@ -615,6 +643,19 @@ the row instead, logged by builds from this branch on. - `master_controller` `from_distance`, `to_distance`, `at_most`: the master controller stays at or below the position between the two distances, e.g. at 0 where the scenery tells the driver to coast. +- `on_track` `vehicles`, optional `max_offset` (0.75 m), `max_detour` (5 m): every vehicle whose name starts with + `vehicles` (e.g. `{{vehicle}}`, the train of the case) keeps to the rails in the black box, in each of its states: + its middle is within `max_offset` of the line of a track (level distance, the map of the tracks of the black box), + and of two vehicles coupled to each other the way along the tracks from one to the other (through the ends of the + tracks that meet) is no more than `max_detour` longer than the straight line between them. A vehicle with its + bogies on two tracks that part, or thrown sideways, is off the line; a coach running on beside the locomotive it is + coupled to, on the next track, has a way to it hundreds of metres long. A coach on a curve of 300 m, through the + S of a switch, was up to 0.38 m off. The middle of a vehicle is the middle of the chord between its pivots, so on + a curve of radius R a vehicle running right is a^2 / 8R off the track, a being the distance of the pivots: a 19.5 m + coach 0.59 m at R 80, 0.79 m at R 60. The default suits curves down to about R 65 for such a coach; a case with + tighter curves sets more. The black box lists a vehicle once a second, so a jump between two lists shows up only + as it is at the next one. + 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 diff --git a/tests/scenarios/cases/eu07_td_switch_facing_control.json b/tests/scenarios/cases/eu07_td_switch_facing_control.json new file mode 100644 index 000000000..e512703d7 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_switch_facing_control.json @@ -0,0 +1,52 @@ +{ + "description": "Switch under a train, the control of the facing cases (#289 review 2b): an EU07 with three coaches runs from the west line into Stacja1 on td.scn, facing through switch zwr01, which is set to track 1 from the start (keyctrl02, with the entry signal at 40). Nothing is thrown. The train has to stop before a signal at stop on track 1 and stay on the rails.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_switch_thrown.scn", + "vars": { + "trainsets": [ + "trainset none start 80.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "route": "node -1 0 autotest_route_launcher eventlauncher 0 0 0 -1 none 1034 keyctrl02 end", + "throw": "zwr01_1", + "trigger": "", + "order": "Shunt -1 0" + }, + "track_events": { + "start": "event0 autotest_wake", + "tdo_n1725": [ + "event2 autotest_signal1_info", + "event0 autotest_pass" + ], + "tdo_n1734": [ + "eventall1 autotest_fail", + "eventall2 autotest_fail" + ] + }, + "test_config": [ + "test.timeout 400", + "test.standstill 120" + ], + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 30, + "within": 200 + }, + { + "type": "on_track", + "vehicles": "{{vehicle}}", + "max_offset": 0.6 + }, + { + "type": "log_lacks", + "pattern": "Bad driving" + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_switch_thrown_facing_behind.json b/tests/scenarios/cases/eu07_td_switch_thrown_facing_behind.json new file mode 100644 index 000000000..7798cef47 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_switch_thrown_facing_behind.json @@ -0,0 +1,50 @@ +{ + "description": "Switch thrown under a train running facing through it (#289 review 2b): as eu07_td_switch_thrown_facing_head, but zwr01 is thrown to track 1 when the locomotive has left the switch for track 2 (event of tor2p, set off by its rear axle), with the coaches still before and on the switch. A train cannot run on two tracks at once: every vehicle has to keep to the line of a track, whatever the throw does to them.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_switch_thrown.scn", + "vars": { + "trainsets": [ + "trainset none start 80.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "route": "node -1 0 autotest_route_launcher eventlauncher 0 0 0 -1 none 1034 keyctrl01 end", + "throw": "zwr01_1 zwr01_V40", + "trigger": "", + "order": "Shunt -1 0" + }, + "track_events": { + "start": "event0 autotest_wake", + "tor2p": [ + "event1 autotest_throw", + "event2 autotest_throw" + ], + "tdo_n109": "event0 autotest_pass" + }, + "test_config": [ + "test.timeout 400", + "test.standstill 120" + ], + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 30, + "within": 200 + }, + { + "type": "on_track", + "vehicles": "{{vehicle}}", + "max_offset": 0.6 + }, + { + "type": "log_lacks", + "pattern": "Bad driving" + } + ], + "xfail": "#289 review 2b, as before the stack (TrkFoll reverted in c268673c): the axles still on the switch leave it by the way it is set to now, those behind it take that way too, so the coaches go to track 1 and the locomotive they are coupled to runs on along track 2, 4.6 m beside them, with nothing derailed or broken" +} diff --git a/tests/scenarios/cases/eu07_td_switch_thrown_facing_head.json b/tests/scenarios/cases/eu07_td_switch_thrown_facing_head.json new file mode 100644 index 000000000..c02cad4d7 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_switch_thrown_facing_head.json @@ -0,0 +1,57 @@ +{ + "description": "Switch thrown under a train running facing through it (#289 review 2b): as eu07_td_switch_facing_control, but the way is set to track 2 (keyctrl01) and zwr01 is thrown to track 1 when the locomotive has run onto the switch with both its bogies (event of the switch track, set off by its rear axle). The locomotive and the train behind it have to go on to track 1 and stay on the rails, and the AI has to stop before the signal at stop on track 1.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_switch_thrown.scn", + "vars": { + "trainsets": [ + "trainset none start 80.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "route": "node -1 0 autotest_route_launcher eventlauncher 0 0 0 -1 none 1034 keyctrl01 end", + "throw": "zwr01_1 zwr01_V40", + "trigger": "", + "order": "Shunt -1 0" + }, + "track_events": { + "start": "event0 autotest_wake", + "zwr01": [ + "event1 autotest_throw", + "event2 autotest_throw" + ], + "tdo_n1725": [ + "event2 autotest_signal1_info", + "event0 autotest_pass" + ], + "tdo_n1734": [ + "eventall1 autotest_fail", + "eventall2 autotest_fail" + ] + }, + "test_config": [ + "test.timeout 400", + "test.standstill 120" + ], + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 30, + "within": 200 + }, + { + "type": "on_track", + "vehicles": "{{vehicle}}", + "max_offset": 0.6 + }, + { + "type": "log_lacks", + "pattern": "Bad driving" + } + ], + "xfail": "#289 review 2b, as before the stack (TrkFoll reverted in c268673c): an axle keeps the way of the switch it ran onto but leaves by the way the switch is set to now, so the locomotive jumps 1.9 m sideways at the end of the switch, an axle at a time; and the AI keeps the route it scanned before the throw (a switch behind the head of the train is not scanned again), so on track 1 it brakes for the exit signal of track 2 and runs past the signal at stop of track 1 at 40 km/h" +} diff --git a/tests/scenarios/cases/eu07_td_switch_thrown_standing_facing.json b/tests/scenarios/cases/eu07_td_switch_thrown_standing_facing.json new file mode 100644 index 000000000..fb3694906 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_switch_thrown_standing_facing.json @@ -0,0 +1,49 @@ +{ + "description": "Switch thrown under a standing train, which then leaves facing through it (#289 review 2b): an EU07 with three coaches stands cold across zwr01 on td.scn, the locomotive on track 2, the last coaches over the switch, which is set to track 2. 5 s after the start the switch is thrown to track 1; then the driver gets the order to go, into the station, facing through the switch. Every vehicle has to keep to the line of a track.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_switch_thrown.scn", + "vars": { + "trainsets": [ + "trainset none tor2p 50.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "route": "", + "throw": "zwr01_1 zwr01_V40", + "trigger": [ + "event autotest_throw_later multiple 5 none autotest_throw endevent", + "node -1 0 autotest_throw_launcher eventlauncher 0 0 0 -1 none 1034 autotest_throw_later end" + ], + "order": "Shunt -1 0" + }, + "track_events": { + "tor2p": "event0 autotest_wake_after_throw", + "tdo_n109": "event0 autotest_pass" + }, + "test_config": [ + "test.timeout 400", + "test.standstill 120" + ], + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 200 + }, + { + "type": "on_track", + "vehicles": "{{vehicle}}", + "max_offset": 0.6 + }, + { + "type": "log_lacks", + "pattern": "Bad driving" + } + ], + "xfail": "#289 review 2b, as before the stack (TrkFoll reverted in c268673c): the axles that stood on the switch leave it by the way it is set to now, so the second coach runs with one bogie on track 2 and the other on track 1, 4.6 m apart, its body 2.3 m off both, with nothing derailed or broken; and the AI scans its route from the last vehicle through the switch as now set, reads the signals of track 1 while it runs on track 2, and its head is counted past the exit signal of track 1 at stop" +} diff --git a/tests/scenarios/cases/eu07_td_switch_thrown_standing_trailing.json b/tests/scenarios/cases/eu07_td_switch_thrown_standing_trailing.json new file mode 100644 index 000000000..321806476 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_switch_thrown_standing_trailing.json @@ -0,0 +1,52 @@ +{ + "description": "Switch thrown under a standing train, which then leaves trailing through it (#289 review 2b): an EU07 with three coaches stands cold across zwr02 on td.scn, the locomotive on the line, the coaches behind it over the switch and on track 2, the switch set to track 2. 5 s after the start it is thrown to track 1; then the driver gets the order to go, out to the line. The wheels coming from track 2 push the switch back over (as through any switch set against them from the frog end); every vehicle has to keep to the line of a track. Passes once the locomotive runs onto tdo_n176, with the train clear of the switch.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_switch_thrown.scn", + "vars": { + "trainsets": [ + "trainset none tdo_n145 40.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "route": "", + "throw": "zwr02_1 zwr02_v40", + "trigger": [ + "event autotest_throw_later multiple 5 none autotest_throw endevent", + "node -1 0 autotest_throw_launcher eventlauncher 0 0 0 -1 none 1034 autotest_throw_later end" + ], + "order": "Obey_train 0 0" + }, + "track_events": { + "tdo_n145": "event0 autotest_wake_after_throw", + "tdo_n176": [ + "event1 autotest_pass_running", + "event2 autotest_pass_running" + ] + }, + "test_config": [ + "test.timeout 400", + "test.standstill 120", + "test.no_movement_before_pass no" + ], + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 10, + "within": 200 + }, + { + "type": "on_track", + "vehicles": "{{vehicle}}", + "max_offset": 0.6 + }, + { + "type": "log_lacks", + "pattern": "Bad driving" + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_switch_thrown_trailing.json b/tests/scenarios/cases/eu07_td_switch_thrown_trailing.json new file mode 100644 index 000000000..21d0d7bac --- /dev/null +++ b/tests/scenarios/cases/eu07_td_switch_thrown_trailing.json @@ -0,0 +1,56 @@ +{ + "description": "Switch thrown under a train running trailing through it (#289 review 2b): the td/rozklad timetable train, an EU07 with three coaches, leaves track 1 of Stacja1 on td.scn through zwr02 from its frog end; when the locomotive has run onto the line (event of tdo_n145, set off by its rear axle) the switch is thrown to track 2 under the coaches. The wheels coming from track 1 push it back over; the train has to stay on the rails and run its timetable to the stop at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_switch_thrown.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 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "route": "node -1 0 autotest_route_launcher eventlauncher 0 0 0 -1 none 1034 keyctrl04 end", + "throw": "zwr02_0 zwr02_vmax", + "trigger": "", + "order": "Obey_train 0 0" + }, + "track_events": { + "tdo_n145": [ + "event1 autotest_throw", + "event2 autotest_throw" + ] + }, + "duration": 300, + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 240 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 0, + "min_distance": 1380, + "max_distance": 1420 + }, + { + "type": "on_track", + "vehicles": "{{vehicle}}", + "max_offset": 0.6 + }, + { + "type": "log_lacks", + "pattern": "Bad driving" + }, + { + "type": "log_contains", + "pattern": "EVENT LAUNCHED.*: autotest_throw_done$" + } + ] +} diff --git a/tests/scenarios/cases/td_switch_thrown.scn b/tests/scenarios/cases/td_switch_thrown.scn new file mode 100644 index 000000000..b7706034b --- /dev/null +++ b/tests/scenarios/cases/td_switch_thrown.scn @@ -0,0 +1,45 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a switch of Stacja1 thrown by an event while a train stands or runs over it (the review of MaSzyna-EU07/maszyna#289, +// point 2b). Both switches of the station have their points (point 1) towards the line and two ways from there to +// the station: position 0 straight to track 2 (x 0.4), position 1 curved to track 1 (x 2.3 at the end of the switch, +// x 5.0 further on). The events of zwrp34r300.inc / zwrl34r300.inc: + sets position 0, - position 1 +// (and the speed of the switch: none on the straight, 40 on the curve). +// - zwr01, west end: points at z 336, the ways end at z 370 (tor2p, track 2; tdo_n1641, track 1). A train running +// towards z 2000 (into the station) goes through it facing, from the points. +// - zwr02, east end: points at z 1436 (tdo_n145, the line), the ways end at z 1402 (tor2k, track 2; tdo_n1744, +// track 1). A train running towards z 2000 (out of the station) goes through it trailing, from the frog end. +// A trainset faces point 2 of its track (towards z 2000 on all these tracks): the first vehicle has its front as many +// metres past point 1 as the trainset says, the others stand behind it. +{{trainsets}} + +// the way set at the start, if any (a launcher with a positive time fires once at that hour, the scenery starts +// at 10:34) +{{route}} + +// the throw (vars.throw), once: whichever of the events hung on the tracks of the case (track_events) or the +// launcher (vars.trigger) sets it off first, the memory cell keeps the others from doing it again +node -1 0 autotest_thrown memcell 0 0 0 thrown 0 0 none endmemcell +event autotest_throw multiple 0 autotest_thrown {{throw}} autotest_throw_done condition memcompare * 0 * endevent +event autotest_throw_done UpdateValues 0 autotest_thrown * 1 * endevent +{{trigger}} + +// a driver of a trainset of velocity 0 sleeps until it gets an order. event0 of the track its vehicle stands on +// (track_events) gives it, once: vars.order, e.g. Shunt -1 0 (go on shunting with the whole train; a proceed aspect +// of a main signal ahead turns that into a train run) or Obey_train 0 0. autotest_wake gives it at once, +// autotest_wake_after_throw only once the switch has been thrown (for a train standing over the switch) +node -1 0 autotest_ordered memcell 0 0 0 ordered 0 0 none endmemcell +event autotest_wake_after_throw multiple 0 autotest_thrown autotest_wake condition memcompare * 1 * endevent +event autotest_wake multiple 0 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event autotest_order PutValues 0 none 0 0 0 {{order}} endevent +event autotest_order_given UpdateValues 0 autotest_ordered * 1 * endevent + +// a signal at stop on track 1 for a train running towards z 2000: the memory cell stands beside the track at z 1100 +// and event2 of tdo_n1725 (z 1065-1165, track_events) reads it. A train on track 1 has to stop before it, with its head +// on tdo_n1725, where event0 passes the test; running onto tdo_n1734 (z 1165-1265) beyond the signal fails it. On +// track 2 the train stops before the exit signal stacja1_k (z 1316, at stop all the time), with its head on tdo_n109 +// (z 1236-1336) +node -1 0 autotest_signal1 memcell 5.04488 0.2 1100.0 SetVelocity 0 0 none endmemcell +event autotest_signal1_info getvalues 0 autotest_signal1 endevent +event autotest_pass UpdateValues 0 __test.result stopped_before_the_signal 1 * endevent +event autotest_fail UpdateValues 0 __test.result ran_past_the_signal_of_track_1 0 * endevent +event autotest_pass_running UpdateValues 0 __test.result ran_clear_of_the_switch 1 * endevent diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py index fc5ab3397..e11fa8a77 100644 --- a/tests/scenarios/run.py +++ b/tests/scenarios/run.py @@ -27,6 +27,7 @@ Usage: from __future__ import annotations import argparse +import heapq import json import os import math @@ -300,6 +301,7 @@ def read_text(path: Path | None) -> str: # physicslog/_.blackbox. A header, then records: a byte of the kind, the length, the content BLACKBOX_MAGIC = b"EU07BBX\0" BLACKBOX_HEADER = 12 # the magic, the version of the format, two bytes reserved +BLACKBOX_TRACK = 0x10 # the map: a rail track, or one way of a switch, as points along it 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 @@ -329,9 +331,20 @@ class VehicleState: driver: int # 0 none, 1 a user, 2 the AI +@dataclass +class Track: + """A `track` record: a plain track, or one way of a switch (several records under the number of the switch).""" + number: int + name: str + kind: int # 0 a plain track, 1 a way of a switch + branch: int # the switch position this way is taken in + points: list[tuple[float, float, float]] + + @dataclass class Blackbox: vehicles: dict[int, str] = field(default_factory=dict) # names by number + tracks: list[Track] = field(default_factory=list) # the map, in the order written 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 @@ -347,8 +360,22 @@ def find_blackbox(game_dir: Path, scenery: str, since: float) -> Path | None: return max(files, key=lambda p: p.stat().st_mtime, default=None) +def _blackbox_text(content: bytes, start: int) -> tuple[str, int]: + """A text of a black box record at `start`, and where the field after it begins.""" + # its length in 7 bit groups, low first, the high bit set on all but the last + size, shift = 0, 0 + while True: + byte = content[start] + start += 1 + size |= (byte & 0x7F) << shift + shift += 7 + if byte < 0x80: + break + return content[start: start + size].decode("utf-8", errors="replace"), start + size + + def read_blackbox(path: Path | None) -> Blackbox | None: - """The vehicles and the coupling records of a black box; None when there is none or it can't be read.""" + """The map, the vehicles and the coupling records of a black box; None when there is none or it can't be read.""" try: data = path.read_bytes() if path else b"" except FileNotFoundError: @@ -366,16 +393,14 @@ def read_blackbox(path: Path | None) -> Blackbox | None: at += 5 + length if kind == BLACKBOX_VEHICLE: number, = struct.unpack_from(" reached.get(node, math.inf) or cost >= min(best, limit): + continue + if node in goal: + best = min(best, cost + goal[node]) + for nxt, length in self.edges.get(node, []): + if cost + length < reached.get(nxt, math.inf): + reached[nxt] = cost + length + heapq.heappush(queue, (cost + length, nxt)) + return best if best <= limit else math.inf + + +def _coupled_pairs(box, chosen, upto): + """The pairs of vehicles (by number) among `chosen` whose couplers hold each other at the time `upto`.""" + held = {} + for c in box.couplings: + if c.time > upto: + break + held[(c.vehicle, c.side)] = (c.other, c.flags) + return {tuple(sorted((vehicle, other))) for (vehicle, _), (other, flags) in held.items() + if flags & COUPLING_COUPLER and vehicle in chosen and other in chosen} + + +def check_on_track(box, vehicles, max_offset=0.75, max_detour=5.0): + """Every vehicle whose name starts with `vehicles` stays on the line of a track in every state the black box has of + it, and the vehicles coupled to each other stay on one way: the way along the tracks from one to the other is no + more than `max_detour` [m] longer than the straight line between them. A vehicle thrown sideways has its middle off + any track; one with its bogies on two tracks that part too, once they are apart; and a train whose vehicles went + two ways at a switch runs on with two coupled vehicles on two tracks, side by side, with the way between them back + through the switch.""" + if not box.tracks: + return False, "the black box has no map of the tracks" + chosen = {number: name for number, name in box.vehicles.items() if name.lower().startswith(vehicles.lower())} + if not chosen: + return False, f"the black box has no vehicle named {vehicles}..." + network = _TrackMap(box.tracks) + # the states of the chosen vehicles by time: a vehicle is listed when it moved, or every 60 s + times = sorted({s.time for number in chosen for s in box.states.get(number, [])}) + if not times: + return False, f"the black box has no state of {', '.join(chosen.values())}" + latest, index, places = {}, {number: 0 for number in chosen}, {} + worst_offset, worst_detour, failures = None, None, [] + for when in times: + for number in chosen: + states = box.states.get(number, []) + while index[number] < len(states) and states[index[number]].time <= when: + latest[number] = states[index[number]] + index[number] += 1 + for number, state in latest.items(): + if (number, state.time) in places: + continue + places[(number, state.time)] = network.places(state.position, max_offset) + nearest = min(places[(number, state.time)], key=lambda p: p[1]) + if worst_offset is None or nearest[1] > worst_offset[0]: + worst_offset = (nearest[1], chosen[number], state, box.tracks[nearest[0]]) + for one, other in _coupled_pairs(box, chosen, when): + if one not in latest or other not in latest: + continue + straight = math.dist(latest[one].position, latest[other].position) + at_one, at_other = places[(one, latest[one].time)], places[(other, latest[other].time)] + way = min(network.distance(a, b, straight + 1000.0) for a in at_one for b in at_other) + detour = way - straight + if worst_detour is None or detour > worst_detour[0]: + worst_detour = (detour, chosen[one], chosen[other], when, at_one, at_other) + offset, name, state, track = worst_offset + where = f"{name} at t={state.time:.1f}s ({abs(state.speed):.1f} km/h) {offset:.2f} m off {_track_label(track)}" + if offset > max_offset: + failures.append(f"{where}, more than {max_offset} m") + detail = f"the farthest off a track {where}" + if worst_detour is not None: + detour, one, other, when, at_one, at_other = worst_detour + tracks = (f"{_track_label(box.tracks[min(at_one, key=lambda p: p[1])[0]])} and " + f"{_track_label(box.tracks[min(at_other, key=lambda p: p[1])[0]])}") + length = "no way along the tracks" if math.isinf(detour) else f"the way along the tracks {detour:.1f} m longer than the straight line" + said = f"{one} and {other}, coupled, at t={when:.1f}s on {tracks}: {length}" + if detour > max_detour: + failures.append(f"{said}, more than {max_detour} m") + detail += f"; of the coupled ones {said}" + if failures: + return False, "; ".join(failures) + return True, f"{len(chosen)} vehicle(s), {detail}" + + # checks on the black box of the run rather than on the physicslog rows BLACKBOX_CHECKS = { "couples": check_couples, @@ -930,6 +1108,7 @@ BLACKBOX_CHECKS = { "driver_changes": check_driver_changes, "stops_driverless": check_stops_driverless, "moves": check_moves, + "on_track": check_on_track, } From a25abe6d5d3cf809c152d0597529981c454e223e Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 26 Nov 2026 22:25:59 +0100 Subject: [PATCH 125/136] fix(editor): stray switch drives told once a frame, by the same switch lookup the deletion uses (#509) * fix(editor): tell the stray switch drives once a frame, by the test the deletion uses stray_drives() was built anew by each caller in a frame (the notice at the start, the red marks in the view, the list in the switch tool). It now keeps its list for the frame and builds it again after a step of the undo history. A drive whose switch shares its name with another switch was listed as having no switch once the later of the two was deleted: the name went with the deleted track, and only the deletion looked for the other track of the name. Both now use switch_drives::standing_switches, which falls back to the tracks of the scenery when the name finds none. The switches each drive template throws were read once per file until a restart. switch_drives::template_switches reads them again when the templates change (a rescan or a save in the editor), and a file that could not be read is tried again in a later frame. Refs #330 * test(editor): the switch lookup of the drives and the cache of the drive templates Refs #330 * test(editor): include for std::ranges::find Refs #330 --- CMakeLists.txt | 1 + application/editormode.h | 16 ++- application/editormodeswitchdrive.cpp | 78 +++++++---- editor/editorSwitchDrives.cpp | 68 +++++++++ editor/editorSwitchDrives.hpp | 76 ++++++++++ tests/unit/CMakeLists.txt | 2 + tests/unit/test_editor_switch_drives.cpp | 171 +++++++++++++++++++++++ 7 files changed, 382 insertions(+), 30 deletions(-) create mode 100644 editor/editorSwitchDrives.cpp create mode 100644 editor/editorSwitchDrives.hpp create mode 100644 tests/unit/test_editor_switch_drives.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 34be53811..6f5885352 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -192,6 +192,7 @@ set(SOURCES "editor/editorModelSets.cpp" "editor/editorTrackPresets.cpp" "editor/editorIncludeInfo.cpp" +"editor/editorSwitchDrives.cpp" "editor/editorTerrain.cpp" "editor/editorTrack.cpp" "editor/editorTrackTrace.cpp" diff --git a/application/editormode.h b/application/editormode.h index d25840e18..5542e265c 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -39,6 +39,7 @@ http://mozilla.org/MPL/2.0/. #include "editor/editorAlignmentStore.hpp" #include "editor/editorSwitchStore.hpp" #include "editor/editorSwitchCurve.hpp" +#include "editor/editorSwitchDrives.hpp" #include "editor/editorKilometrage.hpp" #include "editor/editorSpeed.hpp" #include "editor/editorRoad.hpp" @@ -2679,7 +2680,7 @@ class editor_mode : public application_mode, private editor_track::observer, pri // "a".."d" for one of a double switch, whose switches are named a..d. none for a template which isn't a drive. the ones not // described for the editor have no family (-1) std::vector const &drive_switches(std::string const &File, std::map, std::less<>> const &Variants); - std::map, std::less<>> m_drive_templates; // read once for each file + switch_drives::template_switches m_drive_templates; // read once for each file, again when the templates change // a drive set to a switch the scenery hasn't got: left by a switch deleted or renamed by hand or in an earlier editor, its events // throw nothing struct stray_drive @@ -2698,10 +2699,19 @@ class editor_mode : public application_mode, private editor_track::observer, pri std::size_t instances{0}; }; std::optional m_drives_named; + // the drives whose switch isn't in the scenery, told once a frame for the list in the switch tool and the marks in the view, and again + // after a step made, undone or redone in the frame + struct drives_stray + { + std::vector drives; + std::optional frame; // none: to be told again + std::size_t history{0}; // the revision of the undo history + }; + drives_stray m_drives_stray; // the include of a drive or a template changed: what's kept of the drives standing is read again void drives_changed(); - // the drives whose switch isn't in the scenery, checked against the tracks each time - std::vector stray_drives(bool Wait = false); + // the drives whose switch isn't in the scenery, checked against the tracks once a frame. the list holds until the next call + std::vector const &stray_drives(bool Wait = false); void render_stray_drives(); void draw_stray_drives(); scene::layer_handle output_layer(std::string const &Part) override; diff --git a/application/editormodeswitchdrive.cpp b/application/editormodeswitchdrive.cpp index 931350af1..e9e6a6313 100644 --- a/application/editormodeswitchdrive.cpp +++ b/application/editormodeswitchdrive.cpp @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "application/editorprojection.h" #include "editor/editorFormat.hpp" #include "editor/editorIncludeInfo.hpp" +#include "editor/editorSwitchDrives.hpp" #include "world/Segment.h" #include "world/Track.h" @@ -35,15 +36,14 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include namespace { std::string drive_file(std::string Text) { - std::replace(Text.begin(), Text.end(), '\\', '/'); - std::transform(Text.begin(), Text.end(), Text.begin(), [](unsigned char Character) { return static_cast(std::tolower(Character)); }); - return Text; + return switch_drives::game_name(std::move(Text)); } // the track the events of a drive find by the name: the game reads the names of the tracks lower case, the parameters of an include as @@ -54,6 +54,30 @@ TTrack *track_named(std::string const &Name) return track != nullptr ? track : simulation::Paths.find(drive_file(Name)); } +// whether the track a name finds is removed, none when it finds no track +std::optional named_removed(std::string const &Name) +{ + auto const *track{track_named(Name)}; + return track != nullptr ? std::optional{track->m_editorremoved} : std::nullopt; +} + +// the names of all the tracks of the scenery not removed +std::vector standing_names() +{ + std::vector names; + for (auto const *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_editorremoved) + names.push_back(track->name()); + return names; +} + +// the switches standing, told by the names as the events of the drives find them in the game; with no track found by a name, a track of +// the name left by the deletion of the other of two is looked for in the whole scenery +switch_drives::standing_switches switches_standing() +{ + return switch_drives::standing_switches{named_removed, standing_names}; +} + // a template by the name of its file, with no folder: told to the user, who picks the drives by their names std::string file_name(std::string const &File) { @@ -307,10 +331,8 @@ std::vector const &editor_mode::drive_switches(std::string const &F static std::vector const single{std::string{}}; if (Variants.contains(File)) return single; - auto const [found, fresh]{m_drive_templates.try_emplace(File)}; - if (fresh) - editor_includes::switched_tracks(File, found->second); - return found->second; + // a template changed is read again with the next revision of the templates, one which couldn't be read in the next frame + return m_drive_templates.of(File, EditorIncludes.revision(), ImGui::GetFrameCount(), editor_includes::switched_tracks); } std::map, std::less<>> editor_mode::drive_variants() const @@ -330,7 +352,7 @@ void editor_mode::drives_changed() m_drives_named.reset(); } -std::vector editor_mode::stray_drives(bool const Wait) +std::vector const &editor_mode::stray_drives(bool const Wait) { scan_switch_drives(Wait); auto const instances{static_cast(scene::Layers.instance_count())}; @@ -348,31 +370,38 @@ std::vector editor_mode::stray_drives(bool const Wait) drive.switches.push_back(standing.values[0] + suffix); kept->drives.push_back(std::move(drive)); } + m_drives_stray.frame.reset(); } - // a switch is told by the name, as the events of the drive find it in the game; a drive of a double switch is stray with all of its - // switches gone, while one stands it still throws it - std::vector stray; + // the list in the switch tool and the marks in the view ask in each frame: told once, and again after a step in the frame + auto &stray{m_drives_stray}; + auto const frame{ImGui::GetFrameCount()}; + auto const history{history_revision()}; + if (stray.frame == frame && stray.history == history) + return stray.drives; + stray.frame = frame; + stray.history = history; + stray.drives.clear(); + // a switch is told by the name, as the events of the drive find it in the game, by the same test the deletion of a switch takes its + // drive away by; a drive of a double switch is stray with all of its switches gone, while one stands it still throws it + auto switches{switches_standing()}; for (auto const &drive : kept->drives) { auto const &included{scene::Layers.instance(drive.instance)}; // a gate, a derailer or a turntable of the same kind of template throws a track of another kind: only a track gone counts - if (included.removed || included.dead || std::any_of(drive.switches.begin(), drive.switches.end(), [](std::string const &Name) { - auto const *track{track_named(Name)}; - return track != nullptr && false == track->m_editorremoved; - })) + if (included.removed || included.dead || switches.any_stands(drive.switches)) continue; std::string missing; for (auto const &name : drive.switches) missing += (missing.empty() ? "" : ", ") + name; - stray.push_back(drive); - stray.back().name = std::move(missing); + stray.drives.push_back(drive); + stray.drives.back().name = std::move(missing); } - return stray; + return stray.drives; } void editor_mode::render_stray_drives() { - auto const stray{stray_drives()}; + auto const &stray{stray_drives()}; if (stray.empty()) return; ImGui::PushID("straydrives"); @@ -400,7 +429,7 @@ void editor_mode::render_stray_drives() // a red mark by each drive with no switch in sight, so it's seen in the view and over the photo, not only in the list void editor_mode::draw_stray_drives() { - auto const stray{stray_drives()}; + auto const &stray{stray_drives()}; if (stray.empty()) return; // the ones far off would only crowd the view of the whole line @@ -528,13 +557,8 @@ void editor_mode::drives_deleted(std::vector const &Switches) auto const named = [&](std::string const &Name) { return std::find(deleted.begin(), deleted.end(), drive_file(Name)) != deleted.end(); }; // an older scenery may have two tracks of a name, the name finding the later; the earlier one, left by the deletion of the other, // still has the drive and the ballast, so it's looked for too - auto const stands = [](std::string const &Name) { - if (auto const *track{track_named(Name)}; track != nullptr) - return false == track->m_editorremoved; - auto const name{drive_file(Name)}; - auto const &tracks{simulation::Paths.sequence()}; - return std::any_of(tracks.begin(), tracks.end(), [&](TTrack const *Track) { return Track != nullptr && false == Track->m_editorremoved && drive_file(Track->name()) == name; }); - }; + auto switches{switches_standing()}; + auto const stands = [&switches](std::string const &Name) { return switches.stands(Name); }; auto const take_away = [&](scene::instance_handle const Instance) { if (false == scene::Layers.removable(Instance)) return; diff --git a/editor/editorSwitchDrives.cpp b/editor/editorSwitchDrives.cpp new file mode 100644 index 000000000..8a6bbecfe --- /dev/null +++ b/editor/editorSwitchDrives.cpp @@ -0,0 +1,68 @@ +/* +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 "editor/editorSwitchDrives.hpp" + +#include +#include +#include + +namespace switch_drives +{ + +std::string game_name(std::string Name) +{ + std::ranges::replace(Name, '\\', '/'); + std::ranges::transform(Name, Name.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + return Name; +} + +standing_switches::standing_switches(finder Find, lister Names) : m_find{std::move(Find)}, m_names{std::move(Names)} {} + +bool standing_switches::stands(std::string const &Name) +{ + if (auto const removed{m_find(Name)}; removed.has_value()) + return false == *removed; + if (false == m_standing.has_value()) + { + m_standing.emplace(); + for (auto const &name : m_names()) + m_standing->insert(game_name(name)); + } + return m_standing->contains(game_name(Name)); +} + +bool standing_switches::any_stands(std::vector const &Names) +{ + return std::ranges::any_of(Names, [this](std::string const &Name) { return stands(Name); }); +} + +std::vector const &template_switches::of(std::string const &File, int const Revision, int const Frame, reader const &Read) +{ + if (m_revision != Revision) + { + m_files.clear(); + m_revision = Revision; + } + auto const [found, fresh]{m_files.try_emplace(File)}; + auto &entry{found->second}; + // read once; one that couldn't be read again in each frame at most, as each include of it asks + if (false == fresh && (false == entry.failed.has_value() || *entry.failed == Frame)) + return entry.suffixes; + entry.failed.reset(); + if (false == Read(File, entry.suffixes)) + { + entry.suffixes.clear(); + entry.failed = Frame; + } + return entry.suffixes; +} + +} // namespace switch_drives diff --git a/editor/editorSwitchDrives.hpp b/editor/editorSwitchDrives.hpp new file mode 100644 index 000000000..d21df9bec --- /dev/null +++ b/editor/editorSwitchDrives.hpp @@ -0,0 +1,76 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include +#include +#include +#include + +// what the switch tool of the editor tells of the drives of the switches, with no track and no window of its own +namespace switch_drives +{ + +// a name as the game finds a track by it: '/' for '\', lower case +std::string game_name(std::string Name); + +// whether the switches a drive throws stand in the scenery, told by their names as the events of the drive find them in the game +class standing_switches +{ + public: + // nullopt when the name finds no track, else whether the track it finds is removed + using finder = std::function(std::string const &Name)>; + // the names of all the tracks of the scenery not removed, as they're written + using lister = std::function()>; + + standing_switches(finder Find, lister Names); + + // the track the name finds stands while it isn't removed. an older scenery may have two tracks of a name, the name finding the later + // one; deleted, it takes the name away, and the earlier one left still stands, so with no track found by the name any track of this + // name not removed counts + bool stands(std::string const &Name); + // a drive of a double switch throws four of them: it still throws one while one of them stands + bool any_stands(std::vector const &Names); + + private: + finder m_find; + lister m_names; + // the game names of the tracks not removed, read once, at the first name finding none + std::optional> m_standing; +}; + +// the switches each template of a drive throws, read once from each file while the templates found stay the same: a template changed +// on the disk is found again by a rescan or by its save in the editor, either changing the revision of the templates. a file which +// can't be read is read again, in a later frame, so a template missing for a moment isn't taken for one that isn't a drive until the +// next rescan +class template_switches +{ + public: + // what follows the first parameter in the names of the switches File throws, as editor_includes::switched_tracks() tells it. + // returns: false if the file can't be read + using reader = std::function &Suffixes)>; + + // the switches File throws, none for a template which isn't a drive or can't be read. Revision: of the templates found, Frame: the + // frame asked in. the reference holds until a call with another revision + std::vector const &of(std::string const &File, int Revision, int Frame, reader const &Read); + + private: + struct entry + { + std::vector suffixes; + std::optional failed; // the frame the file couldn't be read in + }; + std::map> m_files; + std::optional m_revision; +}; + +} // namespace switch_drives diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index 180285912..ac5dabdfd 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -34,6 +34,8 @@ add_executable(${UNIT_TESTS_NAME} "${CMAKE_SOURCE_DIR}/editor/editorFouling.cpp" # and the http client the editor fetches its aids with "${CMAKE_SOURCE_DIR}/editor/editorHttp.cpp" + # and what the switch tool tells of the drives of the switches + "${CMAKE_SOURCE_DIR}/editor/editorSwitchDrives.cpp" # the camera, for the order of its rotations (test_camera.cpp) "${CMAKE_SOURCE_DIR}/vehicle/Camera.cpp" ${UNIT_TEST_CASES}) diff --git a/tests/unit/test_editor_switch_drives.cpp b/tests/unit/test_editor_switch_drives.cpp new file mode 100644 index 000000000..aeff9c7e2 --- /dev/null +++ b/tests/unit/test_editor_switch_drives.cpp @@ -0,0 +1,171 @@ +#include "stdafx.h" +#include "doctest.h" +#include "editor/editorSwitchDrives.hpp" + +#include +#include +#include +#include +#include + +namespace { + +// a track of the scenery: its name as written, and whether the editor removed it +struct track +{ + std::string name; + bool removed{false}; +}; + +// the scenery as the game finds its tracks: Paths finds a name as written or lower case, the later of two tracks of a name; a track +// deleted takes its name away (editor_track::retire()), Retired lists those names +struct scenery +{ + std::vector tracks; + std::vector retired; + int lookups{0}; // of the whole sequence + + std::optional find(std::string const &Name) const + { + auto const name{switch_drives::game_name(Name)}; + if (std::ranges::find(retired, name) != retired.end()) + return std::nullopt; + std::optional found; + for (auto const &entry : tracks) + if (switch_drives::game_name(entry.name) == name) + found = entry.removed; // the later one + return found; + } + + std::vector standing() + { + ++lookups; + std::vector names; + for (auto const &entry : tracks) + if (false == entry.removed) + names.push_back(entry.name); + return names; + } + + switch_drives::standing_switches lookup() + { + return switch_drives::standing_switches{[this](std::string const &Name) { return find(Name); }, [this] { return standing(); }}; + } + + // deletes the later track of the name, as the editor does + void erase_later(std::string const &Name) + { + auto const name{switch_drives::game_name(Name)}; + for (auto entry{tracks.rbegin()}; entry != tracks.rend(); ++entry) + if (switch_drives::game_name(entry->name) == name && false == entry->removed) + { + entry->removed = true; + retired.push_back(name); + return; + } + } +}; + +} // namespace + +TEST_CASE("switch drives: a name is found as the game finds it") +{ + CHECK(switch_drives::game_name("Zwr\\12A") == "zwr/12a"); + CHECK(switch_drives::game_name("zwr_1") == "zwr_1"); + + scenery line{{{"Zwr1"}, {"zwr2", true}}, {}}; + auto switches{line.lookup()}; + CHECK(switches.stands("Zwr1")); + CHECK(switches.stands("ZWR1")); + // one the name finds, removed, doesn't stand + CHECK_FALSE(switches.stands("zwr2")); + CHECK_FALSE(switches.stands("zwr3")); +} + +TEST_CASE("switch drives: two switches of one name, the later deleted, leave the drive throwing the earlier") +{ + // an older scenery has two tracks of the name; the drive set to it throws the one the game finds + scenery line{{{"zwr7"}, {"other"}, {"Zwr7"}}, {}}; + line.erase_later("zwr7"); + REQUIRE_FALSE(line.find("zwr7").has_value()); // the name went with the track deleted + { + auto switches{line.lookup()}; + // the earlier one still stands: the drive isn't stray, and a hint to delete it would delete a working drive + CHECK(switches.stands("zwr7")); + CHECK(switches.stands("ZWR7")); + CHECK(switches.any_stands({"zwr7"})); + CHECK_FALSE(switches.stands("zwr8")); + // the tracks of the scenery are read once, however many names find none + CHECK(line.lookups == 1); + } + // both deleted: the drive throws nothing now + line.erase_later("zwr7"); + auto switches{line.lookup()}; + CHECK_FALSE(switches.stands("zwr7")); + CHECK_FALSE(switches.any_stands({"zwr7"})); +} + +TEST_CASE("switch drives: the drive of a double switch stands while one of its four switches does") +{ + scenery line{{{"dkw1a"}, {"dkw1b"}, {"dkw1c"}, {"dkw1d"}}, {}}; + std::vector const names{"dkw1a", "dkw1b", "dkw1c", "dkw1d"}; + for (auto const *name : {"dkw1a", "dkw1b", "dkw1c"}) + { + line.erase_later(name); + CHECK(line.lookup().any_stands(names)); + } + line.erase_later("dkw1d"); + CHECK_FALSE(line.lookup().any_stands(names)); +} + +TEST_CASE("switch drives: the switches of a template are read once while the templates stay the same") +{ + switch_drives::template_switches templates; + std::map reads; + std::map> files{{"napedy/naped_l.inc", {""}}, {"napedy/dkw.inc", {"a", "b", "c", "d"}}, {"podsypka.inc", {}}}; + auto const read = [&reads, &files](std::string const &File, std::vector &Suffixes) { + ++reads[File]; + auto const found{files.find(File)}; + if (found == files.end()) + return false; + Suffixes = found->second; + return true; + }; + + SUBCASE("read once in a revision") + { + CHECK(templates.of("napedy/naped_l.inc", 1, 10, read) == std::vector{""}); + CHECK(templates.of("napedy/naped_l.inc", 1, 11, read) == std::vector{""}); + CHECK(templates.of("napedy/dkw.inc", 1, 12, read).size() == 4); + CHECK(templates.of("podsypka.inc", 1, 12, read).empty()); + CHECK(templates.of("podsypka.inc", 1, 13, read).empty()); + CHECK(reads["napedy/naped_l.inc"] == 1); + CHECK(reads["napedy/dkw.inc"] == 1); + CHECK(reads["podsypka.inc"] == 1); + } + + SUBCASE("a template changed is read again in the next revision") + { + CHECK(templates.of("napedy/naped_l.inc", 1, 10, read) == std::vector{""}); + // saved in the editor, or changed on the disk and rescanned: no drive any more + files["napedy/naped_l.inc"] = {}; + CHECK(templates.of("napedy/naped_l.inc", 1, 11, read) == std::vector{""}); + CHECK(templates.of("napedy/naped_l.inc", 2, 11, read).empty()); + CHECK(reads["napedy/naped_l.inc"] == 2); + } + + SUBCASE("a file that can't be read is tried again in a later frame") + { + CHECK(templates.of("napedy/nowy.inc", 1, 10, read).empty()); + // each include of it asks in the same frame: read once + CHECK(templates.of("napedy/nowy.inc", 1, 10, read).empty()); + CHECK(reads["napedy/nowy.inc"] == 1); + CHECK(templates.of("napedy/nowy.inc", 1, 11, read).empty()); + CHECK(reads["napedy/nowy.inc"] == 2); + // there now, with the same revision: no rescan needed + files["napedy/nowy.inc"] = {""}; + CHECK(templates.of("napedy/nowy.inc", 1, 12, read) == std::vector{""}); + CHECK(templates.of("napedy/nowy.inc", 1, 13, read) == std::vector{""}); + CHECK(reads["napedy/nowy.inc"] == 3); + } +} From 7b878e336c59dc1cb5674c2dd629007d3a0988e8 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 26 Nov 2026 22:26:06 +0100 Subject: [PATCH 126/136] test(brakes): pin the fill and release times of an ESt3 with the AL2 relay (#513) A 413S freight wagon (ESt3AL2, values of its .fiz) in G and P with the empty/loaded lever in each of its three positions: the cylinder pressure of an emergency application, the time to 95% of it and the release time down to 0.4 bar, measured on staging 5a24a1048 and held to 1% and 5%. Since bb43f559e set the AL2 impulse chamber to 1 l there was no test of it. --- tests/unit/test_est3al2_relay.cpp | 145 ++++++++++++++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100644 tests/unit/test_est3al2_relay.cpp diff --git a/tests/unit/test_est3al2_relay.cpp b/tests/unit/test_est3al2_relay.cpp new file mode 100644 index 000000000..63296901b --- /dev/null +++ b/tests/unit/test_est3al2_relay.cpp @@ -0,0 +1,145 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +#include "McZapkie/hamulce.h" + +#include +#include + +using test::definition; +using test::vehicle; + +// the fill and release times of the brake cylinder of an ESt3 distributor with the AL2 load relay (TNESt3 with +// TPrzekCiagly), in G and in P, with the empty/loaded lever in each of its three positions. bb43f559e made the +// relay's impulse chamber 1 l and scaled the cylinder nozzles to the times of table 3-9 of the ESt3 data; before it +// they were set by eye. this pins what the valve does today, so a change of the relay or of the nozzles shows + +namespace { + +// a Fas 413S four-axle freight wagon (pkp/413s_v1/413s.fiz of the game data): ESt3AL2, 100 l reservoir, one +// 16" cylinder, the empty/medium/loaded lever at 1.5/2.6/3.8 bar, brake delays G and P. not among the converted +// real vehicles of tests/unit/data/fiz, so its lines are set over the test wagon +definition fas_413s() { + return definition::load("wagon") + .set("Param", "M", 25300) + .set("Param", "Vmax", 100) + .set("Load", "MaxLoad", 56) + .set("Load", "LoadQ", "tonns") + .set("Load", "LoadAccepted", "coal,gravel") + .set("Dimensions", "L", 14.4) + .set("Wheels", "D", 0.92) + .set("Wheels", "Axle", "2'2'") + .set("Wheels", "Ad", 2.0) + .set("Wheels", "Bd", 8.5) + .set("Brake", "BrakeValve", "ESt3AL2") + .set("Brake", "Size", 100) + .set("Brake", "MBF", 144) + .set("Brake", "MaxBP", 3.8) + .set("Brake", "TareMaxBP", 1.5) + .set("Brake", "MedMaxBP", 2.6) + .set("Brake", "BCN", 1) + .set("Brake", "BCR", 0.2032) + .set("Brake", "BCD", 0.14) + .set("Brake", "BCM", 11.75) + .set("Brake", "NBpA", 4) + .set("Brake", "BM", "P10-Bg") + .set("Brake", "BCS", 2.7) + .set("Brake", "BSA", 16.0) + .set("Brake", "BVV", 100) + .set("Brake", "BRE", 0.8) + .set("Cntrl", "BrakeDelays", "GP") + .remove("Cntrl", "MaxBPMass"); +} + +struct times { + double charged; // in the cylinder after charging [bar] + double applied; // in the cylinder 60 s after the emergency application [bar] + double fill; // from the pipe emptied to 95% of applied [s] + double release; // from the pipe back at 5 bar to 0.4 bar in the cylinder [s] +}; + +// charges the wagon, empties the pipe at once (an emergency application) and fills it again at once, stepping +// the physics in 0.01 s steps as the game does +times measure(int const Delay, int const Lever) { + test::reseed_random(); + vehicle wagon{fas_413s()}; + REQUIRE(wagon->BrakeValve == TBrakeValve::ESt3AL2); + if (wagon->BrakeDelayFlag != Delay) { + REQUIRE(wagon->BrakeDelaySwitch(Delay)); + } + // an empty wagon starts with the lever at empty (TMoverParameters::CheckLocomotiveParameters) + REQUIRE(wagon->LoadFlag == 1); + while (wagon->LoadFlag < Lever) { + REQUIRE(wagon->IncBrakeMult()); + } + REQUIRE(wagon->LoadFlag == Lever); + + times result{}; + wagon.hold_brake_pipe(5.0); + wagon.run(180.0); + result.charged = wagon->BrakePress; + + double constexpr step{0.01}; + std::vector cylinder; + wagon.hold_brake_pipe(0.0); + for (int i = 0; i < 6000; ++i) { + wagon.step(); + cylinder.push_back(wagon->BrakePress); + } + result.applied = cylinder.back(); + result.fill = -1.0; + for (std::size_t i = 0; i < cylinder.size(); ++i) { + if (cylinder[i] >= 0.95 * result.applied) { + result.fill = static_cast(i + 1) * step; + break; + } + } + + wagon.hold_brake_pipe(5.0); + result.release = -1.0; + for (int i = 0; i < 18000; ++i) { + wagon.step(); + if (wagon->BrakePress <= 0.4) { + result.release = static_cast(i + 1) * step; + break; + } + } + return result; +} + +} // namespace + +TEST_CASE("ESt3AL2: fill and release times of the cylinder of a 413S wagon, G and P, empty, medium and loaded") { + struct expected { + char const *name; + int delay; + int lever; // LoadFlag: 1 empty, 2 medium, 3 loaded + double applied; // [bar] + double fill; // [s] + double release; // [s] + }; + // measured on staging 5a24a1048, held to 1% (the pressure) and 5% (the times). the fill time is to 95% of the + // pressure 60 s after the pipe was emptied, the release time down to 0.4 bar. both count from a step of the pipe, + // 5 to 0 bar and back at once, not from the rate of a driver's brake valve or of a test bench. for comparison only, + // UIC 540 asks for G fill 18-30 s, release 45-60 s, P fill 3-5 s, release 15-20 s: the fill times are within, the + // release times shorter. the emergency application gives the cylinder 0.19-0.27 bar more than the lever's + // TareMaxBP, MedMaxBP and MaxBP (1.5, 2.6, 3.8 bar) + for (auto const &[name, delay, lever, applied, fill, release] : { + expected{"G empty", bdelay_G, 1, 1.736, 22.81, 33.89}, + expected{"G medium", bdelay_G, 2, 2.870, 21.98, 40.82}, + expected{"G loaded", bdelay_G, 3, 3.991, 21.15, 43.98}, + expected{"P empty", bdelay_P, 1, 1.737, 3.84, 10.98}, + expected{"P medium", bdelay_P, 2, 2.871, 3.71, 13.18}, + expected{"P loaded", bdelay_P, 3, 3.995, 3.62, 14.19}, + }) { + CAPTURE(name); + auto const measured{measure(delay, lever)}; + INFO(std::format("{}: charged {:.3f} bar, applied {:.3f} bar, fill {:.2f} s, release {:.2f} s", name, measured.charged, measured.applied, measured.fill, + measured.release)); + CHECK(measured.charged < 0.05); + CHECK(measured.applied == doctest::Approx(applied).epsilon(0.01)); + CHECK(measured.fill == doctest::Approx(fill).epsilon(0.05)); + CHECK(measured.release == doctest::Approx(release).epsilon(0.05)); + } +} From 7e9612f66d1f4bdabc72be7718865e5dc69cd5bb Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 26 Nov 2026 22:26:17 +0100 Subject: [PATCH 127/136] docs(scenarios): a seed repeats a run only with a fixed step (#512) The physics steps of a frame follow the wall clock outside the test mode, so the same seed alone doesn't give the same run. Say that the test mode fixes the step, that --watch doesn't, and what deltaoverride does. --- tests/scenarios/README.md | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index cfd959343..31ae111cf 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -37,8 +37,10 @@ With `--test` the simulator: test mode are applied again after it, - runs the simulation as fast as it can in fixed steps of 0.03 s of simulation time per frame (three 10 ms physics steps), whatever the real time, the time speed or the machine, -- seeds its random numbers with a fixed seed unless `-seed` or `randomseed` gives one, so two - runs of a scenery come out the same (the physicslogs of two runs are byte for byte equal), +- seeds its random numbers with a fixed seed unless `-seed` or `randomseed` gives one, so, + with the fixed step above, two runs of a scenery come out the same (the physicslogs of two + runs are byte for byte equal; a seed without the fixed step isn't enough, see + [A seed alone doesn't make a run repeatable](#a-seed-alone-doesnt-make-a-run-repeatable)), - quits when the test ends, and says how it ended in the exit code and in a `test: ...` line on stdout and in the log. A command line it can't take, a start that fails, or an exception thrown by the simulator (of any type, on Linux too) ends the same way, with the @@ -148,7 +150,29 @@ Python 3.10+, no extra packages. Options: it runs alone, after the others. - `--seed N` (a number or a word) runs the cases with another seed of the simulator's random numbers (`randomseed`) than the fixed one of the test mode, for a bug that shows up only - sometimes: run the case with a few seeds. + sometimes: run the case with a few seeds. A seed repeats a run only in the test mode, see + below. + +### A seed alone doesn't make a run repeatable + +The same seed gives the same run only when every frame lasts the same simulation time. Each +frame the simulator splits the time since the last one into physics steps of at most 10 ms +(`driver_mode::update()`); outside the test mode that time comes from the wall clock (times +`timespeed`), so the number and the length of the steps follow the frame rate, and with them +the speeds, the pressures and the moments the AI decides things. Two runs of one scenery with +one seed then drift apart, the more so on a busy machine. + +- The test mode (`--test`, what `run.py` runs by default) sets a fixed step itself: 0.03 s of + simulation time per frame, three 10 ms steps, whatever the wall clock + (`Timer::set_fixed_step()` in `driver_mode::enter()`). A case run twice with the same + `--seed`, or with none, comes out the same. This is the way to repeat a run. +- `--watch` doesn't use the test mode: it runs on the wall clock, so a watched run isn't + repeatable, seed or not. Use it to look at a case, not to repeat one. +- Outside the test mode (`--watch`, or the simulator started by hand with `-seed`) the setting + `deltaoverride N` makes every frame last 1/N s of simulation time, whatever the wall clock + and `timespeed` (`Timer::set_delta_override()`). It goes in `eu07.ini`, a `-ini` file or a + case's `ini` list. In the test mode it takes the place of the 0.03 s step. Whether a watched + run with it repeats byte for byte hasn't been checked. Exit code is 0 when every case passed, or failed as its `xfail` mark says it does (`XFAIL` in the summary); a case marked `xfail` that passes (`XPASS`) fails the run, so that the mark gets From b0339badb2e8290af219f96baee51fc0b6c5197a Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 26 Nov 2026 22:26:29 +0100 Subject: [PATCH 128/136] docs: behaviour changes accepted in review (#438) * docs: behaviour changes accepted in review, for release notes and triage * docs: the physics log entries after the revert of #408 #443 reverted #408 on staging and brought master's #385. physicslog yes logs road vehicles again, the closing waits for every log, and the 2 s thread, the illegal characters, physicslog.trains and blackbox come from #385. The test.* keys show in the settings dump of log.txt, not in an editor save. --- docs/behaviour-changes.md | 135 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 135 insertions(+) create mode 100644 docs/behaviour-changes.md diff --git a/docs/behaviour-changes.md b/docs/behaviour-changes.md new file mode 100644 index 000000000..069bb6e90 --- /dev/null +++ b/docs/behaviour-changes.md @@ -0,0 +1,135 @@ +# Behaviour changes + +Changes accepted in review that players, scenery authors or data makers can notice, for release notes and for +triaging new bug reports ("it worked differently before"). Each entry says what changed, who notices, what +data or eu07.ini it needs, and the pull request (#NNN, MaSzyna-EU07/maszyna). Written against `staging` as of +2026-11-24; the list starts at #266 (merged 2026-11-08). Keys marked "optional" change nothing until the data uses them. +#443 (2026-11-22) reverted #408 and merged `master` into `staging`; of the changes it brought from `master` only the +physics log ones, which replace those of #408, are listed here. + +The last section lists the new optional data keys, so that data makers can find them; they change nothing for +existing data. + +## Logs and files + +- **physicslog has a new last column `VehicleVelocity[km/h]`** (#266). The header line of every physics log + (`physicslog yes`, the black box tapes) changed: `WaterAuxTemp[Deg]` is now followed by a space and the new column, + the vehicle's speed (the second column is the speed of the wheels, which stays 0 while they are locked). + Notices: anyone parsing the logs by column count or by the exact header. The old columns keep their positions. + Needs: nothing. +- **Passing a signal at stop is logged in every session** (#266). The line ` passed signal at danger` + goes to the log for AI and player drivers alike, rail vehicles only, for a signal showing `SetVelocity 0 0` + (not an automatic block signal with `SetVelocity 0 x`). Before it was only counted in test runs. Notices: log.txt + of any scenery with trains running red signals. Needs: nothing. +- **The settings dump at the start of log.txt lists the `test.*` keys** (#266): `test.timeout`, `test.standstill`, + `test.pass_on_standstill`, `test.fail_if_stop_overran`, `test.no_movement_before_pass` (and `test.wall_timeout`, + `test.vehicle` when set), also in normal sessions, with their defaults. They are ignored outside the test mode. +- **The physics logs are written every 2 s by a thread of their own** (#385 on `master`, on `staging` with #443). + The files are opened only for the moment of writing; a crash loses the last 2 s. A log whose file can't be written + keeps its lines and is retried (up to 64 MB in all). `physicslog yes` still logs every driver, road vehicles + included. The closing writes out everything left, with no time limit; only the test mode stops waiting after 2 s. +- **Characters illegal in Windows file names are replaced by `_` in log file names, on every system** (#385, with + #443): a spawned vehicle `spawn_ezt:12` logs to `spawn_ezt_12.dat`. +- **`physicslog.trains yes`** (#385, with #443, new): `.dat` logs of the drivers of rail vehicles only (no passengers, + no road vehicles). **`blackbox yes|no`** (#385, with #443, new): the black box on its own; with no entry it goes with + `physicslog` (or `physicslog.trains`) as before. +- **A failed start ends with exit code 1 and the reason in the log** (#425); a closing from the player's side still + ends with 0. The crash dump written by the Windows crash handler is small by default (stacks and data segments, + tens of MB instead of the whole memory); `crashdump.full yes` brings back the full one. +- **The region cache `.sbt` is written through a temporary file and checked whole when read** (#351): a + damaged file is turned down ("Bad file: ... ignored") and the scenery loads from the text and writes the cache again. + Format unchanged. +- **Test mode** (#266, `--test`; see `tests/scenarios/README.md`): takes no input from outside, does not read the + player's own eu07.ini, writes only its verdict to the standard output, and has exit codes of its own (kept clear of 1 + and 3). + +## AI + +- **AI on a diesel with a shunting gear drives in the shunting mode** (#275). For a `DieselEngine` with + `ShuntModeAllow` (the SM03's 2Ls150 gear) the AI sets the shunting mode when its order is Shunt/Loose_shunt or the + consist is over 224 t. Before, `CurrentSwitch()` took the call for the motor overload relay threshold and the mode + was never set, so the AI always ran in the running mode. Notices: trains of SM03 on a shunting order or over 224 t + get another speed/power curve, so running times in timetables can change. The same PR makes the first move of the + SM42/SP42 switch set the shunt mode at once. Needs: nothing. +- **A Connect first order releases the hand brake** (#339). +- **The AI's wagon inspector sets G/P/R by Cw-1 par. 18-19 and cuts out the brake of wagons without G in a G train** + (#282 and its review commits). A cut-out skipped on the run is done once the train stands. `ai.brakesetting.cw1 no` + in eu07.ini restores the earlier behaviour (default yes). Notices: another brake setting of formed freight and + passenger trains, brakes cut out on some wagons. Needs: nothing. +- **Braking for a stop**: making for a passenger stop leaves room for the brake's fill time only, no look-ahead floor + (#297); the passenger-stop flag no longer flips on every scan (#295); the W4 stop point is shifted by the margin the + stop is judged by (#321); the shunting AI brakes for a stop point again (#409); gradients of 2.5 per mille and more + count as up gradients for the hold and the start (#265). Notices: stops at platforms and signals look different, + running times can move a little. +- **A reduced signal speed ends at a marked end of the interlocking area** (#305): only where the scenery puts the + `SignalAreaEnd` putvalues event. Without it the old rule holds. +- **No multiple-unit control between electric and diesel traction vehicles** (#279): `Attach()` leaves the control + connection out, also for the scenery and the AI (a Vectron and an SM42 no longer run in multiple); logged. + `controlcoupling.enginecheck no` in eu07.ini brings the old behaviour back (default yes). + +## Cab controls + +- **A lone two-state `main_sw` with a latch needs two presses to switch on after a trip** (#277). The single toggle + lever of the line breaker (no `main_on_bt`/`main_off_bt` in the cab) stays where it was put; after the breaker was + knocked out (the converter overload relay of the EP05) the first press puts the lever off, the second closes the + breaker. Applies to every cab with a lone two-state `main_sw`: e6act, ep03, ep05, et21, et22-2000, eu05, wmb10 (list + from the review; the cab files are in the SVN and were not checked here). Notices: whoever expects one press. +- **A `main_off_bt` declared `type: toggle` is the bistable hold coil lever of the ET22 and EP09** (#268): off opens the + breaker and keeps it from closing, back on only feeds the coil. Cabs keep a push button unless their `.mmd` says + `toggle`. +- **The cruise control has a switch of its own** where the secondary controller shunts the field (6Dg, ST45, BR285) + (#391): `tempomat_sw`/`tempomatoff_sw` follow the cruise control, not `ScndCtrl`. Vehicles with only one of the two + are unchanged. No new keys. +- **The compartment lights keyboard toggle** latches also in cabs without `compartmentlights_sw:` or with the on/off + push buttons (#353); the light preset selector with `Wrap=Yes` turns past its end with animation and sound (#345). +- **The HUD shows the radio channel only with the radio fuse closed**; the radio has a fuse and a hint "Close radio + fuse" (#280). +- **Door closure lamp (SOD) of the whole consist** (#291): the three-state lamp (lit locked, blinking released, dark + open) works only on vehicles with `Doors: DoorClosureSignal=Yes` in the `.fiz`. Old EN57/ED72 consists without + `DoorNeedPermit` do not get the key (they would blink at every standstill) and keep the old lamp that shows the lock + of the vehicle's own doors. The eu07.ini switch `doorclosuresignal` was removed: the data decides. Needs: the key + in the `.fiz` of the vehicle whose cab shows the lamp. +- **Separate engine start buttons work only with new data** (#294): the cab controls `mainb_*` and `mainc_*` + (`_sw`, `_on_bt`, `_off_bt`) start the second and third vehicle of a train in multiple, and `Engine: JointEngineStart=No` + stops the cab's `main_*` from touching the other vehicles. According to the data owners no cab in the SVN has + `mainb_*`/`mainc_*` yet (not checked here); without them and without `JointEngineStart=No` nothing changes + (default `Yes`). New commands `linebreakertoggleb/c`, `linebreakeropenb/c`, `linebreakercloseb/c`, no default keys. + +## Physics and scenery + +- **`physics.collisions` defaults to `new`** (#379, with #377 and #378): rail vehicle collisions past the buffers + crush the ends, a vehicle may ride up or be pushed off the track; road traffic keeps the old rule. `old` or + `monitor` in eu07.ini bring back the earlier behaviour. Notices: harder collisions, derailments of struck vehicles, + crushed ends that stay until repaired (resetconsist or repair). `physics.derailment` defaults to `monitor` (the + legacy draw decides, the log tells what the criteria would do); `new` is opt-in. `physics.trackcheck` and + `couplerphysics` (slack, hysteresis and breaking of the coupler; commits c85aab4f to 226155d4, no PR number) are + off by default. +- **Welded track buckles in the heat** (#378) when the scenery or an event sets it; no effect otherwise. +- **The cab shake is taken at the frame's moment** (#403, #414) and no longer moves in steps. +- **Station names keep their Polish letters** in the interface and timetables, a W4 finds its station by one key + (#418). A station of departure written in capitals is still a stop (#343). +- **Timetable service flags** (#398): the header row `[ Flagi AI | ... ]` and station entries such as + `kierownik=nie` change how the AI serves the train; a timetable without them drives as before. Old builds skip the + header row. +- **New putvalues commands** for sceneries: `Crew: ` puts an AI driver in a vehicle or takes + it off (#422); `SignalAreaEnd` (#305, above); the parameter `H` after the coupling of a vehicle prepares it for + hauling dead in a train, the "pullee mode" (#419). + +## Data keys that need new data + +All optional; without the key everything is as before. The data files are in the SVN, not here. + +| Key / file | What it does | Data to change | PR | +|---|---|---|---| +| `.fiz` Cntrl `SBDReleaseDelay` (s, default 0) | The holding brake of a unit with the MED (SBD) lets go only after power was demanded for that long. | Elf files with SBD would get `1.0` (its `IniCDelay`). | #424 | +| `.fiz` Engine `PressureSwitchBrakeCylinder=No`, Cntrl `EmergencyBrakeMainOff=` | Pressure switch of the EP05 with the brake pipe alone; an emergency application on a power position opens the line breaker (pantographs drop with `PantRequiresMain`). | `ep05_v2/ep05.fiz`, `ep05v1.fiz`: `No` and `2.5`. | #421 | +| `.fiz` Cntrl `PantRequiresMain=Yes` | Line breaker closes before the pantographs, on the low voltage; pantograph valve stays open only with the breaker closed; the AI closes the breaker first. | `ep05_v2`, `ep05v1`, `181_cz1.fiz`. | #272 | +| `.fiz` Cntrl `ScndCtrlResistiveLock=Yes` | The field shunt can't be stepped up or down at zero or on a resistive position; it drops to 0 there. | ET21, ET22, EP09 files. | #278 | +| `.fiz` AI `ShuntPantstate=1/2/3` | Pantographs the AI keeps up while shunting. | ET41 files (`203e-a.fiz`, `203e-b.fiz`, `_dsa150`). | #281 | +| `.fiz` Engine `EDBrake`, `EDBrakeFmax/Pmax/V0/V1/Rate/Blending` | Dynamic brake of diesel-electric vehicles. | BR285 and the like. | #394 | +| `.fiz` Doors `DoorClosureSignal=Yes` | SOD lamp of the whole consist, see above. | Vehicles with `DoorNeedPermit`. | #291 | +| `.fiz` Engine `JointEngineStart=No`, `.mmd` `mainb_*`, `mainc_*` | Separate engine start per vehicle (ST43, SP32, SN61), see above. | Cabs and `.fiz` of those vehicles. | #294 | +| `.fiz` security system `AwareOffInShuntMode=Yes` | The SM42's vigilance device (CA) is off in the shunt mode. | SM42/SP42 files. | #275 | +| `.mmd` `animdoor` per door wing | Door wings of different kinds on one side. | Vehicles with mixed doors. | #397 | +| `.mmd` `i-compartmentlights`, `radioon_sw:` etc. | New lamps and radio fuse switches. | Cabs that have them. | #352, #280 | +| eu07.ini `sound.*` | The OpenAL Soft options, each defaulting to what the simulator did before. | Optional. | #404 | From bc2d1323a344c3616f35d794db15a39ad3fd6fdb Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 26 Nov 2026 22:26:37 +0100 Subject: [PATCH 129/136] feat(physics): a derailed vehicle leaves the track and moves on the ground (physics.derailment new) (#451) * feat(physics): the motion of a derailed vehicle on the ground With physics.derailment new a vehicle off the rails gets a motion of its own on the ground (vehicle/derailmotion.h, in eu07_core): it runs on along its heading, turned out of the curve by the sideways speed it left the rail with, slides across it down slopes steeper than the friction holds, follows the height and the slope of the ground under its supports, and tips over about the wheels of one side (while still guided by the curve, or on a slope, or sliding sideways) until it lies on its side. The vehicle holds the motion and what derailed it (the cause, the lateral acceleration out of the curve, the side a coupling pulled it to). While the motion runs, its friction (0.1 tipping on the outer wheels, 0.3 upright, up to 0.5 on its side) and the grade under it go into the longitudinal force. Off the end of the track the vehicle now slides on with the friction of the ballast instead of stopping within g, and a coupling can pull a vehicle off the rails (pull_off). Nothing of it with physics.derailment monitor, old or off. * feat(physics): a derailed vehicle leaves the track in the scenery TDynamicObject begins the motion of vehicle/derailmotion.h once its vehicle derails with physics.derailment new, and from then on places the model by it: off the axis of the track, pitched and rolled by the ground, on its side once it falls over, the bogies straight under the body. The ground is the scenery's terrain around the place (its opaque shapes and the heightmap terrain), with the ballast bed of the track over it; level ground at the top of the ballast where the scenery has none. The axles keep going along the track by the projection of the move, so the vehicle stays on the track nearest to it for its neighbours, the events and the drawing. A coupled vehicle still on the rails is pulled off when the sideways part of the coupler force puts its leading wheel over the climbing limit over 2 m. An uncoupled vehicle on the track and one off it run into each other only when in line. The derail sound loops while the vehicle scrapes along, and the log tells where it is every second and where it came to rest. Move() is split into move_axles() and place_by_axles(), the code of both unchanged. * feat(blackbox): a vehicle leaving the track and coming to rest off it A new record of the black box, 0x38 derailment, written when a vehicle leaves the track (physics.derailment new) and when it comes to rest off it: what derailed it, its position, heading, speed, offset from the axis of the track, roll, the distance it went and whether it lies on its side (blackbox_doc.md). The scenario runner reads it with the leaves_track check, and seven cases run it on td.scn: an EU07 with coaches into the buckled curve at 46 km/h (the AI) and at 133 km/h, over the overturning speed of the R 600 m curve at 190 km/h, off the end of a track, and overturning at 150 km/h on a curve of R 300 m on level ground, on an embankment and in a cutting. The runner also drops the cached geometry of a case's scenery (.sbt) once the case's fragment is newer than it, as it did for the base scenery: the curve cases carry their own terrain. * feat(physics): the yaw of a derailed body, and what differs between vehicles The body off the track (physics.derailment new) now turns about its vertical axis by itself, apart from the way it travels. Its heading is the way the vehicle goes, along which the Mover's speed runs; its axis is the way its front faces, with a yaw rate and the inertia of a box of its length and width. The friction of the ground holds it: under the two ends of its base while upright, along all of its length on its side, 0.3 to 0.5 along the body and 0.5 across it, each point against the way it slides there. Turning resists the yaw; a body going askew slides harder (mu along cos^2 + mu across sin^2 of the slip, which the Mover takes), its heading is drawn to the body and the sideways scrubbing trips it over. At a standstill it doesn't turn while the friction holds. The forces of the couplings at its ends turn it: two ends meet along the bisector of the bend between the bodies, the push goes through the inner buffer of the bend, off the middle of the beam by up to half the buffer spacing, as far as the buffers meet in height (a derailed body is lower than one on the rails, a rolled one misses them) and as much as a buffer takes (1 MN). Pushed from behind past what the buffers hold, a train of bodies bends further at each joint, the next one the other way: the zigzag of a train folding up. The gap of two ends is taken where they are, not from the distance between the middles, which would press the buffers of every bent pair. Past a right angle the heading turns about with the speed, so the Mover's front stays the body's front. Each vehicle draws its own scatter from the seed of the run and its name: the departure angle +-0.01 rad, yaw +-0.02 rad and +-0.02 rad/s, the friction under each half of it 0.85..1.15, and in two vehicles of three its leading end digging in 0.2..1.5 s after it left the rails, for 0.3..0.8 s, two to four times the friction under that half at one wheel or corner. The same seed gives the same outcome. * feat(physics): a derailed train folds up, and the derailment watches its own cost TDynamicObject gives the body off the track the forces of its couplings as vectors: the gap of a coupling with a vehicle off the track (coupled or meeting it) is that of the two ends as they are, and the force of each end goes to the body at the buffer it pushes through, or towards the other beam it is pulled to. A vehicle still on the rails coupled to one off it is taken off by the part of that force across its axis on its leading wheels (Y/Q over 1.2 over 2 m), pushed by the buffers as well as pulled by the coupling, to the side the force goes. Each vehicle off the track draws its scatter from the seed of the run and its name, and the model and the coupling points follow the yaw of the body. What a derailment costs is watched: the terrain is gathered again at most once a second per vehicle and kept to the nearest 400 000 triangles, the axles of a vehicle off the track follow it along the track by 10 cm steps (a body rocking in place moved them to and fro over the ends of tracks, firing their events every frame), and the gathering, a frame of the motion and the whole update of a vehicle off the track write a warning to the log when they take over 20 ms. The scenario runner gets the consist_folds check: the headings of a train's vehicles at rest off the track differ by a given angle at a given number of joints, optionally alternating, optionally on both sides of the track. eu07_td_off_track_buckle_fast checks the folding, eu07_td_off_track_buckle the coupled coach pulled off at an angle to the locomotive, and the bounds of the other cases are narrowed to the new outcomes. * feat(physics): derailed bodies run into each other instead of through With physics.derailment new the bodies of the vehicles off the track no longer go into each other, nor into the vehicles near them: once a frame, before the vehicles update, every vehicle off the track is checked against those around it (its own train coupled or not, a vehicle still on the rails, another train), by bounding circles and then by the footprints of their bodies: the box of each, less its buffers, rolled and pitched as it lies, seen from above, with the height it reaches. Two footprints in each other are separated along the axis they overlap least across. A hit is an impulse at the point of contact, which takes away the speed the two close in with there (they part with a fifth of it) with the mass, the vertical inertia and the arm of each, and the friction of their sides sliding along each other (0.3). It goes into the velocity and the yaw rate of a body off the track, which then goes the way it is thrown, and into the speed of a vehicle on the rails along them; across the rails it pushes on the leading wheels of that vehicle, which is pushed off when the Y/Q passes 1.2 over 2 m of sliding, or three times that at once. What the bodies still overlap by is taken out by moving them apart. The buffers of two ends keep meeting through meet() and force_on(); the bodies, shorter by the buffers, touch only once the ends are pressed past them or folded corner to corner. The log has the most any two bodies overlapped by every second, and the runner checks it with no_overlap in all off-track cases: before this the coaches went up to 1.64 m into each other at 190 km/h and 0.68 m stayed in each other at rest at 133 km/h; now at most 0.10 m on the way and none at rest. * fix(sonar): the reliability and security issues of the derailment SonarCloud failed the quality gate of the pull request on the new reliability and security ratings: - cpp:S836 (dereference of an undefined pointer value) in the timing watch of TDynamicObject::Update: the analyser lost the reference held in a std::optional. The watch is now always made, with a null vehicle when it is on the track, and does nothing then; copying it is deleted. Only the timing of the update off the track and its warning use it, the physics is the same. - cpp:S2245 (pseudorandom number generator) on the std::mt19937 of draw_scatter: it is seeded on purpose so that a derailment repeats, and nothing secret is drawn; marked NOSONAR like the seeded generators of the editor self tests. - cpp:S2193 (a for loop counter of floating type) in three loops of tests/unit/test_derail_motion.cpp: they count integer steps now. * fix(physics): the scraping of a derailed vehicle stops when it is put back on the rails The derail: sound loops while a vehicle off the track slides, and it was stopped only while the vehicle was still off the track, once it came to rest. rerail() (resetconsist, SetDamage taking dtrain_out off) ends the motion off the track at once, also while the vehicle still slides, and the scraping then went on for good. The vehicle now remembers that it plays the loop and stops it as soon as it isn't sliding off the track any more, at rest or back on the rails. The one-shot derail: sound of the other derailment models is not touched. * fix(physics): a vehicle put back on the rails forgets what derailed it rerail() reset only the side a coupling pulled the vehicle off to, and kept the cause and the lateral acceleration of the derailment. A vehicle that is put back on the rails and later leaves them in a way which doesn't set those (as the fork derailment of #496 does now) would leave the track with the cause and the acceleration of the earlier derailment. rerail() resets both now; the unit tests check it after repair_damage(). * fix(physics): the neighbour scan goes on past a derailed vehicle beside the line update_neighbours() took the nearest vehicle the scan of the track found, and when one of the two was off the track and the other not in line with it, gave up on that end. A vehicle lying beside the line so hid the vehicles beyond it: in a pile-up a wagon still on the rails had no front neighbour while running into a wagon in line further on, until the bodies were already deep in each other. The scan now passes such a vehicle and goes on to the next one (ABuFindObject() with InLine, only from update_neighbours(); the obstacle scan of the AI is as it was). * fix(physics): the moves out of other bodies go into the axles of a derailed vehicle The axles of a vehicle off the track follow it along the track by the displacement of the body, which move_off_track() measured from where the body was at the start of its own step. The contacts of the bodies move it out of the others between the frames, after that, so those moves never reached the axles, and the axles drifted along the track away from the body (the track it is registered on, the events it fires). The displacement is now measured from where the body was when its move went into the axles last. * perf(physics): derailed vehicles share the terrain and let it go at rest Each vehicle off the track gathered its own copy of the terrain, up to 600 m around it and 400 000 triangles (some 30-50 MB with the cell index), and kept it until the scenery unloaded: not let go at rest nor when put back on the rails, and gathered again for every vehicle of a pile-up, with a stall of tens of ms each. - The terrain gathered for a vehicle is kept in vehicle_table as a weak reference. A vehicle leaving the track (or gathering again near the edge) takes one which covers the way it may slide - around it and around where it stops going straight on, by its length and the margin the terrain is gathered again at - instead of gathering its own. A terrain cut down to the nearest triangles of a dense scenery is not shared. - At rest a vehicle keeps only the triangles under it (half its length and 40 m around, mesh_ground::cropped()); the big terrain goes once no vehicle holds it. Moving again, it gathers the terrain anew as before. - Back on the rails (rerail()) the vehicle lets its terrain go. The ground under a vehicle is the same as before: a shared terrain holds every triangle of the scenery reaching into its area. Unit tests: mesh_ground::covers() of an area and cropped(). --- CMakeLists.txt | 1 + McZapkie/MOVER.h | 17 + McZapkie/Mover.cpp | 76 +- blackbox_doc.md | 20 + simulation/blackboxrecorder.cpp | 54 + simulation/blackboxrecorder.h | 4 + tests/scenarios/README.md | 31 + .../cases/eu07_td_off_track_buckle.json | 56 + .../cases/eu07_td_off_track_buckle_fast.json | 55 + .../eu07_td_off_track_curve_cutting.json | 36 + .../eu07_td_off_track_curve_embankment.json | 37 + .../cases/eu07_td_off_track_curve_flat.json | 37 + .../cases/eu07_td_off_track_end.json | 46 + .../cases/eu07_td_off_track_overturn.json | 46 + tests/scenarios/cases/td_off_track.scn | 14 + .../cases/td_off_track_curve_cutting.scn | 441 +++++++ .../cases/td_off_track_curve_embankment.scn | 273 ++++ .../cases/td_off_track_curve_flat.scn | 21 + tests/scenarios/make_off_track_curves.py | 118 ++ tests/scenarios/run.py | 134 +- tests/unit/test_blackbox.cpp | 37 + tests/unit/test_derail_motion.cpp | 1093 +++++++++++++++++ vehicle/DynObj.cpp | 790 +++++++++++- vehicle/DynObj.h | 86 +- vehicle/blackbox.cpp | 16 + vehicle/blackbox.h | 31 + vehicle/derailmotion.cpp | 907 ++++++++++++++ vehicle/derailmotion.h | 496 ++++++++ world/TrkFoll.cpp | 16 + world/TrkFoll.h | 3 + 30 files changed, 4967 insertions(+), 25 deletions(-) create mode 100644 tests/scenarios/cases/eu07_td_off_track_buckle.json create mode 100644 tests/scenarios/cases/eu07_td_off_track_buckle_fast.json create mode 100644 tests/scenarios/cases/eu07_td_off_track_curve_cutting.json create mode 100644 tests/scenarios/cases/eu07_td_off_track_curve_embankment.json create mode 100644 tests/scenarios/cases/eu07_td_off_track_curve_flat.json create mode 100644 tests/scenarios/cases/eu07_td_off_track_end.json create mode 100644 tests/scenarios/cases/eu07_td_off_track_overturn.json create mode 100644 tests/scenarios/cases/td_off_track.scn create mode 100644 tests/scenarios/cases/td_off_track_curve_cutting.scn create mode 100644 tests/scenarios/cases/td_off_track_curve_embankment.scn create mode 100644 tests/scenarios/cases/td_off_track_curve_flat.scn create mode 100644 tests/scenarios/make_off_track_curves.py create mode 100644 tests/unit/test_derail_motion.cpp create mode 100644 vehicle/derailmotion.cpp create mode 100644 vehicle/derailmotion.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 6f5885352..6ed3b325e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -551,6 +551,7 @@ set(CORE_SOURCES "McZapkie/couplerphysics.cpp" "McZapkie/derailment.cpp" "McZapkie/collision.cpp" +"vehicle/derailmotion.cpp" "world/TrackCheck.cpp" "world/SleeperPack.cpp" "McZapkie/Oerlikon_ESt.cpp" diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index e34dbc252..84a597e87 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -19,6 +19,7 @@ http://mozilla.org/MPL/2.0/. #include "derailment.h" #include "collision.h" #include "scripting/ladderlogic.h" +#include "vehicle/derailmotion.h" #include "vehicle/odometerreading.h" class cParser; @@ -2553,6 +2554,22 @@ class TMoverParameters // derailment, which stops it as the legacy model does (with physics.collisions new by a friction of its weight, the // forces of the vehicles coupled to it acting on it) derailment::outcome Derailed{derailment::outcome::none}; + // physics.derailment new: how the vehicle left the rails, for the way it leaves the track (vehicle/derailmotion.h): + // what derailed it, the lateral acceleration of its body out of the curve then [m/s2] (negative into the curve, where a + // buckle bends the line the other way), and the side it was pulled off to by a coupling (1 the left of its front, -1 + // the right; 0 the side the acceleration throws it to, from the track) + derail_motion::cause DerailCause{derail_motion::cause::off_rails}; + double DerailAcceleration{0.0}; + int DerailSide{0}; + // the vehicle off the track, on the ground: begun and stepped by TDynamicObject, which knows the ground; its friction + // and the grade under it go into the forces of this one + derail_motion::body OffTrack; + // physics.derailment new: the vehicle derailed by the physical criteria, the end of the track or a collision has to + // leave the track and its motion on the ground isn't begun yet. never with physics.derailment monitor, old or off + bool leaves_track() const; + // physics.derailment new: a coupling of a vehicle off the track pulls this one off the rails sideways, to the Side + // (1 the left of its front, -1 the right), with the lateral acceleration [m/s2] of the pull on it + void pull_off(int Side, double Acceleration, std::string const &Why); // physics.collisions new: what the vehicle is for the defaults of its crush and its buffers, the crush curve and the // height of the buffers of an end, and how long the push of its ends held its wheels over the climbing limit collision::vehicle_kind collision_kind() const; diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 5143b359a..1a25aac20 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -82,6 +82,15 @@ bool legacy_derailed_slides(TMoverParameters const &Vehicle) Vehicle.Derailed == derailment::outcome::none; } +// a derailed vehicle tears its brake hoses: the brake pipe vents and the rest of the train brakes in emergency +void tear_brake_hoses(TMoverParameters &Vehicle) +{ + if (std::any_of(std::begin(Vehicle.Couplers), std::end(Vehicle.Couplers), [](auto const &Coupler) { return (Coupler.CouplingFlag & coupling::brakehose) == coupling::brakehose; })) + { + Vehicle.AlarmChainFlag = true; + } +} + } // namespace int DirF(int CouplerN) @@ -1605,6 +1614,9 @@ void TMoverParameters::derail_in_collision(DerailReason const Reason, std::strin } // upright, it slides on the sleepers and keeps passing the forces on Derailed = derailment::outcome::off_rails; + DerailCause = derail_motion::cause::collision; + DerailAcceleration = 0.0; + DerailSide = 0; CollisionDerail = Reason; EventFlag = true; MainSwitch(false, range_t::local); @@ -1615,10 +1627,7 @@ void TMoverParameters::derail_in_collision(DerailReason const Reason, std::strin SlippingWheels = false; } // the brake hoses tear: the brake pipe vents and the rest of the train brakes in emergency - if (std::any_of(std::begin(Couplers), std::end(Couplers), [](auto const &Coupler) { return (Coupler.CouplingFlag & coupling::brakehose) == coupling::brakehose; })) - { - AlarmChainFlag = true; - } + tear_brake_hoses(*this); derailment_monitor.reset(); pushed_off_monitor.reset(); ErrorLog(std::format("Bad driving: {} derailed in a collision, {}: {}", Name, Reason == COLLISION_OVERRIDE ? "overriding" : "pushed off the track", Why)); @@ -2082,13 +2091,14 @@ void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::ve return; } Derailed = Verdict.result; + DerailCause = Verdict.result == derailment::outcome::overturned ? derail_motion::cause::overturned : derail_motion::cause::off_rails; + // out of the curve; a buckle bending the line against the curve more than the curve does throws it into the curve + DerailAcceleration = std::abs(Track.radius) > 1e-3 && derailment::line_curvature(Track) < 0.0 ? -Verdict.acceleration : Verdict.acceleration; + DerailSide = 0; EventFlag = true; MainSwitch(false, range_t::local); // the brake hoses tear: the brake pipe vents and the rest of the train brakes in emergency - if (std::any_of(std::begin(Couplers), std::end(Couplers), [](auto const &Coupler) { return (Coupler.CouplingFlag & coupling::brakehose) == coupling::brakehose; })) - { - AlarmChainFlag = true; - } + tear_brake_hoses(*this); ErrorLog("Bad driving: " + Name + " " + derailment::report(Verdict, Vehicle, Track, V, TrackName != nullptr ? *TrackName : std::string{})); if (Track.buckle_curvature != 0.0) { @@ -2101,6 +2111,11 @@ void TMoverParameters::rerail() { ClearFlag(DamageFlag, dtrain_out); Derailed = derailment::outcome::none; + // and back on the track; what derailed it before has no say in how it leaves the track the next time + OffTrack.reset(); + DerailCause = derail_motion::cause::off_rails; + DerailAcceleration = 0.0; + DerailSide = 0; derailment_monitor.reset(); derailment_distance = 0.0; derailment_reported.reset(); @@ -2154,6 +2169,16 @@ void TMoverParameters::Derail(DerailReason const Reason) nrot = 0.0; SlippingWheels = false; } + // physics.derailment new: off the end of the track the vehicle runs on straight on its wheels, sliding on the + // ground as the vehicles the criteria derail do, and its brake hoses tear + if (Reason == END_OF_TRACK && Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1)) + { + Derailed = derailment::outcome::off_rails; + DerailCause = derail_motion::cause::end_of_track; + DerailAcceleration = 0.0; + DerailSide = 0; + tear_brake_hoses(*this); + } // Print a message in the log. if (Reason == END_OF_TRACK) @@ -2171,6 +2196,30 @@ void TMoverParameters::Derail(DerailReason const Reason) } } +bool TMoverParameters::leaves_track() const +{ + return Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1) && TestFlag(DamageFlag, dtrain_out) && Derailed != derailment::outcome::none && + false == OffTrack.active(); +} + +void TMoverParameters::pull_off(int const Side, double const Acceleration, std::string const &Why) +{ + if (Global.derailment != global_settings::derailment_model::physical || false == SetFlag(DamageFlag, dtrain_out)) + { + return; + } + // upright, its flange climbs the rail the coupling pulls it over + Derailed = derailment::outcome::off_rails; + DerailCause = derail_motion::cause::pulled_off; + DerailAcceleration = Acceleration; + DerailSide = Side; + EventFlag = true; + MainSwitch(false, range_t::local); + tear_brake_hoses(*this); + derailment_monitor.reset(); + ErrorLog(std::format("Bad driving: {} pulled off the track by the vehicle coupled to it, {}", Name, Why)); +} + void TMoverParameters::change_train_velocity(double const Change) { // the vehicles coupled to this one in a line, each with the direction of its axis to the axis of this one @@ -2215,6 +2264,11 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap // abs(ElectricTraction.TractionResistivity * Itot * // 0)*/; // zasadniczo ED oporowe nie zmienia napięcia w sieci } + else if (OffTrack.active()) + { + // off the track the grade is that of the ground under it, along its heading + RunningShape.dHtrack = Shape.dHtrack; + } if (CategoryFlag == 4) OffsetTrackV = TotalMass / (Dim.L * Dim.W * 1000.0); @@ -6201,8 +6255,10 @@ void TMoverParameters::ComputeTotalForce(double dt) { if (Derailed != derailment::outcome::none) { - // off the rails by the physical criteria: the vehicle slides on the sleepers and the ballast, or on its side - FStand = derailment::sliding_friction(Derailed) * (TotalMass - Mred) * g; + // off the rails by the physical criteria: the vehicle slides on the sleepers and the ballast, or on its side; + // off the track on the ground, as far as it tipped over (physics.derailment new) + auto const friction{OffTrack.active() ? OffTrack.friction() : derailment::sliding_friction(Derailed)}; + FStand = friction * (TotalMass - Mred) * g; } else if (legacy_derailed_slides(*this)) { diff --git a/blackbox_doc.md b/blackbox_doc.md index 9314b94e6..ce2108484 100644 --- a/blackbox_doc.md +++ b/blackbox_doc.md @@ -550,6 +550,26 @@ What is coupled: 0x01 the coupler, 0x02 the brake pipe, 0x04 the control (multip voltage, 0x10 the gangway, 0x20 the main reservoir pipe, 0x40 the train heating, 0x80 a coupling not to be undone in shunting (between the cars of a unit). +### 0x38 derailment + +A vehicle off the track, with `physics.derailment new` in `eu07.ini`: it doesn't follow the track any more +and moves on the ground by itself until it stops. Written when it leaves the track, and when it comes to +rest off it, looked at every second. A vehicle put back on the rails and derailed again is written again. + +| type | field | +|---------|--------------------------------------------------------------------------------| +| `f64` | t | +| `u32` | number of the vehicle | +| `u8` | 0 it left the track, 1 it came to rest off it | +| `u8` | what derailed it: 1 the flange climbed the rail, 2 it overturned in a curve, 3 the end of the track, 4 a coupling of a vehicle off the track pulled it off, 5 a collision | +| `dvec3` | position of the vehicle | +| `f32` | heading [rad] of its front, from +z towards +x | +| `f32` | speed [km/h], positive along its front | +| `f32` | offset [m] from the axis of the track at the place nearest to it, to the left of its front positive | +| `f32` | roll [rad] of its body, to the left positive: about 1.57 on its side | +| `f32` | distance [m] it went on the ground since it left the rails | +| `u8` | 1 lying on its side, 0 upright | + ### 0x3F end Last, when the simulator closes. diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index 345bae36c..e4161ce61 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -544,6 +544,7 @@ void blackbox_recorder::look_around(bool const Keyframe) { look_at_vehicles(Keyframe); auto const vehicles{clock::now()}; look_at_couplers(); + look_at_derailments(); auto const couplers{clock::now()}; look_at_switches(); auto const switches{clock::now()}; @@ -557,6 +558,59 @@ void blackbox_recorder::look_around(bool const Keyframe) { } } +namespace { + +std::uint8_t cause_of(derail_motion::cause const Cause) { + switch (Cause) { + case derail_motion::cause::overturned: + return blackbox::derailment_causes::overturned; + case derail_motion::cause::end_of_track: + return blackbox::derailment_causes::end_of_track; + case derail_motion::cause::pulled_off: + return blackbox::derailment_causes::pulled_off; + case derail_motion::cause::collision: + return blackbox::derailment_causes::collision; + default: + return blackbox::derailment_causes::flange_climbed; + } +} + +} // namespace + +void blackbox_recorder::look_at_derailments() { + for (auto *vehicle : simulation::Vehicles.sequence()) { + if (false == vehicle->bEnabled) + continue; + auto const &motion{vehicle->MoverParameters->OffTrack}; + auto const id{vehicle_id(vehicle)}; + auto &entry{m_vehicles[vehicle]}; + if (false == motion.active()) { + entry.derailment = 0; + continue; + } + auto const phase{motion.at_rest() ? 2 : 1}; + if (entry.derailment >= phase) + continue; + blackbox::derailment_state state; + state.time = m_time; + state.vehicle = id; + state.cause = cause_of(motion.reason()); + state.position = vehicle->GetPosition(); + state.heading = static_cast(std::atan2(vehicle->VectorFront().x, vehicle->VectorFront().z)); + state.speed_kmh = static_cast(vehicle->MoverParameters->V * 3.6); + state.offset = static_cast(vehicle->off_track_offset()); + state.roll = static_cast(motion.roll()); + state.travelled = static_cast(motion.travelled()); + state.lying = motion.lying(); + // seen first at rest, it left the track before + for (auto written = entry.derailment + 1; written <= phase; ++written) { + state.phase = (written == 1 ? blackbox::derailment_phases::left_track : blackbox::derailment_phases::at_rest); + m_writer->derailment(state); + } + entry.derailment = phase; + } +} + void blackbox_recorder::look_at_couplers() { for (auto *vehicle : simulation::Vehicles.sequence()) { if (false == vehicle->bEnabled) diff --git a/simulation/blackboxrecorder.h b/simulation/blackboxrecorder.h index 140503e39..cdc61da61 100644 --- a/simulation/blackboxrecorder.h +++ b/simulation/blackboxrecorder.h @@ -69,6 +69,8 @@ private: bool listed{false}; std::array couplers; // as seen last bool couplers_known{false}; + // off the track: 0 not, 1 written as leaving it, 2 written as at rest + int derailment{0}; }; struct switch_entry { TTrack *track{nullptr}; @@ -99,6 +101,8 @@ private: void look_at_signals(); // the couplers of every vehicle against the last look: those coupled at the first look, then the changes void look_at_couplers(); + // the vehicles leaving the track and coming to rest off it (physics.derailment new) + void look_at_derailments(); void write_camera(); // the timetable of the train the user is in, written again when it is another one; none isn't written void look_at_timetable(TDynamicObject const &Vehicle, std::uint32_t Id); diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index 31ae111cf..600d8fa14 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -368,6 +368,21 @@ an ET21 and its AI driver on it. The pantographs go up and find no wire, so the start: the driver has to say so in the log, once, naming the locomotive and where it stands, and not mistake it for a wire without voltage. It ends on the standstill. +The `eu07_td_off_track_*` cases run with `physics.derailment new`, where a derailed vehicle leaves the track and +moves on the ground by itself (`vehicle/derailmotion.h`); they check what the black box records of it with +`leaves_track`, and the log has a line of each vehicle off the track every second (`derailment: ... off the track`). +`td_off_track.scn` keeps an EU07 with an AI driver standing on track 1 of Stacja1 to log its physics, and has the train +of the case, without a driver, run at `vars.velocity` km/h from `vars.offset` m past point 1 of `vars.track`: +`eu07_td_off_track_buckle_fast` (133 km/h, `tdo_n222` buckled 600 mm over 8 m from the start with the `buckle` +keyword of the track) and `eu07_td_off_track_overturn` (190 km/h, over the overturning speed of the R 600 m curve) +from `tdo_n157`, `eu07_td_off_track_end` off the end of a track of its own (`vars.track_nodes`). +`eu07_td_off_track_buckle` is `td_buckle_event.scn` with an EU07 and three coaches on the timetable, at the 46 km/h +of the AI. The `eu07_td_off_track_curve_*` cases have an EU07 overturn at 150 km/h on a track of R 300 m of their own, +on level ground, on an embankment 4 m high and in a cutting, made of triangle strips in the fragment +(`td_off_track_curve_*.scn`, written by `make_off_track_curves.py`: a curve of R 300 m from (-300, 400) about the +centre (-600, 400), the cross section swept along it every 0.03 rad; the banks of the cutting rise 4 m at 1:1.5, then +on at 1:5). + `eu07_td_cold_connect` (fragment `td_cold_connect.scn`) has an EU07 with a hand brake (`4E-ZEZ_GREY`; the plain `4e` has none) standing cold on track 1 of Stacja1 (trainset velocity 0, so it starts with the hand brake on) and two coaches standing 45 m ahead of it. Its driver sleeps @@ -666,6 +681,22 @@ the row instead, logged by builds from this branch on. it stays at or above `at_least`, e.g. no power lost under an insulator. - `master_controller` `from_distance`, `to_distance`, `at_most`: the master controller stays at or below the position between the two distances, e.g. at 0 where the scenery tells the driver to coast. +- `leaves_track` `vehicle`, optional `cause` (`flange climbed`, `overturned`, `end of track`, `pulled off`, + `collision`), `min_offset`, `max_offset`, `min_distance`, `max_distance`, `lying`: with + `physics.derailment new` the black box has the vehicle leave the track and come to rest off it; at rest its + distance from the axis of the track (either side) and the distance it went on the ground are within the + bounds, and it lies on its side, or not, as `lying` says. +- `consist_folds` `vehicles` (the names of the train front to back, comma separated), `min_bend`, optional + `min_folds` (1), `alternate`, `both_sides`: with `physics.derailment new` the train came to rest folded up off + the track: at least `min_folds` of the bends between neighbours at rest (the angle between their headings in the + black box, either way along) are `min_bend` degrees or more; with `alternate` neighbouring bends of that size turn + opposite ways (a zigzag), with `both_sides` some of the vehicles rest on either side of the track. A vehicle that + stayed on the rails has no bend with its neighbours. +- `no_overlap` `max_transient`, `max_at_rest` (a check on the log): with `physics.derailment new` the bodies of the + vehicles off the track and of those near them don't go into each other. The simulator logs every second the most + any two of them overlapped by (`derailment: the bodies overlap by up to ... m (which two, how they are related) + over the last second, ... m now`), and once more when all vehicles off the track are at rest (`, all at rest`); the + most on the way is at most `max_transient` m, the overlap at rest at most `max_at_rest` m. - `on_track` `vehicles`, optional `max_offset` (0.75 m), `max_detour` (5 m): every vehicle whose name starts with `vehicles` (e.g. `{{vehicle}}`, the train of the case) keeps to the rails in the black box, in each of its states: diff --git a/tests/scenarios/cases/eu07_td_off_track_buckle.json b/tests/scenarios/cases/eu07_td_off_track_buckle.json new file mode 100644 index 000000000..29768b643 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_off_track_buckle.json @@ -0,0 +1,56 @@ +{ + "description": "physics.derailment new: EU07 with three coaches on td.scn on the td/rozklad timetable; at 10:35, as it leaves, the curve tdo_n222 about 950 m ahead buckles hard with a trackbuckle event (600 mm out of the curve over a main lobe of 8 m). The AI runs into it at the 33-35 km/h it has there with the coaches (46 km/h alone): the locomotive overturns on the buckle, goes off the track towards the bulge, falls on its side and stops on the ground some 30 m on; the coupling pulls the first coach off the rails.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_buckle_event.scn", + "vars": { + "amplitude": "600 8", + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_w1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_w2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_w3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic" + ] + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "expect": "timeout", + "duration": 240, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "Track \\\"tdo_n222\\\" buckled \\(event autotest_buckle\\): 600 mm" + }, + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+ leaves the track" + }, + { + "type": "starts", + "min_speed": 20, + "within": 150 + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}", + "min_offset": 3, + "max_distance": 45, + "min_distance": 15, + "lying": true + }, + { + "type": "consist_folds", + "vehicles": "{{vehicle}},{{vehicle}}_w1", + "min_bend": 15 + }, + { + "type": "no_overlap", + "max_transient": 0.2, + "max_at_rest": 0.05 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_off_track_buckle_fast.json b/tests/scenarios/cases/eu07_td_off_track_buckle_fast.json new file mode 100644 index 000000000..6b7154396 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_off_track_buckle_fast.json @@ -0,0 +1,55 @@ +{ + "description": "physics.derailment new: an EU07 with three coaches and no driver runs at 133 km/h into the curve tdo_n222 of td.scn (R 600 m, cant 65 mm), buckled hard 600 mm over a main lobe of 8 m from the start (the buckle keyword of the track). The locomotive overturns on the buckle: it leaves the track, falls on its side within a second and slides on the ground to a stop some 170 m on, 30 m off the track; the coaches behind it go off and over as well, and the train comes to rest folded, the vehicles turned against each other by 10 to 20 degrees.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_off_track.scn", + "vars": { + "track": "tdo_n157", + "offset": "60", + "velocity": "133", + "track_nodes": "", + "consist": [ + "node -1 0 {{vehicle}}_off dynamic pkp\\4e_v1 4e-004 4e 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_off_w1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_off_w2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_off_w3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic" + ] + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "expect": "timeout", + "duration": 60, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+_off leaves the track" + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}_off", + "cause": "overturned", + "min_offset": 20, + "min_distance": 120, + "max_distance": 230, + "lying": true + }, + { + "type": "consist_folds", + "vehicles": "{{vehicle}}_off,{{vehicle}}_off_w1,{{vehicle}}_off_w2,{{vehicle}}_off_w3", + "min_bend": 8, + "min_folds": 2 + }, + { + "type": "no_overlap", + "max_transient": 0.2, + "max_at_rest": 0.05 + } + ], + "track_events": { + "tdo_n222": "buckle 600;8" + } +} diff --git a/tests/scenarios/cases/eu07_td_off_track_curve_cutting.json b/tests/scenarios/cases/eu07_td_off_track_curve_cutting.json new file mode 100644 index 000000000..8b930e541 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_off_track_curve_cutting.json @@ -0,0 +1,36 @@ +{ + "description": "physics.derailment new: an EU07 without a driver runs at 150 km/h into a curve of R 300 m without cant, a track of 150 m laid on its own in the fields of td.scn (autotest_curve), in a cutting with banks of 1:1.5 4 m high, the ground rising on beyond them at 1:5 (triangles of the fragment). Over its overturning speed (about 120 km/h) it overturns out of the curve: it runs into the bank on the outside of the curve, climbs it and stops sooner than on level ground.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_off_track_curve_cutting.scn", + "vars": { + "velocity": "150" + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "expect": "timeout", + "duration": 60, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+_off leaves the track" + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}_off", + "cause": "overturned", + "min_offset": 40, + "min_distance": 150, + "max_distance": 230 + }, + { + "type": "no_overlap", + "max_transient": 0.2, + "max_at_rest": 0.05 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_off_track_curve_embankment.json b/tests/scenarios/cases/eu07_td_off_track_curve_embankment.json new file mode 100644 index 000000000..6db8b4ed8 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_off_track_curve_embankment.json @@ -0,0 +1,37 @@ +{ + "description": "physics.derailment new: an EU07 without a driver runs at 150 km/h into a curve of R 300 m without cant, a track of 150 m laid on its own in the fields of td.scn (autotest_curve), on an embankment 4 m high with slopes of 1:1.5 (triangles of the fragment). Over its overturning speed (about 120 km/h) it overturns out of the curve: it falls on its side over the edge of the embankment, slides down its slope and on over the level ground at its foot, 4 m lower.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_off_track_curve_embankment.scn", + "vars": { + "velocity": "150" + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "expect": "timeout", + "duration": 60, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+_off leaves the track" + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}_off", + "cause": "overturned", + "min_offset": 40, + "min_distance": 150, + "max_distance": 280, + "lying": true + }, + { + "type": "no_overlap", + "max_transient": 0.2, + "max_at_rest": 0.05 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_off_track_curve_flat.json b/tests/scenarios/cases/eu07_td_off_track_curve_flat.json new file mode 100644 index 000000000..df4103e81 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_off_track_curve_flat.json @@ -0,0 +1,37 @@ +{ + "description": "physics.derailment new: an EU07 without a driver runs at 150 km/h into a curve of R 300 m without cant, a track of 150 m laid on its own in the fields of td.scn (autotest_curve), on level ground (the grass of td.scn). Over its overturning speed (about 120 km/h) it overturns out of the curve: it slides on the grass out of the curve, falls on its side and stops.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_off_track_curve_flat.scn", + "vars": { + "velocity": "150" + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "expect": "timeout", + "duration": 60, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+_off leaves the track" + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}_off", + "cause": "overturned", + "min_offset": 40, + "min_distance": 150, + "max_distance": 260, + "lying": true + }, + { + "type": "no_overlap", + "max_transient": 0.2, + "max_at_rest": 0.05 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_off_track_end.json b/tests/scenarios/cases/eu07_td_off_track_end.json new file mode 100644 index 000000000..5a37cb2d0 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_off_track_end.json @@ -0,0 +1,46 @@ +{ + "description": "physics.derailment new: an EU07 with three coaches and no driver runs at 60 km/h off the end of a track of 150 m laid on its own in the fields of td.scn (autotest_stub): it runs straight on, upright, on the ground, and stops some 30 m on (the friction of 0.3 against the 39 km/h left of its 60 km/h as it drops off the end of the rails, the coaches pushing it); the first coach follows it off the end.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_off_track.scn", + "vars": { + "track": "autotest_stub", + "offset": "100", + "velocity": "60", + "track_nodes": "node -1 0 autotest_stub track normal 150.0 1.435 0.15 25.0 20 0 flat vis\n rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1\n-150.0 0.2 600.0 0.0 //point 1\n0.0 0.0 0.0 //control vector 1\n0.0 0.0 0.0 //control vector 2\n-150.0 0.2 750.0 0.0 //point 2\n0\nendtrack", + "consist": [ + "node -1 0 {{vehicle}}_off dynamic pkp\\4e_v1 4e-004 4e 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_off_w1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_off_w2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_off_w3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic" + ] + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "expect": "timeout", + "duration": 60, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+_off leaves the track" + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}_off", + "cause": "end of track", + "max_offset": 0.5, + "min_distance": 5, + "max_distance": 60, + "lying": false + }, + { + "type": "no_overlap", + "max_transient": 0.2, + "max_at_rest": 0.05 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_off_track_overturn.json b/tests/scenarios/cases/eu07_td_off_track_overturn.json new file mode 100644 index 000000000..c1bff7403 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_off_track_overturn.json @@ -0,0 +1,46 @@ +{ + "description": "physics.derailment new: an EU07 with three coaches and no driver runs at 190 km/h into the curve of R 600 m of td.scn (tdo_n213, tdo_n222), cant 65 mm: over the overturning speed (about 165 km/h) it overturns out of the curve, falls on its side and slides off the track to a stop; the coaches go over as well.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_off_track.scn", + "vars": { + "track": "tdo_n157", + "offset": "60", + "velocity": "190", + "track_nodes": "", + "consist": [ + "node -1 0 {{vehicle}}_off dynamic pkp\\4e_v1 4e-004 4e 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_off_w1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_off_w2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_off_w3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic" + ] + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "expect": "timeout", + "duration": 60, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+_off leaves the track" + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}_off", + "cause": "overturned", + "min_offset": 50, + "min_distance": 250, + "max_distance": 420, + "lying": true + }, + { + "type": "no_overlap", + "max_transient": 0.2, + "max_at_rest": 0.05 + } + ] +} diff --git a/tests/scenarios/cases/td_off_track.scn b/tests/scenarios/cases/td_off_track.scn new file mode 100644 index 000000000..0318e961d --- /dev/null +++ b/tests/scenarios/cases/td_off_track.scn @@ -0,0 +1,14 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed (physics.derailment new, the vehicles +// off the track moving on the ground, vehicle/derailmotion.h): +// an EU07 with an AI driver and no timetable stands on track 1 of Stacja1, where td.scn keeps its timetable train, +// so it stays put and logs its physics; the train of the case has no driver and runs at {{velocity}} km/h from +// {{offset}} m past point 1 of {{track}} towards its point 2. on the line of td.scn, from tdo_n157 on, that is the +// curve of R 600 m (tdo_n213, tdo_n222, tdo_n231), cant 65 mm +{{track_nodes}} +trainset none tdo_n1734 0.0 0.0 +node -1 0 {{vehicle}} dynamic pkp\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic +endtrainset + +trainset none {{track}} {{offset}} {{velocity}} +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_off_track_curve_cutting.scn b/tests/scenarios/cases/td_off_track_curve_cutting.scn new file mode 100644 index 000000000..2c32a3f50 --- /dev/null +++ b/tests/scenarios/cases/td_off_track_curve_cutting.scn @@ -0,0 +1,441 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed (physics.derailment new, the vehicles +// off the track moving on the ground, vehicle/derailmotion.h): a track of R 300 m without cant laid on its own in the +// fields of td.scn (autotest_curve), in a cutting with banks of 1:1.5 4 m high, the ground rising on beyond them at 1:5; written by a script, see the README. +// an EU07 with an AI driver and no timetable stands on track 1 of Stacja1, where td.scn keeps its timetable train, so +// it stays put and logs its physics; the EU07 of the case has no driver and runs at {{velocity}} km/h from 20 m past +// point 1 of the curve towards its point 2 +node -1 0 none triangle_strip grass +-456.70 32.10 355.67 0 1 0 0 0 end +-322.47 4.00 314.15 0 1 0 0 0 end +-455.43 32.10 359.99 0 1 0 0 0 end +-320.02 4.00 322.51 0 1 0 0 0 end +-454.30 32.10 364.34 0 1 0 0 0 end +-317.83 4.00 330.95 0 1 0 0 0 end +-453.30 32.10 368.73 0 1 0 0 0 end +-315.88 4.00 339.44 0 1 0 0 0 end +-452.42 32.10 373.15 0 1 0 0 0 end +-314.19 4.00 347.99 0 1 0 0 0 end +-451.68 32.10 377.58 0 1 0 0 0 end +-312.76 4.00 356.59 0 1 0 0 0 end +-451.08 32.10 382.04 0 1 0 0 0 end +-311.59 4.00 365.22 0 1 0 0 0 end +-450.61 32.10 386.52 0 1 0 0 0 end +-310.68 4.00 373.89 0 1 0 0 0 end +-450.27 32.10 391.01 0 1 0 0 0 end +-310.02 4.00 382.58 0 1 0 0 0 end +-450.07 32.10 395.50 0 1 0 0 0 end +-309.63 4.00 391.29 0 1 0 0 0 end +-450.00 32.10 400.00 0 1 0 0 0 end +-309.50 4.00 400.00 0 1 0 0 0 end +-450.07 32.10 404.50 0 1 0 0 0 end +-309.63 4.00 408.71 0 1 0 0 0 end +-450.27 32.10 408.99 0 1 0 0 0 end +-310.02 4.00 417.42 0 1 0 0 0 end +-450.61 32.10 413.48 0 1 0 0 0 end +-310.68 4.00 426.11 0 1 0 0 0 end +-451.08 32.10 417.96 0 1 0 0 0 end +-311.59 4.00 434.78 0 1 0 0 0 end +-451.68 32.10 422.42 0 1 0 0 0 end +-312.76 4.00 443.41 0 1 0 0 0 end +-452.42 32.10 426.85 0 1 0 0 0 end +-314.19 4.00 452.01 0 1 0 0 0 end +-453.30 32.10 431.27 0 1 0 0 0 end +-315.88 4.00 460.56 0 1 0 0 0 end +-454.30 32.10 435.66 0 1 0 0 0 end +-317.83 4.00 469.05 0 1 0 0 0 end +-455.43 32.10 440.01 0 1 0 0 0 end +-320.02 4.00 477.49 0 1 0 0 0 end +-456.70 32.10 444.33 0 1 0 0 0 end +-322.47 4.00 485.85 0 1 0 0 0 end +-458.09 32.10 448.61 0 1 0 0 0 end +-325.17 4.00 494.13 0 1 0 0 0 end +-459.62 32.10 452.84 0 1 0 0 0 end +-328.12 4.00 502.34 0 1 0 0 0 end +-461.26 32.10 457.03 0 1 0 0 0 end +-331.31 4.00 510.44 0 1 0 0 0 end +-463.04 32.10 461.16 0 1 0 0 0 end +-334.75 4.00 518.45 0 1 0 0 0 end +-464.93 32.10 465.24 0 1 0 0 0 end +-338.42 4.00 526.36 0 1 0 0 0 end +-466.95 32.10 469.27 0 1 0 0 0 end +-342.33 4.00 534.15 0 1 0 0 0 end +-469.09 32.10 473.23 0 1 0 0 0 end +-346.47 4.00 541.82 0 1 0 0 0 end +-471.34 32.10 477.12 0 1 0 0 0 end +-350.84 4.00 549.36 0 1 0 0 0 end +-473.71 32.10 480.94 0 1 0 0 0 end +-355.43 4.00 556.76 0 1 0 0 0 end +-476.20 32.10 484.70 0 1 0 0 0 end +-360.24 4.00 564.03 0 1 0 0 0 end +-478.80 32.10 488.37 0 1 0 0 0 end +-365.27 4.00 571.15 0 1 0 0 0 end +-481.50 32.10 491.97 0 1 0 0 0 end +-370.51 4.00 578.11 0 1 0 0 0 end +-484.31 32.10 495.48 0 1 0 0 0 end +-375.95 4.00 584.91 0 1 0 0 0 end +-487.23 32.10 498.91 0 1 0 0 0 end +-381.60 4.00 591.55 0 1 0 0 0 end +-490.25 32.10 502.25 0 1 0 0 0 end +-387.44 4.00 598.02 0 1 0 0 0 end +-493.36 32.10 505.49 0 1 0 0 0 end +-393.48 4.00 604.30 0 1 0 0 0 end +-496.58 32.10 508.64 0 1 0 0 0 end +-399.70 4.00 610.41 0 1 0 0 0 end +-499.88 32.10 511.70 0 1 0 0 0 end +-406.10 4.00 616.32 0 1 0 0 0 end +-503.28 32.10 514.65 0 1 0 0 0 end +-412.68 4.00 622.04 0 1 0 0 0 end +-506.76 32.10 517.50 0 1 0 0 0 end +-419.42 4.00 627.56 0 1 0 0 0 +endtri +node -1 0 none triangle_strip grass +-322.47 4.00 314.15 0 1 0 0 0 end +-316.74 0.00 312.38 0 1 0 0 0 end +-320.02 4.00 322.51 0 1 0 0 0 end +-314.24 0.00 320.91 0 1 0 0 0 end +-317.83 4.00 330.95 0 1 0 0 0 end +-312.00 0.00 329.52 0 1 0 0 0 end +-315.88 4.00 339.44 0 1 0 0 0 end +-310.01 0.00 338.19 0 1 0 0 0 end +-314.19 4.00 347.99 0 1 0 0 0 end +-308.29 0.00 346.92 0 1 0 0 0 end +-312.76 4.00 356.59 0 1 0 0 0 end +-306.83 0.00 355.69 0 1 0 0 0 end +-311.59 4.00 365.22 0 1 0 0 0 end +-305.63 0.00 364.51 0 1 0 0 0 end +-310.68 4.00 373.89 0 1 0 0 0 end +-304.70 0.00 373.35 0 1 0 0 0 end +-310.02 4.00 382.58 0 1 0 0 0 end +-304.03 0.00 382.22 0 1 0 0 0 end +-309.63 4.00 391.29 0 1 0 0 0 end +-303.63 0.00 391.11 0 1 0 0 0 end +-309.50 4.00 400.00 0 1 0 0 0 end +-303.50 0.00 400.00 0 1 0 0 0 end +-309.63 4.00 408.71 0 1 0 0 0 end +-303.63 0.00 408.89 0 1 0 0 0 end +-310.02 4.00 417.42 0 1 0 0 0 end +-304.03 0.00 417.78 0 1 0 0 0 end +-310.68 4.00 426.11 0 1 0 0 0 end +-304.70 0.00 426.65 0 1 0 0 0 end +-311.59 4.00 434.78 0 1 0 0 0 end +-305.63 0.00 435.49 0 1 0 0 0 end +-312.76 4.00 443.41 0 1 0 0 0 end +-306.83 0.00 444.31 0 1 0 0 0 end +-314.19 4.00 452.01 0 1 0 0 0 end +-308.29 0.00 453.08 0 1 0 0 0 end +-315.88 4.00 460.56 0 1 0 0 0 end +-310.01 0.00 461.81 0 1 0 0 0 end +-317.83 4.00 469.05 0 1 0 0 0 end +-312.00 0.00 470.48 0 1 0 0 0 end +-320.02 4.00 477.49 0 1 0 0 0 end +-314.24 0.00 479.09 0 1 0 0 0 end +-322.47 4.00 485.85 0 1 0 0 0 end +-316.74 0.00 487.62 0 1 0 0 0 end +-325.17 4.00 494.13 0 1 0 0 0 end +-319.50 0.00 496.08 0 1 0 0 0 end +-328.12 4.00 502.34 0 1 0 0 0 end +-322.51 0.00 504.45 0 1 0 0 0 end +-331.31 4.00 510.44 0 1 0 0 0 end +-325.76 0.00 512.73 0 1 0 0 0 end +-334.75 4.00 518.45 0 1 0 0 0 end +-329.27 0.00 520.90 0 1 0 0 0 end +-338.42 4.00 526.36 0 1 0 0 0 end +-333.02 0.00 528.97 0 1 0 0 0 end +-342.33 4.00 534.15 0 1 0 0 0 end +-337.01 0.00 536.92 0 1 0 0 0 end +-346.47 4.00 541.82 0 1 0 0 0 end +-341.23 0.00 544.74 0 1 0 0 0 end +-350.84 4.00 549.36 0 1 0 0 0 end +-345.69 0.00 552.44 0 1 0 0 0 end +-355.43 4.00 556.76 0 1 0 0 0 end +-350.38 0.00 560.00 0 1 0 0 0 end +-360.24 4.00 564.03 0 1 0 0 0 end +-355.29 0.00 567.42 0 1 0 0 0 end +-365.27 4.00 571.15 0 1 0 0 0 end +-360.42 0.00 574.68 0 1 0 0 0 end +-370.51 4.00 578.11 0 1 0 0 0 end +-365.77 0.00 581.79 0 1 0 0 0 end +-375.95 4.00 584.91 0 1 0 0 0 end +-371.33 0.00 588.73 0 1 0 0 0 end +-381.60 4.00 591.55 0 1 0 0 0 end +-377.09 0.00 595.51 0 1 0 0 0 end +-387.44 4.00 598.02 0 1 0 0 0 end +-383.05 0.00 602.11 0 1 0 0 0 end +-393.48 4.00 604.30 0 1 0 0 0 end +-389.21 0.00 608.52 0 1 0 0 0 end +-399.70 4.00 610.41 0 1 0 0 0 end +-395.56 0.00 614.75 0 1 0 0 0 end +-406.10 4.00 616.32 0 1 0 0 0 end +-402.10 0.00 620.79 0 1 0 0 0 end +-412.68 4.00 622.04 0 1 0 0 0 end +-408.81 0.00 626.62 0 1 0 0 0 end +-419.42 4.00 627.56 0 1 0 0 0 end +-415.69 0.00 632.26 0 1 0 0 0 +endtri +node -1 0 none triangle_strip grass +-316.74 0.00 312.38 0 1 0 0 0 end +-310.06 0.00 310.31 0 1 0 0 0 end +-314.24 0.00 320.91 0 1 0 0 0 end +-307.50 0.00 319.05 0 1 0 0 0 end +-312.00 0.00 329.52 0 1 0 0 0 end +-305.20 0.00 327.86 0 1 0 0 0 end +-310.01 0.00 338.19 0 1 0 0 0 end +-303.17 0.00 336.73 0 1 0 0 0 end +-308.29 0.00 346.92 0 1 0 0 0 end +-301.40 0.00 345.66 0 1 0 0 0 end +-306.83 0.00 355.69 0 1 0 0 0 end +-299.91 0.00 354.65 0 1 0 0 0 end +-305.63 0.00 364.51 0 1 0 0 0 end +-298.68 0.00 363.67 0 1 0 0 0 end +-304.70 0.00 373.35 0 1 0 0 0 end +-297.73 0.00 372.72 0 1 0 0 0 end +-304.03 0.00 382.22 0 1 0 0 0 end +-297.05 0.00 381.80 0 1 0 0 0 end +-303.63 0.00 391.11 0 1 0 0 0 end +-296.64 0.00 390.90 0 1 0 0 0 end +-303.50 0.00 400.00 0 1 0 0 0 end +-296.50 0.00 400.00 0 1 0 0 0 end +-303.63 0.00 408.89 0 1 0 0 0 end +-296.64 0.00 409.10 0 1 0 0 0 end +-304.03 0.00 417.78 0 1 0 0 0 end +-297.05 0.00 418.20 0 1 0 0 0 end +-304.70 0.00 426.65 0 1 0 0 0 end +-297.73 0.00 427.28 0 1 0 0 0 end +-305.63 0.00 435.49 0 1 0 0 0 end +-298.68 0.00 436.33 0 1 0 0 0 end +-306.83 0.00 444.31 0 1 0 0 0 end +-299.91 0.00 445.35 0 1 0 0 0 end +-308.29 0.00 453.08 0 1 0 0 0 end +-301.40 0.00 454.34 0 1 0 0 0 end +-310.01 0.00 461.81 0 1 0 0 0 end +-303.17 0.00 463.27 0 1 0 0 0 end +-312.00 0.00 470.48 0 1 0 0 0 end +-305.20 0.00 472.14 0 1 0 0 0 end +-314.24 0.00 479.09 0 1 0 0 0 end +-307.50 0.00 480.95 0 1 0 0 0 end +-316.74 0.00 487.62 0 1 0 0 0 end +-310.06 0.00 489.69 0 1 0 0 0 end +-319.50 0.00 496.08 0 1 0 0 0 end +-312.88 0.00 498.35 0 1 0 0 0 end +-322.51 0.00 504.45 0 1 0 0 0 end +-315.96 0.00 506.92 0 1 0 0 0 end +-325.76 0.00 512.73 0 1 0 0 0 end +-319.29 0.00 515.39 0 1 0 0 0 end +-329.27 0.00 520.90 0 1 0 0 0 end +-322.88 0.00 523.76 0 1 0 0 0 end +-333.02 0.00 528.97 0 1 0 0 0 end +-326.71 0.00 532.01 0 1 0 0 0 end +-337.01 0.00 536.92 0 1 0 0 0 end +-330.80 0.00 540.15 0 1 0 0 0 end +-341.23 0.00 544.74 0 1 0 0 0 end +-335.12 0.00 548.16 0 1 0 0 0 end +-345.69 0.00 552.44 0 1 0 0 0 end +-339.69 0.00 556.04 0 1 0 0 0 end +-350.38 0.00 560.00 0 1 0 0 0 end +-344.48 0.00 563.78 0 1 0 0 0 end +-355.29 0.00 567.42 0 1 0 0 0 end +-349.51 0.00 571.37 0 1 0 0 0 end +-360.42 0.00 574.68 0 1 0 0 0 end +-354.76 0.00 578.81 0 1 0 0 0 end +-365.77 0.00 581.79 0 1 0 0 0 end +-360.24 0.00 586.08 0 1 0 0 0 end +-371.33 0.00 588.73 0 1 0 0 0 end +-365.93 0.00 593.19 0 1 0 0 0 end +-377.09 0.00 595.51 0 1 0 0 0 end +-371.83 0.00 600.12 0 1 0 0 0 end +-383.05 0.00 602.11 0 1 0 0 0 end +-377.93 0.00 606.88 0 1 0 0 0 end +-389.21 0.00 608.52 0 1 0 0 0 end +-384.24 0.00 613.45 0 1 0 0 0 end +-395.56 0.00 614.75 0 1 0 0 0 end +-390.74 0.00 619.82 0 1 0 0 0 end +-402.10 0.00 620.79 0 1 0 0 0 end +-397.43 0.00 626.00 0 1 0 0 0 end +-408.81 0.00 626.62 0 1 0 0 0 end +-404.30 0.00 631.97 0 1 0 0 0 end +-415.69 0.00 632.26 0 1 0 0 0 end +-411.34 0.00 637.74 0 1 0 0 0 +endtri +node -1 0 none triangle_strip grass +-310.06 0.00 310.31 0 1 0 0 0 end +-304.32 4.00 308.54 0 1 0 0 0 end +-307.50 0.00 319.05 0 1 0 0 0 end +-301.71 4.00 317.45 0 1 0 0 0 end +-305.20 0.00 327.86 0 1 0 0 0 end +-299.37 4.00 326.43 0 1 0 0 0 end +-303.17 0.00 336.73 0 1 0 0 0 end +-297.30 4.00 335.48 0 1 0 0 0 end +-301.40 0.00 345.66 0 1 0 0 0 end +-295.50 4.00 344.59 0 1 0 0 0 end +-299.91 0.00 354.65 0 1 0 0 0 end +-293.98 4.00 353.75 0 1 0 0 0 end +-298.68 0.00 363.67 0 1 0 0 0 end +-292.73 4.00 362.95 0 1 0 0 0 end +-297.73 0.00 372.72 0 1 0 0 0 end +-291.75 4.00 372.18 0 1 0 0 0 end +-297.05 0.00 381.80 0 1 0 0 0 end +-291.06 4.00 381.44 0 1 0 0 0 end +-296.64 0.00 390.90 0 1 0 0 0 end +-290.64 4.00 390.72 0 1 0 0 0 end +-296.50 0.00 400.00 0 1 0 0 0 end +-290.50 4.00 400.00 0 1 0 0 0 end +-296.64 0.00 409.10 0 1 0 0 0 end +-290.64 4.00 409.28 0 1 0 0 0 end +-297.05 0.00 418.20 0 1 0 0 0 end +-291.06 4.00 418.56 0 1 0 0 0 end +-297.73 0.00 427.28 0 1 0 0 0 end +-291.75 4.00 427.82 0 1 0 0 0 end +-298.68 0.00 436.33 0 1 0 0 0 end +-292.73 4.00 437.05 0 1 0 0 0 end +-299.91 0.00 445.35 0 1 0 0 0 end +-293.98 4.00 446.25 0 1 0 0 0 end +-301.40 0.00 454.34 0 1 0 0 0 end +-295.50 4.00 455.41 0 1 0 0 0 end +-303.17 0.00 463.27 0 1 0 0 0 end +-297.30 4.00 464.52 0 1 0 0 0 end +-305.20 0.00 472.14 0 1 0 0 0 end +-299.37 4.00 473.57 0 1 0 0 0 end +-307.50 0.00 480.95 0 1 0 0 0 end +-301.71 4.00 482.55 0 1 0 0 0 end +-310.06 0.00 489.69 0 1 0 0 0 end +-304.32 4.00 491.46 0 1 0 0 0 end +-312.88 0.00 498.35 0 1 0 0 0 end +-307.20 4.00 500.29 0 1 0 0 0 end +-315.96 0.00 506.92 0 1 0 0 0 end +-310.34 4.00 509.03 0 1 0 0 0 end +-319.29 0.00 515.39 0 1 0 0 0 end +-313.74 4.00 517.67 0 1 0 0 0 end +-322.88 0.00 523.76 0 1 0 0 0 end +-317.40 4.00 526.20 0 1 0 0 0 end +-326.71 0.00 532.01 0 1 0 0 0 end +-321.31 4.00 534.62 0 1 0 0 0 end +-330.80 0.00 540.15 0 1 0 0 0 end +-325.48 4.00 542.92 0 1 0 0 0 end +-335.12 0.00 548.16 0 1 0 0 0 end +-329.89 4.00 551.09 0 1 0 0 0 end +-339.69 0.00 556.04 0 1 0 0 0 end +-334.54 4.00 559.13 0 1 0 0 0 end +-344.48 0.00 563.78 0 1 0 0 0 end +-339.43 4.00 567.02 0 1 0 0 0 end +-349.51 0.00 571.37 0 1 0 0 0 end +-344.56 4.00 574.76 0 1 0 0 0 end +-354.76 0.00 578.81 0 1 0 0 0 end +-349.92 4.00 582.34 0 1 0 0 0 end +-360.24 0.00 586.08 0 1 0 0 0 end +-355.50 4.00 589.76 0 1 0 0 0 end +-365.93 0.00 593.19 0 1 0 0 0 end +-361.30 4.00 597.01 0 1 0 0 0 end +-371.83 0.00 600.12 0 1 0 0 0 end +-367.32 4.00 604.08 0 1 0 0 0 end +-377.93 0.00 606.88 0 1 0 0 0 end +-373.54 4.00 610.97 0 1 0 0 0 end +-384.24 0.00 613.45 0 1 0 0 0 end +-379.97 4.00 617.66 0 1 0 0 0 end +-390.74 0.00 619.82 0 1 0 0 0 end +-386.60 4.00 624.17 0 1 0 0 0 end +-397.43 0.00 626.00 0 1 0 0 0 end +-393.42 4.00 630.47 0 1 0 0 0 end +-404.30 0.00 631.97 0 1 0 0 0 end +-400.43 4.00 636.56 0 1 0 0 0 end +-411.34 0.00 637.74 0 1 0 0 0 end +-407.61 4.00 642.44 0 1 0 0 0 +endtri +node -1 0 none triangle_strip grass +-304.32 4.00 308.54 0 1 0 0 0 end +-170.10 32.10 267.02 0 1 0 0 0 end +-301.71 4.00 317.45 0 1 0 0 0 end +-166.30 32.10 279.97 0 1 0 0 0 end +-299.37 4.00 326.43 0 1 0 0 0 end +-162.90 32.10 293.03 0 1 0 0 0 end +-297.30 4.00 335.48 0 1 0 0 0 end +-159.89 32.10 306.19 0 1 0 0 0 end +-295.50 4.00 344.59 0 1 0 0 0 end +-157.27 32.10 319.44 0 1 0 0 0 end +-293.98 4.00 353.75 0 1 0 0 0 end +-155.05 32.10 332.75 0 1 0 0 0 end +-292.73 4.00 362.95 0 1 0 0 0 end +-153.24 32.10 346.13 0 1 0 0 0 end +-291.75 4.00 372.18 0 1 0 0 0 end +-151.82 32.10 359.55 0 1 0 0 0 end +-291.06 4.00 381.44 0 1 0 0 0 end +-150.81 32.10 373.02 0 1 0 0 0 end +-290.64 4.00 390.72 0 1 0 0 0 end +-150.20 32.10 386.50 0 1 0 0 0 end +-290.50 4.00 400.00 0 1 0 0 0 end +-150.00 32.10 400.00 0 1 0 0 0 end +-290.64 4.00 409.28 0 1 0 0 0 end +-150.20 32.10 413.50 0 1 0 0 0 end +-291.06 4.00 418.56 0 1 0 0 0 end +-150.81 32.10 426.98 0 1 0 0 0 end +-291.75 4.00 427.82 0 1 0 0 0 end +-151.82 32.10 440.45 0 1 0 0 0 end +-292.73 4.00 437.05 0 1 0 0 0 end +-153.24 32.10 453.87 0 1 0 0 0 end +-293.98 4.00 446.25 0 1 0 0 0 end +-155.05 32.10 467.25 0 1 0 0 0 end +-295.50 4.00 455.41 0 1 0 0 0 end +-157.27 32.10 480.56 0 1 0 0 0 end +-297.30 4.00 464.52 0 1 0 0 0 end +-159.89 32.10 493.81 0 1 0 0 0 end +-299.37 4.00 473.57 0 1 0 0 0 end +-162.90 32.10 506.97 0 1 0 0 0 end +-301.71 4.00 482.55 0 1 0 0 0 end +-166.30 32.10 520.03 0 1 0 0 0 end +-304.32 4.00 491.46 0 1 0 0 0 end +-170.10 32.10 532.98 0 1 0 0 0 end +-307.20 4.00 500.29 0 1 0 0 0 end +-174.28 32.10 545.82 0 1 0 0 0 end +-310.34 4.00 509.03 0 1 0 0 0 end +-178.85 32.10 558.52 0 1 0 0 0 end +-313.74 4.00 517.67 0 1 0 0 0 end +-183.79 32.10 571.08 0 1 0 0 0 end +-317.40 4.00 526.20 0 1 0 0 0 end +-189.11 32.10 583.49 0 1 0 0 0 end +-321.31 4.00 534.62 0 1 0 0 0 end +-194.80 32.10 595.73 0 1 0 0 0 end +-325.48 4.00 542.92 0 1 0 0 0 end +-200.85 32.10 607.80 0 1 0 0 0 end +-329.89 4.00 551.09 0 1 0 0 0 end +-207.26 32.10 619.68 0 1 0 0 0 end +-334.54 4.00 559.13 0 1 0 0 0 end +-214.03 32.10 631.36 0 1 0 0 0 end +-339.43 4.00 567.02 0 1 0 0 0 end +-221.14 32.10 642.83 0 1 0 0 0 end +-344.56 4.00 574.76 0 1 0 0 0 end +-228.60 32.10 654.09 0 1 0 0 0 end +-349.92 4.00 582.34 0 1 0 0 0 end +-236.39 32.10 665.12 0 1 0 0 0 end +-355.50 4.00 589.76 0 1 0 0 0 end +-244.50 32.10 675.90 0 1 0 0 0 end +-361.30 4.00 597.01 0 1 0 0 0 end +-252.94 32.10 686.44 0 1 0 0 0 end +-367.32 4.00 604.08 0 1 0 0 0 end +-261.69 32.10 696.72 0 1 0 0 0 end +-373.54 4.00 610.97 0 1 0 0 0 end +-270.74 32.10 706.74 0 1 0 0 0 end +-379.97 4.00 617.66 0 1 0 0 0 end +-280.09 32.10 716.48 0 1 0 0 0 end +-386.60 4.00 624.17 0 1 0 0 0 end +-289.73 32.10 725.93 0 1 0 0 0 end +-393.42 4.00 630.47 0 1 0 0 0 end +-299.64 32.10 735.09 0 1 0 0 0 end +-400.43 4.00 636.56 0 1 0 0 0 end +-309.83 32.10 743.95 0 1 0 0 0 end +-407.61 4.00 642.44 0 1 0 0 0 end +-320.28 32.10 752.50 0 1 0 0 0 +endtri +node -1 0 autotest_curve track normal 150.0000 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-300.0000 0.2 400.0000 0.0 //point 1 +-0.0000 0.0 50.2621 //control vector 1 +24.0969 0.0 -44.1091 //control vector 2 +-336.7252 0.2 543.8277 0.0 //point 2 +300.0 +endtrack +trainset none tdo_n1734 0.0 0.0 +node -1 0 {{vehicle}} dynamic pkp\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic +endtrainset + +trainset none autotest_curve 20.0 {{velocity}} +node -1 0 {{vehicle}}_off dynamic pkp\4e_v1 4e-004 4e 0 nobody 0 0 enddynamic +endtrainset diff --git a/tests/scenarios/cases/td_off_track_curve_embankment.scn b/tests/scenarios/cases/td_off_track_curve_embankment.scn new file mode 100644 index 000000000..4f9d6c7c8 --- /dev/null +++ b/tests/scenarios/cases/td_off_track_curve_embankment.scn @@ -0,0 +1,273 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed (physics.derailment new, the vehicles +// off the track moving on the ground, vehicle/derailmotion.h): a track of R 300 m without cant laid on its own in the +// fields of td.scn (autotest_curve), on an embankment 4 m high with slopes of 1:1.5; written by a script, see the README. +// an EU07 with an AI driver and no timetable stands on track 1 of Stacja1, where td.scn keeps its timetable train, so +// it stays put and logs its physics; the EU07 of the case has no driver and runs at {{velocity}} km/h from 20 m past +// point 1 of the curve towards its point 2 +node -1 0 none triangle_strip grass +-322.47 0.00 314.15 0 1 0 0 0 end +-316.74 4.00 312.38 0 1 0 0 0 end +-320.02 0.00 322.51 0 1 0 0 0 end +-314.24 4.00 320.91 0 1 0 0 0 end +-317.83 0.00 330.95 0 1 0 0 0 end +-312.00 4.00 329.52 0 1 0 0 0 end +-315.88 0.00 339.44 0 1 0 0 0 end +-310.01 4.00 338.19 0 1 0 0 0 end +-314.19 0.00 347.99 0 1 0 0 0 end +-308.29 4.00 346.92 0 1 0 0 0 end +-312.76 0.00 356.59 0 1 0 0 0 end +-306.83 4.00 355.69 0 1 0 0 0 end +-311.59 0.00 365.22 0 1 0 0 0 end +-305.63 4.00 364.51 0 1 0 0 0 end +-310.68 0.00 373.89 0 1 0 0 0 end +-304.70 4.00 373.35 0 1 0 0 0 end +-310.02 0.00 382.58 0 1 0 0 0 end +-304.03 4.00 382.22 0 1 0 0 0 end +-309.63 0.00 391.29 0 1 0 0 0 end +-303.63 4.00 391.11 0 1 0 0 0 end +-309.50 0.00 400.00 0 1 0 0 0 end +-303.50 4.00 400.00 0 1 0 0 0 end +-309.63 0.00 408.71 0 1 0 0 0 end +-303.63 4.00 408.89 0 1 0 0 0 end +-310.02 0.00 417.42 0 1 0 0 0 end +-304.03 4.00 417.78 0 1 0 0 0 end +-310.68 0.00 426.11 0 1 0 0 0 end +-304.70 4.00 426.65 0 1 0 0 0 end +-311.59 0.00 434.78 0 1 0 0 0 end +-305.63 4.00 435.49 0 1 0 0 0 end +-312.76 0.00 443.41 0 1 0 0 0 end +-306.83 4.00 444.31 0 1 0 0 0 end +-314.19 0.00 452.01 0 1 0 0 0 end +-308.29 4.00 453.08 0 1 0 0 0 end +-315.88 0.00 460.56 0 1 0 0 0 end +-310.01 4.00 461.81 0 1 0 0 0 end +-317.83 0.00 469.05 0 1 0 0 0 end +-312.00 4.00 470.48 0 1 0 0 0 end +-320.02 0.00 477.49 0 1 0 0 0 end +-314.24 4.00 479.09 0 1 0 0 0 end +-322.47 0.00 485.85 0 1 0 0 0 end +-316.74 4.00 487.62 0 1 0 0 0 end +-325.17 0.00 494.13 0 1 0 0 0 end +-319.50 4.00 496.08 0 1 0 0 0 end +-328.12 0.00 502.34 0 1 0 0 0 end +-322.51 4.00 504.45 0 1 0 0 0 end +-331.31 0.00 510.44 0 1 0 0 0 end +-325.76 4.00 512.73 0 1 0 0 0 end +-334.75 0.00 518.45 0 1 0 0 0 end +-329.27 4.00 520.90 0 1 0 0 0 end +-338.42 0.00 526.36 0 1 0 0 0 end +-333.02 4.00 528.97 0 1 0 0 0 end +-342.33 0.00 534.15 0 1 0 0 0 end +-337.01 4.00 536.92 0 1 0 0 0 end +-346.47 0.00 541.82 0 1 0 0 0 end +-341.23 4.00 544.74 0 1 0 0 0 end +-350.84 0.00 549.36 0 1 0 0 0 end +-345.69 4.00 552.44 0 1 0 0 0 end +-355.43 0.00 556.76 0 1 0 0 0 end +-350.38 4.00 560.00 0 1 0 0 0 end +-360.24 0.00 564.03 0 1 0 0 0 end +-355.29 4.00 567.42 0 1 0 0 0 end +-365.27 0.00 571.15 0 1 0 0 0 end +-360.42 4.00 574.68 0 1 0 0 0 end +-370.51 0.00 578.11 0 1 0 0 0 end +-365.77 4.00 581.79 0 1 0 0 0 end +-375.95 0.00 584.91 0 1 0 0 0 end +-371.33 4.00 588.73 0 1 0 0 0 end +-381.60 0.00 591.55 0 1 0 0 0 end +-377.09 4.00 595.51 0 1 0 0 0 end +-387.44 0.00 598.02 0 1 0 0 0 end +-383.05 4.00 602.11 0 1 0 0 0 end +-393.48 0.00 604.30 0 1 0 0 0 end +-389.21 4.00 608.52 0 1 0 0 0 end +-399.70 0.00 610.41 0 1 0 0 0 end +-395.56 4.00 614.75 0 1 0 0 0 end +-406.10 0.00 616.32 0 1 0 0 0 end +-402.10 4.00 620.79 0 1 0 0 0 end +-412.68 0.00 622.04 0 1 0 0 0 end +-408.81 4.00 626.62 0 1 0 0 0 end +-419.42 0.00 627.56 0 1 0 0 0 end +-415.69 4.00 632.26 0 1 0 0 0 +endtri +node -1 0 none triangle_strip grass +-316.74 4.00 312.38 0 1 0 0 0 end +-310.06 4.00 310.31 0 1 0 0 0 end +-314.24 4.00 320.91 0 1 0 0 0 end +-307.50 4.00 319.05 0 1 0 0 0 end +-312.00 4.00 329.52 0 1 0 0 0 end +-305.20 4.00 327.86 0 1 0 0 0 end +-310.01 4.00 338.19 0 1 0 0 0 end +-303.17 4.00 336.73 0 1 0 0 0 end +-308.29 4.00 346.92 0 1 0 0 0 end +-301.40 4.00 345.66 0 1 0 0 0 end +-306.83 4.00 355.69 0 1 0 0 0 end +-299.91 4.00 354.65 0 1 0 0 0 end +-305.63 4.00 364.51 0 1 0 0 0 end +-298.68 4.00 363.67 0 1 0 0 0 end +-304.70 4.00 373.35 0 1 0 0 0 end +-297.73 4.00 372.72 0 1 0 0 0 end +-304.03 4.00 382.22 0 1 0 0 0 end +-297.05 4.00 381.80 0 1 0 0 0 end +-303.63 4.00 391.11 0 1 0 0 0 end +-296.64 4.00 390.90 0 1 0 0 0 end +-303.50 4.00 400.00 0 1 0 0 0 end +-296.50 4.00 400.00 0 1 0 0 0 end +-303.63 4.00 408.89 0 1 0 0 0 end +-296.64 4.00 409.10 0 1 0 0 0 end +-304.03 4.00 417.78 0 1 0 0 0 end +-297.05 4.00 418.20 0 1 0 0 0 end +-304.70 4.00 426.65 0 1 0 0 0 end +-297.73 4.00 427.28 0 1 0 0 0 end +-305.63 4.00 435.49 0 1 0 0 0 end +-298.68 4.00 436.33 0 1 0 0 0 end +-306.83 4.00 444.31 0 1 0 0 0 end +-299.91 4.00 445.35 0 1 0 0 0 end +-308.29 4.00 453.08 0 1 0 0 0 end +-301.40 4.00 454.34 0 1 0 0 0 end +-310.01 4.00 461.81 0 1 0 0 0 end +-303.17 4.00 463.27 0 1 0 0 0 end +-312.00 4.00 470.48 0 1 0 0 0 end +-305.20 4.00 472.14 0 1 0 0 0 end +-314.24 4.00 479.09 0 1 0 0 0 end +-307.50 4.00 480.95 0 1 0 0 0 end +-316.74 4.00 487.62 0 1 0 0 0 end +-310.06 4.00 489.69 0 1 0 0 0 end +-319.50 4.00 496.08 0 1 0 0 0 end +-312.88 4.00 498.35 0 1 0 0 0 end +-322.51 4.00 504.45 0 1 0 0 0 end +-315.96 4.00 506.92 0 1 0 0 0 end +-325.76 4.00 512.73 0 1 0 0 0 end +-319.29 4.00 515.39 0 1 0 0 0 end +-329.27 4.00 520.90 0 1 0 0 0 end +-322.88 4.00 523.76 0 1 0 0 0 end +-333.02 4.00 528.97 0 1 0 0 0 end +-326.71 4.00 532.01 0 1 0 0 0 end +-337.01 4.00 536.92 0 1 0 0 0 end +-330.80 4.00 540.15 0 1 0 0 0 end +-341.23 4.00 544.74 0 1 0 0 0 end +-335.12 4.00 548.16 0 1 0 0 0 end +-345.69 4.00 552.44 0 1 0 0 0 end +-339.69 4.00 556.04 0 1 0 0 0 end +-350.38 4.00 560.00 0 1 0 0 0 end +-344.48 4.00 563.78 0 1 0 0 0 end +-355.29 4.00 567.42 0 1 0 0 0 end +-349.51 4.00 571.37 0 1 0 0 0 end +-360.42 4.00 574.68 0 1 0 0 0 end +-354.76 4.00 578.81 0 1 0 0 0 end +-365.77 4.00 581.79 0 1 0 0 0 end +-360.24 4.00 586.08 0 1 0 0 0 end +-371.33 4.00 588.73 0 1 0 0 0 end +-365.93 4.00 593.19 0 1 0 0 0 end +-377.09 4.00 595.51 0 1 0 0 0 end +-371.83 4.00 600.12 0 1 0 0 0 end +-383.05 4.00 602.11 0 1 0 0 0 end +-377.93 4.00 606.88 0 1 0 0 0 end +-389.21 4.00 608.52 0 1 0 0 0 end +-384.24 4.00 613.45 0 1 0 0 0 end +-395.56 4.00 614.75 0 1 0 0 0 end +-390.74 4.00 619.82 0 1 0 0 0 end +-402.10 4.00 620.79 0 1 0 0 0 end +-397.43 4.00 626.00 0 1 0 0 0 end +-408.81 4.00 626.62 0 1 0 0 0 end +-404.30 4.00 631.97 0 1 0 0 0 end +-415.69 4.00 632.26 0 1 0 0 0 end +-411.34 4.00 637.74 0 1 0 0 0 +endtri +node -1 0 none triangle_strip grass +-310.06 4.00 310.31 0 1 0 0 0 end +-304.32 0.00 308.54 0 1 0 0 0 end +-307.50 4.00 319.05 0 1 0 0 0 end +-301.71 0.00 317.45 0 1 0 0 0 end +-305.20 4.00 327.86 0 1 0 0 0 end +-299.37 0.00 326.43 0 1 0 0 0 end +-303.17 4.00 336.73 0 1 0 0 0 end +-297.30 0.00 335.48 0 1 0 0 0 end +-301.40 4.00 345.66 0 1 0 0 0 end +-295.50 0.00 344.59 0 1 0 0 0 end +-299.91 4.00 354.65 0 1 0 0 0 end +-293.98 0.00 353.75 0 1 0 0 0 end +-298.68 4.00 363.67 0 1 0 0 0 end +-292.73 0.00 362.95 0 1 0 0 0 end +-297.73 4.00 372.72 0 1 0 0 0 end +-291.75 0.00 372.18 0 1 0 0 0 end +-297.05 4.00 381.80 0 1 0 0 0 end +-291.06 0.00 381.44 0 1 0 0 0 end +-296.64 4.00 390.90 0 1 0 0 0 end +-290.64 0.00 390.72 0 1 0 0 0 end +-296.50 4.00 400.00 0 1 0 0 0 end +-290.50 0.00 400.00 0 1 0 0 0 end +-296.64 4.00 409.10 0 1 0 0 0 end +-290.64 0.00 409.28 0 1 0 0 0 end +-297.05 4.00 418.20 0 1 0 0 0 end +-291.06 0.00 418.56 0 1 0 0 0 end +-297.73 4.00 427.28 0 1 0 0 0 end +-291.75 0.00 427.82 0 1 0 0 0 end +-298.68 4.00 436.33 0 1 0 0 0 end +-292.73 0.00 437.05 0 1 0 0 0 end +-299.91 4.00 445.35 0 1 0 0 0 end +-293.98 0.00 446.25 0 1 0 0 0 end +-301.40 4.00 454.34 0 1 0 0 0 end +-295.50 0.00 455.41 0 1 0 0 0 end +-303.17 4.00 463.27 0 1 0 0 0 end +-297.30 0.00 464.52 0 1 0 0 0 end +-305.20 4.00 472.14 0 1 0 0 0 end +-299.37 0.00 473.57 0 1 0 0 0 end +-307.50 4.00 480.95 0 1 0 0 0 end +-301.71 0.00 482.55 0 1 0 0 0 end +-310.06 4.00 489.69 0 1 0 0 0 end +-304.32 0.00 491.46 0 1 0 0 0 end +-312.88 4.00 498.35 0 1 0 0 0 end +-307.20 0.00 500.29 0 1 0 0 0 end +-315.96 4.00 506.92 0 1 0 0 0 end +-310.34 0.00 509.03 0 1 0 0 0 end +-319.29 4.00 515.39 0 1 0 0 0 end +-313.74 0.00 517.67 0 1 0 0 0 end +-322.88 4.00 523.76 0 1 0 0 0 end +-317.40 0.00 526.20 0 1 0 0 0 end +-326.71 4.00 532.01 0 1 0 0 0 end +-321.31 0.00 534.62 0 1 0 0 0 end +-330.80 4.00 540.15 0 1 0 0 0 end +-325.48 0.00 542.92 0 1 0 0 0 end +-335.12 4.00 548.16 0 1 0 0 0 end +-329.89 0.00 551.09 0 1 0 0 0 end +-339.69 4.00 556.04 0 1 0 0 0 end +-334.54 0.00 559.13 0 1 0 0 0 end +-344.48 4.00 563.78 0 1 0 0 0 end +-339.43 0.00 567.02 0 1 0 0 0 end +-349.51 4.00 571.37 0 1 0 0 0 end +-344.56 0.00 574.76 0 1 0 0 0 end +-354.76 4.00 578.81 0 1 0 0 0 end +-349.92 0.00 582.34 0 1 0 0 0 end +-360.24 4.00 586.08 0 1 0 0 0 end +-355.50 0.00 589.76 0 1 0 0 0 end +-365.93 4.00 593.19 0 1 0 0 0 end +-361.30 0.00 597.01 0 1 0 0 0 end +-371.83 4.00 600.12 0 1 0 0 0 end +-367.32 0.00 604.08 0 1 0 0 0 end +-377.93 4.00 606.88 0 1 0 0 0 end +-373.54 0.00 610.97 0 1 0 0 0 end +-384.24 4.00 613.45 0 1 0 0 0 end +-379.97 0.00 617.66 0 1 0 0 0 end +-390.74 4.00 619.82 0 1 0 0 0 end +-386.60 0.00 624.17 0 1 0 0 0 end +-397.43 4.00 626.00 0 1 0 0 0 end +-393.42 0.00 630.47 0 1 0 0 0 end +-404.30 4.00 631.97 0 1 0 0 0 end +-400.43 0.00 636.56 0 1 0 0 0 end +-411.34 4.00 637.74 0 1 0 0 0 end +-407.61 0.00 642.44 0 1 0 0 0 +endtri +node -1 0 autotest_curve track normal 150.0000 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-300.0000 4.2 400.0000 0.0 //point 1 +-0.0000 0.0 50.2621 //control vector 1 +24.0969 0.0 -44.1091 //control vector 2 +-336.7252 4.2 543.8277 0.0 //point 2 +300.0 +endtrack +trainset none tdo_n1734 0.0 0.0 +node -1 0 {{vehicle}} dynamic pkp\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic +endtrainset + +trainset none autotest_curve 20.0 {{velocity}} +node -1 0 {{vehicle}}_off dynamic pkp\4e_v1 4e-004 4e 0 nobody 0 0 enddynamic +endtrainset diff --git a/tests/scenarios/cases/td_off_track_curve_flat.scn b/tests/scenarios/cases/td_off_track_curve_flat.scn new file mode 100644 index 000000000..ddaf4f287 --- /dev/null +++ b/tests/scenarios/cases/td_off_track_curve_flat.scn @@ -0,0 +1,21 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed (physics.derailment new, the vehicles +// off the track moving on the ground, vehicle/derailmotion.h): a track of R 300 m without cant laid on its own in the +// fields of td.scn (autotest_curve), on level ground; written by a script, see the README. +// an EU07 with an AI driver and no timetable stands on track 1 of Stacja1, where td.scn keeps its timetable train, so +// it stays put and logs its physics; the EU07 of the case has no driver and runs at {{velocity}} km/h from 20 m past +// point 1 of the curve towards its point 2 +node -1 0 autotest_curve track normal 150.0000 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-300.0000 0.2 400.0000 0.0 //point 1 +-0.0000 0.0 50.2621 //control vector 1 +24.0969 0.0 -44.1091 //control vector 2 +-336.7252 0.2 543.8277 0.0 //point 2 +300.0 +endtrack +trainset none tdo_n1734 0.0 0.0 +node -1 0 {{vehicle}} dynamic pkp\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic +endtrainset + +trainset none autotest_curve 20.0 {{velocity}} +node -1 0 {{vehicle}}_off dynamic pkp\4e_v1 4e-004 4e 0 nobody 0 0 enddynamic +endtrainset diff --git a/tests/scenarios/make_off_track_curves.py b/tests/scenarios/make_off_track_curves.py new file mode 100644 index 000000000..447d8ddb1 --- /dev/null +++ b/tests/scenarios/make_off_track_curves.py @@ -0,0 +1,118 @@ +"""Writes the eu07_td_off_track_curve_* cases and their fragments (cases/td_off_track_curve_*.scn): a track of R 300 m +laid on its own in the fields of td.scn, on level ground, on an embankment 4 m high and in a cutting whose banks rise +4 m at 1:1.5 and on at 1:5, with an EU07 without a driver overturning on it (physics.derailment new). + + python tests/scenarios/make_off_track_curves.py +""" +import json +import math +from pathlib import Path + +CASES = str(Path(__file__).resolve().parent / "cases") + "/" +R = 300.0 +CENTRE = (-600.0, 400.0) # x, z +THETA = 0.5 # rad of the track, 150 m +RAIL = {'flat': 0.2, 'embankment': 4.2, 'cutting': 0.2} +# the cross section of the ground: (offset from the axis, height), outwards from the centre of the curve positive; +# the grass of td.scn lies at 0 around it +SECTIONS = { + 'embankment': [(-9.5, 0.0), (-3.5, 4.0), (3.5, 4.0), (9.5, 0.0)], + 'cutting': [(-150.0, 32.1), (-9.5, 4.0), (-3.5, 0.0), (3.5, 0.0), (9.5, 4.0), (150.0, 32.1)], +} +BACKSLASH = chr(92) +NEWLINE = chr(10) + + +def point(phi, offset, height): + # outwards: away from the centre of the curve + r = R + offset + return (CENTRE[0] + r * math.cos(phi), height, CENTRE[1] + r * math.sin(phi)) + + +def triangles(kind): + # a triangle strip for each band of the cross section, along the curve every 0.03 rad (9 m) + nodes = [] + section = SECTIONS[kind] + phis = [-0.3 + 0.03 * i for i in range(41)] # 90 m before the track to 120 m past it + for (o1, h1), (o2, h2) in zip(section, section[1:]): + lines = [] + for phi in phis: + for offset, height in ((o1, h1), (o2, h2)): + x, y, z = point(phi, offset, height) + lines.append(f"{x:.2f} {y:.2f} {z:.2f} 0 1 0 0 0") + nodes.append("node -1 0 none triangle_strip grass" + NEWLINE + (" end" + NEWLINE).join(lines) + NEWLINE + "endtri") + return nodes + + +def track(kind): + y = RAIL[kind] + p1 = point(0.0, 0.0, y) + p2 = point(THETA, 0.0, y) + k = 4.0 / 3.0 * math.tan(THETA / 4.0) * R + t1 = (-math.sin(0.0), math.cos(0.0)) + t2 = (-math.sin(THETA), math.cos(THETA)) + return NEWLINE.join([ + f"node -1 0 autotest_curve track normal {R * THETA:.4f} 1.435 0.15 25.0 20 0 flat vis", + " rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1", + f"{p1[0]:.4f} {y} {p1[2]:.4f} 0.0 //point 1", + f"{t1[0] * k:.4f} 0.0 {t1[1] * k:.4f} //control vector 1", + f"{-t2[0] * k:.4f} 0.0 {-t2[1] * k:.4f} //control vector 2", + f"{p2[0]:.4f} {y} {p2[2]:.4f} 0.0 //point 2", + f"{R}", + "endtrack"]) + + +WORDS = { + 'flat': ("on level ground", "the grass of td.scn", + "it slides on the grass out of the curve, falls on its side and stops"), + 'embankment': ("on an embankment 4 m high with slopes of 1:1.5", "triangles of the fragment", + "it falls on its side over the edge of the embankment, slides down its slope and on over the level ground at its foot, 4 m lower"), + 'cutting': ("in a cutting with banks of 1:1.5 4 m high, the ground rising on beyond them at 1:5", "triangles of the fragment", + "it runs into the bank on the outside of the curve, climbs it and stops sooner than on level ground"), +} +CHECKS = { + 'flat': {"min_offset": 3, "min_distance": 50, "max_distance": 250, "lying": True}, + 'embankment': {"min_offset": 5, "min_distance": 30, "max_distance": 300, "lying": True}, + 'cutting': {"min_offset": 3, "min_distance": 20, "max_distance": 230}, +} +HEADER = [ + "// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed (physics.derailment new, the vehicles", + "// off the track moving on the ground, vehicle/derailmotion.h): a track of R 300 m without cant laid on its own in the", + "// fields of td.scn (autotest_curve), {where}; written by a script, see the README.", + "// an EU07 with an AI driver and no timetable stands on track 1 of Stacja1, where td.scn keeps its timetable train, so", + "// it stays put and logs its physics; the EU07 of the case has no driver and runs at {{velocity}} km/h from 20 m past", + "// point 1 of the curve towards its point 2", +] +TRAINS = [ + "trainset none tdo_n1734 0.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp" + BACKSLASH + "4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic", + "endtrainset", + "", + "trainset none autotest_curve 20.0 {{velocity}}", + "node -1 0 {{vehicle}}_off dynamic pkp" + BACKSLASH + "4e_v1 4e-004 4e 0 nobody 0 0 enddynamic", + "endtrainset", +] +for kind in ('flat', 'embankment', 'cutting'): + nodes = ([] if kind == 'flat' else triangles(kind)) + [track(kind)] + where, source, what = WORDS[kind] + lines = [line.replace("{where}", where) for line in HEADER] + nodes + TRAINS + with open(CASES + f"td_off_track_curve_{kind}.scn", "w", encoding="utf-8", newline=NEWLINE) as out: + out.write(NEWLINE.join(lines) + NEWLINE) + case = { + "description": f"physics.derailment new: an EU07 without a driver runs at 150 km/h into a curve of R 300 m without cant, a track of 150 m laid on its own in the fields of td.scn (autotest_curve), {where} ({source}). Over its overturning speed (about 120 km/h) it overturns out of the curve: {what}.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": f"td_off_track_curve_{kind}.scn", + "vars": {"velocity": "150"}, + "ini": ["gfxrenderer null", "physics.derailment new", "couplerphysics all"], + "expect": "timeout", + "duration": 60, + "timeout": 600, + "checks": [ + {"type": "log_contains", "pattern": "derailment: autotest_" + BACKSLASH + "S+_off leaves the track"}, + dict({"type": "leaves_track", "vehicle": "{{vehicle}}_off", "cause": "overturned"}, **CHECKS[kind]), + ], + } + with open(CASES + f"eu07_td_off_track_curve_{kind}.json", "w", encoding="utf-8", newline=NEWLINE) as out: + out.write(json.dumps(case, indent=2, ensure_ascii=False) + NEWLINE) +print("written") diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py index e11fa8a77..c83899d40 100644 --- a/tests/scenarios/run.py +++ b/tests/scenarios/run.py @@ -29,8 +29,8 @@ from __future__ import annotations import argparse import heapq import json -import os import math +import os import re import shutil import struct @@ -245,9 +245,10 @@ def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> s shutil.copyfile(CASES_DIR / case["timetable"], timetable_path(game_dir, case_name)) # the simulator caches the scenery's static geometry in .sbt and reads it instead of # the terrain in the .scn (tracks, events and trainsets always come from the .scn), so - # drop the cache once the base scenery has changed + # drop the cache once the base scenery, or the fragment of the case (its own terrain), has changed cache = scenery_cache(game_dir, case_name) - if cache.exists() and cache.stat().st_mtime < (scenery_dir / case["base_scenery"]).stat().st_mtime: + sources = [scenery_dir / case["base_scenery"]] + ([CASES_DIR / case["fragment"]] if "fragment" in case else []) + if cache.exists() and cache.stat().st_mtime < max(source.stat().st_mtime for source in sources): cache.unlink() return name @@ -305,6 +306,8 @@ BLACKBOX_TRACK = 0x10 # the map: a rail track, or one way of a switch, as point 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 +BLACKBOX_DERAILMENT = 0x38 # a vehicle left the track, or came to rest off it (physics.derailment new) +DERAILMENT_CAUSES = {1: "flange climbed", 2: "overturned", 3: "end of track", 4: "pulled off", 5: "collision"} 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 @@ -331,6 +334,22 @@ class VehicleState: driver: int # 0 none, 1 a user, 2 the AI +@dataclass +class Derailment: + """A derailment record: a vehicle off the track as it left it (phase 0) or came to rest (phase 1).""" + time: float + vehicle: int + phase: int + cause: int # DERAILMENT_CAUSES + position: tuple[float, float, float] + heading: float # rad + speed: float # km/h + offset: float # m from the axis of the track, to the left of its front positive + roll: float # rad, to the left positive + travelled: float # m on the ground since it left the rails + lying: bool + + @dataclass class Track: """A `track` record: a plain track, or one way of a switch (several records under the number of the switch).""" @@ -346,6 +365,7 @@ class Blackbox: vehicles: dict[int, str] = field(default_factory=dict) # names by number tracks: list[Track] = field(default_factory=list) # the map, in the order written couplings: list[Coupling] = field(default_factory=list) # in the order written + derailments: list[Derailment] = 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 @@ -411,6 +431,11 @@ def read_blackbox(path: Path | None) -> Blackbox | None: elif kind == BLACKBOX_COUPLING: # the position of the coupler follows box.couplings.append(Coupling(*struct.unpack_from(" max_transient: + failed.append(f"over {max_transient} m on the way") + if float(rest.group(3)) > max_at_rest: + failed.append(f"over {max_at_rest} m at rest") + return not failed, detail + ("" if not failed else ": " + "; ".join(failed)) + + LOG_CHECKS = { "log_contains": check_log_contains, "log_lacks": check_log_lacks, + "no_overlap": check_no_overlap, } @@ -948,6 +999,81 @@ def check_moves(box, vehicle, min_speed, direction="front"): 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" +def check_leaves_track(box, vehicle, cause=None, min_offset=None, max_offset=None, min_distance=None, max_distance=None, + lying=None): + """The vehicle leaves the track (physics.derailment new) and comes to rest off it: what derailed it, how far from + the axis of the track (either side) and how far it went on the ground, and whether it ends on its side.""" + numbers = {name.lower(): number for number, name in box.vehicles.items()} + number = numbers.get(vehicle.lower()) + if number is None: + return False, f"the black box has no vehicle {vehicle}" + records = [d for d in box.derailments if d.vehicle == number] + left = next((d for d in records if d.phase == 0), None) + if left is None: + return False, f"{vehicle} never left the track ({len(box.derailments)} derailment record(s) of others)" + rest = next((d for d in records if d.phase == 1 and d.time >= left.time), None) + detail = (f"{vehicle} left the track at t={left.time:.1f}s at {abs(left.speed):.0f} km/h " + f"({DERAILMENT_CAUSES.get(left.cause, left.cause)})") + if rest is None: + return False, detail + ", and never came to rest" + detail += (f", came to rest at t={rest.time:.1f}s {rest.travelled:.1f} m on, {rest.offset:+.1f} m from the axis of the " + f"track, roll {math.degrees(rest.roll):+.0f} deg{', on its side' if rest.lying else ''}") + failed = [] + if cause is not None and DERAILMENT_CAUSES.get(left.cause) != cause: + failed.append(f"derailed by {DERAILMENT_CAUSES.get(left.cause, left.cause)}, wanted {cause}") + if min_offset is not None and abs(rest.offset) < min_offset: + failed.append(f"offset under {min_offset} m") + if max_offset is not None and abs(rest.offset) > max_offset: + failed.append(f"offset over {max_offset} m") + if min_distance is not None and rest.travelled < min_distance: + failed.append(f"went under {min_distance} m") + if max_distance is not None and rest.travelled > max_distance: + failed.append(f"went over {max_distance} m") + if lying is not None and rest.lying != lying: + failed.append("lying on its side" if rest.lying else "upright") + return not failed, detail + ("" if not failed else ": " + "; ".join(failed)) + + +def check_consist_folds(box, vehicles, min_bend, min_folds=1, alternate=False, both_sides=False): + """The vehicles of a train (names, front to back, comma separated) left the track (physics.derailment new) and came + to rest folded up: at least `min_folds` of the bends between neighbours at rest (the angle between their headings, + either way along) are `min_bend` degrees or more; with `alternate` the bends of neighbouring joints turn opposite + ways, a zigzag; with `both_sides` some of them rest on one side of the track and some on the other.""" + numbers = {name.lower(): number for number, name in box.vehicles.items()} + names = [name.strip() for name in vehicles.split(",") if name.strip()] + rests = [] + for name in names: + number = numbers.get(name.lower()) + rests.append(next((d for d in box.derailments if number is not None and d.vehicle == number and d.phase == 1), None)) + if all(rest is None for rest in rests): + return False, f"none of {', '.join(names)} came to rest off the track" + bends = [] + for first, second in zip(rests, rests[1:]): + if first is None or second is None: + bends.append(None) + continue + # either way along: a vehicle turned about in the train has its heading the other way + bends.append(math.degrees(math.remainder(math.remainder(second.heading - first.heading, 2 * math.pi), math.pi))) + folds = [bend for bend in bends if bend is not None and abs(bend) >= min_bend] + sides = {1 if rest.offset > 0 else -1 for rest in rests if rest is not None and abs(rest.offset) > 0.5} + detail = "at rest: " + "; ".join( + f"{name} " + ("on the track" if rest is None else + f"{rest.travelled:.0f} m on, {rest.offset:+.1f} m, heading {math.degrees(rest.heading):+.0f} deg") + for name, rest in zip(names, rests)) + detail += "; bends " + ", ".join("-" if bend is None else f"{bend:+.0f}" for bend in bends) + " deg" + failed = [] + if len(folds) < min_folds: + failed.append(f"{len(folds)} bend(s) of {min_bend} deg or more, wanted {min_folds}") + if alternate: + pairs = [(a, b) for a, b in zip(bends, bends[1:]) if a is not None and b is not None + and abs(a) >= min_bend and abs(b) >= min_bend] + if not pairs or any(a * b > 0 for a, b in pairs): + failed.append("the bends don't alternate") + if both_sides and len(sides) < 2: + failed.append("all on one side of the track") + return not failed, detail + ("" if not failed else ": " + "; ".join(failed)) + + def _along_track(track, x, z): """Where the point (x, z) lies by the track: its level distance [m] from the line of the track, and how far along the track [m] from its first point that nearest point of the line is.""" @@ -1103,6 +1229,8 @@ def check_on_track(box, vehicles, max_offset=0.75, max_detour=5.0): # checks on the black box of the run rather than on the physicslog rows BLACKBOX_CHECKS = { + "leaves_track": check_leaves_track, + "consist_folds": check_consist_folds, "couples": check_couples, "parts": check_parts, "driver_changes": check_driver_changes, diff --git a/tests/unit/test_blackbox.cpp b/tests/unit/test_blackbox.cpp index cad1920a1..77e3e55f4 100644 --- a/tests/unit/test_blackbox.cpp +++ b/tests/unit/test_blackbox.cpp @@ -439,6 +439,43 @@ TEST_CASE("blackbox: the camera and the couplings are written field by field") { } } +TEST_CASE("blackbox: a vehicle off the track is written field by field") { + std::ostringstream file; + blackbox::writer out{file}; + out.header(); + blackbox::derailment_state state; + state.time = 21.5; + state.vehicle = 6; + state.phase = blackbox::derailment_phases::at_rest; + state.cause = blackbox::derailment_causes::overturned; + state.position = {100.0, 2.5, -40.0}; + state.heading = 0.75f; + state.speed_kmh = 0.0f; + state.offset = -12.25f; + state.roll = -1.5f; + state.travelled = 87.5f; + state.lying = true; + out.derailment(state); + auto const all{records(file.str())}; + REQUIRE(all.size() == 1); + CHECK(all[0].type == blackbox::record::derailment); + reader derailment{all[0].payload}; + CHECK(derailment.get() == 21.5); + CHECK(derailment.get() == 6); + CHECK(derailment.get() == 1); + CHECK(derailment.get() == 2); + CHECK(derailment.get() == 100.0); + CHECK(derailment.get() == 2.5); + CHECK(derailment.get() == -40.0); + CHECK(derailment.get() == 0.75f); + CHECK(derailment.get() == 0.0f); + CHECK(derailment.get() == -12.25f); + CHECK(derailment.get() == -1.5f); + CHECK(derailment.get() == 87.5f); + CHECK(derailment.get() == 1); + CHECK(derailment.done()); +} + TEST_CASE("blackbox: a look at the vehicles takes 25 bytes a vehicle") { std::ostringstream file; blackbox::writer out{file}; diff --git a/tests/unit/test_derail_motion.cpp b/tests/unit/test_derail_motion.cpp new file mode 100644 index 000000000..5423f2400 --- /dev/null +++ b/tests/unit/test_derail_motion.cpp @@ -0,0 +1,1093 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "vehicle/derailmotion.h" +#include "McZapkie/derailment.h" +#include "McZapkie/MOVER.h" +#include "utilities/Globals.h" + +#include +#include +#include +#include +#include +#include + +// a vehicle off the rails moving on the ground by itself (physics.derailment new): vehicle/derailmotion.h, and what +// the vehicle of TMoverParameters makes of it + +using test::definition; +using test::vehicle; +namespace dm = derail_motion; +namespace dr = derailment; + +namespace { + +constexpr double kmh{1.0 / 3.6}; +constexpr double degree{std::numbers::pi / 180.0}; + +// the given model of derailment for the test, restored after it +class model_setting { +public: + explicit model_setting(global_settings::derailment_model Model) : m_previous{Global.derailment} { Global.derailment = Model; } + ~model_setting() { Global.derailment = m_previous; } + model_setting(model_setting const &) = delete; + model_setting &operator=(model_setting const &) = delete; + +private: + global_settings::derailment_model m_previous; +}; + +// EU07 (4E of data/fiz): its dimensions and the centre of gravity of its body +dm::vehicle_shape eu07() { + dm::vehicle_shape shape; + shape.length = 15.915; + shape.width = 2.903; + shape.height = 4.348; + shape.centre_of_gravity = dr::default_centre_of_gravity(4.348, dr::vehicle_class::powered); + shape.contact_spacing = dr::contact_spacing(1.435); + shape.base = 8.0; + return shape; +} + +// the lateral acceleration [m/s2] the wheels of EU07 lift at: the wheel unloading of derailment.h reaches 1 +double const eu07_tipping{dr::overturning_acceleration(eu07().centre_of_gravity, dr::contact_spacing(1.435))}; + +// the track along +z at the height 0, its left (+x) the outside of the curve +dm::start leaving(double const Speed, dm::cause const Reason, int const Outward = 0, double const Acceleration = 0.0) { + dm::start start; + start.position = glm::dvec3{0.0}; + start.front = glm::dvec3{0.0, 0.0, 1.0}; + start.line = start.front; + start.speed = Speed; + start.reason = Reason; + start.outward = Outward; + start.acceleration = Acceleration; + return start; +} + +// the ground across the track, along +z: the top of the ballast 0.2 m under the rails out to 3 m each side, then the +// Slope (rise per metre outwards, negative down) to the Depth under the top (above it, rising). as a scenery has it, +// a level ground lies under it all, at the lowest of it: what is over the ceiling asked for isn't found, that is +class profile final : public dm::ground { +public: + profile(double const Slope, double const Depth, bool const Bothsides = false) : m_slope{Slope}, m_depth{Depth}, m_bothsides{Bothsides} {} + std::optional height(double const X, double, double const Ceiling) const override { + constexpr double top{-0.2}; + constexpr double edge{3.0}; + auto const across{m_bothsides ? std::abs(X) : X}; + auto const floor{std::min(top, top + std::clamp(m_slope * 1e6, -std::abs(m_depth), std::abs(m_depth)))}; + auto surface{top}; + if (across > edge) { + surface += std::clamp(m_slope * (across - edge), -std::abs(m_depth), std::abs(m_depth)); + } + return surface <= Ceiling ? surface : floor; + } + +private: + double m_slope; + double m_depth; + bool m_bothsides; +}; + +struct outcome { + double time{0.0}; + double travelled{0.0}; + double along{0.0}; + double across{0.0}; + double tipping{0.0}; + double roll{0.0}; + double height{0.0}; + bool lying{false}; + double lying_at{-1.0}; // the time it came to lie on its side, -1 never +}; + +// the vehicle slides as TMoverParameters drives it: its speed along the heading falls with the friction of the motion +// and the gravity of the grade under it, the distance of each step goes to the motion +outcome slide(dm::start const &Start, dm::ground const &Ground, double const Dt = 0.01, dm::vehicle_shape const &Shape = eu07(), double const Seconds = 60.0) { + dm::body body; + body.begin(Start, Shape, Ground); + auto speed{Start.speed}; + outcome result; + while (result.time < Seconds) { + auto const direction{speed >= 0.0 ? 1.0 : -1.0}; + auto const deceleration{dm::gravity * (body.friction() * direction + body.grade())}; + auto next{speed - deceleration * Dt}; + if (next * speed <= 0.0 && std::abs(body.grade()) <= body.friction()) { + next = 0.0; + } + auto const reversals{body.reversals()}; + body.step(Dt, 0.5 * (speed + next) * Dt, next, Ground); + speed = (body.reversals() - reversals) % 2 != 0 ? -next : next; + result.time += Dt; + if (body.lying() && result.lying_at < 0.0) { + result.lying_at = result.time; + } + if (body.at_rest()) { + break; + } + } + result.travelled = body.travelled(); + result.along = body.along(); + result.across = body.across(); + result.tipping = body.tipping(); + result.roll = body.roll(); + result.height = body.current().position.y; + result.lying = body.lying(); + return result; +} + +dm::flat_ground const ballast{-0.2}; + +} // namespace + +TEST_CASE("derail motion: the distance it slides goes with the square of the speed and against the friction") { + auto const fast{dm::stopping_distance(133.0 * kmh, dr::off_rails_friction)}; + auto const slow{dm::stopping_distance(40.0 * kmh, dr::off_rails_friction)}; + REQUIRE(fast.has_value()); + REQUIRE(slow.has_value()); + CHECK(*fast == doctest::Approx(232.0).epsilon(0.01)); + CHECK(*slow == doctest::Approx(21.0).epsilon(0.01)); + CHECK(*fast / *slow == doctest::Approx(133.0 * 133.0 / (40.0 * 40.0)).epsilon(1e-9)); + // on its side + CHECK(*dm::stopping_distance(133.0 * kmh, dr::overturned_friction) == doctest::Approx(*fast * 0.3 / 0.5).epsilon(1e-9)); + // uphill sooner, downhill further, down a slope steeper than the friction it doesn't stop + CHECK(*dm::stopping_distance(40.0 * kmh, 0.3, 0.05) < *slow); + CHECK(*dm::stopping_distance(40.0 * kmh, 0.3, -0.05) > *slow); + CHECK_FALSE(dm::stopping_distance(40.0 * kmh, 0.3, -0.4).has_value()); + + SUBCASE("the vehicle off the end of the track slides as far, straight on, upright") { + for (auto const speed : {133.0, 40.0}) { + CAPTURE(speed); + auto const result{slide(leaving(speed * kmh, dm::cause::end_of_track), ballast)}; + MESSAGE(std::format("off the end of the track at {:.0f} km/h: {:.1f} m in {:.1f} s", speed, result.travelled, result.time)); + CHECK(result.travelled == doctest::Approx(*dm::stopping_distance(speed * kmh, dr::off_rails_friction)).epsilon(0.02)); + CHECK(result.along == doctest::Approx(result.travelled).epsilon(1e-6)); + CHECK(std::abs(result.across) < 1e-6); + CHECK(result.tipping == 0.0); + // on the top of the ballast, not on the rails nor under the ground + CHECK(result.height == doctest::Approx(-0.2)); + } + } + SUBCASE("the friction along it rises from the one on its wheels to the one on its side") { + CHECK(dm::sliding_friction(0.0, false) == dr::off_rails_friction); + CHECK(dm::sliding_friction(dm::body::half_turn, false) == dr::overturned_friction); + CHECK(dm::sliding_friction(0.5 * dm::body::half_turn, false) == doctest::Approx(0.5 * (dr::off_rails_friction + dr::overturned_friction))); + CHECK(dm::sliding_friction(0.0, true) == dm::guided_friction); + } +} + +TEST_CASE("derail motion: the way it leaves the track by what derailed it") { + SUBCASE("off the end of the track and in a collision: straight on") { + CHECK(dm::departure_angle(dm::cause::end_of_track, 30.0, 10.0) == 0.0); + CHECK(dm::departure_angle(dm::cause::collision, 30.0, 10.0) == 0.0); + auto const result{slide(leaving(100.0 * kmh, dm::cause::collision, 1, 5.0), ballast)}; + CHECK(std::abs(result.across) < 1e-6); + } + SUBCASE("the flange climbing the rail: towards the rail it climbed, out of the curve, upright") { + for (auto const outward : {1, -1}) { + CAPTURE(outward); + auto const result{slide(leaving(100.0 * kmh, dm::cause::off_rails, outward, 3.0), ballast)}; + MESSAGE(std::format("climbed out of the curve to the {}: {:.1f} m across in {:.1f} m", outward > 0 ? "left" : "right", result.across, result.travelled)); + CHECK(result.across * outward > 1.0); + CHECK(result.tipping == 0.0); + CHECK_FALSE(result.lying); + } + // the faster the speed against the sideways one, the smaller the angle + CHECK(dm::departure_angle(dm::cause::off_rails, 40.0, 3.0) < dm::departure_angle(dm::cause::off_rails, 10.0, 3.0)); + CHECK(dm::departure_angle(dm::cause::off_rails, 0.1, 1000.0) == dm::most_departure); + } + SUBCASE("backwards, out of the curve as well") { + auto const result{slide(leaving(-100.0 * kmh, dm::cause::off_rails, 1, 3.0), ballast)}; + CHECK(result.along < -10.0); + CHECK(result.across > 1.0); + } + SUBCASE("overturned: out of the curve, falling on its side there") { + for (auto const outward : {1, -1}) { + CAPTURE(outward); + auto const result{slide(leaving(120.0 * kmh, dm::cause::overturned, outward, 2.0 * eu07_tipping), ballast)}; + MESSAGE(std::format("overturned to the {}: {:.1f} m across in {:.1f} m, on its side after {:.2f} s", outward > 0 ? "left" : "right", result.across, result.travelled, result.lying_at)); + CHECK(result.across * outward > 1.0); + CHECK(result.lying); + CHECK(result.tipping * outward == doctest::Approx(dm::body::half_turn)); + CHECK(result.roll * outward == doctest::Approx(dm::body::half_turn)); + // lying on its side on the top of the ballast, the origin of its model is half the width of its body up + CHECK(result.height == doctest::Approx(-0.2 + 0.5 * eu07().width)); + } + } + SUBCASE("pulled off by a coupling: to the side it is pulled to") { + auto const result{slide(leaving(50.0 * kmh, dm::cause::pulled_off, -1, 2.0), ballast)}; + CHECK(result.across < -0.1); + } +} + +TEST_CASE("derail motion: tipping over goes as far as the overturning went over its limit") { + // the curve keeps pushing it out while its outer wheels are on the rail: the further over the limit, the sooner it lies + auto const barely{slide(leaving(120.0 * kmh, dm::cause::overturned, 1, 1.2 * eu07_tipping), ballast)}; + auto const well{slide(leaving(120.0 * kmh, dm::cause::overturned, 1, 2.0 * eu07_tipping), ballast)}; + auto const hard{slide(leaving(120.0 * kmh, dm::cause::overturned, 1, 5.0 * eu07_tipping), ballast)}; + MESSAGE(std::format("on its side after {:.2f} / {:.2f} / {:.2f} s at a wheel unloading of 1.2 / 2 / 5", barely.lying_at, well.lying_at, hard.lying_at)); + REQUIRE(barely.lying); + REQUIRE(well.lying); + REQUIRE(hard.lying); + CHECK(barely.lying_at > well.lying_at); + CHECK(well.lying_at > hard.lying_at); + // it takes its time to fall over, it doesn't jump onto its side + CHECK(hard.lying_at > 0.3); + + SUBCASE("a body on the rails stays upright, on a level ground it isn't tipped by anything") { + auto const upright{slide(leaving(120.0 * kmh, dm::cause::off_rails, 1, 2.0 * eu07_tipping), ballast)}; + CHECK(upright.tipping == 0.0); + } + SUBCASE("slowing down below the limit, the curve doesn't tip it any more") { + dm::body body; + body.begin(leaving(30.0 * kmh, dm::cause::overturned, 1, 1.05 * eu07_tipping), eu07(), ballast); + // stopped at once: the curve pushes it out no more, it falls back on its wheels + body.step(0.01, 0.0, 0.0, ballast); + for (int step = 0; step < 300; ++step) { + body.step(0.01, 0.0, 0.0, ballast); + } + CHECK_FALSE(body.guided()); + CHECK(body.tipping() == 0.0); + } +} + +TEST_CASE("derail motion: the ground under it") { + SUBCASE("off the edge of an embankment it slides down the slope and falls on its side towards the bottom") { + // 1:1.5 down 4 m to the left, the vehicle leaving the track 4 degrees to the left at 60 km/h + profile const embankment{-1.0 / 1.5, 4.0}; + auto start{leaving(60.0 * kmh, dm::cause::off_rails)}; + start.front = glm::dvec3{std::sin(4.0 * degree), 0.0, std::cos(4.0 * degree)}; + auto const result{slide(start, embankment)}; + MESSAGE(std::format("down the embankment: {:.1f} m across, {:.1f} m down, tipped {:.0f} degrees, after {:.1f} m", result.across, -0.2 - result.height, result.tipping / degree, result.travelled)); + CHECK(result.across > 4.0); + // lying on the slope, its body half its width up off the ground + CHECK(result.height < -1.5); + CHECK(result.lying); + CHECK(result.tipping > 0.0); + } + SUBCASE("on a gentle slope it stays upright, leaning with the ground") { + profile const gentle{-1.0 / 6.0, 4.0}; + auto start{leaving(80.0 * kmh, dm::cause::off_rails)}; + start.front = glm::dvec3{std::sin(6.0 * degree), 0.0, std::cos(6.0 * degree)}; + auto const result{slide(start, gentle)}; + CHECK_FALSE(result.lying); + CHECK(result.tipping == 0.0); + // leaning left, down the slope + CHECK(result.roll == doctest::Approx(std::atan(1.0 / 6.0)).epsilon(0.05)); + } + SUBCASE("a lower centre of gravity tips over on a steeper slope only") { + // a 1:2.2 slope, 24 degrees: the steepest one EU07 stands on is 1:2.8 (20 degrees), a flat wagon tips past 1:1.7 + profile const slope{-1.0 / 2.2, 6.0}; + auto start{leaving(50.0 * kmh, dm::cause::off_rails)}; + start.front = glm::dvec3{std::sin(10.0 * degree), 0.0, std::cos(10.0 * degree)}; + auto low{eu07()}; + low.centre_of_gravity = 0.9; + low.height = 2.0; + CHECK(slide(start, slope).lying); + CHECK_FALSE(slide(start, slope, 0.01, low).lying); + } + SUBCASE("in a cutting it climbs the bank, stops sooner and leans (here falls) back towards the track") { + profile const cutting{1.0 / 1.5, 4.0}; + auto start{leaving(60.0 * kmh, dm::cause::off_rails)}; + start.front = glm::dvec3{std::sin(4.0 * degree), 0.0, std::cos(4.0 * degree)}; + auto const level{slide(start, ballast)}; + auto const result{slide(start, cutting)}; + MESSAGE(std::format("into a cutting: {:.1f} m against {:.1f} m on a level ground, roll {:.0f} degrees", result.travelled, level.travelled, result.roll / degree)); + CHECK(result.travelled < level.travelled); + CHECK(result.height > -0.2); + CHECK(result.roll < 0.0); + } + SUBCASE("it doesn't sink into the ground, it falls off a step") { + // off a wall 3 m high + profile const wall{-100.0, 3.0}; + auto start{leaving(40.0 * kmh, dm::cause::off_rails)}; + start.front = glm::dvec3{std::sin(20.0 * degree), 0.0, std::cos(20.0 * degree)}; + dm::body body; + body.begin(start, eu07(), wall); + auto lowest{0.0}; + auto speed{start.speed}; + for (int index = 0; index < 1000; ++index) { + auto const next{std::max(0.0, speed - dm::gravity * body.friction() * 0.01)}; + body.step(0.01, 0.5 * (speed + next) * 0.01, next, wall); + speed = next; + auto const &position{body.current().position}; + auto const ground{*wall.height(position.x, position.z, 1e9)}; + CHECK(position.y >= ground - 1e-9); + lowest = std::min(lowest, position.y); + } + CHECK(lowest < -3.0); + } +} + +TEST_CASE("derail motion: the same with steps of 0.01, 0.03 and 0.05 s") { + profile const embankment{-1.0 / 1.5, 4.0}; + auto down{leaving(60.0 * kmh, dm::cause::off_rails)}; + down.front = glm::dvec3{std::sin(4.0 * degree), 0.0, std::cos(4.0 * degree)}; + auto const overturning{leaving(120.0 * kmh, dm::cause::overturned, -1, 2.0 * eu07_tipping)}; + auto const climbing{leaving(100.0 * kmh, dm::cause::off_rails, 1, 3.0)}; + auto const fine{slide(down, embankment, 0.01)}; + auto const finetip{slide(overturning, ballast, 0.01)}; + auto const fineclimb{slide(climbing, ballast, 0.01)}; + for (auto const dt : {0.03, 0.05}) { + CAPTURE(dt); + auto const coarse{slide(down, embankment, dt)}; + CHECK(coarse.travelled == doctest::Approx(fine.travelled).epsilon(0.02)); + CHECK(coarse.across == doctest::Approx(fine.across).epsilon(0.05)); + CHECK(coarse.lying == fine.lying); + auto const coarsetip{slide(overturning, ballast, dt)}; + CHECK(coarsetip.travelled == doctest::Approx(finetip.travelled).epsilon(0.02)); + CHECK(coarsetip.across == doctest::Approx(finetip.across).epsilon(0.02)); + CHECK(coarsetip.lying_at == doctest::Approx(finetip.lying_at).epsilon(0.1)); + auto const coarseclimb{slide(climbing, ballast, dt)}; + CHECK(coarseclimb.across == doctest::Approx(fineclimb.across).epsilon(0.02)); + } +} + +TEST_CASE("derail motion: the ground of the scenery") { + SUBCASE("the triangles of the terrain") { + std::vector triangles; + // a square 10 m wide at 2 m rising to 4 m along x, and a roof over half of it at 10 m + triangles.push_back({glm::dvec3{0.0, 2.0, 0.0}, glm::dvec3{10.0, 4.0, 0.0}, glm::dvec3{10.0, 4.0, 10.0}}); + triangles.push_back({glm::dvec3{0.0, 2.0, 0.0}, glm::dvec3{10.0, 4.0, 10.0}, glm::dvec3{0.0, 2.0, 10.0}}); + triangles.push_back({glm::dvec3{0.0, 10.0, 0.0}, glm::dvec3{5.0, 10.0, 0.0}, glm::dvec3{0.0, 10.0, 10.0}}); + dm::mesh_ground const terrain{triangles, glm::dvec2{-5.0, -5.0}, glm::dvec2{15.0, 15.0}, 2.0}; + CHECK(terrain.size() == 3); + CHECK(*terrain.height(5.0, 5.0, 8.0) == doctest::Approx(3.0)); + CHECK(*terrain.height(7.5, 2.5, 8.0) == doctest::Approx(3.5)); + // under the roof the ground, over it the roof + CHECK(*terrain.height(1.0, 1.0, 8.0) == doctest::Approx(2.2)); + CHECK(*terrain.height(1.0, 1.0, 12.0) == doctest::Approx(10.0)); + CHECK_FALSE(terrain.height(12.0, 5.0, 8.0).has_value()); + CHECK_FALSE(terrain.height(50.0, 5.0, 8.0).has_value()); + CHECK(terrain.covers(14.0, -4.0)); + CHECK_FALSE(terrain.covers(16.0, 0.0)); + // the area of another vehicle: inside the one gathered or not + CHECK(terrain.covers(glm::dvec2{-5.0, -5.0}, glm::dvec2{15.0, 15.0})); + CHECK(terrain.covers(glm::dvec2{0.0, 2.0}, glm::dvec2{10.0, 12.0})); + CHECK_FALSE(terrain.covers(glm::dvec2{0.0, 2.0}, glm::dvec2{10.0, 16.0})); + CHECK_FALSE(terrain.covers(glm::dvec2{-6.0, 0.0}, glm::dvec2{0.0, 1.0})); + // cut down to the ground under a vehicle at rest: the triangles reaching into it, the same height there + auto const under{terrain.cropped(glm::dvec2{6.0, 0.0}, glm::dvec2{9.0, 4.0})}; + CHECK(under.size() == 2); + CHECK(*under.height(7.5, 2.5, 8.0) == doctest::Approx(3.5)); + CHECK(under.covers(6.0, 4.0)); + CHECK_FALSE(under.covers(5.0, 2.0)); + CHECK_FALSE(under.height(5.0, 2.0, 8.0).has_value()); + CHECK(terrain.cropped(glm::dvec2{0.5, 0.5}, glm::dvec2{1.0, 1.0}).size() == 3); + CHECK(terrain.cropped(glm::dvec2{20.0, 20.0}, glm::dvec2{30.0, 30.0}).size() == 0); + } + SUBCASE("the bed of the track over the terrain, level ground without one") { + dm::formation bed; + bed.point = glm::dvec3{0.0, 10.0, 0.0}; + bed.direction = glm::dvec3{0.0, 0.0, 1.0}; + bed.half_width = 2.0; + CHECK(bed.height(1.5, 100.0) == doctest::Approx(9.8)); + CHECK(bed.height(-2.0, -50.0) == doctest::Approx(9.8)); + CHECK(bed.height(3.5, 0.0) == doctest::Approx(9.8 - 1.0)); + dm::flat_ground const low{7.0}; + dm::site const embankment{&low, bed}; + CHECK(*embankment.height(0.0, 0.0, 12.0) == doctest::Approx(9.8)); + CHECK(*embankment.height(4.0, 0.0, 12.0) == doctest::Approx(9.8 - 2.0 / 1.5)); + CHECK(*embankment.height(20.0, 0.0, 12.0) == doctest::Approx(7.0)); + dm::site const bare{nullptr, bed}; + CHECK(*bare.height(20.0, 0.0, 12.0) == doctest::Approx(9.8)); + } +} + +TEST_CASE("derail motion: a coupling pulling sideways") { + // EU07, 80 t on 4 axles: a wheel carries 98 kN + CHECK(dm::pull_ratio(300e3, 0.0, 80e3, 4) == 0.0); + CHECK(dm::pull_ratio(300e3, 30.0 * degree, 80e3, 4) == doctest::Approx(0.5 * 150e3 / (80e3 * dm::gravity / 8.0))); + CHECK(dm::pull_ratio(-300e3, -30.0 * degree, 80e3, 4) == dm::pull_ratio(300e3, 30.0 * degree, 80e3, 4)); + // an empty wagon of 20 t goes over the climbing limit with a force the locomotive takes + CHECK(dm::pull_ratio(300e3, 30.0 * degree, 20e3, 4) > dr::climbing_limit); + CHECK(dm::pull_ratio(300e3, 30.0 * degree, 80e3, 4) < dr::climbing_limit); +} + +TEST_CASE("derail motion: the vehicle leaves the track with physics.derailment new only") { + test::track curve; + curve.radius = 300.0; + auto const critical{dr::overturning_speed(300.0, 0.0, eu07().centre_of_gravity, 1.435) / kmh}; + + SUBCASE("new: derailed by the criteria it leaves the track, then slides with the friction of the motion") { + model_setting const physical{global_settings::derailment_model::physical}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical + 20.0}; + for (int step = 0; step < 10; ++step) { + eu07vehicle.step(curve); + } + REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned); + CHECK(eu07vehicle->DerailCause == dm::cause::overturned); + CHECK(eu07vehicle->DerailAcceleration > eu07_tipping); + CHECK(eu07vehicle->leaves_track()); + eu07vehicle->OffTrack.begin(leaving(eu07vehicle->V, eu07vehicle->DerailCause, 1, eu07vehicle->DerailAcceleration), eu07(), ballast); + CHECK_FALSE(eu07vehicle->leaves_track()); + // tipping over on its outer wheels it hardly slows down + auto const start{eu07vehicle->V}; + for (int step = 0; step < 20; ++step) { + eu07vehicle.step(curve); + } + auto const deceleration{(start - eu07vehicle->V) / 0.2}; + CHECK(deceleration == doctest::Approx(dm::guided_friction * dr::gravity * 80.0 / 96.0).epsilon(0.1)); + // back on the rails, not off the track any more, and what derailed it forgotten + eu07vehicle->repair_damage(); + CHECK_FALSE(eu07vehicle->OffTrack.active()); + CHECK_FALSE(eu07vehicle->leaves_track()); + CHECK(eu07vehicle->DerailCause == dm::cause::off_rails); + CHECK(eu07vehicle->DerailAcceleration == 0.0); + } + SUBCASE("new: off the end of the track it slides on its wheels, straight on") { + model_setting const physical{global_settings::derailment_model::physical}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 40.0}; + eu07vehicle.damage_track(dtrack_norail); + eu07vehicle.step(); + REQUIRE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + CHECK(eu07vehicle->Derailed == dr::outcome::off_rails); + CHECK(eu07vehicle->DerailCause == dm::cause::end_of_track); + CHECK(eu07vehicle->leaves_track()); + } + SUBCASE("new: a vehicle pulled off by a coupling, upright, to the side it was pulled to") { + model_setting const physical{global_settings::derailment_model::physical}; + vehicle pulled{definition::fiz("4e_v1/4e"), 40.0}; + pulled->pull_off(-1, 5.0, "test"); + CHECK(TestFlag(pulled->DamageFlag, dtrain_out)); + CHECK(pulled->Derailed == dr::outcome::off_rails); + CHECK(pulled->DerailCause == dm::cause::pulled_off); + CHECK(pulled->DerailSide == -1); + CHECK(pulled->leaves_track()); + pulled->repair_damage(); + CHECK(pulled->DerailCause == dm::cause::off_rails); + CHECK(pulled->DerailAcceleration == 0.0); + CHECK(pulled->DerailSide == 0); + } +} + +TEST_CASE("derail motion: with physics.derailment monitor and old the vehicle stays on the track, as before") { + test::track curve; + curve.radius = 300.0; + for (auto const model : {global_settings::derailment_model::monitor, global_settings::derailment_model::old}) { + auto const number{static_cast(model)}; + CAPTURE(number); + model_setting const setting{model}; + vehicle fast{definition::fiz("4e_v1/4e"), 160.0}; + for (int step = 0; step < 600; ++step) { + fast.step(curve); + } + REQUIRE(TestFlag(fast->DamageFlag, dtrain_out)); + CHECK(fast->Derailed == dr::outcome::none); + CHECK_FALSE(fast->leaves_track()); + CHECK_FALSE(fast->OffTrack.active()); + // stopped dead by the legacy model + CHECK(fast->V == doctest::Approx(0.0).epsilon(0.01)); + vehicle ending{definition::fiz("4e_v1/4e"), 40.0}; + ending.damage_track(dtrack_norail); + ending.step(); + REQUIRE(TestFlag(ending->DamageFlag, dtrain_out)); + CHECK(ending->Derailed == dr::outcome::none); + CHECK_FALSE(ending->leaves_track()); + // nor is a vehicle pulled off it + vehicle pulled{definition::fiz("4e_v1/4e"), 40.0}; + pulled->pull_off(1, 5.0, "test"); + CHECK_FALSE(TestFlag(pulled->DamageFlag, dtrain_out)); + } +} + +// ---- the yaw of the body, the train folding up, the scatter + +namespace { + +// a coach of 40 t, 24.5 m over the buffers +dm::vehicle_shape coach() { + dm::vehicle_shape shape; + shape.length = 24.5; + shape.width = 2.825; + shape.height = 4.05; + shape.centre_of_gravity = dr::default_centre_of_gravity(4.05, dr::vehicle_class::unpowered); + shape.contact_spacing = dr::contact_spacing(1.435); + shape.base = 17.2; + shape.mass = 40e3; + return shape; +} + +// an end of the body: its front (Front) or its rear, at the height of the buffers +dm::end_point end_of(dm::body const &Body, bool const Front) { + // over its base, as TDynamicObject takes it + auto const half{0.5 * Body.shape().length * (Front ? 1.0 : -1.0)}; + return dm::end_point{Body.base() + glm::dvec3{0.0, dm::buffer_height, 0.0} + Body.axis() * half, Front ? Body.axis() : -Body.axis(), Body.tipping()}; +} + +struct car { + dm::body body; + double speed{0.0}; + double gap{0.0}; // of the coupling behind it +}; + +// the train of bodies off the track on level ground as TMoverParameters and TDynamicObject drive it: their buffers and +// couplings a spring of 2 MN/m with its damping, the longitudinal motion of each from the forces of its couplings along +// its heading and the friction of its motion; the forces across turn them. Dt the step [s]; till all stop or 30 s +std::vector run_train(std::vector> const &Starts, dm::vehicle_shape const &Shape, double const Dt = 0.01) { + std::vector train(Starts.size()); + for (std::size_t index = 0; index < train.size(); ++index) { + train[index].body.begin(Starts[index].first, Shape, ballast, Starts[index].second); + train[index].speed = Starts[index].first.speed; + } + for (std::size_t index = 0; index + 1 < train.size(); ++index) { + train[index].gap = dm::meet(end_of(train[index].body, false), end_of(train[index + 1].body, true)).gap; + } + constexpr double stiffness{2e6}; + auto const damping{0.3 * 2.0 * std::sqrt(stiffness * Shape.mass)}; + constexpr double slack{0.05}; + for (int step = 0; step * Dt < 30.0; ++step) { + std::vector> ends(train.size()); + for (std::size_t index = 0; index + 1 < train.size(); ++index) { + auto &ahead{train[index]}; + auto &behind{train[index + 1]}; + auto const rear{dm::meet(end_of(ahead.body, false), end_of(behind.body, true))}; + auto const front{dm::meet(end_of(behind.body, true), end_of(ahead.body, false))}; + auto const closing{(ahead.gap - rear.gap) / Dt}; + ahead.gap = rear.gap; + auto compression{0.0}; + if (rear.gap < 0.0) { + compression = std::max(0.0, -stiffness * rear.gap + damping * closing); + } + else if (rear.gap > slack) { + compression = std::min(0.0, -stiffness * (rear.gap - slack) + damping * closing); + } + ends[index][1] = dm::force_on(rear, compression); + ends[index + 1][0] = dm::force_on(front, compression); + } + auto moving{false}; + for (std::size_t index = 0; index < train.size(); ++index) { + auto &item{train[index]}; + auto const push{glm::dot(ends[index][0].force + ends[index][1].force, item.body.heading()) / Shape.mass}; + auto const friction{dm::gravity * item.body.friction()}; + auto next{item.speed + push * Dt}; + if (std::abs(next) <= friction * Dt) { + next = 0.0; + } + else { + next -= (next > 0.0 ? 1.0 : -1.0) * friction * Dt; + } + auto const reversals{item.body.reversals()}; + item.body.step(Dt, 0.5 * (item.speed + next) * Dt, next, ballast, ends[index]); + item.speed = (item.body.reversals() - reversals) % 2 != 0 ? -next : next; + moving |= (false == item.body.at_rest()); + } + if (false == moving) { + break; + } + } + return train; +} + +// a train of four coaches at 133 km/h overturning out of the curve to the left, the leading one ploughing into the +// ground; each scattered by the seed, or none of them +std::vector> overturning_train(std::uint32_t const Seed, bool const Scattered = true) { + std::vector> starts; + for (int index = 0; index < 4; ++index) { + auto start{leaving(133.0 * kmh, dm::cause::overturned, 1, 2.0 * eu07_tipping)}; + // one after the other along the way they leave the track + auto const angle{dm::departure_angle(start.reason, start.speed, start.acceleration)}; + start.position = -index * coach().length * glm::dvec3{std::sin(angle), 0.0, std::cos(angle)}; + auto scatter{Scattered ? dm::draw_scatter(dm::seed_of(Seed, std::format("coach{}", index))) : dm::scatter{}}; + if (index == 0 && Scattered) { + // the leading one ploughs into the ground: held back harder all the way, the ones behind push into it + scatter.friction_front *= 1.5; + scatter.friction_rear *= 1.5; + } + starts.emplace_back(start, scatter); + } + return starts; +} + +// the bends between the bodies of the train, from the front [rad] +std::vector bends(std::vector const &Train) { + std::vector result; + for (std::size_t index = 0; index + 1 < Train.size(); ++index) { + result.push_back(std::remainder(Train[index + 1].body.yaw() - Train[index].body.yaw(), 2.0 * std::numbers::pi)); + } + return result; +} + +std::string described(std::vector const &Train) { + std::string result; + for (auto const &item : Train) { + result += std::format(" [{:.1f} m along, {:+.1f} m across, yaw {:+.1f} deg]", item.body.along(), item.body.across(), item.body.yaw() / degree); + } + return result; +} + +} // namespace + +TEST_CASE("derail motion: the buffers and the coupling of two ends") { + // two ends facing each other, the second 10 degrees to the left of the axis of the first, the buffers pressed 20 mm + dm::end_point const first{glm::dvec3{0.0, 1.0, 0.0}, glm::dvec3{0.0, 0.0, 1.0}}; + auto const angle{10.0 * degree}; + dm::end_point const second{glm::dvec3{0.0, 1.0, -0.02}, -glm::dvec3{std::sin(angle), 0.0, std::cos(angle)}}; + auto const pressed{dm::meet(first, second)}; + CHECK(pressed.bend == doctest::Approx(angle)); + CHECK(pressed.gap == doctest::Approx(-0.02 * std::cos(0.5 * angle))); + CHECK(pressed.overlap == doctest::Approx(1.0)); + // the push of the buffers: against the bisector of the bend, through the inner buffer (to the left); less far out + // once the push is more than a buffer takes + auto const light{dm::force_on(pressed, 200e3)}; + CHECK(light.force.z == doctest::Approx(-200e3 * std::cos(0.5 * angle))); + CHECK(light.force.x == doctest::Approx(-200e3 * std::sin(0.5 * angle))); + CHECK(light.point.x == doctest::Approx(dm::buffer_half_spacing * std::cos(0.5 * angle)).epsilon(1e-3)); + auto const heavy{dm::force_on(pressed, 4.0 * dm::buffer_limit)}; + CHECK(heavy.point.x == doctest::Approx(0.25 * dm::buffer_half_spacing * std::cos(0.5 * angle)).epsilon(1e-3)); + // a body lower by a buffer head misses the buffers of the other one: the push goes through the middle of the beams + dm::end_point low{second}; + low.point.y -= dm::buffer_head; + CHECK(dm::force_on(dm::meet(first, low), 200e3).point.x == doctest::Approx(0.0)); + // the coupling pulls towards the other beam, taken 1 m to the side + dm::end_point aside{second}; + aside.point = glm::dvec3{1.0, 1.0, 0.5}; + auto const pulled{dm::meet(first, aside)}; + CHECK(pulled.gap == doctest::Approx(std::hypot(1.0, 0.5)).epsilon(0.1)); + auto const pull{dm::force_on(pulled, -100e3)}; + CHECK(pull.force.x == doctest::Approx(100e3 / std::hypot(1.0, 0.5))); + // gone past each other side by side: the coupling stretched + aside.point = glm::dvec3{3.0, 1.0, -5.0}; + CHECK(dm::meet(first, aside).gap > 5.0); + // a body turned about, its end facing the same way as the first one, 5 m behind it: they don't press each other + dm::end_point const about{glm::dvec3{0.0, 1.0, -5.0}, glm::dvec3{0.0, 0.0, 1.0}}; + CHECK(dm::meet(first, about).gap == doctest::Approx(5.0)); +} + +TEST_CASE("derail motion: the yaw of the body") { + auto shape{eu07()}; + shape.mass = 80e3; + SUBCASE("a push off the middle turns it, the friction under it holds it against a small one") { + for (auto const side : {1.0, -1.0}) { + CAPTURE(side); + dm::body body; + body.begin(leaving(0.0, dm::cause::off_rails), shape, ballast); + // 300 kN across at the front end, to the Side: it turns its front that way + std::array ends{}; + ends[0] = dm::end_force{glm::dvec3{side * 300e3, 0.0, 0.0}, glm::dvec3{0.0, 1.0, 0.5 * shape.length}}; + for (int step = 0; step < 50; ++step) { + body.step(0.01, 0.0, 0.0, ballast, ends); + } + CHECK(body.yaw_rate() * side > 0.0); + CHECK(body.yaw() * side > 0.0); + // through the middle along the body it doesn't turn it + dm::body straight; + straight.begin(leaving(0.0, dm::cause::off_rails), shape, ballast); + ends[0] = dm::end_force{glm::dvec3{0.0, 0.0, -300e3}, glm::dvec3{0.0, 1.0, 0.5 * shape.length}}; + straight.step(0.5, 0.0, 0.0, ballast, ends); + CHECK(straight.yaw() == 0.0); + // 30 kN across: the friction holds it, once it stands on the ground + dm::flat_ground const rails{0.0}; + dm::body held; + held.begin(leaving(0.0, dm::cause::off_rails), shape, rails); + ends[0] = dm::end_force{glm::dvec3{side * 30e3, 0.0, 0.0}, glm::dvec3{0.0, 1.0, 0.5 * shape.length}}; + held.step(0.5, 0.0, 0.0, rails, ends); + CHECK(held.yaw() == 0.0); + CHECK(held.at_rest()); + } + } + SUBCASE("the friction under it stops the turning, sliding or standing") { + for (auto const speed : {0.0, 30.0}) { + CAPTURE(speed); + dm::scatter spin; + spin.yaw_rate = 0.5; + dm::body body; + body.begin(leaving(speed, dm::cause::off_rails), shape, ballast, spin); + auto current{speed}; + auto most{0.0}; + auto halfway{0.0}; + for (int step = 0; step < 3000 && false == body.at_rest(); ++step) { + auto const next{std::max(0.0, current - dm::gravity * body.friction() * 0.01)}; + body.step(0.01, 0.5 * (current + next) * 0.01, next, ballast); + if (current > 0.5 * speed && next <= 0.5 * speed) { + halfway = body.yaw_rate(); + } + current = next; + most = std::max(most, std::abs(body.yaw_rate())); + } + MESSAGE(std::format("set turning at 0.5 rad/s at {:.0f} m/s: turned {:.1f} deg", speed, body.yaw() / degree)); + CHECK(body.at_rest()); + CHECK(body.yaw_rate() == 0.0); + // it never turns faster than it was set to + CHECK(most <= 0.5 + 1e-9); + CHECK(body.yaw() > 0.0); + // standing it stops within a turn of a few degrees; sliding fast, little holds it (the friction under it goes + // almost all against the way it slides), it slows the turning as it slows down + if (speed > 0.0) { + CHECK(halfway < 0.4); + CHECK(body.yaw() < 180.0 * degree); + } + else { + CHECK(body.yaw() < 15.0 * degree); + } + } + } + SUBCASE("a body going askew slides harder, and the way it goes turns to the body") { + dm::scatter askew; + askew.yaw = 20.0 * degree; + dm::body body; + body.begin(leaving(30.0, dm::cause::off_rails), shape, ballast, askew); + CHECK(body.friction() > dr::off_rails_friction); + CHECK(body.friction() < dm::lateral_friction); + auto const before{std::abs(std::remainder(std::atan2(body.heading().x, body.heading().z) - body.yaw(), 2.0 * std::numbers::pi))}; + auto current{30.0}; + for (int step = 0; step < 100; ++step) { + auto const next{current - dm::gravity * body.friction() * 0.01}; + body.step(0.01, 0.5 * (current + next) * 0.01, next, ballast); + current = next; + } + auto const after{std::abs(std::remainder(std::atan2(body.heading().x, body.heading().z) - body.yaw(), 2.0 * std::numbers::pi))}; + CHECK(after < before); + } +} + +TEST_CASE("derail motion: a train off the track pushed from behind folds into a zigzag") { + // the leading one held back harder, the ones behind push into it: a chaotic matter, so over eight seeds most of the + // trains fold, and the folds next to each other turn opposite ways + auto foldedtrains{0}; + auto pairs{0}; + auto zigzags{0}; + for (std::uint32_t seed = 1; seed <= 8; ++seed) { + CAPTURE(seed); + auto const train{run_train(overturning_train(seed), coach())}; + auto const bent{bends(train)}; + MESSAGE((std::format("seed {} at rest:", seed) + described(train))); + for (auto const &item : train) { + CHECK(item.body.at_rest()); + } + auto folds{0}; + for (std::size_t index = 0; index < bent.size(); ++index) { + if (std::abs(bent[index]) > 10.0 * degree) { + ++folds; + if (index + 1 < bent.size() && std::abs(bent[index + 1]) > 10.0 * degree) { + ++pairs; + zigzags += (bent[index] * bent[index + 1] < 0.0 ? 1 : 0); + } + } + } + foldedtrains += (folds > 0 ? 1 : 0); + } + MESSAGE(std::format("{} of 8 trains folded, {} of {} neighbouring folds turn opposite ways", foldedtrains, zigzags, pairs)); + CHECK(foldedtrains >= 4); + CHECK(pairs >= 2); + CHECK(zigzags * 4 >= pairs * 3); + SUBCASE("without the bite and the scatter it stays in line") { + auto const straight{run_train(overturning_train(1, false), coach())}; + MESSAGE((std::string{"unscattered at rest:"} + described(straight))); + for (auto const bend : bends(straight)) { + CHECK(std::abs(bend) < 1.0 * degree); + } + } +} + +TEST_CASE("derail motion: the scatter") { + SUBCASE("the same seed, the same scatter; another seed, another one") { + auto const one{dm::draw_scatter(dm::seed_of(7, "coach1"))}; + auto const again{dm::draw_scatter(dm::seed_of(7, "coach1"))}; + auto const other{dm::draw_scatter(dm::seed_of(8, "coach1"))}; + auto const next{dm::draw_scatter(dm::seed_of(7, "coach2"))}; + CHECK(one.departure == again.departure); + CHECK(one.friction_front == again.friction_front); + CHECK(one.dig_in == again.dig_in); + CHECK(one.yaw != other.yaw); + CHECK(one.yaw != next.yaw); + auto bites{0}; + for (std::uint32_t seed = 0; seed < 300; ++seed) { + auto const scatter{dm::draw_scatter(seed)}; + CHECK(std::abs(scatter.departure) <= 0.01); + CHECK(std::abs(scatter.yaw) <= 0.02); + CHECK(std::abs(scatter.yaw_rate) <= 0.02); + CHECK(scatter.friction_front >= 0.85); + CHECK(scatter.friction_rear <= 1.15); + CHECK((scatter.dig_in < 0.0 || (scatter.dig_in >= 0.2 && scatter.dig_in <= 1.5))); + bites += (scatter.dig_in >= 0.0 ? 1 : 0); + } + CHECK(bites > 150); + CHECK(bites < 250); + } + SUBCASE("the train: the same seed, the same way; another seed, another way") { + auto const one{bends(run_train(overturning_train(1), coach()))}; + auto const again{bends(run_train(overturning_train(1), coach()))}; + auto const othertrain{run_train(overturning_train(2), coach())}; + auto const other{bends(othertrain)}; + MESSAGE((std::string{"seed 2 at rest:"} + described(othertrain))); + CHECK(one == again); + auto apart{0.0}; + for (std::size_t index = 0; index < one.size(); ++index) { + apart = std::max(apart, std::abs(one[index] - other[index])); + } + MESSAGE(std::format("the bends of seed 1 and seed 2 differ by {:.1f} deg at most", apart / degree)); + CHECK(apart > 2.0 * degree); + } + SUBCASE("the same with steps of 0.01, 0.03 and 0.05 s") { + auto starts{overturning_train(3)}; + starts.resize(1); + auto const fine{run_train(starts, coach(), 0.01)}; + for (auto const dt : {0.03, 0.05}) { + CAPTURE(dt); + auto const coarse{run_train(starts, coach(), dt)}; + CHECK(coarse[0].body.travelled() == doctest::Approx(fine[0].body.travelled()).epsilon(0.02)); + CHECK(coarse[0].body.across() == doctest::Approx(fine[0].body.across()).epsilon(0.05)); + CHECK(coarse[0].body.yaw() == doctest::Approx(fine[0].body.yaw()).epsilon(0.05)); + } + } +} + +// ---- the bodies running into each other + +namespace { + +// a body off the track and the speed its vehicle goes with along its heading, as TMoverParameters keeps it +struct slider { + dm::body body; + double speed{0.0}; +}; + +dm::footprint print_of(dm::body const &Body) { + return dm::footprint_of(Body.current(), Body.shape().length, Body.shape().width, Body.shape().height); +} + +dm::contact_body contact_of(dm::body const &Body) { + dm::contact_body result; + result.mass = Body.shape().mass; + result.base = Body.base(); + result.velocity = Body.velocity(); + result.yaw_rate = Body.yaw_rate(); + result.gyration = Body.gyration(); + return result; +} + +// the kinetic energy of the body per its motion along and about the vertical [J] +double energy_of(dm::contact_body const &Body) { + return 0.5 * Body.mass * (glm::dot(Body.velocity, Body.velocity) + Body.gyration * Body.yaw_rate * Body.yaw_rate); +} + +// the hit of two bodies as vehicle_table::update_off_track_contacts() takes it: the impulse, the kick of each, the two +// moved apart by the overlap; the depth of it [m] +double touch(slider &First, slider &Second) { + auto const hit{dm::collide(print_of(First.body), print_of(Second.body))}; + if (false == hit.has_value()) { + return 0.0; + } + auto const first{contact_of(First.body)}; + auto const second{contact_of(Second.body)}; + auto const impulse{dm::contact_impulse(*hit, first, second)}; + auto const [velocity, yawrate]{dm::impulse_change(first, -impulse, hit->point)}; + auto const [othervelocity, otheryawrate]{dm::impulse_change(second, impulse, hit->point)}; + if (glm::length(impulse) > 0.0) { + First.body.kick(velocity, yawrate); + First.speed = First.body.speed(); + Second.body.kick(othervelocity, otheryawrate); + Second.speed = Second.body.speed(); + } + auto const correction{dm::contact_correction * std::max(0.0, hit->depth - dm::contact_slop)}; + First.body.nudge(-hit->normal * (0.5 * correction)); + Second.body.nudge(hit->normal * (0.5 * correction)); + return hit->depth; +} + +void slide_on(slider &Item, double const Dt) { + auto const friction{dm::gravity * Item.body.friction()}; + auto next{Item.speed}; + if (std::abs(next) <= friction * Dt) { + next = 0.0; + } + else { + next -= (next > 0.0 ? 1.0 : -1.0) * friction * Dt; + } + auto const reversals{Item.body.reversals()}; + Item.body.step(Dt, 0.5 * (Item.speed + next) * Dt, next, ballast); + Item.speed = (Item.body.reversals() - reversals) % 2 != 0 ? -next : next; +} + +struct hit_outcome { + double most{0.0}; // the deepest the two went into each other [m] + double resting{0.0}; // at rest + double furthest{0.0}; // the furthest the first one got along +z [m] + glm::dvec3 first{0.0}; // where the bodies came to rest + glm::dvec3 second{0.0}; + double second_yaw{0.0}; +}; + +// a coach upright at Speed along +z into another one standing Distance ahead of it, turned by the Angle, offset +// Across; the step Dt +hit_outcome run_into(double const Speed, double const Angle, double const Across = 0.0, double const Dt = 0.01, double const Distance = 40.0) { + slider first; + first.body.begin(leaving(Speed, dm::cause::end_of_track), coach(), ballast); + first.speed = Speed; + slider second; + auto standing{leaving(0.0, dm::cause::end_of_track)}; + standing.position = glm::dvec3{Across, 0.0, Distance}; + standing.front = glm::dvec3{std::sin(Angle), 0.0, std::cos(Angle)}; + second.body.begin(standing, coach(), ballast); + hit_outcome result; + for (int step = 0; step * Dt < 30.0; ++step) { + result.most = std::max(result.most, touch(first, second)); + slide_on(first, Dt); + slide_on(second, Dt); + result.furthest = std::max(result.furthest, first.body.base().z); + if (first.body.at_rest() && second.body.at_rest()) { + break; + } + } + result.resting = touch(first, second); + result.first = first.body.base(); + result.second = second.body.base(); + result.second_yaw = second.body.yaw(); + return result; +} + +} // namespace + +TEST_CASE("derail motion: the footprint of a body and two bodies in each other") { + dm::pose upright; + auto const print{dm::footprint_of(upright, 24.5, 2.8, 4.0)}; + CHECK(print.half_length == doctest::Approx(12.25 - dm::buffer_length)); + CHECK(print.half_width == doctest::Approx(1.4)); + CHECK(print.low == doctest::Approx(0.0)); + CHECK(print.high == doctest::Approx(4.0)); + // on its side to the left: as wide on the ground as it is high, all of it to the left, as low as it is wide + dm::pose lying; + lying.left = glm::dvec3{0.0, -1.0, 0.0}; + lying.up = glm::dvec3{1.0, 0.0, 0.0}; + lying.position = glm::dvec3{0.0, 1.4, 0.0}; + auto const side{dm::footprint_of(lying, 24.5, 2.8, 4.0)}; + CHECK(side.half_width == doctest::Approx(2.0)); + CHECK(side.centre.x == doctest::Approx(2.0)); + CHECK(side.high - side.low == doctest::Approx(2.8)); + // side by side 2.5 m apart: 0.3 m in each other, out of the first to the left (+x) + auto beside{print}; + beside.centre.x = 2.5; + auto const hit{dm::collide(print, beside)}; + REQUIRE(hit.has_value()); + CHECK(hit->depth == doctest::Approx(0.3)); + CHECK(hit->normal.x == doctest::Approx(1.0)); + // apart, or one over the other: no contact + beside.centre.x = 3.0; + CHECK_FALSE(dm::collide(print, beside).has_value()); + beside.centre.x = 2.5; + beside.low = 3.9; + beside.high = 7.0; + CHECK_FALSE(dm::collide(print, beside).has_value()); + // the lying one beside the upright one, low as it is: they hit + CHECK(dm::collide(print, side).has_value()); +} + +TEST_CASE("derail motion: an impulse never adds energy") { + // two bodies meeting at all kinds of points and angles, turning or not, one of them on the rails or not + auto worst{-1e9}; + for (int index = 0; index < 400; ++index) { + auto const draw = [index](int Which) { return std::sin(index * 12.9898 + Which * 78.233) * 0.5 + 0.5; }; + dm::contact hit; + auto const angle{draw(1) * 2.0 * std::numbers::pi}; + hit.normal = glm::dvec3{std::cos(angle), 0.0, std::sin(angle)}; + hit.point = glm::dvec3{draw(2) * 20.0 - 10.0, 0.0, draw(3) * 6.0 - 3.0}; + hit.depth = 0.1; + dm::contact_body first{40e3, glm::dvec3{0.0}, glm::dvec3{draw(4) * 40.0 - 20.0, 0.0, draw(5) * 40.0 - 20.0}, draw(6) - 0.5, 50.0}; + dm::contact_body second{80e3, glm::dvec3{draw(7) * 6.0, 0.0, draw(8) * 6.0}, glm::dvec3{draw(9) * 10.0 - 5.0, 0.0, 0.0}, draw(10) - 0.5, 22.0}; + if (index % 3 == 0) { + second.guided = true; + second.guide = glm::dvec3{1.0, 0.0, 0.0}; + second.yaw_rate = 0.0; + } + auto const before{energy_of(first) + energy_of(second)}; + auto const impulse{dm::contact_impulse(hit, first, second)}; + auto const [velocity, yawrate]{dm::impulse_change(first, -impulse, hit.point)}; + auto const [othervelocity, otheryawrate]{dm::impulse_change(second, impulse, hit.point)}; + first.velocity += velocity; + first.yaw_rate += yawrate; + second.velocity += othervelocity; + second.yaw_rate += otheryawrate; + auto const after{energy_of(first) + energy_of(second)}; + worst = std::max(worst, after - before); + CHECK(after <= before * (1.0 + 1e-9) + 1e-6); + } + MESSAGE(std::format("the most energy an impulse added: {:.3g} J", worst)); +} + +TEST_CASE("derail motion: a body running into another one doesn't go through it") { + SUBCASE("head on into the side of one standing across: it stops at it, pushes it, never through") { + auto const result{run_into(20.0, 0.5 * std::numbers::pi)}; + MESSAGE(std::format("at 20 m/s into the side of a coach: {:.2f} m in at most, {:.3f} m at rest, its front got to z {:.1f} (the side of the other at {:.1f}), the other pushed to z {:.1f}", result.most, result.resting, result.furthest + 0.5 * coach().length, 40.0 - 0.5 * coach().width, result.second.z)); + CHECK(result.most < 0.6); + CHECK(result.resting < 0.05); + // the first one stays behind the other one: its middle never gets past the other's + CHECK(result.furthest < result.second.z); + // the other one is pushed on + CHECK(result.second.z > 40.5); + } + SUBCASE("glancing off the end of one standing in line, offset: it goes past it, pushed aside, not into it") { + auto const result{run_into(15.0, 0.0, 2.0)}; + MESSAGE(std::format("at 15 m/s, 2 m aside, into the end of a coach: {:.2f} m in at most, {:.3f} m at rest; at rest {:.1f} m apart across", result.most, result.resting, std::abs(result.second.x - result.first.x))); + CHECK(result.resting < 0.05); + CHECK(result.most < 0.6); + } + SUBCASE("the same with steps of 0.01, 0.03 and 0.05 s") { + auto const fine{run_into(20.0, 0.5 * std::numbers::pi, 0.0, 0.01)}; + for (auto const dt : {0.03, 0.05}) { + CAPTURE(dt); + auto const coarse{run_into(20.0, 0.5 * std::numbers::pi, 0.0, dt)}; + CHECK(coarse.second.z == doctest::Approx(fine.second.z).epsilon(0.03)); + CHECK(coarse.first.z == doctest::Approx(fine.first.z).epsilon(0.03)); + CHECK(coarse.resting < 0.05); + } + } +} + +TEST_CASE("derail motion: two bodies folded past a right angle stay apart") { + // a coach turned 100 degrees off the next one, their ends together at the joint (in each other by a metre at the + // start), sliding on: they push apart within half a second, at rest not in each other + slider first; + auto start{leaving(10.0, dm::cause::end_of_track)}; + first.body.begin(start, coach(), ballast); + first.speed = 10.0; + slider second; + auto const angle{100.0 * degree}; + auto other{leaving(5.0, dm::cause::end_of_track)}; + // its front end at the rear end of the first one, folded to the left + glm::dvec3 const front{std::sin(angle), 0.0, std::cos(angle)}; + other.front = front; + other.position = glm::dvec3{0.0, 0.0, -0.5 * coach().length} - front * (0.5 * coach().length - 1.0); + second.body.begin(other, coach(), ballast); + second.speed = 5.0; + auto most{0.0}; + for (int step = 0; step < 2000; ++step) { // 20 s in steps of 0.01 s + auto const depth{touch(first, second)}; + if (step > 50) { // after half a second + most = std::max(most, depth); + } + slide_on(first, 0.01); + slide_on(second, 0.01); + } + auto const resting{touch(first, second)}; + MESSAGE(std::format("folded 100 degrees: {:.2f} m in at most after half a second, {:.3f} m at rest", most, resting)); + CHECK(resting < 0.05); + CHECK(most < 0.1); +} + +TEST_CASE("derail motion: a body hitting one on the rails from the side") { + // a coach off the track at 10 m/s into the side of one standing on the rails (along x): the one on the rails takes + // none of it along them, the first stops against it (bounces off), and the push across the rails is over what + // its wheels hold + dm::contact hit; + hit.normal = glm::dvec3{0.0, 0.0, 1.0}; + hit.point = glm::dvec3{0.0, 0.0, 0.0}; + hit.depth = 0.05; + dm::contact_body first{40e3, glm::dvec3{0.0, 0.0, -10.0}, glm::dvec3{0.0, 0.0, 10.0}, 0.0, 50.0}; + dm::contact_body second{40e3, glm::dvec3{0.0, 0.0, 1.4}, glm::dvec3{0.0}, 0.0, 50.0, true, glm::dvec3{1.0, 0.0, 0.0}}; + auto const impulse{dm::contact_impulse(hit, first, second)}; + auto const [velocity, yawrate]{dm::impulse_change(first, -impulse, hit.point)}; + auto const [othervelocity, otheryawrate]{dm::impulse_change(second, impulse, hit.point)}; + CHECK(glm::length(othervelocity) == doctest::Approx(0.0)); + CHECK(first.velocity.z + velocity.z == doctest::Approx(-10.0 * dm::contact_restitution)); + // the push across the rails over a frame of 0.05 s against the wheels of a coach of 40 t on 4 axles + auto const ratio{dm::pull_ratio(std::abs(impulse.z) / 0.05, 0.5 * std::numbers::pi, 40e3, 4)}; + MESSAGE(std::format("the hit across the rails at 10 m/s: Y/Q {:.1f}", ratio)); + CHECK(ratio > 3.0 * dr::climbing_limit); + // a hit at an angle along the rails pushes it along them + hit.normal = glm::normalize(glm::dvec3{1.0, 0.0, 1.0}); + first.velocity = glm::dvec3{10.0, 0.0, 10.0}; + auto const slanted{dm::contact_impulse(hit, first, second)}; + CHECK(dm::impulse_change(second, slanted, hit.point).first.x > 0.5); +} diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 7a301930a..f057ae917 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -27,9 +27,16 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Driver.h" #include +#include #include +#include #include +#include +#include +#include #include +#include +#include #include "utilities/Globals.h" #include "utilities/Timer.h" #include "utilities/Logs.h" @@ -41,6 +48,7 @@ http://mozilla.org/MPL/2.0/. #include "model/Model3d.h" #include "vehicle/doorwings.h" #include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" #include "application/uitranscripts.h" #include "input/messaging.h" #include "application/application.h" @@ -1589,6 +1597,14 @@ void TDynamicObject::ABuBogies() { // Obracanie wozkow na zakretach. Na razie // uwzględnia tylko zakręty, // bez zadnych gorek i innych przeszkod. + if( smBogie[ 0 ] != nullptr && smBogie[ 1 ] != nullptr && MoverParameters->OffTrack.active() ) { + // off the track the bogies stay straight under the body, they don't follow the track any more + bogieRot[ 0 ] = glm::vec3 { 0.f }; + bogieRot[ 1 ] = glm::vec3 { 0.f }; + smBogie[ 0 ]->SetRotateXYZ( bogieRot[ 0 ] ); + smBogie[ 1 ]->SetRotateXYZ( bogieRot[ 1 ] ); + return; + } if (smBogie[0] != nullptr && smBogie[1] != nullptr) { // modelRot.z=ABuAcos(Axle0.pPosition-Axle1.pPosition); //kąt obrotu pojazdu @@ -1625,7 +1641,7 @@ void TDynamicObject::ABuCheckMyTrack() // Ra: w poniższej funkcji jest problem ze sprzęgami TDynamicObject * -TDynamicObject::ABuFindObject( int &Foundcoupler, double &Distance, TTrack const *Track, int const Direction, int const Mycoupler ) const +TDynamicObject::ABuFindObject( int &Foundcoupler, double &Distance, TTrack const *Track, int const Direction, int const Mycoupler, bool const InLine ) const { // Zwraca wskaźnik najbliższego obiektu znajdującego się // na torze w określonym kierunku, ale tylko wtedy, kiedy // obiekty mogą się zderzyć, tzn. nie mijają się. @@ -1667,6 +1683,10 @@ TDynamicObject::ABuFindObject( int &Foundcoupler, double &Distance, TTrack const for( auto dynamic : Track->Dynamics ) { if( dynamic == this ) { continue; } // szukający się nie liczy + // physics.derailment new: one of the two off the track beside the other one, they don't meet + if( InLine && ( MoverParameters->OffTrack.active() || dynamic->MoverParameters->OffTrack.active() ) && false == in_line_with( *dynamic ) ) { + continue; + } /* if( ( ( dynamic == PrevConnected ) && ( MoverParameters->Couplers[ TMoverParameters::side::front ].CouplingFlag != coupling::faux ) ) || ( ( dynamic == NextConnected ) && ( MoverParameters->Couplers[ TMoverParameters::side::rear ].CouplingFlag != coupling::faux ) ) ){ @@ -2771,6 +2791,22 @@ void TDynamicObject::FastMove(double fDistance) } void TDynamicObject::Move(double fDistance) +{ + if( MoverParameters->OffTrack.active() ) { + // physics.derailment new: off the track it goes on the ground + move_off_track( fDistance ); + return; + } + move_axles( fDistance ); + if( fDistance != 0.0 || m_offtrackplaced ) // nie liczyć ponownie, jeśli stoi + { // liczenie pozycji pojazdu tutaj, bo jest używane w wielu miejscach + // (also once the vehicle off the track is back on the rails) + m_offtrackplaced = false; + place_by_axles(); + } +} + +void TDynamicObject::move_axles(double fDistance) { // przesuwanie pojazdu po // trajektorii polega na // przesuwaniu poszczególnych osi @@ -2802,8 +2838,10 @@ void TDynamicObject::Move(double fDistance) bEnabled &= Axle1.Move(fDistance, iAxleFirst != 0); // oś z tyłu pojazdu prusza się pierwsza bEnabled &= Axle0.Move(fDistance, iAxleFirst == 0); // oś z przodu pojazdu } - if (fDistance != 0.0) // nie liczyć ponownie, jeśli stoi - { // liczenie pozycji pojazdu tutaj, bo jest używane w wielu miejscach +} + +void TDynamicObject::place_by_axles() +{ // liczenie pozycji pojazdu tutaj, bo jest używane w wielu miejscach vPosition = 0.5 * (Axle1.pPosition + Axle0.pPosition); //środek między skrajnymi osiami vFront = Axle0.pPosition - Axle1.pPosition; // wektor pomiędzy skrajnymi osiami // Ra 2F1J: to nie jest stabilne (powoduje rzucanie taborem) i wymaga @@ -2913,8 +2951,448 @@ void TDynamicObject::Move(double fDistance) } } } +} + +namespace { + +using ground_triangles = std::vector; + +bool outside( glm::dvec3 const &Centre, double const Radius, glm::dvec2 const &Min, glm::dvec2 const &Max ) { + return Centre.x + Radius < Min.x || Centre.x - Radius > Max.x || Centre.z + Radius < Min.y || Centre.z - Radius > Max.y; +} + +void add_triangle( glm::dvec3 const &A, glm::dvec3 const &B, glm::dvec3 const &C, glm::dvec2 const &Min, glm::dvec2 const &Max, ground_triangles &Out ) { + if( std::max( { A.x, B.x, C.x } ) < Min.x || std::min( { A.x, B.x, C.x } ) > Max.x + || std::max( { A.z, B.z, C.z } ) < Min.y || std::min( { A.z, B.z, C.z } ) > Max.y ) { + return; } -}; + Out.push_back( { A, B, C } ); +} + +// the triangles of a piece of the scenery's geometry within the rectangle (x, z), as the editor gathers the ground +void add_shape( scene::shape_node const &Shape, glm::dvec2 const &Min, glm::dvec2 const &Max, ground_triangles &Out ) { + auto const &data { Shape.data() }; + if( data.area.radius >= 0.f && outside( data.area.center, data.area.radius, Min, Max ) ) { + return; + } + if( false == data.vertices.empty() ) { + for( std::size_t i = 0; i + 2 < data.vertices.size(); i += 3 ) { + add_triangle( data.vertices[ i ].position, data.vertices[ i + 1 ].position, data.vertices[ i + 2 ].position, Min, Max, Out ); + } + return; + } + // once the shape is uploaded its world-space source is released; the renderer keeps an origin-relative copy + if( data.geometry.bank == 0 && data.geometry.chunk == 0 ) { + return; + } + auto const &vertices { GfxRenderer->Vertices( data.geometry ) }; + auto const &indices { GfxRenderer->Indices( data.geometry ) }; + auto const point = [ &data, &vertices ]( std::size_t const Index ) { return data.origin + glm::dvec3 { vertices[ Index ].position }; }; + if( indices.empty() ) { + for( std::size_t i = 0; i + 2 < vertices.size(); i += 3 ) { + add_triangle( point( i ), point( i + 1 ), point( i + 2 ), Min, Max, Out ); + } + return; + } + for( std::size_t i = 0; i + 2 < indices.size(); i += 3 ) { + if( std::max( { indices[ i ], indices[ i + 1 ], indices[ i + 2 ] } ) >= vertices.size() ) { + continue; + } + add_triangle( point( indices[ i ] ), point( indices[ i + 1 ] ), point( indices[ i + 2 ] ), Min, Max, Out ); + } +} + +// the ground of the scenery within the rectangle (x, z): its terrain and the other opaque geometry of its sections, +// and the heightmap terrain where it is loaded. the models aren't ground +ground_triangles scenery_ground( glm::dvec2 const &Min, glm::dvec2 const &Max ) { + ground_triangles triangles; + if( simulation::Region == nullptr ) { + return triangles; + } + auto const centre { 0.5 * ( Min + Max ) }; + std::vector sections; + simulation::Region->sections( glm::dvec3 { centre.x, 0.0, centre.y }, static_cast( 0.5 * glm::length( Max - Min ) ), sections ); + for( auto const *section : sections ) { + for( auto const &shape : section->m_shapes ) { + add_shape( shape, Min, Max, triangles ); + } + for( auto const &cell : section->m_cells ) { + if( outside( cell.m_area.center, cell.m_area.radius, Min, Max ) ) { + continue; + } + for( auto const &shape : cell.m_shapesopaque ) { + add_shape( shape, Min, Max, triangles ); + } + } + } + if( EditorTerrain.active() ) { + EditorTerrain.gather_triangles( Min, Max, triangles ); + } + return triangles; +} + +glm::dvec3 level_left_of( glm::dvec3 const &Front ) { + return glm::dvec3 { Front.z, 0.0, -Front.x }; +} + +// the end of the vehicle where it meets the one coupled to it: the middle of its buffer beam, the way it faces. off the +// track, over its base on the ground as it stands: rolled over, its ends go with it as far as the coupling holds them, +// and the buffers of the side it rolled to miss those of an upright one +derail_motion::end_point end_point_of( TDynamicObject const &Vehicle, int const End ) { + auto const facing { End == end::front ? 1.0 : -1.0 }; + auto const &motion { Vehicle.MoverParameters->OffTrack }; + glm::dvec3 const front { Vehicle.VectorFront().x, 0.0, Vehicle.VectorFront().z }; + auto const length { glm::length( front ) }; + auto const axis { length > 1e-6 ? front / length : glm::dvec3 { 0.0, 0.0, 1.0 } }; + auto const middle { motion.active() ? motion.base() : Vehicle.GetPosition() }; + return derail_motion::end_point { + middle + glm::dvec3 { 0.0, derail_motion::buffer_height, 0.0 } + axis * ( facing * 0.5 * Vehicle.MoverParameters->Dim.L ), + axis * facing, + motion.active() ? motion.tipping() : 0.0 }; +} + +// the push of the buffers on the end of the vehicle [N], negative the pull of its coupling +double compression_of( TMoverParameters const &Vehicle, int const End ) { + return ( End == end::front ? -1.0 : 1.0 ) * Vehicle.Couplers[ End ].CForce; +} + +// the time spent off the track in a frame which makes it worth a warning [s] +constexpr double off_track_slow { 0.02 }; + +using off_track_clock = std::chrono::steady_clock; + +double seconds_since( off_track_clock::time_point const Start ) { + return std::chrono::duration( off_track_clock::now() - Start ).count(); +} + +std::string_view side_name( int const Side ) { + if( Side > 0 ) { + return "left"; + } + return Side < 0 ? "right" : "none"; +} + +} // namespace + +double TDynamicObject::off_track_gap( int const End ) const { + + auto const *neighbour { MoverParameters->Neighbours[ End ].vehicle }; + if( neighbour == nullptr ) { + return 0.0; + } + return derail_motion::meet( end_point_of( *this, End ), end_point_of( *neighbour, MoverParameters->Neighbours[ End ].vehicle_end ) ).gap; +} + +double TDynamicObject::off_track_offset() const { + + if( false == MoverParameters->OffTrack.active() ) { + return 0.0; + } + auto const middle { 0.5 * ( Axle0.pPosition + Axle1.pPosition ) }; + auto const offset { vPosition - middle }; + return glm::dot( glm::dvec3 { offset.x, 0.0, offset.z }, level_left_of( track_front() ) ); +} + +glm::dvec3 TDynamicObject::track_front() const { + + auto const along { Axle0.pPosition - Axle1.pPosition }; + glm::dvec3 const flat { along.x, 0.0, along.z }; + auto const length { glm::length( flat ) }; + return length > 1e-6 ? flat / length : glm::dvec3 { 0.0, 0.0, 1.0 }; +} + +derail_motion::formation TDynamicObject::track_bed() const { + + derail_motion::formation bed; + bed.point = 0.5 * ( Axle0.pPosition + Axle1.pPosition ); + bed.direction = track_front(); + if( auto const *track { RaTrackGet() }; track != nullptr ) { + // the ballast out of the rails, as wide as the track draws it + bed.half_width = std::clamp( 0.5 * std::abs( track->fTrackWidth ) + std::abs( track->fTexWidth ), 1.2, 3.5 ); + } + return bed; +} + +int TDynamicObject::outward_side() const { + + // the track as designed turns from the rear axle to the front one: the outside of its curve, or its inside where a + // buckle bends the line the other way more than the curve does (the criteria of derailment, McZapkie/derailment.h) + if( auto const design { std::sin( Axle1.vAngles.z - Axle0.vAngles.z ) }; std::abs( design ) >= 1e-4 ) { + auto const outside { design > 0.0 ? -1 : 1 }; + return MoverParameters->DerailAcceleration < 0.0 ? -outside : outside; + } + // a straight track: the path under the vehicle as it is, a buckle on it, turns from the rear axle to the front one + auto const front { Axle0.PathDirection() }; + auto const rear { Axle1.PathDirection() }; + auto const turn { glm::dot( front, level_left_of( rear ) ) }; + // a turn under a tenth of a milliradian is a straight track + if( std::abs( turn ) < 1e-4 ) { + return 0; + } + // turning left, the outside of the curve is on the right + return turn > 0.0 ? -1 : 1; +} + +void TDynamicObject::gather_off_track_terrain() { + + auto const &mover { *MoverParameters }; + auto const &position { mover.OffTrack.active() ? mover.OffTrack.current().position : vPosition }; + // as far as it may slide, and some + auto const slide { derail_motion::stopping_distance( mover.V, derailment::off_rails_friction ).value_or( 0.0 ) }; + auto const reach { std::min( slide + mover.Dim.L + 50.0, 600.0 ) }; + m_offtrackgathered = m_offtracktotal; + m_offtrackcropped = false; + // the terrain of another vehicle, where it covers the way this one goes: around it and around where it stops going + // straight on, by its length and the margin the terrain is gathered again at + glm::dvec3 heading { vFront.x, 0.0, vFront.z }; + if( mover.OffTrack.active() ) { + heading = mover.OffTrack.heading(); + } + auto const length { glm::length( heading ) }; + auto const stop { length > 1e-6 ? position + heading * ( std::copysign( std::max( reach - mover.Dim.L - 50.0, 0.0 ), mover.V ) / length ) : position }; + auto const margin { mover.Dim.L + 30.0 }; + if( auto shared { simulation::Vehicles.off_track_terrain( + glm::dvec2 { std::min( position.x, stop.x ) - margin, std::min( position.z, stop.z ) - margin }, + glm::dvec2 { std::max( position.x, stop.x ) + margin, std::max( position.z, stop.z ) + margin } ) }; + shared != nullptr ) { + m_offtrackterrain = std::move( shared ); + m_offtrackmin = m_offtrackterrain->minimum(); + m_offtrackmax = m_offtrackterrain->maximum(); + m_offtracksite.terrain( m_offtrackterrain.get() ); + return; + } + m_offtrackmin = glm::dvec2 { position.x - reach, position.z - reach }; + m_offtrackmax = glm::dvec2 { position.x + reach, position.z + reach }; + auto const started { off_track_clock::now() }; + auto triangles { scenery_ground( m_offtrackmin, m_offtrackmax ) }; + auto const trimmed { triangles.size() > off_track_triangles }; + if( trimmed ) { + // a scenery dense enough to make it slow: the triangles nearest to it are enough + std::nth_element( triangles.begin(), triangles.begin() + off_track_triangles, triangles.end(), + [ &position ]( auto const &Left, auto const &Right ) { + auto const distance = [ &position ]( auto const &Triangle ) { + auto const middle { ( Triangle[ 0 ] + Triangle[ 1 ] + Triangle[ 2 ] ) / 3.0 }; + return std::max( std::abs( middle.x - position.x ), std::abs( middle.z - position.z ) ); }; + return distance( Left ) < distance( Right ); } ); + triangles.resize( off_track_triangles ); + ErrorLog( std::format( "derailment: warning: {} found more than {} triangles of terrain around it, took the nearest", MoverParameters->Name, off_track_triangles ) ); + } + if( triangles.empty() ) { + // a scenery without terrain: level with the top of the ballast + m_offtrackterrain.reset(); + } + else { + m_offtrackterrain = std::make_shared( triangles, m_offtrackmin, m_offtrackmax ); + // the vehicles sliding over it take it as it is; the nearest triangles of a dense scenery are its own + if( false == trimmed ) { + simulation::Vehicles.share_off_track_terrain( m_offtrackterrain ); + } + } + m_offtracksite.terrain( m_offtrackterrain.get() ); + auto const took { seconds_since( started ) }; + if( took > off_track_slow ) { + ErrorLog( std::format( "derailment: warning: gathering the terrain of {:.0f} m around {} took {:.0f} ms ({} triangles)", reach, MoverParameters->Name, took * 1000.0, triangles.size() ) ); + } +} + +void TDynamicObject::crop_off_track_terrain() { + + if( m_offtrackcropped || m_offtrackterrain == nullptr ) { + return; + } + m_offtrackcropped = true; + // the ground under it, and as far around as it gathers the terrain anew once it moves again + auto const &position { MoverParameters->OffTrack.current().position }; + auto const reach { 0.5 * MoverParameters->Dim.L + 40.0 }; + m_offtrackmin = glm::dvec2 { position.x - reach, position.z - reach }; + m_offtrackmax = glm::dvec2 { position.x + reach, position.z + reach }; + m_offtrackterrain = std::make_shared( m_offtrackterrain->cropped( m_offtrackmin, m_offtrackmax ) ); + m_offtracksite.terrain( m_offtrackterrain.get() ); +} + +void TDynamicObject::begin_off_track() { + + auto &mover { *MoverParameters }; + derail_motion::vehicle_shape shape; + shape.length = mover.Dim.L; + shape.width = mover.Dim.W > 0.5 ? mover.Dim.W : 3.0; + // a height up to 2 m in the definition is the height of the floor, the older meaning of the key + shape.height = mover.Dim.H > 2.0 ? mover.Dim.H : 4.0; + shape.centre_of_gravity = mover.centre_of_gravity(); + shape.contact_spacing = derailment::contact_spacing( mover.TrackW ); + shape.base = std::max( static_cast( fAxleDist ), 1.0 ); + shape.mass = mover.TotalMass; + + derail_motion::start start; + start.position = vPosition; + start.front = vFront; + start.line = track_front(); + start.speed = mover.V; + start.reason = mover.DerailCause; + start.outward = ( mover.DerailSide != 0 ? mover.DerailSide : outward_side() ); + start.acceleration = mover.DerailAcceleration; + + // the terrain as far as it may slide, and some + m_offtracktotal = 0.0; + gather_off_track_terrain(); + m_offtracksite = derail_motion::site { m_offtrackterrain.get(), track_bed() }; + // each vehicle its own way of going off, from the seed of the run (the same seed, the same way) + auto const scatter { derail_motion::draw_scatter( derail_motion::seed_of( Global.random_seed, mover.Name ) ) }; + mover.OffTrack.begin( start, shape, m_offtracksite, scatter ); + m_pulledoff = {}; + m_offtracklogdue = 0.0; + m_offtrackslowdue = 0.0; + m_offtrackaxles = 0.0; + m_offtrackfrom = mover.OffTrack.current().position; + + auto const heading { mover.OffTrack.heading() }; + auto const front { glm::dvec3 { vFront.x, 0.0, vFront.z } }; + auto const turn { std::asin( std::clamp( glm::dot( heading, level_left_of( glm::normalize( front ) ) ), -1.0, 1.0 ) ) }; + std::string terrain { "no terrain, level ground" }; + if( m_offtrackterrain != nullptr ) { + terrain = std::format( "{} triangles of terrain", m_offtrackterrain->size() ); + } + WriteLog( std::format( + "derailment: {} leaves the track at {:.0f} km/h on track {}, heading turned {:.1f} deg to the {}, the outside of the curve to the {}; {} around it", + mover.Name, std::abs( mover.V ) * 3.6, MyTrack != nullptr ? MyTrack->name() : std::string { "(none)" }, + std::abs( glm::degrees( turn ) ), side_name( turn >= 0.0 ? 1 : -1 ), side_name( start.outward ), terrain ) ); + WriteLog( std::format( + "derailment: {} scattered by {:+.2f} deg of departure, {:+.2f} deg of yaw at {:+.3f} rad/s, the friction under its ends x{:.2f} / x{:.2f}{}", + mover.Name, glm::degrees( scatter.departure ), glm::degrees( scatter.yaw ), scatter.yaw_rate, scatter.friction_front, scatter.friction_rear, + scatter.dig_in >= 0.0 ? std::format( ", its leading end digs in after {:.2f} s, x{:.2f} for {:.2f} s", scatter.dig_in, scatter.dig_in_friction, scatter.dig_in_time ) : std::string {} ) ); +} + +void TDynamicObject::move_off_track( double const Distance ) { + + auto const started { off_track_clock::now() }; + auto &motion { MoverParameters->OffTrack }; + auto const time { std::exchange( m_offtracktime, 0.0 ) }; + m_offtracktotal += time; + // near the edge of the terrain gathered, the terrain further on; not more than once a second, whatever happens + if( m_offtrackterrain != nullptr && Distance != 0.0 && m_offtracktotal - m_offtrackgathered >= 1.0 ) { + auto const &position { motion.current().position }; + constexpr double margin { 30.0 }; + if( position.x - margin < m_offtrackmin.x || position.x + margin > m_offtrackmax.x + || position.z - margin < m_offtrackmin.y || position.z + margin > m_offtrackmax.y ) { + gather_off_track_terrain(); + } + } + m_offtracksite.bed( track_bed() ); + // the buffers and the couplings of its ends push and pull it, at an angle to it where the vehicle coupled there is + std::array ends {}; + for( int end = end::front; end <= end::rear; ++end ) { + auto const *neighbour { MoverParameters->Neighbours[ end ].vehicle }; + auto const compression { compression_of( *MoverParameters, end ) }; + if( neighbour == nullptr || compression == 0.0 ) { + continue; + } + ends[ end ] = derail_motion::force_on( + derail_motion::meet( end_point_of( *this, end ), end_point_of( *neighbour, MoverParameters->Neighbours[ end ].vehicle_end ) ), compression ); + } + auto const reversals { motion.reversals() }; + motion.step( time, Distance, MoverParameters->V, m_offtracksite, ends ); + if( ( motion.reversals() - reversals ) % 2 != 0 ) { + // the body turned about against the way it goes: the vehicle goes rear first, its speed the other way along it + MoverParameters->V = -MoverParameters->V; + } + auto const &pose { motion.current() }; + // the axles go along the track as far as the vehicle went along it, for the track nearest to it: the vehicles on it + // find it there, the events of the track are passed. by 10 cm at least: a body turning or rocking in place moves + // the axles back and forth by millimetres, which over the end of a track would fire its events every frame. from + // where it was the last time, so the moves out of the other bodies between the frames go into the axles too + m_offtrackaxles += glm::dot( pose.position - std::exchange( m_offtrackfrom, pose.position ), track_front() ); + if( std::abs( m_offtrackaxles ) >= 0.1 ) { + move_axles( std::exchange( m_offtrackaxles, 0.0 ) ); + } + + place_off_track(); + if( motion.at_rest() ) { + crop_off_track_terrain(); + } + + pull_neighbours( Distance ); + + // what it cost: a frame of the vehicle off the track should take well under a millisecond + auto const took { seconds_since( started ) }; + m_offtrackslowdue -= time; + if( took > off_track_slow && m_offtrackslowdue <= 0.0 ) { + m_offtrackslowdue = 1.0; + ErrorLog( std::format( "derailment: warning: moving {} off the track took {:.0f} ms in a frame of {:.3f} s", MoverParameters->Name, took * 1000.0, time ) ); + } +} + +void TDynamicObject::place_off_track() { + + auto const &pose { MoverParameters->OffTrack.current() }; + vPosition = pose.position; + vFront = pose.front; + vLeft = pose.left; + vUp = pose.up; + modelRot.z = std::atan2( -vFront.x, vFront.z ); + mMatrix = glm::inverse( BasisChange( vLeft, vUp, vFront ) ); + auto const half { 0.5 * MoverParameters->Dim.L * vFront }; + vCoulpler[ end::front ] = vPosition + half; + vCoulpler[ end::rear ] = vPosition - half; + m_offtrackplaced = true; +} + +void TDynamicObject::pull_neighbours( double const Distance ) { + + for( int end = end::front; end <= end::rear; ++end ) { + auto const &coupler { MoverParameters->Couplers[ end ] }; + auto *neighbour { MoverParameters->Neighbours[ end ].vehicle }; + if( coupler.CouplingFlag == coupling::faux || neighbour == nullptr || neighbour->MoverParameters->OffTrack.active() + || TestFlag( neighbour->MoverParameters->DamageFlag, dtrain_out ) ) { + m_pulledoff[ end ].reset(); + continue; + } + auto &other { *neighbour->MoverParameters }; + auto const otherend { MoverParameters->Neighbours[ end ].vehicle_end }; + glm::dvec3 const otherfront { neighbour->vFront.x, 0.0, neighbour->vFront.z }; + if( glm::length( otherfront ) < 1e-6 ) { + continue; + } + // the coupling pulls the end of the other vehicle towards the beam of this one, the buffers push it along the + // bisector of the bend between them: at an angle to its axis, the part across it on its leading wheels + auto const compression { compression_of( other, otherend ) }; + auto const force { derail_motion::force_on( derail_motion::meet( end_point_of( *neighbour, otherend ), end_point_of( *this, end ) ), compression ).force }; + auto const axis { glm::normalize( otherfront ) }; + auto const across { glm::dot( force, level_left_of( axis ) ) }; + auto const angle { std::atan2( std::abs( across ), std::abs( glm::dot( force, axis ) ) ) }; + auto const magnitude { glm::length( glm::dvec3 { force.x, 0.0, force.z } ) }; + auto const mass { other.TotalMass - other.Mred }; + auto const ratio { derail_motion::pull_ratio( magnitude, angle, mass, other.NAxles ) }; + if( false == m_pulledoff[ end ].update( ratio >= derailment::climbing_limit, Distance ) ) { + continue; + } + // the way the force across it goes: towards this one pulled, away from it pushed + auto const side { across >= 0.0 ? 1 : -1 }; + other.pull_off( + side, + mass > 0.0 ? std::abs( across ) / mass : 0.0, + std::format( "Y/Q {:.2f} from the {} of {} at {:.0f} deg, {:.0f} kN", ratio, compression > 0.0 ? "buffers" : "coupling", MoverParameters->Name, glm::degrees( angle ), magnitude / 1000.0 ) ); + m_pulledoff[ end ].reset(); + } +} + +void TDynamicObject::update_off_track( double const Deltatime ) { + + auto const &motion { MoverParameters->OffTrack }; + if( false == motion.active() || m_offtracklogdue < 0.0 ) { + // on the track, or came to rest and told so + return; + } + m_offtracklogdue -= Deltatime; + auto const resting { motion.at_rest() }; + if( m_offtracklogdue > 0.0 && false == resting ) { + return; + } + m_offtracklogdue = ( resting ? -1.0 : 1.0 ); + WriteLog( std::format( + "derailment: {} {} {:.1f} m from where it left the rails, {:.1f} m from the axis of the track, at {:.1f} km/h, sliding sideways at {:.1f} m/s, tipped {:.0f} deg, roll {:.0f} deg, yaw {:+.1f} deg turning at {:+.1f} deg/s{}", + MoverParameters->Name, resting ? "came to rest" : "off the track", motion.travelled(), off_track_offset(), std::abs( MoverParameters->V ) * 3.6, motion.sideways(), + glm::degrees( motion.tipping() ), glm::degrees( motion.roll() ), glm::degrees( motion.yaw() ), glm::degrees( motion.yaw_rate() ), motion.lying() ? ", lying on its side" : "" ) ); +} void TDynamicObject::AttachNext(TDynamicObject *Object, int iType) { // Ra: doczepia Object na końcu składu (nazwa funkcji może być myląca) @@ -3268,9 +3746,52 @@ bool TDynamicObject::Update(double dt, double dt1) { if (dt1 == 0.0) return true; // Ra: pauza + // physics.derailment new: all of the update of a vehicle off the track, timed; a warning once a second at most when it + // takes long, to find what makes a derailment slow + // (no vehicle when it is on the track: nothing is timed then) + class off_track_watch { + public: + off_track_watch( TDynamicObject *Vehicle, double const Frame ) : + vehicle { Vehicle }, frame { Frame } { + if( vehicle != nullptr ) { + started = off_track_clock::now(); + } + } + off_track_watch( off_track_watch const & ) = delete; + off_track_watch &operator=( off_track_watch const & ) = delete; + ~off_track_watch() { + if( vehicle == nullptr ) { + return; + } + auto const took { seconds_since( started ) }; + vehicle->m_offtrackupdatedue -= frame; + if( took > off_track_slow && vehicle->m_offtrackupdatedue <= 0.0 ) { + vehicle->m_offtrackupdatedue = 1.0; + ErrorLog( std::format( "derailment: warning: the update of {} off the track took {:.0f} ms in a frame of {:.3f} s", vehicle->MoverParameters->Name, took * 1000.0, frame ) ); + } + } + private: + TDynamicObject *vehicle; + double frame; + off_track_clock::time_point started {}; + }; + off_track_watch const watch { MoverParameters->OffTrack.active() ? this : nullptr, dt1 }; + if( m_offtrackterrain != nullptr && false == MoverParameters->OffTrack.active() ) { + // physics.derailment new: back on the rails (rerail()), the terrain it slid over is let go + m_offtrackterrain.reset(); + m_offtracksite.terrain( nullptr ); + } if (!MoverParameters->PhysicActivation && - !MechInside) // to drugie, bo będąc w maszynowym blokuje się fizyka + !MechInside) { // to drugie, bo będąc w maszynowym blokuje się fizyka + // physics.derailment new: a vehicle off the track stopped along its heading still settles: it slides down a + // slope, falls over, or comes to rest after the step its physics stopped in + if( MoverParameters->OffTrack.active() && false == MoverParameters->OffTrack.at_rest() && bEnabled ) { + m_offtracktime = dt1; + Move( 0.0 ); + update_off_track( dt1 ); + } return true; // McZapkie: wylaczanie fizyki gdy nie potrzeba + } if (!MyTrack) return false; // pojazdy postawione na torach portalowych mają MyTrack==NULL if (!bEnabled) @@ -3786,8 +4307,14 @@ bool TDynamicObject::Update(double dt, double dt1) // TBD: place the meter on mover logic level? simulation::Train->add_distance( dDOMoveLen ); } + // physics.derailment new: derailed, the vehicle leaves the track and goes on the ground + if( MoverParameters->leaves_track() ) { + begin_off_track(); + } + m_offtracktime = dt1; glm::dvec3 old_pos = vPosition; Move(dDOMoveLen); + update_off_track( dt1 ); m_future_movement = (vPosition - old_pos) / dt1 * Timer::GetDeltaRenderTime(); @@ -5328,6 +5855,18 @@ void TDynamicObject::RenderSounds() { MoverParameters->SoundFlag = 0; // McZapkie! - koniec obslugi dzwiekow z mover.pas + // physics.derailment new: off the track the vehicle scrapes along the ground until it stops, or until it is put back + // on the rails (rerail()) while still sliding + if( MoverParameters->OffTrack.active() && false == MoverParameters->OffTrack.at_rest() ) { + if( false == rsDerailment.is_playing() ) { + rsDerailment.play( sound_flags::exclusive | sound_flags::looping ); + } + m_offtrackscraping = true; + } + else if( std::exchange( m_offtrackscraping, false ) && rsDerailment.is_playing() ) { + rsDerailment.stop(); + } + // special events if( MoverParameters->EventFlag ) { // McZapkie: w razie wykolejenia @@ -7842,6 +8381,11 @@ TDynamicObject::update_neighbours() { // neighbour.vehicle = coupler.Connected; // neighbour.vehicle_end = coupler.ConnectedNr; neighbour.distance = TMoverParameters::CouplerDist( MoverParameters, coupler.Connected ); + if( MoverParameters->OffTrack.active() || neighbour.vehicle->MoverParameters->OffTrack.active() ) { + // physics.derailment new: off the track the bodies turn against each other, the ends meet where they are + // (the distance between the middles less the half lengths would press the buffers of a bent pair) + neighbour.distance = off_track_gap( end ); + } // take into account potential adapters attached to the couplers auto const &othercoupler { neighbour.vehicle->MoverParameters->Couplers[ neighbour.vehicle_end ] }; neighbour.distance -= coupler.adapter_length; @@ -7853,7 +8397,9 @@ TDynamicObject::update_neighbours() { neighbour = neighbour_data(); // 10m ~= 140 km/h at 4 fps + safety margin, potential distance between outer axles of involved vehicles auto const scanrange { std::max( 10.0, std::abs( MoverParameters->V ) ) + 40.0 }; - auto const lookup { find_vehicle( end, scanrange ) }; + // physics.derailment new: a vehicle off the track beside the other one doesn't run into it, the scan goes on + // past it to the vehicles beyond + auto const lookup { find_vehicle( end, scanrange, true ) }; if( false == std::get( lookup ) ) { continue; } @@ -7865,6 +8411,10 @@ TDynamicObject::update_neighbours() { && neighbour.distance < (neighbour.vehicle->MoverParameters->CategoryFlag == 2 ? 50 : 100) ) { // at short distances (re)calculate range between couplers directly neighbour.distance = TMoverParameters::CouplerDist( MoverParameters, neighbour.vehicle->MoverParameters ); + if( MoverParameters->OffTrack.active() || neighbour.vehicle->MoverParameters->OffTrack.active() ) { + // physics.derailment new: the ends where they are, as for a coupled pair + neighbour.distance = off_track_gap( end ); + } // take into account potential adapters attached to the couplers auto const &othercoupler { neighbour.vehicle->MoverParameters->Couplers[ neighbour.vehicle_end ] }; neighbour.distance -= coupler.adapter_length; @@ -7874,10 +8424,20 @@ TDynamicObject::update_neighbours() { } } +bool +TDynamicObject::in_line_with( TDynamicObject const &Other ) const { + + // the middle of the other one off the axis of this one, and this one off the axis of the other one, by less than + // the half widths of both: their ends can meet + auto const reach { 0.5 * ( MoverParameters->Dim.W + Other.MoverParameters->Dim.W ) }; + auto const apart { Other.vPosition - vPosition }; + return std::abs( glm::dot( apart, vLeft ) ) < reach && std::abs( glm::dot( apart, Other.vLeft ) ) < reach; +} + // locates potential collision source within specified range, scanning track in specified direction. returns: true if neighbour was located, false otherwise // NOTE: reuses legacy code. TBD, TODO: review, refactor? std::tuple -TDynamicObject::find_vehicle( int const Direction, double const Distance ) const { +TDynamicObject::find_vehicle( int const Direction, double const Distance, bool const InLine ) const { auto direction { ( Direction == end::front ? 1 : -1 ) }; auto const initialdirection { direction }; // zapamiętanie kierunku poszukiwań na torze początkowym, względem sprzęgów @@ -7892,7 +8452,7 @@ TDynamicObject::find_vehicle( int const Direction, double const Distance ) const auto const mycoupler { ( initialdirection < 0 ? end::rear : end::front ) }; // numer sprzęgu do podłączenia w obiekcie szukajacym auto foundcoupler { -1 }; // numer sprzęgu w znalezionym obiekcie (znaleziony wypełni) auto distance { 0.0 }; // przeskanowana odleglość; odległość do zawalidrogi - auto *foundobject { ABuFindObject( foundcoupler, distance, track, direction, mycoupler ) }; // zaczynamy szukać na tym samym torze + auto *foundobject { ABuFindObject( foundcoupler, distance, track, direction, mycoupler, InLine ) }; // zaczynamy szukać na tym samym torze if( foundobject == nullptr ) { // jeśli nie ma na tym samym, szukamy po okolicy szukanie najblizszego toru z jakims obiektem @@ -7929,7 +8489,7 @@ TDynamicObject::find_vehicle( int const Direction, double const Distance ) const } if (track) { // jesli jest kolejny odcinek toru - foundobject = ABuFindObject(foundcoupler, distance, track, direction, mycoupler); // przejrzenie pojazdów tego toru + foundobject = ABuFindObject(foundcoupler, distance, track, direction, mycoupler, InLine); // przejrzenie pojazdów tego toru if (foundobject) { break; } @@ -9161,6 +9721,8 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { auto const totaltime { Deltatime * Iterationcount }; // całkowity czas + update_off_track_contacts( totaltime ); + for( auto *vehicle : m_items ) { // Ra 2015-01: tylko tu przelicza sieć trakcyjną vehicle->Update( Deltatime, totaltime ); @@ -9177,6 +9739,216 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { } } +namespace { + +// the body of the vehicle as it stands, for the contacts: off the track by its motion, on the track upright on it +derail_motion::footprint footprint_of( TDynamicObject const &Vehicle ) { + + auto const &mover { *Vehicle.MoverParameters }; + derail_motion::pose pose; + if( mover.OffTrack.active() ) { + pose = mover.OffTrack.current(); + } + else { + pose.position = Vehicle.GetPosition(); + pose.front = Vehicle.VectorFront(); + pose.left = Vehicle.VectorLeft(); + pose.up = Vehicle.VectorUp(); + } + auto const &shape { mover.OffTrack.shape() }; + return derail_motion::footprint_of( + pose, mover.Dim.L, + mover.OffTrack.active() ? shape.width : ( mover.Dim.W > 0.5 ? mover.Dim.W : 3.0 ), + mover.OffTrack.active() ? shape.height : ( mover.Dim.H > 2.0 ? mover.Dim.H : 4.0 ) ); +} + +// the vehicle as a body in a contact +derail_motion::contact_body contact_body_of( TDynamicObject const &Vehicle ) { + + auto const &mover { *Vehicle.MoverParameters }; + derail_motion::contact_body body; + body.mass = mover.TotalMass; + if( mover.OffTrack.active() ) { + body.base = mover.OffTrack.base(); + body.velocity = mover.OffTrack.velocity(); + body.yaw_rate = mover.OffTrack.yaw_rate(); + body.gyration = mover.OffTrack.gyration(); + } + else { + // on the rails it goes along them only + glm::dvec3 const front { Vehicle.VectorFront().x, 0.0, Vehicle.VectorFront().z }; + auto const length { glm::length( front ) }; + body.guided = true; + body.guide = length > 1e-6 ? front / length : glm::dvec3 { 0.0, 0.0, 1.0 }; + body.base = Vehicle.GetPosition(); + body.velocity = body.guide * mover.V; + } + return body; +} + +// how the two came to overlap, for the log +std::string_view overlap_kind( TDynamicObject const &First, TDynamicObject const &Second ) { + + auto const offtrack { First.MoverParameters->OffTrack.active() && Second.MoverParameters->OffTrack.active() }; + for( int end = end::front; end <= end::rear; ++end ) { + if( First.MoverParameters->Couplers[ end ].Connected == Second.MoverParameters + && First.MoverParameters->Couplers[ end ].CouplingFlag != coupling::faux ) { + return offtrack ? "coupled, both off the track" : "coupled, one on the rails"; + } + if( First.MoverParameters->Neighbours[ end ].vehicle == &Second ) { + return offtrack ? "neighbours, both off the track" : "neighbours, one on the rails"; + } + } + return offtrack ? "not neighbours, both off the track" : "not neighbours, one on the rails"; +} + +} // namespace + +void +vehicle_table::update_off_track_contacts( double const Deltatime ) { + + if( Global.derailment != global_settings::derailment_model::physical || Deltatime <= 0.0 ) { + return; + } + // by their places in the table: the order the pairs are taken in is the same in every run + std::vector offtrack; + for( std::size_t index = 0; index < m_items.size(); ++index ) { + if( m_items[ index ]->bEnabled && m_items[ index ]->MoverParameters->OffTrack.active() ) { + offtrack.push_back( index ); + } + } + if( offtrack.empty() ) { + return; + } + auto const started { off_track_clock::now() }; + auto deepest { 0.0 }; + std::string deepestpair; + auto resting { true }; + for( auto const place : offtrack ) { + auto *vehicle { m_items[ place ] }; + resting = resting && vehicle->MoverParameters->OffTrack.at_rest(); + auto const print { footprint_of( *vehicle ) }; + auto const reach { std::hypot( print.half_length, print.half_width ) }; + for( std::size_t otherplace = 0; otherplace < m_items.size(); ++otherplace ) { + auto *other { m_items[ otherplace ] }; + if( otherplace == place || false == other->bEnabled ) { + continue; + } + // each pair of two off the track once + auto const otheroff { other->MoverParameters->OffTrack.active() }; + if( otheroff && otherplace < place ) { + continue; + } + // the bounding circles first + auto const apart { other->GetPosition() - vehicle->GetPosition() }; + auto const otherreach { 0.5 * other->MoverParameters->Dim.L + std::max( other->MoverParameters->Dim.W, other->MoverParameters->Dim.H ) }; + if( glm::length( glm::dvec3 { apart.x, 0.0, apart.z } ) > reach + otherreach + 1.0 ) { + continue; + } + auto const otherprint { footprint_of( *other ) }; + auto const hit { derail_motion::collide( print, otherprint ) }; + if( false == hit.has_value() ) { + continue; + } + if( hit->depth > deepest ) { + deepest = hit->depth; + deepestpair = std::format( "{} and {}, {}", vehicle->MoverParameters->Name, other->MoverParameters->Name, overlap_kind( *vehicle, *other ) ); + } + auto const body { contact_body_of( *vehicle ) }; + auto const otherbody { contact_body_of( *other ) }; + auto const impulse { derail_motion::contact_impulse( *hit, body, otherbody ) }; + // the one off the track: kicked, and moved out of the other one (half of the way when both are off it) + auto const [ velocity, yawrate ] { derail_motion::impulse_change( body, -impulse, hit->point ) }; + auto &motion { vehicle->MoverParameters->OffTrack }; + auto const share { otheroff ? 0.5 : 1.0 }; + auto const correction { derail_motion::contact_correction * std::max( 0.0, hit->depth - derail_motion::contact_slop ) }; + if( glm::length( impulse ) > 0.0 ) { + motion.kick( velocity, yawrate ); + vehicle->MoverParameters->V = motion.speed(); + } + if( correction > 0.0 ) { + motion.nudge( -hit->normal * ( share * correction ) ); + vehicle->place_off_track(); + } + if( otheroff ) { + auto const [ othervelocity, otheryawrate ] { derail_motion::impulse_change( otherbody, impulse, hit->point ) }; + auto &othermotion { other->MoverParameters->OffTrack }; + if( glm::length( impulse ) > 0.0 ) { + othermotion.kick( othervelocity, otheryawrate ); + other->MoverParameters->V = othermotion.speed(); + } + if( correction > 0.0 ) { + othermotion.nudge( hit->normal * ( share * correction ) ); + other->place_off_track(); + } + continue; + } + // one on the rails: along them into its speed, across them on its wheels, as a coupling pulls them off + auto &othermover { *other->MoverParameters }; + othermover.V += glm::dot( impulse, otherbody.guide ) / std::max( othermover.TotalMass, 1.0 ); + if( TestFlag( othermover.DamageFlag, dtrain_out ) ) { + continue; + } + glm::dvec3 const otherleft { otherbody.guide.z, 0.0, -otherbody.guide.x }; + auto const across { glm::dot( impulse, otherleft ) / Deltatime }; + auto const mass { othermover.TotalMass - othermover.Mred }; + auto const ratio { derail_motion::pull_ratio( std::abs( across ), 0.5 * std::numbers::pi, mass, othermover.NAxles ) }; + // held over the window of the climbing as the bodies slide along each other, or a hit three times as hard + // at once: the wheels jump the rail + auto const sliding { glm::length( derail_motion::velocity_at( body, hit->point ) - otherbody.velocity ) * Deltatime }; + if( other->m_struck.update( ratio >= derailment::climbing_limit, sliding ) || ratio >= 3.0 * derailment::climbing_limit ) { + othermover.pull_off( + across >= 0.0 ? 1 : -1, + mass > 0.0 ? std::abs( across ) / mass : 0.0, + std::format( "Y/Q {:.2f} from {} running into it, {:.0f} kN across", ratio, vehicle->MoverParameters->Name, std::abs( across ) / 1000.0 ) ); + other->m_struck.reset(); + } + } + } + // the log: every second the most the bodies overlapped by, once more when all of them are at rest + if( deepest > m_overlapmost ) { + m_overlapmost = deepest; + m_overlappair = deepestpair; + } + m_overlapdue -= Deltatime; + if( ( m_overlapdue <= 0.0 && false == resting ) || ( resting && false == m_overlaplogged ) ) { + WriteLog( std::format( + "derailment: the bodies overlap by up to {:.2f} m{} over the last second, {:.2f} m now{}", + m_overlapmost, m_overlapmost > 0.0 ? " (" + m_overlappair + ")" : std::string {}, deepest, resting ? ", all at rest" : "" ) ); + m_overlapmost = 0.0; + m_overlappair.clear(); + m_overlapdue = 1.0; + m_overlaplogged = resting; + } + if( false == resting ) { + m_overlaplogged = false; + } + auto const took { seconds_since( started ) }; + if( took > off_track_slow ) { + ErrorLog( std::format( "derailment: warning: the contacts of {} vehicles off the track took {:.0f} ms", offtrack.size(), took * 1000.0 ) ); + } +} + +std::shared_ptr +vehicle_table::off_track_terrain( glm::dvec2 const &Min, glm::dvec2 const &Max ) { + + std::erase_if( m_offtrackterrains, []( auto const &Terrain ) { return Terrain.expired(); } ); + for( auto const &terrain : m_offtrackterrains ) { + if( auto shared { terrain.lock() }; shared != nullptr && shared->covers( Min, Max ) ) { + return shared; + } + } + return {}; +} + +void +vehicle_table::share_off_track_terrain( std::shared_ptr const &Terrain ) { + + if( Terrain != nullptr ) { + m_offtrackterrains.emplace_back( Terrain ); + } +} + // the air exchange through the brake and main reservoir hoses of the vehicles which stepped their physics, after all of them did void vehicle_table::update_brake_pipes( double const Deltatime ) { diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index 4db7d32c3..98b639a08 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -25,6 +25,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/doorwings.h" #include "scripting/scriptscreenrules.h" +#include #include #include @@ -200,6 +201,7 @@ class TDynamicObject { // klasa pojazdu friend opengl_renderer; friend opengl33_renderer; + friend class vehicle_table; public: static bool bDynamicRemove; // moved from ground @@ -654,7 +656,7 @@ private: std::string asModel; private: - TDynamicObject *ABuFindObject( int &Foundcoupler, double &Distance, TTrack const *Track, int const Direction, int const Mycoupler ) const; + TDynamicObject *ABuFindObject( int &Foundcoupler, double &Distance, TTrack const *Track, int const Direction, int const Mycoupler, bool const InLine = false ) const; void ABuCheckMyTrack(); std::string rTypeName; // nazwa typu pojazdu @@ -749,6 +751,61 @@ private: bool FastUpdate(double dt); void Move(double fDistance); void FastMove(double fDistance); + // physics.derailment new, the vehicle off the track (vehicle/derailmotion.h): the offset of its body from the axis of + // the track at the place nearest to it, to the left of its front positive [m]; 0 while it's on the track + double off_track_offset() const; + // the gap between the ends of the vehicle and the one at its End, as they meet off the track [m]: negative the + // buffers pressed in + double off_track_gap( int End ) const; +private: + // the axles moved along their tracks by the distance + void move_axles( double Distance ); + // the vehicle placed on the track by its axles + void place_by_axles(); + // the vehicle leaves the track: its motion on the ground begun, with the terrain around it + void begin_off_track(); + // the vehicle off the track moved on the ground, by the distance along its heading, in the time of the frame + void move_off_track( double Distance ); + // the terrain of the scenery around the vehicle off the track, as far as it may slide, for the ground under it: the + // one gathered for another vehicle where it covers that, gathered anew where it doesn't + void gather_off_track_terrain(); + // at rest it keeps only the terrain under it, the rest of what was gathered (shared with others, perhaps) let go + void crop_off_track_terrain(); + // the bed of the track at the axles, the level direction of the track there, and the side the derailment throws the + // vehicle to (1 the left of the front, -1 the right, 0 none): out of the curve of the track as designed, into it + // where a buckle bends the line the other way more (McZapkie/derailment.h); on a straight track out of the turn of + // the path as it lies, a buckle on it + derail_motion::formation track_bed() const; + glm::dvec3 track_front() const; + int outward_side() const; + // the couplings of this vehicle off the track pull the vehicles coupled to it off the rails sideways, the step + // having travelled the distance + void pull_neighbours( double Distance ); + // the scraping of the vehicle off the track, until it stops, and its state to the log every second + void update_off_track( double Deltatime ); + + std::shared_ptr m_offtrackterrain; // none in a scenery without terrain + glm::dvec2 m_offtrackmin { 0.0 }; // what the terrain was gathered for + glm::dvec2 m_offtrackmax { 0.0 }; + bool m_offtrackcropped { false }; // the terrain cut down to the one under it at rest + derail_motion::site m_offtracksite; + double m_offtracktime { 0.0 }; // of the frame, for the motion + double m_offtracklogdue { 0.0 }; + double m_offtracktotal { 0.0 }; // the time off the track [s] + double m_offtrackgathered { 0.0 }; // the time the terrain was gathered at [s] + double m_offtrackslowdue { 0.0 }; // till another warning of a slow frame [s] + double m_offtrackupdatedue { 0.0 }; // and of a slow update + double m_offtrackaxles { 0.0 }; // the move along the track the axles didn't make yet [m] + glm::dvec3 m_offtrackfrom { 0.0 }; // where the body was when its move went into the axles last + bool m_offtrackscraping { false }; // the scraping of the vehicle off the track plays, looped + // the most triangles of terrain taken around the vehicle off the track + static constexpr std::size_t off_track_triangles { 400000 }; + bool m_offtrackplaced { false }; // placed off the track: placed on it again once it's back on the rails + std::array m_pulledoff; // the distance the coupling of an end pulled the vehicle coupled there over the climbing limit + derailment::stretch m_struck; // on the rails: the distance a body off the track pushed it sideways over the climbing limit + // the model, the axes and the coupling points placed by the motion off the track + void place_off_track(); +public: void RenderSounds(); // plays the sounds of the mirrors on the Side, of the occupied cab, starting the Event void play_mirror_sounds( side const Side, mirror_moves::event const Event ); @@ -852,8 +909,12 @@ private: TDynamicObject * Neighbour(int &dir); // updates potential collision sources void update_neighbours(); - // locates potential collision source within specified range, scanning its route in specified direction - auto find_vehicle( int const Direction, double const Range ) const -> std::tuple; + // physics.derailment new: the vehicle and the other one, one of them off the track, are in line, close enough + // across to run into each other + bool in_line_with( TDynamicObject const &Other ) const; + // locates potential collision source within specified range, scanning its route in specified direction. InLine: + // physics.derailment new, the scan goes on past a vehicle off the track beside the line (or beside this one off it) + auto find_vehicle( int const Direction, double const Range, bool const InLine = false ) const -> std::tuple; // locates potential vehicle connected with specific coupling type and satisfying supplied predicate template auto find_vehicle( coupling const Coupling, Predicate_ const Predicate ) -> TDynamicObject *; @@ -951,6 +1012,13 @@ public: // records the odometer states of the vehicles and saves them for the next sessions void save_odometers(); + // physics.derailment new: the terrain gathered for a vehicle off the track which covers the rectangle from Min to Max + // (x, z), shared by the vehicles which slide over it; none where no vehicle has one. it lives as long as one of them + // keeps it + std::shared_ptr + off_track_terrain( glm::dvec2 const &Min, glm::dvec2 const &Max ); + void + share_off_track_terrain( std::shared_ptr const &Terrain ); private: // maintenance; removes from tracks consists with vehicles marked as disabled @@ -963,9 +1031,21 @@ private: // the air exchange through the brake and main reservoir hoses of the vehicles which stepped their physics, after all of them did void update_brake_pipes( double const Deltatime ); + // physics.derailment new: the bodies of the vehicles off the track and those near them run into each other instead + // of into one another: the impulses of the hits, the bodies moved apart, a vehicle on the rails pushed off them; + // what the bodies overlap by goes to the log every second + void + update_off_track_contacts( double const Deltatime ); double m_odometersavetimer { 0.0 }; // simulation time since the odometers were last saved + // the most the bodies overlapped by, of the vehicles of update_off_track_contacts(), since it was logged last [m], and + // which ones; till the next line in the log [s]; once all of them came to rest it is logged no more + double m_overlapmost { 0.0 }; + std::string m_overlappair; + double m_overlapdue { 1.0 }; + bool m_overlaplogged { false }; std::vector m_brakepipes; // the vehicles of update_brake_pipes(), kept for the memory + std::vector> m_offtrackterrains; // of off_track_terrain() }; diff --git a/vehicle/blackbox.cpp b/vehicle/blackbox.cpp index fc05f7483..0138b6acd 100644 --- a/vehicle/blackbox.cpp +++ b/vehicle/blackbox.cpp @@ -381,6 +381,22 @@ void writer::coupling(coupling_change const &Change) { emit(record::coupling); } +void writer::derailment(derailment_state const &State) { + auto &out{begin()}; + out.f64(State.time); + out.u32(State.vehicle); + out.u8(State.phase); + out.u8(State.cause); + out.dvec3(State.position); + out.f32(State.heading); + out.f32(State.speed_kmh); + out.f32(State.offset); + out.f32(State.roll); + out.f32(State.travelled); + out.u8(State.lying ? 1 : 0); + emit(record::derailment); +} + void writer::clock(double const Time, std::uint16_t const Year, std::uint16_t const Year_day, double const Second_of_day) { auto &out{begin()}; out.f64(Time); diff --git a/vehicle/blackbox.h b/vehicle/blackbox.h index 55ee06ca3..26fe5c6a1 100644 --- a/vehicle/blackbox.h +++ b/vehicle/blackbox.h @@ -52,6 +52,7 @@ enum class record : std::uint8_t { station = 0x35, horn_request = 0x36, coupling = 0x37, + derailment = 0x38, end = 0x3f }; @@ -324,6 +325,35 @@ struct coupling_change { glm::dvec3 position{0.0}; // of the coupler }; +// what put a vehicle off the rails, for the derailment record (vehicle/derailmotion.h) +namespace derailment_causes { +inline constexpr std::uint8_t flange_climbed{1}; +inline constexpr std::uint8_t overturned{2}; +inline constexpr std::uint8_t end_of_track{3}; +inline constexpr std::uint8_t pulled_off{4}; // by the coupling of a vehicle off the track +inline constexpr std::uint8_t collision{5}; +} // namespace derailment_causes + +namespace derailment_phases { +inline constexpr std::uint8_t left_track{0}; // it left the track +inline constexpr std::uint8_t at_rest{1}; // it came to rest off the track +} // namespace derailment_phases + +// a vehicle off the track (physics.derailment new): as it leaves it, and where it comes to rest +struct derailment_state { + double time{0.0}; + std::uint32_t vehicle{no_vehicle}; + std::uint8_t phase{derailment_phases::left_track}; + std::uint8_t cause{derailment_causes::flange_climbed}; + glm::dvec3 position{0.0}; // of the vehicle + float heading{0.0f}; // [rad] of its front, from +z towards +x + float speed_kmh{0.0f}; // signed: positive along its front + float offset{0.0f}; // [m] from the axis of the track at the place nearest to it, to the left of its front positive + float roll{0.0f}; // [rad] of its body against the level, to the left positive; 90 degrees on its side + float travelled{0.0f}; // [m] on the ground since it left the rails + bool lying{false}; // on its side +}; + struct vehicle_state { std::uint32_t id{no_vehicle}; glm::vec3 position{0.0f}; @@ -378,6 +408,7 @@ public: void horn_request(double Time, std::uint32_t Vehicle, float Duration, float Tone, glm::dvec3 const &Position); void camera(camera_state const &Camera); void coupling(coupling_change const &Change); + void derailment(derailment_state const &State); void vehicle(vehicle_data const &Vehicle); void vehicle_removed(double Time, std::uint32_t Id); void cab(cab_sample const &Sample); diff --git a/vehicle/derailmotion.cpp b/vehicle/derailmotion.cpp new file mode 100644 index 000000000..89b9a1831 --- /dev/null +++ b/vehicle/derailmotion.cpp @@ -0,0 +1,907 @@ +/* +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/derailmotion.h" + +#include "McZapkie/derailment.h" + +#include +#include +#include +#include + +namespace derail_motion { + +namespace { + +glm::dvec3 const world_up{0.0, 1.0, 0.0}; + +// the vector level, of unit length; the fallback for one standing up +glm::dvec3 level(glm::dvec3 const &Vector, glm::dvec3 const &Fallback = {0.0, 0.0, 1.0}) { + glm::dvec3 const flat{Vector.x, 0.0, Vector.z}; + auto const length{glm::length(flat)}; + return length > 1e-9 ? flat / length : Fallback; +} + +// to the left of a level heading, as TDynamicObject has it: up x front +glm::dvec3 left_of(glm::dvec3 const &Front) { + return glm::dvec3{Front.z, 0.0, -Front.x}; +} + +// the vector turned about the axis by the angle, right-handed +glm::dvec3 turned(glm::dvec3 const &Vector, glm::dvec3 const &Axis, double const Angle) { + auto const c{std::cos(Angle)}; + auto const s{std::sin(Angle)}; + return Vector * c + glm::cross(Axis, Vector) * s + Axis * (glm::dot(Axis, Vector) * (1.0 - c)); +} + +double sign_of(double const Value) { + if (Value > 0.0) { + return 1.0; + } + return Value < 0.0 ? -1.0 : 0.0; +} + +// the height of the triangle over the point, if it is over it (in the plan) +std::optional height_in(mesh_ground::triangle const &Triangle, double const X, double const Z) { + auto const &a{Triangle[0]}; + auto const &b{Triangle[1]}; + auto const &c{Triangle[2]}; + auto const determinant{(b.z - c.z) * (a.x - c.x) + (c.x - b.x) * (a.z - c.z)}; + if (std::abs(determinant) < 1e-12) { + // standing on its edge, a wall + return std::nullopt; + } + auto const u{((b.z - c.z) * (X - c.x) + (c.x - b.x) * (Z - c.z)) / determinant}; + auto const v{((c.z - a.z) * (X - c.x) + (a.x - c.x) * (Z - c.z)) / determinant}; + auto const w{1.0 - u - v}; + constexpr double edge{-1e-9}; + if (u < edge || v < edge || w < edge) { + return std::nullopt; + } + return u * a.y + v * b.y + w * c.y; +} + +} // namespace + +namespace { + +// the angle [rad] from the first level direction to the second, to the left positive +double angle_between(glm::dvec3 const &From, glm::dvec3 const &To) { + return std::atan2(glm::dot(To, left_of(From)), glm::dot(To, From)); +} + +// the beams of two ends further apart across than this have gone past each other [m] +constexpr double beam_reach{2.0}; +// nor do they meet pressed into each other deeper than this: the buffers and the ends behind them crushed [m] +constexpr double beam_depth{1.5}; +// the buffers of two ends this far apart along the line between them are apart, the coupling straight between [m] +constexpr double buffer_reach{0.1}; + +} // namespace + +double sliding_friction(double const Tipping, bool const Guided) { + if (Guided) { + return guided_friction; + } + auto const share{std::clamp(std::abs(Tipping) / body::half_turn, 0.0, 1.0)}; + return std::lerp(derailment::off_rails_friction, derailment::overturned_friction, share); +} + +double departure_angle(cause const Cause, double const Speed, double const Acceleration) { + if (Cause == cause::end_of_track || Cause == cause::collision) { + return 0.0; + } + auto const sideways{std::sqrt(2.0 * std::abs(Acceleration) * climb_width)}; + return std::min(most_departure, std::atan2(sideways, std::max(std::abs(Speed), 1.0))); +} + +scatter draw_scatter(std::uint32_t const Seed) { + // the raw numbers of the engine are the same with every library, the distributions of aren't + std::mt19937 engine{Seed}; // NOSONAR: seeded on purpose, so that a derailment can be repeated; nothing secret is drawn + auto const uniform = [&engine](double const Low, double const High) { return Low + (High - Low) * ((static_cast(engine()) + 0.5) / 4294967296.0); }; + scatter result; + result.departure = uniform(-0.01, 0.01); + result.yaw = uniform(-0.02, 0.02); + result.yaw_rate = uniform(-0.02, 0.02); + result.friction_front = uniform(0.85, 1.15); + result.friction_rear = uniform(0.85, 1.15); + auto const bites{uniform(0.0, 1.0) < 2.0 / 3.0}; + auto const when{uniform(0.2, 1.5)}; + auto const howlong{uniform(0.3, 0.8)}; + auto const how{uniform(2.0, 4.0)}; + auto const side{uniform(0.0, 1.0) < 0.5 ? -1 : 1}; + if (bites) { + result.dig_in = when; + result.dig_in_time = howlong; + result.dig_in_friction = how; + result.dig_in_side = side; + } + return result; +} + +std::uint32_t seed_of(std::uint32_t const Run, std::string_view const Name) { + // FNV-1a of the name, mixed with the seed of the run + std::uint32_t hash{2166136261u}; + for (auto const character : Name) { + hash = (hash ^ static_cast(character)) * 16777619u; + } + hash ^= Run + 0x9e3779b9u + (hash << 6) + (hash >> 2); + return hash; +} + +meeting meet(end_point const &First, end_point const &Second) { + meeting result; + auto const outward{level(First.outward)}; + auto const otherward{level(Second.outward, -outward)}; + result.point = First.point; + result.push = level(outward - otherward, outward); + result.bend = angle_between(outward, -otherward); + glm::dvec3 const apart{Second.point.x - First.point.x, 0.0, Second.point.z - First.point.z}; + auto const along{glm::dot(apart, result.push)}; + auto const across{glm::dot(apart, left_of(result.push))}; + auto const distance{glm::length(apart)}; + result.pull = distance > 0.05 ? apart / distance : result.push; + // the ends face each other (bent by less than a right angle) and meet within the depth of the buffers and the ends + // crushed behind them + auto const facing{glm::dot(outward, otherward) < 0.0}; + if (along <= 0.0 && facing && along > -beam_depth && std::abs(across) < beam_reach) { + // the buffers press into each other + result.gap = along; + } + else if (along <= 0.0) { + // the ends went past each other, or one body turned about: only the coupling holds them, stretched + result.gap = distance; + } + else { + // apart, the coupling between the middles of the beams; as they come together, the buffers in line + result.gap = std::hypot(along, across) - std::abs(across) * std::max(0.0, 1.0 - along / buffer_reach); + } + // the buffers of the outer side of a body rolled against the other one lift or drop by its roll + auto const apartinheight{std::abs(Second.point.y - First.point.y) + buffer_half_spacing * std::abs(std::sin(Second.roll - First.roll))}; + result.overlap = std::clamp(1.0 - apartinheight / buffer_head, 0.0, 1.0); + return result; +} + +end_force force_on(meeting const &Meeting, double const Compression) { + end_force result; + result.point = Meeting.point; + if (Compression > 0.0) { + // the inner buffer of the bend takes more of the push, all of it past the play of the buffers; as far as the + // buffers meet in height, and as much of it as a buffer takes, the rest at the middle of the beam + auto const holding{buffer_half_spacing * Meeting.overlap * std::min(1.0, buffer_limit / Compression)}; + result.point += left_of(Meeting.push) * (holding * std::clamp(Meeting.bend / buffer_lock, -1.0, 1.0)); + result.force = -Meeting.push * Compression; + } + else { + result.force = Meeting.pull * (-Compression); + } + return result; +} + +footprint footprint_of(pose const &Pose, double const Length, double const Width, double const Height) { + footprint result; + result.axis = level(Pose.front); + auto const left{left_of(result.axis)}; + result.half_length = std::max(0.5 * Length - buffer_length, 0.5) * std::max(std::hypot(Pose.front.x, Pose.front.z), 0.1); + // the corners of its cross section, from the rails to the roof, as it is rolled + auto low{std::numeric_limits::max()}; + auto high{std::numeric_limits::lowest()}; + auto mostleft{std::numeric_limits::lowest()}; + auto mostright{std::numeric_limits::max()}; + for (auto const across : {-0.5 * Width, 0.5 * Width}) { + for (auto const up : {0.0, Height}) { + auto const corner{Pose.position + Pose.left * across + Pose.up * up}; + auto const aside{glm::dot(corner - Pose.position, left)}; + mostleft = std::max(mostleft, aside); + mostright = std::min(mostright, aside); + low = std::min(low, corner.y); + high = std::max(high, corner.y); + } + } + result.half_width = 0.5 * (mostleft - mostright); + result.centre = glm::dvec3{Pose.position.x, 0.0, Pose.position.z} + left * (0.5 * (mostleft + mostright)); + // pitched, the ends rise and drop by the slope over half its length + auto const rise{std::abs(Pose.front.y) / std::max(std::hypot(Pose.front.x, Pose.front.z), 0.1) * result.half_length}; + result.low = low - rise; + result.high = high + rise; + return result; +} + +namespace { + +// the corners of the footprint, in turn round it +std::array corners_of(footprint const &Print) { + auto const along{Print.axis * Print.half_length}; + auto const across{left_of(Print.axis) * Print.half_width}; + return {Print.centre + along + across, Print.centre + along - across, Print.centre - along - across, Print.centre - along + across}; +} + +// whether the point is inside the footprint (in the plan) +bool inside(footprint const &Print, glm::dvec3 const &Point) { + glm::dvec3 const offset{Point.x - Print.centre.x, 0.0, Point.z - Print.centre.z}; + return std::abs(glm::dot(offset, Print.axis)) <= Print.half_length && std::abs(glm::dot(offset, left_of(Print.axis))) <= Print.half_width; +} + +double cross_up(glm::dvec3 const &Arm, glm::dvec3 const &Force) { + // about the vertical, to the left positive + return Arm.z * Force.x - Arm.x * Force.z; +} + +// the inverse of the mass the body moves with at the point the way of the direction +double inverse_mass(contact_body const &Body, glm::dvec3 const &Point, glm::dvec3 const &Direction) { + if (Body.mass <= 0.0) { + return 0.0; + } + if (Body.guided) { + auto const along{glm::dot(Direction, Body.guide)}; + return along * along / Body.mass; + } + glm::dvec3 const arm{Point.x - Body.base.x, 0.0, Point.z - Body.base.z}; + auto const turning{cross_up(arm, Direction)}; + return (1.0 + turning * turning / std::max(Body.gyration, 1e-3)) / Body.mass; +} + +} // namespace + +std::optional collide(footprint const &First, footprint const &Second) { + if (std::min(First.high, Second.high) - std::max(First.low, Second.low) < height_overlap) { + // one goes over the other + return std::nullopt; + } + // the separating axes: the sides of both rectangles; the one they overlap least across is the way out + auto const first{corners_of(First)}; + auto const second{corners_of(Second)}; + glm::dvec3 const apart{Second.centre.x - First.centre.x, 0.0, Second.centre.z - First.centre.z}; + contact result; + result.depth = std::numeric_limits::max(); + for (auto const &axis : {First.axis, left_of(First.axis), Second.axis, left_of(Second.axis)}) { + auto spread = [&axis](std::array const &Corners) { + auto low{std::numeric_limits::max()}; + auto high{std::numeric_limits::lowest()}; + for (auto const &corner : Corners) { + auto const along{glm::dot(corner, axis)}; + low = std::min(low, along); + high = std::max(high, along); + } + return std::pair{low, high}; + }; + auto const [low1, high1]{spread(first)}; + auto const [low2, high2]{spread(second)}; + auto const overlap{std::min(high1, high2) - std::max(low1, low2)}; + if (overlap <= 0.0) { + return std::nullopt; + } + if (overlap < result.depth) { + result.depth = overlap; + result.normal = glm::dot(apart, axis) >= 0.0 ? axis : -axis; + } + } + // the point: the middle of the corners of each inside the other, or of where the overlap is + glm::dvec3 sum{0.0}; + auto count{0}; + for (auto const &corner : first) { + if (inside(Second, corner)) { + sum += corner; + ++count; + } + } + for (auto const &corner : second) { + if (inside(First, corner)) { + sum += corner; + ++count; + } + } + if (count > 0) { + result.point = sum / static_cast(count); + } + else { + // crossed without a corner inside the other (two long sides across each other): between the middles + result.point = 0.5 * (First.centre + Second.centre); + } + result.point.y = 0.0; + return result; +} + +glm::dvec3 velocity_at(contact_body const &Body, glm::dvec3 const &Point) { + if (Body.guided) { + return Body.velocity; + } + // turning about the vertical at the yaw rate: up x arm + glm::dvec3 const arm{Point.x - Body.base.x, 0.0, Point.z - Body.base.z}; + return Body.velocity + Body.yaw_rate * glm::dvec3{arm.z, 0.0, -arm.x}; +} + +glm::dvec3 contact_impulse(contact const &Contact, contact_body const &First, contact_body const &Second) { + auto const &normal{Contact.normal}; + auto const relative{velocity_at(Second, Contact.point) - velocity_at(First, Contact.point)}; + auto const closing{glm::dot(relative, normal)}; + if (closing >= 0.0) { + // parting already + return glm::dvec3{0.0}; + } + auto const inverse{inverse_mass(First, Contact.point, normal) + inverse_mass(Second, Contact.point, normal)}; + if (inverse <= 0.0) { + return glm::dvec3{0.0}; + } + auto const push{-(1.0 + contact_restitution) * closing / inverse}; + glm::dvec3 result{normal * push}; + // the friction of the sides sliding along each other, no more than stops the sliding + auto const sliding{relative - normal * closing}; + auto const slide{glm::length(sliding)}; + if (slide > 1e-6) { + auto const along{sliding / slide}; + auto const alonginverse{inverse_mass(First, Contact.point, along) + inverse_mass(Second, Contact.point, along)}; + if (alonginverse > 0.0) { + result -= along * std::min(contact_friction * push, slide / alonginverse); + } + } + return result; +} + +std::pair impulse_change(contact_body const &Body, glm::dvec3 const &Impulse, glm::dvec3 const &Point) { + if (Body.mass <= 0.0) { + return {glm::dvec3{0.0}, 0.0}; + } + if (Body.guided) { + return {Body.guide * (glm::dot(Impulse, Body.guide) / Body.mass), 0.0}; + } + glm::dvec3 const arm{Point.x - Body.base.x, 0.0, Point.z - Body.base.z}; + return {glm::dvec3{Impulse.x, 0.0, Impulse.z} / Body.mass, cross_up(arm, Impulse) / (Body.mass * std::max(Body.gyration, 1e-3))}; +} + +std::optional stopping_distance(double const Speed, double const Friction, double const Grade) { + auto const angle{std::atan(Grade)}; + auto const deceleration{gravity * (Friction * std::cos(angle) + std::sin(angle))}; + if (deceleration <= 0.0) { + return std::nullopt; + } + return Speed * Speed / (2.0 * deceleration); +} + +double pull_ratio(double const Force, double const Angle, double const Mass, int const Axles) { + auto const axles{std::max(Axles, 2)}; + auto const load{Mass * gravity / (2.0 * axles)}; + if (load <= 0.0) { + return 0.0; + } + auto const across{std::abs(Force * std::sin(Angle))}; + return across / (0.5 * axles) / load; +} + +// ---- the ground + +std::optional flat_ground::height(double, double, double) const { + return m_level; +} + +mesh_ground::mesh_ground(std::vector const &Triangles, glm::dvec2 const &Min, glm::dvec2 const &Max, double const Cell) : m_min{Min}, m_max{glm::max(Max, Min + glm::dvec2{1.0})}, m_cell{std::max(Cell, 1.0)} { + auto const size{m_max - m_min}; + // a million cells at most + m_cell = std::max(m_cell, std::sqrt(size.x * size.y / 1e6)); + m_columns = static_cast(std::ceil(size.x / m_cell)); + m_rows = static_cast(std::ceil(size.y / m_cell)); + m_cells.resize(m_columns * m_rows); + auto const column = [this](double const X) { return static_cast(std::clamp(std::floor((X - m_min.x) / m_cell), 0.0, static_cast(m_columns - 1))); }; + auto const row = [this](double const Z) { return static_cast(std::clamp(std::floor((Z - m_min.y) / m_cell), 0.0, static_cast(m_rows - 1))); }; + for (auto const &triangle : Triangles) { + auto const low{glm::min(glm::min(triangle[0], triangle[1]), triangle[2])}; + auto const high{glm::max(glm::max(triangle[0], triangle[1]), triangle[2])}; + if (high.x < m_min.x || low.x > m_max.x || high.z < m_min.y || low.z > m_max.y) { + continue; + } + auto const index{m_triangles.size()}; + m_triangles.push_back(triangle); + for (auto r = row(low.z); r <= row(high.z); ++r) { + for (auto c = column(low.x); c <= column(high.x); ++c) { + m_cells[r * m_columns + c].push_back(index); + } + } + } +} + +bool mesh_ground::covers(double const X, double const Z) const { + return X >= m_min.x && X <= m_max.x && Z >= m_min.y && Z <= m_max.y; +} + +bool mesh_ground::covers(glm::dvec2 const &Min, glm::dvec2 const &Max) const { + return Min.x >= m_min.x && Min.y >= m_min.y && Max.x <= m_max.x && Max.y <= m_max.y; +} + +mesh_ground mesh_ground::cropped(glm::dvec2 const &Min, glm::dvec2 const &Max) const { + return mesh_ground{m_triangles, Min, Max, m_cell}; +} + +std::optional mesh_ground::cell_of(double const X, double const Z) const { + if (false == covers(X, Z) || m_cells.empty()) { + return std::nullopt; + } + auto const column{std::min(static_cast((X - m_min.x) / m_cell), m_columns - 1)}; + auto const row{std::min(static_cast((Z - m_min.y) / m_cell), m_rows - 1)}; + return row * m_columns + column; +} + +std::optional mesh_ground::height(double const X, double const Z, double const Ceiling) const { + auto const cell{cell_of(X, Z)}; + if (false == cell.has_value()) { + return std::nullopt; + } + std::optional highest; + for (auto const index : m_cells[*cell]) { + auto const found{height_in(m_triangles[index], X, Z)}; + if (found.has_value() && *found <= Ceiling && (false == highest.has_value() || *found > *highest)) { + highest = found; + } + } + return highest; +} + +double formation::height(double const X, double const Z) const { + auto const across{std::abs(glm::dot(glm::dvec3{X, 0.0, Z} - glm::dvec3{point.x, 0.0, point.z}, left_of(level(direction))))}; + auto const top{point.y - depth}; + if (across <= half_width) { + return top; + } + return top - (across - half_width) / std::max(slope, 0.1); +} + +std::optional site::height(double const X, double const Z, double const Ceiling) const { + auto const bed{m_bed.height(X, Z)}; + std::optional result; + if (m_terrain == nullptr) { + // no terrain: level with the top of the ballast + result = m_bed.point.y - m_bed.depth; + } + else { + result = m_terrain->height(X, Z, Ceiling); + } + if (bed <= Ceiling && (false == result.has_value() || bed > *result)) { + result = bed; + } + return result; +} + +// ---- the vehicle + +void body::begin(start const &Start, vehicle_shape const &Shape, ground const &Ground, scatter const &Scatter) { + *this = body{}; + m_active = true; + m_reason = Start.reason; + m_shape = Shape; + m_scatter = Scatter; + // the body a box turning about its middle + m_yawgyration = std::max((Shape.length * Shape.length + Shape.width * Shape.width) / 12.0, 1.0); + + m_pivot = 0.5 * std::max(Shape.contact_spacing, 0.5); + auto const centre{std::max(Shape.centre_of_gravity, 0.3)}; + m_lever = centre + Shape.flexibility * std::max(0.0, centre - Shape.roll_centre); + m_tipangle = std::atan2(m_pivot, m_lever); + m_reach = std::hypot(m_pivot, m_lever); + // the body a box rolling about its middle, carried over to the wheels it tips about + m_gyration = m_reach * m_reach + (Shape.width * Shape.width + Shape.height * Shape.height) / 12.0; + + m_position = Start.position; + m_origin = Start.position; + m_front = level(Start.front); + m_line = level(Start.line, m_front); + m_speed = Start.speed; + // out of the curve, the way it travels + auto const direction{Start.speed < 0.0 ? -1.0 : 1.0}; + auto turn{Start.outward * direction * departure_angle(Start.reason, Start.speed, Start.acceleration)}; + if (Start.reason != cause::end_of_track && Start.reason != cause::collision) { + turn += Scatter.departure; + } + m_front = level(turned(m_front, world_up, turn), m_front); + m_axis = level(turned(m_front, world_up, Scatter.yaw), m_front); + + if (Start.reason == cause::overturned) { + m_guided = true; + m_outward = Start.outward != 0 ? Start.outward : 1; + m_guideacceleration = std::abs(Start.acceleration); + m_guidespeed = std::max(std::abs(Start.speed), 0.1); + } + else { + m_yawrate = Scatter.yaw_rate; + } + auto const foot{find_footing(Ground)}; + m_pitch = foot.grade; + m_grade = foot.grade; + m_cross = foot.cross; + place(); +} + +void body::step(double const Dt, double const Distance, double const Speed, ground const &Ground, std::array const &Ends) { + if (false == m_active || Dt <= 0.0) { + return; + } + // where the forces of the couplings act on the body, which turns under them through the step + for (std::size_t end = 0; end < Ends.size(); ++end) { + glm::dvec3 const arm{Ends[end].point.x - m_position.x, 0.0, Ends[end].point.z - m_position.z}; + m_ends[end].force = glm::dvec3{Ends[end].force.x, 0.0, Ends[end].force.z}; + m_ends[end].along = glm::dot(arm, m_axis); + m_ends[end].across = glm::dot(arm, left_of_heading()); + } + auto const steps{std::max(1, static_cast(std::ceil(Dt / substep - 1e-9)))}; + auto const dt{Dt / steps}; + auto const startspeed{m_speed}; + // the heading turned about within the step goes the other way along with the rest of the step + auto direction{1.0}; + for (int index = 1; index <= steps; ++index) { + auto const speed{std::lerp(startspeed, direction * Speed, static_cast(index) / steps)}; + auto const reversals{m_reversals}; + advance(dt, direction * Distance / steps, speed, Ground); + if (m_reversals != reversals) { + direction = -direction; + } + } + m_speed = direction * Speed; + place(); +} + +void body::advance(double const Dt, double const Distance, double const Speed, ground const &Ground) { + m_position += m_front * Distance + left_of_heading() * (m_lateral * Dt); + m_travelled += std::hypot(Distance, m_lateral * Dt); + m_time += Dt; + auto const foot{find_footing(Ground)}; + m_pitch = foot.grade; + // along the way it goes: of the slope along the body and across it + m_grade = foot.grade * glm::dot(m_front, m_axis) + foot.cross * glm::dot(m_front, left_of_heading()); + m_cross = foot.cross; + fall(Dt, foot.level, std::hypot(Distance, m_lateral * Dt)); + slide(Dt, foot.cross); + tip(Dt, foot.cross, Speed); + turn(Dt, Speed); + if (m_guided) { + m_guidetime += Dt; + if (m_tipping >= m_tipangle || std::abs(Speed) < 0.5 || m_guidetime > guidance_time) { + m_guided = false; + } + } +} + +body::footing body::find_footing(ground const &Ground) const { + auto const left{left_of_heading()}; + // a step up under the middle, and as much more under a support away from it as a slope of 2 in 1 rises: what is + // higher is over the vehicle, not under it (a bridge, a roof), and the ground under the slope of a bank isn't the + // ground the support stands on + constexpr double steepest{2.0}; + auto const sample = [&Ground, this](glm::dvec3 const &Point) { + auto const reach{std::hypot(Point.x - m_position.x, Point.z - m_position.z)}; + return Ground.height(Point.x, Point.z, m_position.y + step_up + steepest * reach).value_or(m_position.y); + }; + auto const ahead{m_axis * (0.5 * std::max(m_shape.base, 1.0))}; + // upright it stands on its wheels; tipping over, it comes to rest on the side of its body, which reaches out + // from the wheels it tips about as far as the body is high + auto const lean{std::sin(m_tipping)}; + auto const middle{left * (m_side * lean * 0.5 * m_shape.height)}; + auto const span{m_pivot + lean * std::max(0.0, 0.5 * m_shape.height - m_pivot)}; + auto const aside{left * span}; + auto const frontleft{sample(m_position + middle + ahead + aside)}; + auto const frontright{sample(m_position + middle + ahead - aside)}; + auto const rearleft{sample(m_position + middle - ahead + aside)}; + auto const rearright{sample(m_position + middle - ahead - aside)}; + footing result; + result.level = std::max(0.25 * (frontleft + frontright + rearleft + rearright), sample(m_position)); + // a step under one support is no slope steeper than 2 in 1 + result.grade = std::clamp((frontleft + frontright - rearleft - rearright) / (2.0 * std::max(m_shape.base, 1.0)), -steepest, steepest); + result.cross = std::clamp((frontleft + rearleft - frontright - rearright) / (4.0 * span), -steepest, steepest); + return result; +} + +void body::fall(double const Dt, double const Level, double const Travel) { + // on the ground it follows it down a slope as steep as 1:1.5; off a steeper drop it falls + constexpr double follows{1.0 / 1.5}; + if (m_grounded && m_position.y - Level <= std::max(0.02, follows * Travel)) { + m_position.y = Level; + return; + } + m_fallspeed -= gravity * Dt; + auto const height{m_position.y + m_fallspeed * Dt}; + m_grounded = (height <= Level); + if (m_grounded) { + m_position.y = Level; + m_fallspeed = 0.0; + } + else { + m_position.y = height; + } +} + +void body::slide(double const Dt, double const Cross) { + if (false == m_grounded) { + // in the air nothing holds it, nor pushes it + return; + } + auto const angle{std::atan(Cross)}; + // down the slope, to the left positive; held by the friction of its weight on the slope + m_lateral -= gravity * std::sin(angle) * Dt; + auto const held{lateral_friction * gravity * std::cos(angle) * Dt}; + if (std::abs(m_lateral) <= held) { + m_lateral = 0.0; + } + else { + m_lateral -= sign_of(m_lateral) * held; + } +} + +double body::lateral_load(double const Cross, double const Speed) const { + auto const angle{std::atan(Cross)}; + auto load{0.0}; + if (m_grounded) { + if (m_lateral != 0.0) { + // sliding across, the friction under its wheels or its side trips it the way it slides + load = sign_of(m_lateral) * lateral_friction * gravity * std::cos(angle); + } + else { + // standing on the slope, the weight pulls it down the slope, the friction holds its feet + load = -gravity * std::sin(angle); + } + // going askew, the friction across it trips it too + load += m_trip; + } + if (m_guided) { + auto const share{Speed / m_guidespeed}; + load += m_outward * m_guideacceleration * share * share; + } + return load; +} + +void body::tip(double const Dt, double const Cross, double const Speed) { + if (lying()) { + return; + } + auto const normal{gravity * std::cos(std::atan(Cross))}; + auto const load{lateral_load(Cross, Speed)}; + if (m_side == 0) { + // upright: it starts to tip once the load lifts the wheels of the other side + if (std::abs(load) * std::cos(m_tipangle) - normal * std::sin(m_tipangle) <= 0.0) { + return; + } + m_side = load > 0.0 ? 1 : -1; + } + auto const angle{m_tipping - m_tipangle}; + auto const acceleration{m_reach / m_gyration * (m_side * load * std::cos(angle) + normal * std::sin(angle))}; + m_tiprate += acceleration * Dt; + m_tipping += m_tiprate * Dt; + if (m_tipping <= 0.0) { + // back on its wheels + m_tipping = 0.0; + m_tiprate = 0.0; + m_side = 0; + } + else if (m_tipping >= half_turn) { + // on its side, where it stays + m_tipping = half_turn; + m_tiprate = 0.0; + } +} + +glm::dvec3 body::left_of_heading() const { + return left_of(m_axis); +} + +double body::friction_along() const { + return sliding_friction(m_tipping, m_guided); +} + +double body::friction_across() const { + return m_guided ? guided_friction : std::max(lateral_friction, friction_along()); +} + +double body::friction_share(bool const Front) const { + return Front ? m_scatter.friction_front : m_scatter.friction_rear; +} + +int body::biting() const { + if (m_scatter.dig_in < 0.0 || m_guided || false == m_grounded || m_time < m_scatter.dig_in || m_time >= m_scatter.dig_in + m_scatter.dig_in_time) { + return 0; + } + // the end it goes towards + auto const going{m_speed < 0.0 ? -m_front : m_front}; + return glm::dot(going, m_axis) >= 0.0 ? 1 : -1; +} + +double body::friction() const { + auto const along{glm::dot(m_front, m_axis)}; + auto const across{1.0 - along * along}; + auto result{0.5 * (friction_share(true) + friction_share(false)) * (friction_along() * along * along + friction_across() * across)}; + if (biting() != 0) { + // under half of its weight + result += 0.5 * (m_scatter.dig_in_friction - 1.0) * friction_along(); + } + return result; +} + +glm::dvec3 body::velocity() const { + return m_front * m_speed + left_of_heading() * m_lateral; +} + +void body::kick(glm::dvec3 const &Velocity, double const YawRate) { + if (false == m_active) { + return; + } + auto const moving{m_front * m_speed + glm::dvec3{Velocity.x, 0.0, Velocity.z}}; + auto const speed{glm::length(moving)}; + if (speed > 1e-6) { + m_front = moving / speed; + m_speed = speed; + if (glm::dot(m_front, m_axis) < 0.0) { + // it goes rear first + m_front = -m_front; + m_speed = -m_speed; + ++m_reversals; + } + } + else { + m_speed = 0.0; + } + m_yawrate = std::clamp(m_yawrate + YawRate, -most_yaw_rate, most_yaw_rate); +} + +void body::nudge(glm::dvec3 const &Offset) { + if (false == m_active) { + return; + } + m_position += glm::dvec3{Offset.x, 0.0, Offset.z}; + place(); +} + +double body::yaw() const { + return angle_between(m_line, m_axis); +} + +body::drag body::friction_under(double const Speed, double const Yawrate) const { + drag result; + if (false == m_grounded) { + // nothing holds it in the air + return result; + } + auto const left{left_of_heading()}; + auto const along{friction_along()}; + auto const across{friction_across()}; + // upright it stands on its bogies (the ends of its base), on its side it lies along all of its length + auto const share{std::clamp(m_tipping / half_turn, 0.0, 1.0)}; + auto const base{std::max(m_shape.base, 1.0)}; + auto const span{std::max(m_shape.length, base)}; + auto const velocity{m_front * Speed}; + auto const point = [&](double const Along, double const Across, double const Weight) { + // the friction under a point of the body: against the way it slides there, along the body and across it as each + // holds; slower than the creep, as much as it slides + auto const motion{velocity + left * (Yawrate * Along) - m_axis * (Yawrate * Across)}; + auto const speed{std::max(glm::length(motion), creep_speed)}; + auto const force{-(gravity * Weight) * (along * glm::dot(motion, m_axis) * m_axis + across * glm::dot(motion, left) * left) / speed}; + result.force += force; + // about the vertical, to the left positive + result.moment += Along * glm::dot(force, left) - Across * glm::dot(force, m_axis); + }; + if (share < 1.0) { + for (auto const end : {1.0, -1.0}) { + point(end * 0.5 * base, 0.0, (1.0 - share) * 0.5 * friction_share(end > 0.0)); + } + } + if (share > 0.0) { + for (int index = 0; index < friction_points; ++index) { + auto const along_body{span * ((index + 0.5) / friction_points - 0.5)}; + point(along_body, 0.0, share * friction_share(along_body > 0.0) / friction_points); + } + } + if (auto const end{biting()}; end != 0) { + // the leading end bites into the ballast at one of its wheels, under half of its weight; on its side, at a corner + // of its body + point(end * 0.5 * std::lerp(base, 0.5 * span, share), m_scatter.dig_in_side * std::lerp(m_pivot, 0.5 * m_shape.height, share), 0.5 * (m_scatter.dig_in_friction - 1.0)); + } + // the way it slides across, the friction trips it + result.trip = -glm::dot(result.force, left); + return result; +} + +void body::turn(double const Dt, double const Speed) { + // the forces of the couplings, per the mass + auto const left{left_of_heading()}; + auto moment{0.0}; + glm::dvec3 push{0.0}; + if (m_shape.mass > 0.0) { + for (auto const &end : m_ends) { + auto const arm{m_axis * end.along + left * end.across}; + moment += (arm.z * end.force.x - arm.x * end.force.z) / m_shape.mass; + push += end.force / m_shape.mass; + } + } + if (m_guided) { + // on its outer wheels on the rail it goes along the rail + m_yawrate = 0.0; + m_trip = 0.0; + return; + } + // the body: the couplings turn it, and the friction under it where it differs between the ends of a body going + // askew; the friction holds it against turning, never turning it back the other way + auto const driving{friction_under(Speed, 0.0).moment}; + auto rate{m_yawrate + (moment + driving) / m_yawgyration * Dt}; + auto const change{(friction_under(Speed, rate).moment - driving) / m_yawgyration * Dt}; + rate = ((rate + change) * rate <= 0.0 ? 0.0 : rate + change); + if (std::abs(Speed) < creep_speed && m_lateral == 0.0 && std::abs(rate) < 0.01 && m_grounded) { + // at a standstill it doesn't turn as long as the friction under it holds against the couplings + // on its bogies at half the base from the middle, lying along the length a quarter of it on average + auto const share{std::clamp(m_tipping / half_turn, 0.0, 1.0)}; + auto const arm{std::lerp(0.5 * std::max(m_shape.base, 1.0), 0.25 * std::max(m_shape.length, m_shape.base), share)}; + if (std::abs(moment) <= gravity * friction_across() * arm) { + rate = 0.0; + } + } + m_yawrate = std::clamp(rate, -most_yaw_rate, most_yaw_rate); + m_axis = level(turned(m_axis, world_up, m_yawrate * Dt), m_axis); + + // the way it travels: the friction of the body going askew turns it towards the body (no further), the couplings + // pushing across it turn it their way; the faster it goes, the less + auto const drag{friction_under(Speed, m_yawrate)}; + m_trip = drag.trip; + if (m_grounded && std::abs(Speed) >= turning_speed) { + auto const across{left_of(m_front)}; + auto const off{angle_between(m_front, glm::dot(m_front, m_axis) >= 0.0 ? m_axis : -m_axis)}; + auto byfriction{glm::dot(drag.force, across) * Dt / Speed}; + byfriction = (byfriction * off <= 0.0 ? 0.0 : sign_of(off) * std::min(std::abs(byfriction), std::abs(off))); + auto const bypush{glm::dot(push, across) * Dt / Speed}; + auto const turning{std::clamp(byfriction + bypush, -most_yaw_rate * Dt, most_yaw_rate * Dt)}; + m_front = level(turned(m_front, world_up, turning), m_front); + } + if (glm::dot(m_front, m_axis) < 0.0) { + // the body turned past a right angle off the way it goes: it goes rear first, the heading the other way + m_front = -m_front; + m_speed = -m_speed; + ++m_reversals; + } +} + +double body::roll() const { + // the ground rising to the left leans it to the right + return tipping() - std::atan(m_cross); +} + +double body::along() const { + return glm::dot(m_position - m_origin, m_line); +} + +double body::across() const { + return glm::dot(m_position - m_origin, left_of(m_line)); +} + +bool body::at_rest() const { + return m_active && m_grounded && std::abs(m_speed) < 0.01 && m_lateral == 0.0 && m_tiprate == 0.0 && m_yawrate == 0.0 && false == m_guided; +} + +void body::place() { + // the plane of the ground under the supports + auto const front{glm::normalize(m_axis + world_up * m_pitch)}; + auto const flatleft{glm::normalize(left_of_heading() + world_up * m_cross)}; + auto const up{glm::normalize(glm::cross(front, flatleft))}; + auto const left{glm::cross(up, front)}; + // tipped about the wheels of its side: turned about the front, the up going over to that side + auto const angle{-m_side * m_tipping}; + auto const pivot{m_position + left * (m_side * m_pivot)}; + auto origin{pivot + turned(m_position - pivot, front, angle)}; + auto const tippedleft{turned(left, front, angle)}; + auto const tippedup{turned(up, front, angle)}; + // the body doesn't go into the ground: the lowest of the edges of its box on it, from the rails to its roof + auto lowest{std::numeric_limits::max()}; + for (auto const across : {-0.5 * m_shape.width, 0.5 * m_shape.width}) { + for (auto const height : {0.0, m_shape.height}) { + lowest = std::min(lowest, glm::dot(origin + tippedleft * across + tippedup * height - m_position, up)); + } + } + if (lowest < 0.0) { + origin -= up * lowest; + } + m_pose.position = origin; + m_pose.front = front; + m_pose.left = tippedleft; + m_pose.up = tippedup; +} + +} // namespace derail_motion diff --git a/vehicle/derailmotion.h b/vehicle/derailmotion.h new file mode 100644 index 000000000..8513e7e13 --- /dev/null +++ b/vehicle/derailmotion.h @@ -0,0 +1,496 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include + +// a rail vehicle off the rails (physics.derailment new, see McZapkie/derailment.h for when it derails): from then on +// it doesn't follow the track any more, it moves on the ground by itself until the friction stops it. +// +// along: the longitudinal motion stays with the physics of the vehicle (TMoverParameters), which brakes it with the +// friction() of this one, takes the grade() under it and passes the forces of the couplings on; each step gives +// the distance travelled along the heading of the vehicle +// the heading: the way it travels; the one the vehicle had when it derailed, turned out of the curve by the sideways +// speed it left the rail with: none off the end of the track, the speed of the flange climbing over the rail head +// (or of the wheels lifting over it) otherwise. so in a curve it leaves the track to its outside, on a buckle +// towards the bulge. from then on the friction of a body sliding askew (more across it than along it) and the +// sideways part of the forces of its couplings turn it, little at speed +// the yaw: the body turns about its vertical axis by itself, apart from the way it travels: the forces of the +// couplings at its ends (the push of the buffers of two bodies at an angle to each other, off the middle of the +// buffer beam) turn it, the friction of the ground under the length of it holds it. pushed from behind, a train +// of bodies off the track folds up into a zigzag once the bends between them are past what the buffers hold +// sideways: the vehicle slides across its heading only where the ground slopes across it more than the friction +// holds, down an embankment say +// the height and the attitude: the ground under the supports of the vehicle (the ends of its wheelbase, the wheels +// of both sides) gives its height, its pitch and its roll; it doesn't sink into the ground, it falls off a step +// tipping over: about the wheels of one side, the body as a rigid one with the lean of its suspension, so it tips at +// the very lateral acceleration the wheel unloading of McZapkie/derailment.h reaches 1 at. what tips it: the +// overturning in the curve while its outer wheels still run on the rail (the curve keeps pushing it out as v^2/R, +// the excess over the limit the faster it tips), the slope of the ground across it, and the friction under it +// while it slides sideways. once over its tipping angle it falls on its side, at 90 degrees, and stays there +// +// the steps are cut to 0.01 s inside, so the result doesn't depend on the step of the simulation +namespace derail_motion { + +inline constexpr double gravity{9.81}; // [m/s2] +// the longest step of the motion [s] +inline constexpr double substep{0.01}; + +// what put the vehicle off the rails, for the way it leaves the track +enum class cause { + off_rails, // the flange climbed the rail + overturned, // the vehicle fell over out of the curve + end_of_track, // it ran off the end of the track: straight on + pulled_off, // the coupling of a vehicle off the track pulled it off sideways + collision // overriding, or pushed off the track in a collision: straight on +}; + +// ---- the friction [-] + +// of a vehicle tipping over on its outer wheels, which still roll on the outer rail +inline constexpr double guided_friction{0.1}; +// of the wheels, or of the body on its side, sliding across the heading +inline constexpr double lateral_friction{0.5}; +// the friction along the heading: upright on its wheels on the sleepers and the ballast, rising to the friction of a +// vehicle on its side (McZapkie/derailment.h) as it tips over +double sliding_friction(double Tipping, bool Guided); + +// ---- the way the vehicle leaves the track + +// how far the flange or the wheel goes sideways over the head of the rail before it drops off it [m] +inline constexpr double climb_width{0.1}; +// the largest angle the vehicle turns off the track by [rad] +inline constexpr double most_departure{0.2}; +// the angle [rad] the heading turns out of the curve by: the sideways speed sqrt(2 a w) the lateral acceleration a +// [m/s2] gives the wheels over the climb width w, against the speed [m/s]. none off the end of the track or in a +// collision +double departure_angle(cause Cause, double Speed, double Acceleration); + +// ---- the scatter: what differs from one derailed vehicle to the next + +// the ground under it and the way it bites into the ballast: each vehicle draws its own from the seed of the run and its +// name, so a run with the same seed goes the same way and one with another seed another way +struct scatter { + double departure{0.0}; // added to the angle it leaves the track at [rad], not off the end of the track nor in a collision + double yaw{0.0}; // its body turned off the way it travels when it leaves the rails [rad], to the left positive + double yaw_rate{0.0}; // [rad/s] the kick of the leading wheels dropping off the rail head + double friction_front{1.0}; // the friction under the front half of its body, of the friction of the motion + double friction_rear{1.0}; // and under the rear half + double dig_in{-1.0}; // the time after leaving the rails its leading end digs into the ballast [s], -1 never + double dig_in_time{0.0}; // for how long [s] + double dig_in_friction{1.0}; // the friction under the leading half then, of the friction of the motion + int dig_in_side{1}; // the wheel that digs in: 1 the left one of the leading end, -1 the right one +}; +// the scatter of a vehicle: departure angle +-0.01 rad, yaw +-0.02 rad, yaw rate +-0.02 rad/s, the friction under each +// half 0.85..1.15 of the friction of the motion, and in two of three vehicles a bite of the leading end 0.2..1.5 s after +// it left the rails, for 0.3..0.8 s, the friction under that half 2..4 times the friction of the motion then +scatter draw_scatter(std::uint32_t Seed); +// the seed of a vehicle: of the seed of the run and its name +std::uint32_t seed_of(std::uint32_t Run, std::string_view Name); + +// ---- the buffers and the couplings of two vehicles, one of them off the track at least + +// the height of the middle of the buffer beam above the rails [m]: UIC, 940..1065 mm +inline constexpr double buffer_height{1.0}; +// half the spacing of the buffers [m]: UIC, 1750 mm +inline constexpr double buffer_half_spacing{0.875}; +// the height of a buffer head [m]: two buffers further apart in height than that miss each other +inline constexpr double buffer_head{0.34}; +// the bend between two bodies [rad] the push of the buffers goes all onto the inner buffer at: their play, 45 mm of +// difference over the spacing +inline constexpr double buffer_lock{0.05}; +// the most a buffer takes [N]: past it, it is pressed solid and gives way, the frames push against each other at +// the middle of the beams +inline constexpr double buffer_limit{1.0e6}; + +// an end of a vehicle, where it meets the vehicle coupled to it +struct end_point { + glm::dvec3 point{0.0}; // the middle of the buffer beam, at the height of the buffers + glm::dvec3 outward{0.0, 0.0, 1.0}; // the way the end faces, level + // how far the body is rolled [rad]: the buffers of two bodies rolled apart miss each other in height + double roll{0.0}; +}; +// a force on a body [N], at the point it acts at +struct end_force { + glm::dvec3 force{0.0}; + glm::dvec3 point{0.0}; +}; +// two ends meeting, as the first sees it +struct meeting { + // apart [m], negative where the buffers press into each other: along the bisector of the bend while they touch, + // the distance between the middles of the beams once they are apart + double gap{0.0}; + // the bend: the angle [rad] the second body turns off the axis of the first, to the left of its end positive + double bend{0.0}; + glm::dvec3 push{0.0, 0.0, 1.0}; // outwards from the first, the bisector of the bend: the buffers push the other way + glm::dvec3 pull{0.0, 0.0, 1.0}; // the way the coupling draws the first: to the beam of the second + glm::dvec3 point{0.0}; // the middle of the beam of the first + // how well the buffers meet in height: 0 they miss each other (one body lower than the other, or rolled against it), to 1 + double overlap{1.0}; +}; +meeting meet(end_point const &First, end_point const &Second); +// the force on the first end of the meeting, Compression [N] pushing it (negative: the coupling pulling it): through +// the inner buffer of the bend, off the middle of the beam as far as the buffers meet and hold +end_force force_on(meeting const &Meeting, double Compression); + +// ---- the bodies of two vehicles running into each other, one of them off the track at least + +// how far the buffers and the coupling stand out of the body at each end [m]: the body box is shorter by them, so two +// ends meeting through their buffers (meet(), force_on()) don't touch as bodies until the buffers are pressed in by that +inline constexpr double buffer_length{0.6}; +// the least overlap in height [m] two bodies run into each other with: lower, one goes over the other +inline constexpr double height_overlap{0.2}; +// the bodies part after a hit with this share of the speed they met at +inline constexpr double contact_restitution{0.2}; +// the friction of the side of one body sliding along the other +inline constexpr double contact_friction{0.3}; +// the overlap left after a hit, taken out of it by moving the bodies apart: what is over the slop [m], this share of it +// a step +inline constexpr double contact_slop{0.02}; +inline constexpr double contact_correction{0.8}; + +// where a body stands on the ground: the rectangle under its box (the box of the body, the buffers left out, rolled and +// pitched as it lies, seen from above along its level axis), and the height it reaches from and to +struct footprint { + glm::dvec3 centre{0.0}; // of the rectangle, level + glm::dvec3 axis{0.0, 0.0, 1.0}; // along the body, level + double half_length{10.0}; + double half_width{1.5}; + double low{0.0}; // [m] the lowest and the highest point of the box + double high{4.0}; +}; +struct pose; +// the footprint of the body of Length (over the buffers), Width and Height (above the rails) in the Pose +footprint footprint_of(pose const &Pose, double Length, double Width, double Height); +// two bodies in each other: how deep (the least the rectangles overlap across any of their sides), the way out of the +// first into the second (level), and the point they touch at +struct contact { + double depth{0.0}; + glm::dvec3 normal{1.0, 0.0, 0.0}; + glm::dvec3 point{0.0}; +}; +std::optional collide(footprint const &First, footprint const &Second); +// a body in a contact, for the impulse: its mass, the velocity of its middle (base) and how fast it turns; on the rails +// it moves only along the track (Guided: along the Guide), not turning +struct contact_body { + double mass{0.0}; // [kg], none: it doesn't move + glm::dvec3 base{0.0}; + glm::dvec3 velocity{0.0}; + double yaw_rate{0.0}; + double gyration{30.0}; // the square of its radius of gyration about the vertical [m2] + bool guided{false}; + glm::dvec3 guide{0.0, 0.0, 1.0}; +}; +// the velocity of the point of the body [m/s] +glm::dvec3 velocity_at(contact_body const &Body, glm::dvec3 const &Point); +// the impulse [N s] on the second body of the contact (the first gets the opposite one): it stops the two closing in on +// each other at the point, parting them with the restitution, and the friction holds them sliding along each other +glm::dvec3 contact_impulse(contact const &Contact, contact_body const &First, contact_body const &Second); +// the change of the velocity [m/s] and of the yaw rate [rad/s] of the body by the impulse at the point +std::pair impulse_change(contact_body const &Body, glm::dvec3 const &Impulse, glm::dvec3 const &Point); + +// the distance [m] a vehicle slides from the speed [m/s] with the friction, on the grade (rise per metre along the +// way); none when the grade doesn't let it stop +std::optional stopping_distance(double Speed, double Friction, double Grade = 0.0); + +// the Y/Q of the leading wheel of an end of a vehicle which the coupling pulls (or pushes) at the angle [rad] to its +// axis with the force [N]: the part across, taken by the axles of that end (half of them), against the static load of +// a wheel of the vehicle of the mass [kg] +double pull_ratio(double Force, double Angle, double Mass, int Axles); + +// ---- the ground + +// where the vehicle can find the ground +class ground { +public: + virtual ~ground() = default; + // the height of the ground at (X, Z): of the highest surface there at or under Ceiling; none where there is none + virtual std::optional height(double X, double Z, double Ceiling) const = 0; +}; + +// level everywhere +class flat_ground final : public ground { +public: + explicit flat_ground(double Level) : m_level{Level} {} + std::optional height(double X, double Z, double Ceiling) const override; + +private: + double m_level; +}; + +// the triangles of the terrain of the scenery, kept in square cells for the lookup +class mesh_ground final : public ground { +public: + using triangle = std::array; + // the triangles which reach into the rectangle from Min to Max (x, z), in cells of the size [m] + mesh_ground(std::vector const &Triangles, glm::dvec2 const &Min, glm::dvec2 const &Max, double Cell = 8.0); + std::optional height(double X, double Z, double Ceiling) const override; + // whether the point is inside the rectangle the triangles were taken for + bool covers(double X, double Z) const; + // whether the rectangle from Min to Max (x, z) is inside the one the triangles were taken for + bool covers(glm::dvec2 const &Min, glm::dvec2 const &Max) const; + // the ground of a smaller area: the triangles which reach into the rectangle from Min to Max (x, z) + mesh_ground cropped(glm::dvec2 const &Min, glm::dvec2 const &Max) const; + std::size_t size() const { return m_triangles.size(); } + glm::dvec2 const &minimum() const { return m_min; } + glm::dvec2 const &maximum() const { return m_max; } + +private: + std::optional cell_of(double X, double Z) const; + + std::vector m_triangles; + std::vector> m_cells; // the triangles reaching into each cell + glm::dvec2 m_min; + glm::dvec2 m_max; + double m_cell; + std::size_t m_columns{0}; + std::size_t m_rows{0}; +}; + +// the bed of the track at the place nearest to the vehicle: the top of the ballast under the rails, level out to the +// edge of the formation, then the slope of the embankment going down +struct formation { + glm::dvec3 point{0.0}; // on the axis of the track, at the height of the rails + glm::dvec3 direction{0.0, 0.0, 1.0}; // of the axis + double depth{0.2}; // of the top of the ballast under the rails [m] + double half_width{2.0}; // from the axis to the edge of the top [m] + double slope{1.5}; // run of the slope per metre of fall: 1:1.5, of an embankment + double height(double X, double Z) const; +}; + +// the ground as the vehicle finds it: the terrain of the scenery where it has any, level with the top of the ballast +// where it has none (a scenery without terrain), and the bed of the track over it +class site final : public ground { +public: + explicit site(ground const *Terrain = nullptr, formation const &Bed = {}) : m_terrain{Terrain}, m_bed{Bed} {} + void terrain(ground const *Terrain) { m_terrain = Terrain; } + // the bed moves along the track with the vehicle + void bed(formation const &Bed) { m_bed = Bed; } + formation const &bed() const { return m_bed; } + std::optional height(double X, double Z, double Ceiling) const override; + +private: + ground const *m_terrain; + formation m_bed; +}; + +// ---- the vehicle + +// what of the vehicle the motion takes +struct vehicle_shape { + double length{20.0}; // over the buffers [m] + double width{3.0}; // of the body [m] + double height{4.0}; // of the body above the rail [m] + double centre_of_gravity{1.5}; // its height above the rail [m] + double contact_spacing{1.5}; // of the wheels of a wheelset [m] + double base{10.0}; // between the bogie pivots or the outer axles, which it rests on lengthwise [m] + // the lean of the body on the suspension, as McZapkie/derailment.h takes it: flexibility and roll centre + double flexibility{0.4}; + double roll_centre{0.5}; + // [kg] for the forces of the couplings on it; none: they don't move it + double mass{0.0}; +}; + +// how it left the rails +struct start { + glm::dvec3 position{0.0}; // of the vehicle, at the height of the rails + glm::dvec3 front{0.0, 0.0, 1.0}; // the way its front faces + glm::dvec3 line{0.0, 0.0, 1.0}; // the direction of the track there, to measure the offset across it by + double speed{0.0}; // along the front [m/s] + cause reason{cause::off_rails}; + // the outer side of the curve of the line under it: 1 to the left of its front, -1 to the right, 0 straight + int outward{0}; + double acceleration{0.0}; // the lateral acceleration of the body when it derailed, out of the curve [m/s2] +}; + +// where the body is and how it lies: the origin of its model, at the height of the rails between its wheels when +// upright, and its axes +struct pose { + glm::dvec3 position{0.0}; + glm::dvec3 front{0.0, 0.0, 1.0}; + glm::dvec3 left{1.0, 0.0, 0.0}; + glm::dvec3 up{0.0, 1.0, 0.0}; +}; + +class body { +public: + // the vehicle leaves the rails, set apart from the others by the Scatter + void begin(start const &Start, vehicle_shape const &Shape, ground const &Ground, scatter const &Scatter = {}); + // the step of Dt [s], in which the vehicle travelled Distance [m] along its heading (forwards along its front) and + // has the Speed [m/s] along it at its end; the couplings of its ends push or pull it with the Ends through the step + void step(double Dt, double Distance, double Speed, ground const &Ground, std::array const &Ends = {}); + // back on the rails, or never off them + void reset() { *this = body{}; } + + bool active() const { return m_active; } + pose const ¤t() const { return m_pose; } + // the middle of the vehicle on the ground, under it as it stands (not moved over to the side it tipped to) + glm::dvec3 const &base() const { return m_position; } + // the speed along the heading [m/s], and the velocity of the middle, level + double speed() const { return m_speed; } + glm::dvec3 velocity() const; + // the square of the radius of gyration about the vertical [m2] + double gyration() const { return m_yawgyration; } + // hit by another body: the velocity and the yaw rate change by these, the heading becomes the way it goes then + // (turned about where it goes rear first); the speed() after it is the one its vehicle goes on with + void kick(glm::dvec3 const &Velocity, double YawRate); + // moved over by the offset (level), out of another body it is in + void nudge(glm::dvec3 const &Offset); + // the friction along the heading now, of its weight: of the body sliding along itself, more the more askew it goes, + // up to the friction across it going sideways + double friction() const; + // the rise of the ground per metre along the heading, for the force of the gravity along it + double grade() const { return m_grade; } + // how far the body tipped over from its wheels [rad], to the left positive; 90 degrees: it lies on its side + double tipping() const { return m_side * m_tipping; } + // the roll of the body against the level [rad], to the left positive: the tipping and the slope across it + double roll() const; + bool lying() const { return m_tipping >= half_turn - 1e-9; } + // still on its outer wheels on the rail, tipping over out of the curve + bool guided() const { return m_guided; } + // the distance it went on the ground since it left the rails [m] + double travelled() const { return m_travelled; } + // from the place it left the rails at: along the line of the track there, and across it, to the left positive [m] + double along() const; + double across() const; + // the speed it slides with sideways, to the left of its front positive [m/s] + double sideways() const { return m_lateral; } + // at rest: not sliding, not tipping, on the ground + bool at_rest() const; + // the way it travels, level + glm::dvec3 const &heading() const { return m_front; } + // the way the front of its body faces, level + glm::dvec3 const &axis() const { return m_axis; } + // the angle [rad] its body is turned by off the line of the track where it left the rails, to the left positive + double yaw() const; + // how fast it turns [rad/s], to the left positive + double yaw_rate() const { return m_yawrate; } + // how many times the heading was turned about, the body having turned more than a right angle off the way it + // goes: the heading stays within a right angle of the front of the body, so the speed along the heading (of + // TMoverParameters, of its couplers at its ends) goes with the body; the speed changes its sign with each + int reversals() const { return m_reversals; } + cause reason() const { return m_reason; } + // the vehicle the motion was begun with + vehicle_shape const &shape() const { return m_shape; } + + static constexpr double half_turn{1.5707963267948966}; + +private: + // the ground under the supports of the vehicle + struct footing { + double level{0.0}; // under the middle, not under any support + double grade{0.0}; // rise per metre forwards + double cross{0.0}; // rise per metre to the left + }; + + void advance(double Dt, double Distance, double Speed, ground const &Ground); + footing find_footing(ground const &Ground) const; + // down to the ground at the Level, or onto it, having travelled Travel [m] over the ground in the step + void fall(double Dt, double Level, double Travel); + void slide(double Dt, double Cross); + void tip(double Dt, double Cross, double Speed); + // the lateral acceleration [m/s2] on the centre of gravity, to the left positive, in the plane of the ground + double lateral_load(double Cross, double Speed) const; + void place(); + // to the left of the body + glm::dvec3 left_of_heading() const; + // the friction under the body going along its heading at the Speed and turning at the Yawrate, per its mass: the + // force [m/s2], the moment about its middle [m2/s2] and the sideways load that trips it over [m/s2] + struct drag { + glm::dvec3 force{0.0}; + double moment{0.0}; + double trip{0.0}; + }; + drag friction_under(double Speed, double Yawrate) const; + // the friction under the front (Front) or the rear half of the body, of the friction of the motion + double friction_share(bool Front) const; + // the leading end biting into the ballast now: 1 its front, -1 its rear, 0 none + int biting() const; + // the friction along the body and across it + double friction_along() const; + double friction_across() const; + // the body turns, and the way it travels turns, through the substep + void turn(double Dt, double Speed); + + bool m_active{false}; + cause m_reason{cause::off_rails}; + vehicle_shape m_shape; + // the geometry of the tipping: half the spacing of the wheels, the height the lateral force leans the body at, + // the distance of the centre of gravity from the wheels it tips about, the angle it tips over past, and the + // square of the radius of gyration about them + double m_pivot{0.75}; + double m_lever{1.8}; + double m_reach{1.9}; + double m_tipangle{0.4}; + double m_gyration{5.0}; + + glm::dvec3 m_position{0.0}; // of the middle of the vehicle on the ground (at its base) + glm::dvec3 m_front{0.0, 0.0, 1.0}; // the heading, level + glm::dvec3 m_axis{0.0, 0.0, 1.0}; // the front of the body, level + double m_yawrate{0.0}; // [rad/s] + double m_yawgyration{30.0}; // the square of the radius of gyration of the body about its vertical axis [m2] + scatter m_scatter; + double m_time{0.0}; // since it left the rails [s] + int m_reversals{0}; + double m_trip{0.0}; // the load across of the friction of the body going askew [m/s2], the way it slides + // the forces of the couplings through the step: the force, and where it acts, along the body and across it + struct end_load { + glm::dvec3 force{0.0}; + double along{0.0}; + double across{0.0}; + }; + std::array m_ends{}; + glm::dvec3 m_origin{0.0}; // where it left the rails + glm::dvec3 m_line{0.0, 0.0, 1.0}; // the direction of the track there, level + double m_fallspeed{0.0}; // [m/s], downwards negative + // on the ground, not falling. it leaves the rails above the top of the ballast, and drops onto it + bool m_grounded{false}; + double m_lateral{0.0}; // [m/s], to the left positive + double m_grade{0.0}; // along the heading + double m_pitch{0.0}; // along the body + double m_cross{0.0}; + int m_side{0}; // the side it tips to: 1 left, -1 right, 0 upright + double m_tipping{0.0}; // [rad] + double m_tiprate{0.0}; // [rad/s] + // overturning in the curve: the lateral acceleration of the curve at the speed it derailed at, which goes with the + // square of the speed, the side out of the curve, and how long it has been tipping + bool m_guided{false}; + double m_guideacceleration{0.0}; + double m_guidespeed{0.0}; + int m_outward{0}; + double m_guidetime{0.0}; + double m_speed{0.0}; + double m_travelled{0.0}; + pose m_pose; +}; + +// the slowest a point of the body slides at [m/s]: the friction under one going slower holds it as much as it goes +inline constexpr double creep_speed{0.05}; +// the fastest the body turns about its vertical axis [rad/s] +inline constexpr double most_yaw_rate{2.0}; +// the slowest the heading is turned at by the forces across it [m/s]: slower, the vehicle stops where it goes +inline constexpr double turning_speed{0.5}; +// the points the friction under the body is taken at, along it +inline constexpr int friction_points{8}; + +// how long the curve can keep tipping over a vehicle on its outer wheels [s] +inline constexpr double guidance_time{5.0}; +// how high a step up the vehicle can climb onto, for the ground under it [m] +inline constexpr double step_up{1.0}; + +} // namespace derail_motion diff --git a/world/TrkFoll.cpp b/world/TrkFoll.cpp index ca215e3ba..c7be77dcc 100644 --- a/world/TrkFoll.cpp +++ b/world/TrkFoll.cpp @@ -277,6 +277,22 @@ double TTrackFollower::BuckleCurvature( double const Base ) const { return pCurrentTrack != nullptr ? pCurrentTrack->buckle_curvature( fCurrentDistance, Base ) : 0.0; } +glm::dvec3 TTrackFollower::PathDirection( double const Reach ) const { + + if( pCurrentSegment == nullptr ) { + return glm::dvec3 { 0.0 }; + } + auto const length { pCurrentSegment->GetLength() }; + glm::dvec3 ahead; + glm::dvec3 behind; + glm::vec3 rotation; + pCurrentSegment->RaPositionGet( std::clamp( fCurrentDistance + Reach, 0.0, length ), ahead, rotation ); + pCurrentSegment->RaPositionGet( std::clamp( fCurrentDistance - Reach, 0.0, length ), behind, rotation ); + glm::dvec3 const direction { ( ahead.x - behind.x ) * fDirection, 0.0, ( ahead.z - behind.z ) * fDirection }; + auto const size { glm::length( direction ) }; + return size > 1e-6 ? direction / size : glm::dvec3 { 0.0 }; +} + bool TTrackFollower::ComputatePosition() { // ustalenie współrzędnych XYZ if (pCurrentSegment) // o ile jest tor diff --git a/world/TrkFoll.h b/world/TrkFoll.h index f4741e3ec..17de69c80 100644 --- a/world/TrkFoll.h +++ b/world/TrkFoll.h @@ -45,6 +45,9 @@ public: double RailPhase( double const Offset ) const; // TTrack::buckle_curvature at the axle, averaged over Base around it double BuckleCurvature( double const Base ) const; + // the level direction of the path the axle runs on, with its buckle and its uneven track, over Reach [m] behind and + // ahead of it, the way the axle goes forwards; none without a path + glm::dvec3 PathDirection( double const Reach = 1.0 ) const; bool Init(TTrack *pTrack, TDynamicObject *NewOwner, double fDir); void Reset(); void Render(float fNr); From a8e83133431f707d4a2d69d3daec70f05939ad5f Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 26 Nov 2026 22:27:27 +0100 Subject: [PATCH 130/136] feat(odometer): stamp each state with the day it was last updated, drop states not updated for a year (#435) * feat(odometer): stamp the states with the day they were last updated, drop those not updated for a year The odometer store kept every vehicle ever run. Each state now carries the day it was last updated, written as a comment line "# updated " before the states of that day, which the builds without the stamps skip. A state with no stamp counts as updated the day it is read. A save drops the states not updated for more than 365 days, those the other simulations saved included. Refs #283. * test(odometer): cover the stamps of the states and their expiry * fix(odometer): a wrong clock doesn't drop the states, odometer.expiry sets the period Review of #435. A stamp later than today was taken as today on every read, so a session with the clock set back rewrote every state with that day, and the next session with the right clock dropped them all. The stamps are now kept as written and a recorded state keeps its later day, so a day never goes back. The expiry was measured from today, so a clock set forward, or the first save after a break of a year, dropped every state not run in that session. It is now measured from the latest day of the states read at the start of the session when that is earlier than today. The states this session records are stamped today, so the newest day of the merged store would always be today in a save that writes. The period is odometer.expiry in eu07.ini, 365 unless set, 0 for never. A scenery's config block doesn't change it, it would drop the player's states. The states dropped are logged by the save that writes the file without them, not at every save while the write fails. as_written() reads with the day given to save(). --- tests/unit/test_ini_only_settings.cpp | 11 + tests/unit/test_odometer.cpp | 478 ++++++++++++++++++++++++++ utilities/Globals.cpp | 9 + utilities/Globals.h | 3 + utilities/inionlysettings.cpp | 4 +- utilities/inionlysettings.h | 8 +- vehicle/odometer.cpp | 133 ++++++- vehicle/odometer.h | 45 ++- 8 files changed, 667 insertions(+), 24 deletions(-) diff --git a/tests/unit/test_ini_only_settings.cpp b/tests/unit/test_ini_only_settings.cpp index f90e9b2f9..83303aad4 100644 --- a/tests/unit/test_ini_only_settings.cpp +++ b/tests/unit/test_ini_only_settings.cpp @@ -141,3 +141,14 @@ TEST_CASE("ini only settings: nothing changed, nothing to tell") { CHECK(ini.restore(*settings).empty()); CHECK(settings->exec_on_exit == "notify.exe"); } + +TEST_CASE("ini only settings: a scenery's config block doesn't change the period of the odometer states") { + auto const settings{std::make_unique()}; + settings->odometer_expiry = 730; + ini_only_settings const ini{*settings}; + // "config odometer.expiry 1 endconfig" in the .scn would drop the states of the vehicles not run yesterday + settings->odometer_expiry = 1; + auto const changed{ini.restore(*settings)}; + CHECK(settings->odometer_expiry == 730); + CHECK(changed == std::vector{"odometer.expiry"}); +} diff --git a/tests/unit/test_odometer.cpp b/tests/unit/test_odometer.cpp index 295d722cd..b3da8d792 100644 --- a/tests/unit/test_odometer.cpp +++ b/tests/unit/test_odometer.cpp @@ -4,9 +4,23 @@ #include "utilities/Globals.h" #include "vehicle/odometer.h" +#include +#include +#include #include #include +#include +#include +#include #include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif // the odometer of a vehicle, kept between the sessions (eu07/maszyna#72): one state the cab's counters and the // python screens show, saved in one store, taking over the states the python screens kept in their own files @@ -665,3 +679,467 @@ TEST_CASE("odometer: the files of both kinds of python screens are read, by the CHECK_FALSE(odometer::legacy_state(vehicles, "EU07-425", scripts).has_value()); CHECK_FALSE(odometer::legacy_state(vehicles, "", scripts).has_value()); } + +// the day a state was last updated, kept in the file so the vehicles not run for long are dropped from it (review of +// eu07/maszyna#283: the file grew with every vehicle ever run). the tests give the day, the clock of the machine +// doesn't matter + +namespace { + +constexpr odometer::day today{std::chrono::year{2026} / 11 / 21}; + +odometer::day days_ago(int const Days) { + return today - std::chrono::days{Days}; +} + +odometer::day days_on(int const Days) { + return today + std::chrono::days{Days}; +} + +odometer::store read_text(std::string const &Text, odometer::day const Today = today) { + std::stringstream file{Text}; + odometer::store store; + store.read(file, Today); + return store; +} + +std::string read_file(std::filesystem::path const &Path) { + std::ifstream input{Path, std::ios::binary}; + std::stringstream content; + content << input.rdbuf(); + return content.str(); +} + +std::string written(odometer::store const &Store) { + std::stringstream text; + Store.write(text); + return text.str(); +} + +// the reader of the builds before the stamps, as it was (2f127688, odometer::store::read): the states it gets +struct old_state { + double km; + bool guessed; +}; + +std::optional old_line(std::string const &Line, std::string &Name) { + auto const separator{Line.find_first_of(" \t")}; + if (separator == std::string::npos) + return std::nullopt; + auto number{Line.substr(0, separator)}; + auto const guessed{false == number.empty() && number.front() == '~'}; + if (guessed) + number.erase(0, 1); + std::size_t used{0}; + double km{0.0}; + try { + km = std::stod(number, &used); + } catch (std::exception const &) { + return std::nullopt; + } + Name = Line.substr(separator + 1); + if (used != number.size() || false == std::isfinite(km) || km < 0.0 || Name.empty()) + return std::nullopt; + return old_state{km, guessed}; +} + +std::map old_read(std::string const &Text) { + std::map states; + std::stringstream input{Text}; + std::string line; + while (std::getline(input, line)) { + if (false == line.empty() && line.back() == '\r') + line.pop_back(); + if (line.empty() || line.front() == '#') + continue; + std::string name; + if (auto const state{old_line(line, name)}; state.has_value()) + states[name] = *state; + } + return states; +} + +odometer::reading guessed_run(double const Km, double const Metres) { + odometer::reading reading; + reading.begin(Km, odometer::origin::guessed); + reading.run(Metres); + return reading; +} + +} // namespace + +TEST_CASE("odometer: a file of the builds before the stamps is read whole, its states updated the day it's read") { + std::string const unstamped{"# odometer states of the vehicles: , ~ for one counted from a made up state\n" + "1000.0000 EU07-424\n" + "~20000.0000 SM42-001\n" + "42.5000 loco with spaces\n"}; + auto const store{read_text(unstamped)}; + REQUIRE(store.size() == 3); + CHECK(store.find("EU07-424").value() == 1000.0); + CHECK(store.guessed("SM42-001")); + CHECK(store.find("loco with spaces").value() == 42.5); + for (auto const *name : {"EU07-424", "SM42-001", "loco with spaces"}) { + CAPTURE(name); + CHECK(store.updated(name) == today); + } + CHECK_FALSE(store.updated("EU07-425").has_value()); + + // saved, all of them are written with the day they were read, none dropped + scratch_directory directory{"odometer_unstamped"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, unstamped); + auto loaded{read_text(read_file(path))}; + loaded.record("EU07-424", run(1000.0, 1000.0), today); + REQUIRE(odometer::save(loaded, path, today)); + auto const text{read_file(path)}; + CHECK(text.find("# updated 2026-11-21\n") != std::string::npos); + auto const after{read_text(text, days_on(10))}; + CHECK(after.size() == 3); + CHECK(after.find("EU07-424").value() == doctest::Approx(1001.0)); + CHECK(after.find("SM42-001").value() == 20000.0); + CHECK(after.updated("SM42-001") == today); +} + +TEST_CASE("odometer: the day a state was last updated is written with it and read back") { + odometer::store store; + store.record("EU07-424", run(1000.0, 1000.0), days_ago(10)); + store.record("loco with spaces", run(42.0, 500.0), today); + store.record("SM42-001", guessed_run(20000.0, 1000.0), days_ago(10)); + store.record("ET22-001", run(5.0, 1000.0), days_ago(400)); + auto const text{written(store)}; + // grouped by the day, the oldest first, by the name in a group + CHECK(text.find("# updated 2025-10-17\n6.0000 ET22-001\n" + "# updated 2026-11-11\n1001.0000 EU07-424\n~20001.0000 SM42-001\n" + "# updated 2026-11-21\n42.5000 loco with spaces\n") + != std::string::npos); + + auto const read{read_text(text)}; + CHECK(read.size() == 4); + CHECK(read.updated("EU07-424") == days_ago(10)); + CHECK(read.updated("SM42-001") == days_ago(10)); + CHECK(read.guessed("SM42-001")); + CHECK(read.updated("loco with spaces") == today); + CHECK(read.updated("ET22-001") == days_ago(400)); + CHECK(read.find("loco with spaces").value() == doctest::Approx(42.5)); + // the store read writes the same file again + CHECK(written(read) == text); +} + +TEST_CASE("odometer: a build before the stamps reads the file with them as it read its own") { + odometer::store store; + store.record("EU07-424", run(1000.0, 1000.0), days_ago(10)); + store.record("loco with spaces", run(42.0, 500.0), today); + store.record("SM42-001", guessed_run(20000.0, 1000.0), days_ago(300)); + auto const old{old_read(written(store))}; + REQUIRE(old.size() == 3); + CHECK(old.at("EU07-424").km == doctest::Approx(1001.0)); + CHECK_FALSE(old.at("EU07-424").guessed); + CHECK(old.at("loco with spaces").km == doctest::Approx(42.5)); + CHECK(old.at("SM42-001").km == doctest::Approx(20001.0)); + CHECK(old.at("SM42-001").guessed); +} + +TEST_CASE("odometer: a stamp later than the day is kept as written, a malformed one doesn't make a state expire") { + auto const store{read_text("# updated 2099-01-01\n1 future\n" + "# updated 2025-01-01\n2 dated\n" + "# a comment between\n3 after a comment\n" + "# updated nonsense\n4 malformed\n" + "# updated 2026-02-30\n5 no such day\n" + "# updated 2025-1-01\n6 short\n" + "# updated 2025-01-01 \r\n7 trailing space\n" + "#updated 2024-01-01\n8 not a stamp\n")}; + odometer::day const newyear{std::chrono::year{2025} / 1 / 1}; + CHECK(store.size() == 8); + // a clock set back doesn't move it back (review of #435: the next session with the right clock dropped them all) + CHECK(store.updated("future") == odometer::day{std::chrono::year{2099} / 1 / 1}); + CHECK(store.updated("dated") == newyear); + CHECK(store.updated("after a comment") == newyear); + CHECK(store.updated("malformed") == today); + CHECK(store.updated("no such day") == today); + CHECK(store.updated("short") == today); + CHECK(store.updated("trailing space") == newyear); + CHECK(store.updated("not a stamp") == newyear); +} + +TEST_CASE("odometer: a state is updated the day it's recorded, one left as it was keeps its day") { + auto store{read_text("# updated 2026-08-13\n300 known\n")}; + REQUIRE(store.updated("known") == days_ago(100)); + store.record("known", started(300.0), today); + CHECK(store.updated("known") == days_ago(100)); + store.record("known", run(300.0, 1000.0), today); + CHECK(store.updated("known") == today); +} + +TEST_CASE("odometer: of two stores merged, the later day of a state is kept, whichever state is newer") { + auto const other{read_text("# updated 2026-11-01\n100 known\n# updated 2026-11-20\n200 other\n")}; + auto mine{read_text("# updated 2026-11-10\n150 known\n# updated 2026-11-15\n250 other\n")}; + mine.merge(other); + CHECK(mine.find("known").value() == 150.0); + CHECK(mine.updated("known") == days_ago(11)); + CHECK(mine.find("other").value() == 250.0); + CHECK(mine.updated("other") == days_ago(1)); + auto const newer{read_text("# updated 2026-11-01\n500 known\n")}; + mine.merge(newer); + CHECK(mine.find("known").value() == 500.0); + CHECK(mine.updated("known") == days_ago(11)); +} + +TEST_CASE("odometer: a save drops the states not updated for longer than a year, the other simulations' too") { + CHECK(odometer::expiry() == std::chrono::days{365}); + scratch_directory directory{"odometer_expiry"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, "# updated 2025-11-20\n100 over a year\n" + "# updated 2025-11-21\n200 a year\n" + "# updated 2026-11-21\n300 fresh\n"); + auto store{read_text(read_file(path))}; + // another simulation saved meanwhile, with a state as old as one of this one's + write_file(path, "# updated 2025-11-20\n100 over a year\n" + "# updated 2025-11-21\n200 a year\n" + "# updated 2025-06-01\n5 old of another\n" + "# updated 2026-11-21\n300 fresh\n6 fresh of another\n"); + store.record("run today", run(70.0, 1000.0), today); + REQUIRE(odometer::save(store, path, today)); + + auto const saved{read_text(read_file(path))}; + CHECK(saved.size() == 4); + CHECK_FALSE(saved.find("over a year").has_value()); + CHECK_FALSE(saved.find("old of another").has_value()); + CHECK(saved.find("a year").value() == 200.0); + CHECK(saved.updated("a year") == days_ago(365)); + CHECK(saved.find("fresh").value() == 300.0); + CHECK(saved.find("fresh of another").value() == 6.0); + CHECK(saved.find("run today").value() == doctest::Approx(71.0)); + // gone from the store of the simulation too + CHECK_FALSE(store.find("over a year").has_value()); + CHECK(store.size() == 4); + + SUBCASE("the one of a year drops too once the file was updated a day later, in the session that reads it") { + // the session goes on the next day: measured from the day the file had when the session read it + store.record("run today", run(71.0, 1000.0), days_on(1)); + REQUIRE(odometer::save(store, path, days_on(1))); + CHECK(read_text(read_file(path), days_on(1)).find("a year").has_value()); + // the next session + auto next{read_text(read_file(path), days_on(1))}; + next.record("run today", run(72.0, 1000.0), days_on(1)); + REQUIRE(odometer::save(next, path, days_on(1))); + auto const later{read_text(read_file(path), days_on(1))}; + CHECK(later.size() == 3); + CHECK_FALSE(later.find("a year").has_value()); + CHECK(later.updated("run today") == days_on(1)); + } + SUBCASE("a store with nothing recorded since doesn't write the file only to drop them") { + REQUIRE(odometer::save(store, path, today)); + mark(path); + REQUIRE(odometer::save(store, path, days_on(1))); + CHECK(marked(path)); + CHECK(read_text(read_file(path), days_on(1)).find("a year").has_value()); + } +} + +TEST_CASE("odometer: a save lost to another simulation's save is written again with its stamps") { + scratch_directory directory{"odometer_lost_save_stamps"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, "# updated 2026-06-01\n1000 shared\n"); + auto first{read_text(read_file(path))}; + auto second{read_text(read_file(path))}; + first.record("shared", run(1000.0, 5000.0), today); + first.record("first only", run(70.0, 1000.0), today); + second.record("second only", run(80.0, 1000.0), days_ago(1)); + + // the second one reads the file before the first one writes it, and puts its own in place after + auto const view{directory.path / "late_view" / path.filename()}; + std::filesystem::create_directories(view.parent_path()); + std::filesystem::copy_file(path, view); + REQUIRE(odometer::save(first, path, today)); + REQUIRE(odometer::save(second, view, today)); + std::filesystem::rename(view, path); + REQUIRE_FALSE(read_text(read_file(path)).find("first only").has_value()); + + REQUIRE(odometer::save(first, path, today)); + REQUIRE(odometer::save(second, path, today)); + auto const saved{read_text(read_file(path))}; + CHECK(saved.size() == 3); + CHECK(saved.find("shared").value() == doctest::Approx(1005.0)); + CHECK(saved.updated("shared") == today); + CHECK(saved.find("first only").value() == doctest::Approx(71.0)); + CHECK(saved.updated("first only") == today); + CHECK(saved.find("second only").value() == doctest::Approx(81.0)); + CHECK(saved.updated("second only") == days_ago(1)); +} + +// a wrong clock, the period of eu07.ini (odometer.expiry) and the log of what's dropped (review of eu07/maszyna#435) + +// the lines logged while the object lives, kept by the engine stubs (engine_stubs.cpp) +void unit_tests_log_capture(bool Enabled); +std::vector unit_tests_logged_lines(); + +namespace { + +odometer::day const backintime{std::chrono::year{2000} / 1 / 1}; + +int process_id() { +#ifdef _WIN32 + return _getpid(); +#else + return static_cast(getpid()); +#endif +} + +class log_capture { +public: + log_capture() { unit_tests_log_capture(true); } + ~log_capture() { unit_tests_log_capture(false); } + log_capture(log_capture const &) = delete; + log_capture &operator=(log_capture const &) = delete; + + std::size_t count(std::string_view const Text) const { + auto const lines{unit_tests_logged_lines()}; + return static_cast(std::ranges::count_if(lines, [Text](std::string const &Line) { return Line.find(Text) != std::string::npos; })); + } +}; + +std::string const stamped_file{"# updated 2025-12-01\n100 a year ago\n" + "# updated 2026-11-11\n200 driven\n" + "# updated 2026-11-21\n300 fresh\n"}; + +} // namespace + +TEST_CASE("odometer: a clock set back doesn't move the days of the states back, nor drops them then") { + scratch_directory directory{"odometer_clock_back"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, stamped_file); + // a dead battery of the clock: the session starts on 2000-01-01 + auto back{read_text(read_file(path), backintime)}; + CHECK(back.updated("a year ago") == days_ago(355)); + back.record("driven", run(200.0, 1000.0), backintime); + CHECK(back.updated("driven") == days_ago(10)); + REQUIRE(odometer::save(back, path, backintime)); + auto const written{read_file(path)}; + CHECK(written.find("# updated 2000-01-01") == std::string::npos); + CHECK(read_text(written).size() == 3); + + // the next session with the right clock drops none of them + auto right{read_text(written, days_on(1))}; + right.record("fresh", run(300.0, 1000.0), days_on(1)); + REQUIRE(odometer::save(right, path, days_on(1))); + auto const after{read_text(read_file(path), days_on(1))}; + CHECK(after.size() == 3); + CHECK(after.updated("a year ago") == days_ago(355)); + CHECK(after.updated("driven") == days_ago(10)); + CHECK(after.find("driven").value() == doctest::Approx(201.0)); +} + +TEST_CASE("odometer: a clock set forward doesn't drop the states not run in that session") { + scratch_directory directory{"odometer_clock_forward"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, stamped_file); + // two years ahead: measured from the day the file had when the session read it + auto ahead{read_text(read_file(path), days_on(730))}; + ahead.record("driven", run(200.0, 1000.0), days_on(730)); + REQUIRE(odometer::save(ahead, path, days_on(730))); + // the later saves of the session too, which find its own states of that day in the file + ahead.record("driven", run(201.0, 1000.0), days_on(730)); + REQUIRE(odometer::save(ahead, path, days_on(730))); + CHECK(read_text(read_file(path), days_on(730)).size() == 3); + + // the next session with the right clock: the day ahead is kept as written, nothing drops + auto right{read_text(read_file(path), days_on(1))}; + CHECK(right.updated("driven") == days_on(730)); + right.record("fresh", run(300.0, 1000.0), days_on(1)); + REQUIRE(odometer::save(right, path, days_on(1))); + auto const after{read_text(read_file(path), days_on(1))}; + CHECK(after.size() == 3); + CHECK(after.updated("a year ago") == days_ago(355)); + CHECK(after.updated("driven") == days_on(730)); +} + +TEST_CASE("odometer: a player back after a break keeps the states in the session he comes back in") { + scratch_directory directory{"odometer_break"}; + auto const path{directory.path / "eu07_odometers.txt"}; + // the last session was 500 days ago + write_file(path, "# updated 2024-05-19\n10 too old\n" + "# updated 2025-01-31\n20 older\n" + "# updated 2025-07-09\n30 last run\n40 not run since\n"); + REQUIRE(odometer::day{std::chrono::year{2025} / 7 / 9} == days_ago(500)); + auto back{read_text(read_file(path))}; + back.record("last run", run(30.0, 1000.0), today); + REQUIRE(odometer::save(back, path, today)); + auto const first{read_text(read_file(path))}; + // more than a year before the last session: gone, as that session would have dropped it the next day + CHECK_FALSE(first.find("too old").has_value()); + CHECK(first.find("older").has_value()); + CHECK(first.find("not run since").has_value()); + CHECK(first.updated("last run") == today); + + // the session after: not run for a year before the last one, they drop + auto next{read_text(read_file(path), days_on(1))}; + next.record("last run", run(31.0, 1000.0), days_on(1)); + REQUIRE(odometer::save(next, path, days_on(1))); + auto const second{read_text(read_file(path), days_on(1))}; + CHECK(second.size() == 1); + CHECK(second.find("last run").has_value()); +} + +TEST_CASE("odometer: the period is the one eu07.ini gives, 0 keeps every state") { + auto const text{"# updated 2000-01-01\n1 long ago\n# updated 2026-10-21\n2 a month ago\n# updated 2026-11-21\n3 fresh\n"}; + { + auto store{read_text(text)}; + CHECK(store.expire(today, std::chrono::days{0}) == 0); + CHECK(store.size() == 3); + } + { + auto store{read_text(text)}; + CHECK(store.expire(today, std::chrono::days{30}) == 2); + CHECK(store.find("fresh").has_value()); + } + { + // and a save with it + scratch_directory directory{"odometer_never"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, text); + auto store{read_text(read_file(path))}; + store.record("fresh", run(3.0, 1000.0), today); + REQUIRE(odometer::save(store, path, today, std::chrono::days{0})); + CHECK(read_text(read_file(path)).size() == 3); + } + + // odometer.expiry in eu07.ini, a year unless set (the parser of eu07.ini, Globals.cpp, isn't in the build of + // the unit tests) + CHECK(std::make_unique()->odometer_expiry == 365); + // the store of the simulation takes it from the settings, a negative one as 0 + auto const kept{Global.odometer_expiry}; + Global.odometer_expiry = 90; + CHECK(odometer::expiry() == std::chrono::days{90}); + Global.odometer_expiry = 0; + CHECK(odometer::expiry() == std::chrono::days{0}); + Global.odometer_expiry = -5; + CHECK(odometer::expiry() == std::chrono::days{0}); + Global.odometer_expiry = kept; +} + +TEST_CASE("odometer: the states dropped are logged once, by the save that writes the file without them") { + scratch_directory directory{"odometer_dropped_log"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, "# updated 2025-01-01\n1 long ago\n# updated 2026-11-21\n2 fresh\n"); + auto store{read_text(read_file(path))}; + store.record("fresh", run(2.0, 1000.0), today); + constexpr std::string_view dropped{"not updated for 365 days dropped"}; + log_capture const log; + + // the file aside can't be written: each save fails, none logs the states dropped + auto temporary{path}; + temporary += "." + std::to_string(process_id()) + ".tmp"; + std::filesystem::create_directories(temporary / "blocked"); + CHECK_FALSE(odometer::save(store, path, today, std::chrono::days{365})); + CHECK_FALSE(odometer::save(store, path, today, std::chrono::days{365})); + CHECK(log.count(dropped) == 0); + CHECK(read_text(read_file(path)).find("long ago").has_value()); + + std::filesystem::remove_all(temporary); + REQUIRE(odometer::save(store, path, today, std::chrono::days{365})); + CHECK(log.count(dropped) == 1); + CHECK_FALSE(read_text(read_file(path)).find("long ago").has_value()); + // the save after, which finds the file as written, doesn't log them again + REQUIRE(odometer::save(store, path, today, std::chrono::days{365})); + CHECK(log.count(dropped) == 1); +} diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index e920849b2..5e64e40c4 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -614,6 +614,14 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + // the saved odometer states of the vehicles not run for this many days are dropped, 0 = never (vehicle/odometer.h) + if (token == "odometer.expiry") + { + ParseOne(Parser, odometer_expiry); + odometer_expiry = std::max(0, odometer_expiry); + return true; + } + if (token == "blackbox") { bool blackbox{false}; @@ -1890,6 +1898,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "sound.efx.airabsorption", AudioAirAbsorption ); export_as_text( Output, "physicslog", WriteLogFlag ); export_as_text( Output, "physicslog.trains", WriteTrainLogFlag ); + export_as_text( Output, "odometer.expiry", odometer_expiry ); if( BlackBox ) { export_as_text( Output, "blackbox", *BlackBox ); } diff --git a/utilities/Globals.h b/utilities/Globals.h index 3b1441240..d37535778 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -131,6 +131,9 @@ struct global_settings { bool ParserLogIncludes{ true }; // simulation bool RealisticControlMode{ false }; // controls ability to steer the vehicle from outside views + // odometer.expiry: the saved odometer state of a vehicle not run for longer than this many days is dropped from the + // store (vehicle/odometer.h); 0 = never + int odometer_expiry{ 365 }; bool bEnableTraction{ true }; float fFriction{ 1.f }; // mnożnik tarcia - KURS90 float FrictionWeatherFactor{ 1.f }; diff --git a/utilities/inionlysettings.cpp b/utilities/inionlysettings.cpp index 9d6c587c2..fb8d8f58f 100644 --- a/utilities/inionlysettings.cpp +++ b/utilities/inionlysettings.cpp @@ -47,7 +47,8 @@ ini_only_settings::ini_only_settings(global_settings const &Settings) m_uart{Settings.uart_conf}, #endif m_feedback_mode{Settings.iFeedbackMode}, m_feedback_port{Settings.iFeedbackPort}, m_python_enabled{Settings.python_enabled}, - m_luascreens_enabled{Settings.luascreens_enabled}, m_lua_fulllibraries{Settings.lua_fulllibraries}, m_wasm_enabled{Settings.wasm_enabled} + m_luascreens_enabled{Settings.luascreens_enabled}, m_lua_fulllibraries{Settings.lua_fulllibraries}, m_wasm_enabled{Settings.wasm_enabled}, + m_odometer_expiry{Settings.odometer_expiry} { } @@ -90,5 +91,6 @@ std::vector ini_only_settings::restore(global_settings &Settin keep_off(Settings.luascreens_enabled, m_luascreens_enabled, "luascreens.enabled", changed); keep_off(Settings.lua_fulllibraries, m_lua_fulllibraries, "lua.fulllibraries", changed); keep_off(Settings.wasm_enabled, m_wasm_enabled, "wasm.enabled", changed); + keep(Settings.odometer_expiry, m_odometer_expiry, "odometer.expiry", changed); return changed; } diff --git a/utilities/inionlysettings.h b/utilities/inionlysettings.h index 667703b94..6dba86927 100644 --- a/utilities/inionlysettings.h +++ b/utilities/inionlysettings.h @@ -21,9 +21,10 @@ http://mozilla.org/MPL/2.0/. // (state_serializer::deserialize_config, global_settings::ConfigParse), and with these keys it would run a program // (execonexit, extcam.cmd, extcam.rec), write the screenshots elsewhere (screenshotsdir), open connections and ports // (network.server, network.client, zmq.address, motiontelemetry, uart, feedbackmode, feedbackport), switch back on a -// script runtime the player switched off (python.enabled, luascreens.enabled, wasm.enabled) or take its own scripts -// out of the sandbox (lua.fulllibraries). they keep what eu07.ini set; a scenery may still switch a runtime off, or -// keep its scripts in the sandbox when eu07.ini didn't, as it always could +// script runtime the player switched off (python.enabled, luascreens.enabled, wasm.enabled), take its own scripts +// out of the sandbox (lua.fulllibraries) or drop the odometer states the player keeps (odometer.expiry). they keep +// what eu07.ini set; a scenery may still switch a runtime off, or keep its scripts in the sandbox when eu07.ini didn't, +// as it always could class ini_only_settings { public: @@ -53,4 +54,5 @@ class ini_only_settings bool m_luascreens_enabled; bool m_lua_fulllibraries; bool m_wasm_enabled; + int m_odometer_expiry; }; diff --git a/vehicle/odometer.cpp b/vehicle/odometer.cpp index 484998e40..7495cbda2 100644 --- a/vehicle/odometer.cpp +++ b/vehicle/odometer.cpp @@ -15,13 +15,17 @@ http://mozilla.org/MPL/2.0/. #include "utilities/utilities.h" #include +#include #include #include #include +#include #include #include #include +#include #include +#include #ifdef _WIN32 #include #else @@ -62,8 +66,61 @@ std::optional parse_number(std::string const &Text) { } } +// the comment line which gives the day the states after it were last updated +constexpr std::string_view stamp_prefix{"# updated "}; + +// a whole number making up all of the text +std::optional parse_integer(std::string_view const Text) { + if (Text.empty() || Text.front() == '-') + return std::nullopt; + int value{0}; + auto const *const end{Text.data() + Text.size()}; + if (auto const [used, error] {std::from_chars(Text.data(), end, value)}; error != std::errc{} || used != end) + return std::nullopt; + return value; +} + +// day written as yyyy-mm-dd +std::optional parse_day(std::string_view const Text) { + if (Text.size() != 10 || Text[4] != '-' || Text[7] != '-') + return std::nullopt; + auto const year{parse_integer(Text.substr(0, 4))}; + auto const month{parse_integer(Text.substr(5, 2))}; + auto const dayofmonth{parse_integer(Text.substr(8, 2))}; + if (false == (year.has_value() && month.has_value() && dayofmonth.has_value())) + return std::nullopt; + std::chrono::year_month_day const date{std::chrono::year{*year}, std::chrono::month{static_cast(*month)}, + std::chrono::day{static_cast(*dayofmonth)}}; + if (false == date.ok()) + return std::nullopt; + return day{date}; +} + +std::string format_day(day const Day) { + std::chrono::year_month_day const date{Day}; + return std::format("{:04}-{:02}-{:02}", static_cast(date.year()), static_cast(date.month()), + static_cast(date.day())); +} + +// the day of a stamp line, as written, a day later than Today included. Today for a malformed one: the states after it +// are kept +day stamp_day(std::string_view const Line, day const Today) { + auto text{Line.substr(stamp_prefix.size())}; + while (false == text.empty() && (text.back() == ' ' || text.back() == '\t')) + text.remove_suffix(1); + return parse_day(text).value_or(Today); +} + } // namespace +day today() { + return std::chrono::floor(std::chrono::system_clock::now()); +} + +std::chrono::days expiry() { + return std::chrono::days{std::max(0, Global.odometer_expiry)}; +} + void reading::begin(double const Km, origin const Source) { km = Km; start = Km; @@ -89,12 +146,16 @@ bool reading::moved() const { return km != start; } -std::size_t store::read(std::istream &Input) { +std::size_t store::read(std::istream &Input, day const Today) { std::size_t count{0}; + // the states with no stamp before them, as the builds without the stamps wrote them, count as updated today + auto stamp{Today}; std::string line; while (std::getline(Input, line)) { if (false == line.empty() && line.back() == '\r') line.pop_back(); + if (line.starts_with(stamp_prefix)) + stamp = stamp_day(line, Today); if (line.empty() || line.front() == '#') continue; // the name goes last, it's the rest of the line after the separator @@ -109,7 +170,8 @@ std::size_t store::read(std::istream &Input) { auto const name{line.substr(separator + 1)}; if (false == km.has_value() || name.empty()) continue; - m_states[name] = state{*km, guessed}; + m_states[name] = state{*km, guessed, stamp}; + m_read_latest = std::max(m_read_latest.value_or(stamp), stamp); ++count; } return count; @@ -117,9 +179,23 @@ std::size_t store::read(std::istream &Input) { void store::write(std::ostream &Output) const { Output << "# odometer states of the vehicles: , ~ for one counted from a made up state\n"; + Output << "# the states after a line \"" << stamp_prefix << "\" were last updated on that day (UTC)\n"; Output << std::fixed << std::setprecision(4); - for (auto const &[name, state] : m_states) - Output << (state.guessed ? "~" : "") << state.km << ' ' << name << '\n'; + // by the day, then by the name as the map has them + std::vector::value_type const *> entries; + entries.reserve(m_states.size()); + for (auto const &entry : m_states) + entries.push_back(&entry); + std::ranges::stable_sort(entries, {}, [](auto const *Entry) { return Entry->second.updated; }); + std::optional group; + for (auto const *entry : entries) { + auto const &written{entry->second}; + if (group != written.updated) { + group = written.updated; + Output << stamp_prefix << format_day(written.updated) << '\n'; + } + Output << (written.guessed ? "~" : "") << written.km << ' ' << entry->first << '\n'; + } } std::optional store::find(std::string const &Vehicle) const { @@ -129,6 +205,13 @@ std::optional store::find(std::string const &Vehicle) const { return lookup->second.km; } +std::optional store::updated(std::string const &Vehicle) const { + auto const lookup{m_states.find(Vehicle)}; + if (lookup == m_states.end()) + return std::nullopt; + return lookup->second.updated; +} + bool store::guessed(std::string const &Vehicle) const { auto const lookup{m_states.find(Vehicle)}; return lookup != m_states.end() && lookup->second.guessed; @@ -140,10 +223,10 @@ bool store::newer(state const &Left, state const &Right) { return Left.km > Right.km; } -void store::record(std::string const &Vehicle, reading const &Odometer) { +void store::record(std::string const &Vehicle, reading const &Odometer, day const Today) { if (Vehicle.empty() || false == valid(Odometer.km)) return; - state const recorded{Odometer.km, Odometer.source == origin::guessed}; + state const recorded{Odometer.km, Odometer.source == origin::guessed, Today}; auto const lookup{m_states.find(Vehicle)}; if (lookup == m_states.end()) { if (false == Odometer.moved()) @@ -154,7 +237,10 @@ void store::record(std::string const &Vehicle, reading const &Odometer) { } if (false == newer(recorded, lookup->second)) return; + // a clock set back doesn't move the day back + auto const latest{std::max(lookup->second.updated, Today)}; lookup->second = recorded; + lookup->second.updated = latest; m_modified = true; } @@ -171,11 +257,25 @@ void record(store &States, std::string const &Vehicle, bool const Drivercab, rea void store::merge(store const &Other) { for (auto const &[name, other] : Other.m_states) { auto const [lookup, added] {m_states.try_emplace(name, other)}; - if (false == added && newer(other, lookup->second)) - lookup->second = other; + if (added) + continue; + auto &mine{lookup->second}; + auto const latest{std::max(mine.updated, other.updated)}; + if (newer(other, mine)) + mine = other; + mine.updated = latest; } } +std::size_t store::expire(day const Today, std::chrono::days const Period) { + if (Period <= std::chrono::days::zero()) + return 0; + // not from a later Today alone: a clock set forward, or the first save after a break, doesn't drop every state not + // run in this session + auto const since{std::min(Today, m_read_latest.value_or(Today))}; + return std::erase_if(m_states, [since, Period](auto const &Entry) { return since - Entry.second.updated > Period; }); +} + bool store::holds(store const &Other) const { return std::all_of(Other.m_states.begin(), Other.m_states.end(), [this](auto const &Entry) { auto const lookup{m_states.find(Entry.first)}; @@ -287,20 +387,21 @@ store &states() { namespace { // the states as the file holds them once written, the km rounded to the digits written -store as_written(store const &States) { +store as_written(store const &States, day const Today) { std::stringstream text; States.write(text); store result; - result.read(text); + result.read(text, Today); return result; } } // namespace -bool save(store &States, std::filesystem::path const &File) { +bool save(store &States, std::filesystem::path const &File, day const Today, std::chrono::days const Period) { if (false == States.modified() && false == States.unconfirmed()) return true; std::error_code error; + std::size_t expired{0}; if (File.has_parent_path()) std::filesystem::create_directories(File.parent_path(), error); // other simulations on the machine (multiplayer, parallel runs) keep their states in the same file: what they @@ -309,12 +410,16 @@ bool save(store &States, std::filesystem::path const &File) { store saved; std::ifstream input{File, std::ios::binary}; if (input.is_open()) - saved.read(input); + saved.read(input, Today); States.merge(saved); + // the vehicles not run for long, of this simulation and of the others alike, so the file doesn't keep every + // vehicle ever run. they're logged once the file is written without them: a save that doesn't write it leaves + // them in it (the next save that writes it drops them again), and a write that fails is tried again + expired = States.expire(Today, Period); // another simulation that read the file before the last save of this one and put its own in place after it // dropped the states this one wrote. when the file holds them all, the same or newer, there's nothing to write if (false == States.modified()) { - if (saved.holds(as_written(States))) { + if (saved.holds(as_written(States, Today))) { States.confirmed(); return true; } @@ -353,6 +458,8 @@ bool save(store &States, std::filesystem::path const &File) { return false; } States.saved(); + if (expired > 0) + WriteLog(std::format("Odometer states of {} vehicles not updated for {} days dropped", expired, Period.count())); return true; } diff --git a/vehicle/odometer.h b/vehicle/odometer.h index c7aa0950f..958a15f60 100644 --- a/vehicle/odometer.h +++ b/vehicle/odometer.h @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include #include #include #include @@ -23,6 +24,16 @@ http://mozilla.org/MPL/2.0/. // their own files namespace odometer { +// a calendar day, in UTC +using day = std::chrono::sys_days; +day today(); + +// a state not updated for longer than this is dropped from the store when it's saved: the vehicle wasn't run for that +// long. it's odometer.expiry in eu07.ini (global_settings::odometer_expiry), a year unless set there, 0 for never. +// a year so the vehicles of the scenarios played once a season or once a year, and of the players who take a break of a +// few months, keep their states; the file of the vehicles run within a year stays small all the same +std::chrono::days expiry(); + // the saved odometer states of the vehicles, km by vehicle name. the name is the one the scenario gives the vehicle // (the name of its node, TDynamicObject::name(), e.g. EU07-424), the only identity a vehicle has between the sessions: // the vehicles of the same name in any scenarios share one state, whatever their type, and a vehicle the scenario @@ -31,21 +42,36 @@ namespace odometer { class store { public: // reads the states written by write(). lines " ", "~ " for a state counted - // from a made up one, '#' starts a comment line, a malformed line is skipped. returns the number of states read - std::size_t read(std::istream &Input); + // from a made up one, '#' starts a comment line, a malformed line is skipped. returns the number of states read. + // the day a state was last updated is in a comment line "# updated " before it, which the builds + // without the stamps skip as any comment. a state with no stamp before it (a file of such a build) or with a + // malformed one counts as updated Today. a stamp is kept as written, also one later than Today (a clock set back + // doesn't move the days of the states back, expire() doesn't measure from them) + std::size_t read(std::istream &Input, day Today = today()); + // the states grouped by the day they were last updated, the oldest first, each group after its stamp line void write(std::ostream &Output) const; std::optional find(std::string const &Vehicle) const; // the state of the vehicle is counted from a made up one, which the cab's counter can still replace bool guessed(std::string const &Vehicle) const; + // the day the state of the vehicle was last updated + std::optional updated(std::string const &Vehicle) const; // records the state of a vehicle. one not in the store yet gets in only once it has run, so the vehicles // standing in the sceneries don't fill the file. a recorded state is replaced only by a newer one: a larger - // one, or a known one in place of a guessed one - void record(std::string const &Vehicle, reading const &Odometer); + // one, or a known one in place of a guessed one. a state recorded is updated Today, or keeps its later day: the day + // of a state never goes back + void record(std::string const &Vehicle, reading const &Odometer, day Today = today()); // takes the states of the other store (the file, as other simulations have saved it since) newer than these. // the odometers only count up, so of two states of a vehicle the larger is the newer one. they aren't added - // up: two simulations on one machine (multiplayer) count the same runs of the same vehicles + // up: two simulations on one machine (multiplayer) count the same runs of the same vehicles. a state is updated + // on the later of the days the two stores have void merge(store const &Other); + // drops the states not updated for longer than Period, 0 for none. the period is measured back from Today, or from + // the latest day of the states read() took when that's earlier: the last day the file was updated before this + // simulation read it. so a clock set forward doesn't drop the states at once (nor one set back, the days of the + // states are then later than Today), and a player back after a break keeps them in the session he comes back in; + // the states this session records, updated Today, don't count. returns the number dropped + std::size_t expire(day Today, std::chrono::days Period); // this store holds every state of the other one, the same or a newer one bool holds(store const &Other) const; @@ -65,11 +91,14 @@ private: struct state { double km{0.0}; bool guessed{false}; + day updated{}; }; // the first state is newer than the second one static bool newer(state const &Left, state const &Right); std::map m_states; + // the latest day of the states read() took + std::optional m_read_latest; bool m_modified{false}; bool m_unconfirmed{false}; }; @@ -125,8 +154,10 @@ std::filesystem::path file(); // writes the store to the file when anything was recorded since, merged with what other simulations saved in the // file meanwhile. it's written to a file of this process aside first, then put in place. with nothing recorded since, // the file is read once more after a write, and written again when it lacks any of the states (another simulation's -// save put its file over this one's); otherwise left as it is. returns false when the write failed -bool save(store &States, std::filesystem::path const &File); +// save put its file over this one's); otherwise left as it is. the states, those of the other simulations included, +// not updated for longer than Period (store::expire()) are dropped first; the number dropped is logged by the save that +// writes the file without them. returns false when the write failed +bool save(store &States, std::filesystem::path const &File, day Today = today(), std::chrono::days Period = expiry()); // saves the store of the simulation to its file. a test run doesn't save it bool save(); From fdbcdde140b1409d24647891a784b52c68ec80f4 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 26 Nov 2026 22:27:38 +0100 Subject: [PATCH 131/136] Diesel-electrics: a switch for the field shunting, with its cab control (#346) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: a switch of the field shunting of the diesel-electrics, and its cab control (GE#167) The SU45 and SP45 shunt the field of their motors by relays (RelayType 45), which the driver lets work with a toggle switch on the desk ("załączenie bocznikowania"). The game had no such switch: AutoRelay=Yes shunts always, and AutoRelay=Optional on a diesel-electric meant manual shunting with the switch off. No cab control showed the switch either, so the lever of the SU45's cab (zalaczbocznikow) had nothing to follow. - AutoRelay=Optional on a diesel-electric: switched off, no shunting at all (fieldshunting::diesel_electric() in the core library, used by IncScndCtrl() and the shunting relays in TractionForce()). No diesel-electric of the game data uses AutoRelay=Optional; AutoRelay=Yes and No don't change. - A new cab control, autorelay_sw:, showing AutoRelayFlag and toggling it with notchingrelaytoggle on a click. - The AI switches it on as it gets a diesel-electric ready. Needs the game data (SVN) to take effect, after the release: - dynamic/pkp/su45_v2/301d.fiz, sp45_v1/301db.fiz, 301db-152.fiz: AutoRelay=Yes -> AutoRelay=Optional - dynamic/pkp/su45_v2/301d.mmd, sp45_v1/301db.mmd, 301db-152.mmd, 301db_factory.mmd: add autorelay_sw: { zalaczbocznikow rot 0.11 0 0.1 soundinc: 20786_203E_switch_converter_2_on.wav sounddec: 20786_203E_switch_converter_2_of.wav } Without them the vehicles behave as before. * refactor(mover): the field shunting switch without Sonar issues The control is declared in the if that uses it, the relays' branch tests AutoRelayFlag as before (the same condition as the automatic control, and no deeper nesting on a changed line), using enum in diesel_electric(), and the test no longer shadows the name control. No change in behaviour. * fix(ai): the AI turns the field shunting switch on while running too It did so only in PrepareEngine(), which isn't called again while the engine runs, so a running SU45 handed to the AI with the switch off stayed on full field. * fix(mover): AutoRelay=Optional keeps its meaning, the field shunting switch is FieldShuntSwitch=Yes AutoRelay=Optional means again what it did for every diesel-electric: with the switch off, the driver shunts the field by hand with the second controller. The switch that leaves the field full when off, as on the SU45 and SP45, is opted into with a new Cntrl. key, FieldShuntSwitch=Yes, next to AutoRelay=Optional. A key rather than a new AutoRelay value: the parser reads an AutoRelay value it doesn't know as No, so an older exe would take the relays away from the SU45, while it skips an unknown key. The value stays Optional, which every check of the switch looks for. The AI switches it on only in a vehicle with the key; one with AutoRelay=Optional alone is left as before. The SVN data then needs "AutoRelay=Optional FieldShuntSwitch=Yes" on line 9 of su45_v2/301d.fiz, sp45_v1/301db.fiz and sp45_v1/301db-152.fiz, after this is released; without it nothing changes. --- CMakeLists.txt | 1 + McZapkie/MOVER.h | 3 + McZapkie/Mover.cpp | 11 +++- input/drivermouseinput.cpp | 3 + tests/unit/drive.cpp | 7 ++- tests/unit/test_field_shunting.cpp | 99 ++++++++++++++++++++++++++++++ vehicle/Driver.cpp | 17 +++++ vehicle/Driver.h | 1 + vehicle/Train.cpp | 8 +++ vehicle/Train.h | 1 + vehicle/fieldshunting.cpp | 27 ++++++++ vehicle/fieldshunting.h | 32 ++++++++++ 12 files changed, 207 insertions(+), 3 deletions(-) create mode 100644 tests/unit/test_field_shunting.cpp create mode 100644 vehicle/fieldshunting.cpp create mode 100644 vehicle/fieldshunting.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 6ed3b325e..93d374b94 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -574,6 +574,7 @@ set(CORE_SOURCES "utilities/physicslog.cpp" "vehicle/enginestart.cpp" "vehicle/brakesetting.cpp" +"vehicle/fieldshunting.cpp" "vehicle/gaugewrap.cpp" "vehicle/drivingaid.cpp" "vehicle/brakingcurve.cpp" diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 84a597e87..1458c632e 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -1903,6 +1903,9 @@ class TMoverParameters int FastSerialCircuit = 0; /*0 - po kolei zamyka styczniki az do osiagniecia szeregowej, 1 - natychmiastowe wejscie na szeregowa*/ /*hunter-111012*/ int BackwardsBranchesAllowed = 1; int AutoRelayType = 0; /*0 -brak, 1 - jest, 2 - opcja*/ + // FieldShuntSwitch=Yes: the switch of AutoRelay=Optional of a diesel-electric is its switch of the field shunting, as the SU45's + // and SP45's (fieldshunting.h): off, the field stays full. without it, off hands the shunting to the second controller, as before + bool FieldShuntSwitch = false; bool CoupledCtrl = false; /*czy mainctrl i scndctrl sa sprzezone*/ bool HasCamshaft{false}; int DynamicBrakeType = 0; /*patrz dbrake_**/ diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 1a25aac20..037e52fee 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/parser.h" #include "simulation/simulation.h" +#include "vehicle/fieldshunting.h" #include #include @@ -3714,7 +3715,8 @@ bool TMoverParameters::IncScndCtrl(int CtrlSpeed) { // TBD, TODO: refactor this validation as part of relay check routine (currently in tractionforce() // TBD, TODO: diesel electric engine utilize scndctrlactualpos like the other types? - if (EngineType == TEngineType::DieselElectric && (IsMainCtrlNoPowerPos() || AutoRelayFlag || ShuntMode || false == Mains)) + if (EngineType == TEngineType::DieselElectric && + (IsMainCtrlNoPowerPos() || fieldshunting::diesel_electric(AutoRelayType, FieldShuntSwitch, AutoRelayFlag) != fieldshunting::control::manual || ShuntMode || false == Mains)) { OK = false; } @@ -7470,12 +7472,14 @@ void TMoverParameters::DieselElectricTractionForce(double tmp) EngineVoltage = 0; // przekazniki bocznikowania, kazdy inny dla kazdej pozycji - if (false == StLinFlag || ShuntMode) + if (auto const fieldshuntingcontrol{fieldshunting::diesel_electric(AutoRelayType, FieldShuntSwitch, AutoRelayFlag)}; + false == StLinFlag || ShuntMode || fieldshuntingcontrol == fieldshunting::control::off) { ScndCtrlPos = 0; } else if (AutoRelayFlag) { + // the shunting relays set the field shunting (fieldshunting::control::automatic) ShuntFieldRelaysCheck(tmpV, PosRatio, tmp); } } @@ -13307,6 +13311,9 @@ void TMoverParameters::LoadFIZ_CntrlControllers(std::string const &line) { AutoRelayType = 0; } + // a key of its own rather than a new AutoRelay value: an exe that doesn't know it reads the line as before, and the value + // stays Optional, which every check of the switch looks for + extract_value(FieldShuntSwitch, "FieldShuntSwitch", line, ""); extract_value(CoupledCtrl, "CoupledCtrl", line, ""); extract_value(HasCamshaft, "Camshaft", line, ""); diff --git a/input/drivermouseinput.cpp b/input/drivermouseinput.cpp index d8d389f44..90414d312 100644 --- a/input/drivermouseinput.cpp +++ b/input/drivermouseinput.cpp @@ -616,6 +616,9 @@ drivermouse_input::default_bindings() { { "maxcurrent_sw:", { motoroverloadrelaythresholdtoggle, none } }, + { "autorelay_sw:", { + notchingrelaytoggle, + none } }, { "waterpumpbreaker_sw:", { waterpumpbreakertoggle, none } }, diff --git a/tests/unit/drive.cpp b/tests/unit/drive.cpp index b03eeac2d..02fc74c03 100644 --- a/tests/unit/drive.cpp +++ b/tests/unit/drive.cpp @@ -5,6 +5,7 @@ #include "doctest.h" #include "McZapkie/hamulce.h" +#include "vehicle/fieldshunting.h" namespace test { @@ -137,7 +138,8 @@ void close_line_breaker(driven const &Driven) { Driven.cab.MainSwitch(true); } -// the converter, the compressor and the motor blowers, once the line breaker is closed +// the converter, the compressor and the motor blowers, once the line breaker is closed; and the switch of the +// field shunting of a diesel-electric that has one (AutoRelay=Optional with FieldShuntSwitch=Yes), as the AI does void switch_auxiliaries_on(TMoverParameters &Cab) { Cab.ConverterSwitch(true); Cab.CompressorSwitch(true); @@ -147,6 +149,9 @@ void switch_auxiliaries_on(TMoverParameters &Cab) { Cab.MotorBlowersSwitch(true, side); } } + if (Cab.EngineType == TEngineType::DieselElectric && fieldshunting::has_switch(Cab.AutoRelayType, Cab.FieldShuntSwitch)) { + Cab.AutoRelaySwitch(true); + } } } // namespace diff --git a/tests/unit/test_field_shunting.cpp b/tests/unit/test_field_shunting.cpp new file mode 100644 index 000000000..e61783b0e --- /dev/null +++ b/tests/unit/test_field_shunting.cpp @@ -0,0 +1,99 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scenario.h" + +#include "vehicle/fieldshunting.h" + +// the field shunting of the diesel-electric locomotives, set by the driver or by the shunting relays, and the switch +// of the SU45 and the SP45 that lets the relays shunt the field ("załączenie bocznikowania", eu07/maszyna#167) + +using test::definition; +using test::scenario; +using namespace test::channels; + +TEST_CASE("field shunting: who shunts the field of a diesel-electric, by AutoRelay, FieldShuntSwitch and the switch") { + using enum fieldshunting::control; + struct setting { + int type; // AutoRelay: 0 No, 1 Yes, 2 Optional + bool fieldshuntswitch; // FieldShuntSwitch + bool flag; // the switch, AutoRelayFlag + fieldshunting::control expected; + }; + for (auto const &[type, fieldshuntswitch, flag, expected] : + {setting{0, false, false, manual}, setting{1, false, true, automatic}, + // AutoRelay=Optional alone, as before: off, the driver shunts by hand + setting{2, false, true, automatic}, setting{2, false, false, manual}, + // with FieldShuntSwitch=Yes the switch of the field shunting: off, nobody + setting{2, true, true, automatic}, setting{2, true, false, off}, + // FieldShuntSwitch=Yes without the switch (AutoRelay=Yes or No) changes nothing + setting{1, true, true, automatic}, setting{0, true, false, manual}, + // AutoRelaySwitch from a coupled vehicle turns the flag of every one off, as before + setting{1, false, false, manual}, setting{1, true, false, manual}}) { + CAPTURE(type); + CAPTURE(fieldshuntswitch); + CAPTURE(flag); + CHECK(fieldshunting::diesel_electric(type, fieldshuntswitch, flag) == expected); + CHECK(fieldshunting::has_switch(type, fieldshuntswitch) == (type == 2 && fieldshuntswitch)); + } +} + +TEST_CASE("field shunting: the SU45 with its switch, off at full power and switched on and off on the move") { + // the SU45 (RelayType 45) given the switch (AutoRelay=Optional, FieldShuntSwitch=Yes) its cab has, with a coach: + // off, the field stays full and the second controller can't shunt it; on, the relays shunt it as they do with + // AutoRelay=Yes; off again, the shunting drops + scenario scenario{"traction/field shunting switch/su45", motion() + traction()}; + scenario.train().add(definition::fiz("su45_v2/301d").set("Cntrl", "AutoRelay", "Optional").set("Cntrl", "FieldShuntSwitch", "Yes"), 1); + scenario.add("bdhpumn_v3/bdhpumn"); + REQUIRE(scenario.start_up()); + auto &su45{scenario.driver().controlling}; + REQUIRE(su45.AutoRelayType == 2); + REQUIRE(su45.FieldShuntSwitch); + // the driver switches it on as the AI does, getting the locomotive ready + CHECK(su45.AutoRelayFlag); + scenario.act("field shunting off"); + CHECK(su45.AutoRelaySwitch(false)); + scenario.get_going(); + scenario.full_power(120.0); + CHECK(su45.IsMainCtrlMaxPowerPos()); + CHECK(su45.StLinFlag); + CHECK(su45.ScndCtrlPos == 0); + CHECK_FALSE(su45.IncScndCtrl(1)); + scenario.wait(1.0); + CHECK(su45.ScndCtrlPos == 0); + // over 50 km/h, where the relays of the SU45 let the third stage in + CHECK(su45.Vel > 50.0); + scenario.act("field shunting on"); + CHECK(su45.AutoRelaySwitch(true)); + scenario.wait(30.0); + CHECK(su45.ScndCtrlPos == su45.ScndCtrlPosNo); + scenario.act("field shunting off on the move"); + CHECK(su45.AutoRelaySwitch(false)); + scenario.wait(1.0); + CHECK(su45.ScndCtrlPos == 0); + scenario.check(); +} + +TEST_CASE("field shunting: a diesel-electric with AutoRelay=Optional alone shunts by hand with the switch off, as before") { + // the SU45 with AutoRelay=Optional but no FieldShuntSwitch: the switch is the old one, off hands the shunting to the + // second controller, and the start-up (as the AI) leaves it off + scenario scenario{"traction/field shunting switch/su45 optional alone", motion() + traction()}; + scenario.train().add(definition::fiz("su45_v2/301d").set("Cntrl", "AutoRelay", "Optional"), 1); + scenario.add("bdhpumn_v3/bdhpumn"); + REQUIRE(scenario.start_up()); + auto &su45{scenario.driver().controlling}; + REQUIRE(su45.AutoRelayType == 2); + REQUIRE_FALSE(su45.FieldShuntSwitch); + CHECK_FALSE(su45.AutoRelayFlag); + scenario.get_going(); + scenario.full_power(120.0); + CHECK(su45.IsMainCtrlMaxPowerPos()); + CHECK(su45.StLinFlag); + // over 50 km/h: the relays don't shunt, the driver does + CHECK(su45.Vel > 50.0); + CHECK(su45.ScndCtrlPos == 0); + scenario.act("field shunting by hand"); + CHECK(su45.IncScndCtrl(1)); + scenario.wait(1.0); + CHECK(su45.ScndCtrlPos == 1); + scenario.check(); +} diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index dfe4ed1c6..a8477a061 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -23,6 +23,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/brakereleaser.h" #include "vehicle/brakesetting.h" #include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" #include "vehicle/handover.h" #include "vehicle/signalpassing.h" #include "vehicle/timetableservice.h" @@ -3330,6 +3331,7 @@ bool TController::PrepareEngine() cue_action( driver_hint::rearmotorblowerson ); } } + control_field_shunting(); // sync virtual brake state with the 'real' one if( mvOccupied->BrakeHandle != TBrakeHandle::NoHandle ) { std::unordered_map const brakepositions{ @@ -8778,9 +8780,24 @@ TController::control_tractive_and_braking_force() { #endif } +// the switch of the field shunting of a diesel-electric that has one (AutoRelay=Optional with FieldShuntSwitch=Yes): off, +// the field stays full. checked while running too, since a vehicle taken over with its engine running doesn't go through +// PrepareEngine(). a diesel-electric with AutoRelay=Optional alone is left as before, shunting by hand with the switch off +void TController::control_field_shunting() { + + if( AIControllFlag + && mvControlling->EngineType == TEngineType::DieselElectric + && fieldshunting::has_switch( mvControlling->AutoRelayType, mvControlling->FieldShuntSwitch ) + && false == mvControlling->AutoRelayFlag ) { + mvControlling->AutoRelaySwitch( true ); + } +} + // ensure relays are active void TController::control_relays() { + control_field_shunting(); + if( fActionTime < 0.0 ) { return; } if( IsAnyMotorOverloadRelayOpen ) { diff --git a/vehicle/Driver.h b/vehicle/Driver.h index a00a3935f..866c913b6 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -391,6 +391,7 @@ private: bool is_brake_charging_done() const; double consist_max_crp() const; bool is_departure_blocked( double const Delay ) const; + void control_field_shunting(); void control_relays(); void control_motor_connectors(); void control_tractive_force(); diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index f28f11d3b..2c5a8d560 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -1519,6 +1519,8 @@ void TTrain::OnCommand_notchingrelaytoggle(TTrain *Train, command_data const &Co // turn off Train->mvOccupied->AutoRelaySwitch(false); } + // visual feedback + Train->ggAutoRelayButton.UpdateValue(Train->mvOccupied->AutoRelayFlag ? 1.f : 0.f, Train->dsbSwitch); } } @@ -9890,6 +9892,8 @@ bool TTrain::Update(double const Deltatime) ggWiperSw.Update(); ggMaxCurrentCtrl.UpdateValue(true == mvControlled->ShuntModeAllow ? (true == mvControlled->ShuntMode ? 1.f : 0.f) : mvControlled->MotorOverloadRelayHighThreshold ? 1.f : 0.f); ggMaxCurrentCtrl.Update(); + ggAutoRelayButton.UpdateValue(mvOccupied->AutoRelayFlag ? 1.f : 0.f); + ggAutoRelayButton.Update(); // NBMX wrzesien 2003 - drzwi ggDoorLeftPermitButton.Update(lowvoltagepower); ggDoorRightPermitButton.Update(lowvoltagepower); @@ -11552,6 +11556,7 @@ void TTrain::clear_cab_controls() ggBrakeOperationModeCtrl.Clear(); ggWiperSw.Clear(); ggMaxCurrentCtrl.Clear(); + ggAutoRelayButton.Clear(); ggMainOffButton.Clear(); ggMainOnButton.Clear(); for (auto &remotelinebreaker : m_remotelinebreakers) @@ -11924,6 +11929,8 @@ void TTrain::set_cab_controls(int const Cab) ggCompressorListButton.PutValue(static_cast(mvOccupied->CompressorListPos - 1)); // motor overload relay threshold / shunt mode ggMaxCurrentCtrl.PutValue(true == mvControlled->ShuntModeAllow ? (true == mvControlled->ShuntMode ? 1.f : 0.f) : mvControlled->MotorOverloadRelayHighThreshold ? 1.f : 0.f); + // automatic relays (AutoRelay) + ggAutoRelayButton.PutValue(mvOccupied->AutoRelayFlag ? 1.f : 0.f); // lights ggLightsButton.PutValue(static_cast(mvOccupied->LightsPos - 1)); @@ -12329,6 +12336,7 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con {"brakeprofiler_sw:", ggBrakeProfileR}, {"brakeopmode_sw:", ggBrakeOperationModeCtrl}, {"maxcurrent_sw:", ggMaxCurrentCtrl}, + {"autorelay_sw:", ggAutoRelayButton}, {"main_off_bt:", ggMainOffButton}, {"main_on_bt:", ggMainOnButton}, {"mainb_sw:", m_remotelinebreakers[0].main_switch}, diff --git a/vehicle/Train.h b/vehicle/Train.h index c079c3f18..d0c3aaa8b 100644 --- a/vehicle/Train.h +++ b/vehicle/Train.h @@ -599,6 +599,7 @@ public: // reszta może by?publiczna TGauge ggWiperSw; // przelacznik wycieraczek TGauge ggMaxCurrentCtrl; + TGauge ggAutoRelayButton; // przełącznik AutoRelay: rozruch automatyczny, załączenie bocznikowania spalinowozu TGauge ggMainOffButton; TGauge ggMainOnButton; diff --git a/vehicle/fieldshunting.cpp b/vehicle/fieldshunting.cpp new file mode 100644 index 000000000..49300f50b --- /dev/null +++ b/vehicle/fieldshunting.cpp @@ -0,0 +1,27 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/fieldshunting.h" + +namespace fieldshunting { + +bool has_switch(int const Autorelaytype, bool const Fieldshuntswitch) { + return Autorelaytype == 2 && Fieldshuntswitch; +} + +control diesel_electric(int const Autorelaytype, bool const Fieldshuntswitch, bool const Autorelayflag) { + using enum control; + if (Autorelayflag) { + return automatic; + } + return has_switch(Autorelaytype, Fieldshuntswitch) ? off : manual; +} + +} // namespace fieldshunting diff --git a/vehicle/fieldshunting.h b/vehicle/fieldshunting.h new file mode 100644 index 000000000..2dec04be5 --- /dev/null +++ b/vehicle/fieldshunting.h @@ -0,0 +1,32 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +// the field shunting (ScndCtrlPos) of the diesel-electric locomotives +namespace fieldshunting { + +// who sets the field shunting +enum class control : int { + manual, // the driver, with the second controller + automatic, // the shunting relays (RelayType) + off // nobody: the shunting is switched off, the field stays full +}; + +// whether a diesel-electric has the switch that lets the relays shunt the field, as the SU45's and SP45's "załączenie +// bocznikowania" (eu07/maszyna#167): AutoRelay=Optional (Autorelaytype 2) with FieldShuntSwitch=Yes (Fieldshuntswitch) +bool has_switch(int Autorelaytype, bool Fieldshuntswitch); + +// who sets the field shunting of a diesel-electric locomotive, by its AutoRelay (Autorelaytype: 0 No, 1 Yes, 2 Optional), +// its FieldShuntSwitch (Fieldshuntswitch) and its AutoRelayFlag (Autorelayflag). with the flag set, the relays. with the +// switch of the field shunting (has_switch()) switched off, nobody. otherwise the driver, AutoRelay=Optional without +// FieldShuntSwitch included +control diesel_electric(int Autorelaytype, bool Fieldshuntswitch, bool Autorelayflag); + +} // namespace fieldshunting From 169527f33370f1a8ad6ac0d5c219d73b92465ae8 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 26 Nov 2026 22:28:58 +0100 Subject: [PATCH 132/136] feat(editor): dirt road type with looser layout limits in the road tool (#491) * feat(editor): dirt road type with looser layout limits in the road tool Every road shared the limits of a built road, so the road tool refused field tracks that bend tight, kink, have very short straights and fork at sharp angles (#347). Roads now have a type, paved (the default, with the limits as they were) or dirt, chosen in the road settings and saved with each piece as "surfacetype dirt". A dirt road bends down to a 3 m radius instead of 6 m, can be 1 m long instead of 2 m, leaves other roads at 15 degrees instead of 30, may lead off square to the far end when both ends are tied, and may turn up to 240 degrees in a hairpin. The limits come from one table, editor/editorRoadLimits.hpp, whose paved row holds the old constants. A paved road writes nothing new, so existing sceneries load and save byte for byte as before. Switching a road to dirt turns the default asphalt into the field road texture droga_polna from the game data and drops the white markings; a material picked by hand stays. * fix(editor): no bend of a road tighter than the road is wide, pi from , the type's name as a string_view --- application/editormoderoad.cpp | 33 +++++- editor/editorRoad.cpp | 36 +++--- editor/editorRoad.hpp | 14 ++- editor/editorRoadLimits.hpp | 52 +++++++++ lang/editor_pl.po | 12 ++ tests/unit/test_road_surface_type.cpp | 161 ++++++++++++++++++++++++++ world/Road.cpp | 9 ++ world/Road.h | 5 +- world/RoadSurfaceType.h | 63 ++++++++++ 9 files changed, 360 insertions(+), 25 deletions(-) create mode 100644 editor/editorRoadLimits.hpp create mode 100644 tests/unit/test_road_surface_type.cpp create mode 100644 world/RoadSurfaceType.h diff --git a/application/editormoderoad.cpp b/application/editormoderoad.cpp index 9c44c0550..78e2a5707 100644 --- a/application/editormoderoad.cpp +++ b/application/editormoderoad.cpp @@ -973,7 +973,8 @@ editor_mode::road_plan editor_mode::road_preview(bool const Fresh) auto const centre{road != nullptr ? road->definition().point(t) : junction->definition().centre}; // seen from the junction the road comes from where it's being led from glm::dvec2 const from{tool.point.x - centre.x, tool.point.z - centre.z}; - if (false == (road != nullptr ? editor_road::branch_from(*road, t, from, arriving, leaving, lanewidth, plan.end, plan.error) : editor_road::branch_from(*junction, from, arriving, leaving, lanewidth, plan.end, plan.error))) + if (false == (road != nullptr ? editor_road::branch_from(*road, t, from, arriving, leaving, lanewidth, layout.surfacetype, plan.end, plan.error) : + editor_road::branch_from(*junction, from, arriving, leaving, lanewidth, layout.surfacetype, plan.end, plan.error))) return plan; plan.hasend = true; auto const &arm{plan.end.layout.arms[plan.end.arm]}; @@ -1004,8 +1005,9 @@ editor_mode::road_plan editor_mode::road_preview(bool const Fresh) return plan; } // the axis of the road goes away from the junction, so the lanes going against it are the ones leading into the junction - if (false == (tool.branchroad != nullptr ? editor_road::branch_from(*tool.branchroad, tool.branchat, away, layout.backward, layout.forward, lanewidth, plan.start, plan.error) : - editor_road::branch_from(*tool.branchjunction, away, layout.backward, layout.forward, lanewidth, plan.start, plan.error))) + if (false == (tool.branchroad != nullptr ? + editor_road::branch_from(*tool.branchroad, tool.branchat, away, layout.backward, layout.forward, lanewidth, layout.surfacetype, plan.start, plan.error) : + editor_road::branch_from(*tool.branchjunction, away, layout.backward, layout.forward, lanewidth, layout.surfacetype, plan.start, plan.error))) return plan; plan.hasstart = true; auto const &arm{plan.start.layout.arms[plan.start.arm]}; @@ -1038,7 +1040,8 @@ editor_mode::road_plan editor_mode::road_preview(bool const Fresh) plan.error = STR_C("Too far from the last point"); return plan; } - plan.pieces = editor_road::plan(start, hasdirection ? &direction : nullptr, target, tied ? &enddirection : nullptr, Global.ctrlState, plan.error); + plan.pieces = editor_road::plan(start, hasdirection ? &direction : nullptr, target, tied ? &enddirection : nullptr, Global.ctrlState, layout.surfacetype, + 0.5 * std::max(layout.span(0.0), layout.span(1.0)), plan.error); road_profile(plan.pieces, hasgrade ? &startgrade : nullptr, tied ? &endgrade : nullptr, Fresh); return plan; } @@ -2076,6 +2079,28 @@ bool editor_mode::render_road_layout(road_node::state &State) // appearance ImGui::Separator(); + // what the road is made of sets how tight it can be laid out, and a road made dirt gets the look of a field road + char const *surfacetypes[]{STR_C("paved"), STR_C("dirt")}; + int surfacetype{State.surfacetype == road_surface_type::dirt ? 1 : 0}; + ImGui::SetNextItemWidth(120.0f); + if (ImGui::Combo(STR_C("Road type"), &surfacetype, surfacetypes, 2)) + { + auto const previous{State.surfacetype}; + State.surfacetype = (surfacetype == 1 ? road_surface_type::dirt : road_surface_type::paved); + if (State.surfacetype != previous) + { + // a surface left as the other type has it goes with the type, a surface picked by hand stays + if (State.surface == road_surface::default_material(previous)) + State.surface = road_surface::default_material(State.surfacetype); + if (State.surfacetype == road_surface_type::dirt && State.markings == road_node::marking_colour::white) + State.markings = road_node::marking_colour::none; + changed = true; + } + } + item_tooltip("Paved: asphalt, concrete or setts, with the bends and the junction angles of a built road.\n" + "Dirt: a track between fields or through a forest. It bends tighter (3 m radius instead of 6 m), can be shorter (1 m instead of 2 m),\n" + "leaves other roads at sharper angles (15 degrees instead of 30) and can turn back in a hairpin.\n" + "Made dirt, a road with the default asphalt gets the field road texture and loses the white lines"); char const *colours[]{STR_C("no markings"), STR_C("white"), STR_C("orange")}; int colour{State.markings == road_node::marking_colour::white ? 1 : State.markings == road_node::marking_colour::orange ? 2 : 0}; ImGui::SetNextItemWidth(120.0f); diff --git a/editor/editorRoad.cpp b/editor/editorRoad.cpp index b803416a8..32030932f 100644 --- a/editor/editorRoad.cpp +++ b/editor/editorRoad.cpp @@ -20,6 +20,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Globals.h" #include "utilities/utilities.h" #include "utilities/translation.h" +#include "editor/editorRoadLimits.hpp" #include #include @@ -30,10 +31,8 @@ namespace double const kSamePoint{0.25}; // ends of two pieces this close are taken for joined double const kPieceLength{50.0}; // longest piece the planner makes double const kPieceTurn{glm::radians(30.0)}; // largest turn of a single piece -double const kShortestRoad{2.0}; -double const kTightestRadius{6.0}; +// the shortest road, the tightest bend and the sharpest angle between roads go by what the road is made of: road_limits_for() double const kCornerRoom{4.0}; // length of an arm of a junction past the point where its edge meets the edge of the next one, taken by the rounded corner -double const kSharpestBranch{glm::radians(30.0)}; // smallest angle between two roads leaving a junction double const kWidestCorner{glm::radians(120.0)}; // arms further apart than this don't have to make room for each other double const kTransitionLength{30.0}; // length of the road taken by a change of its lanes @@ -276,7 +275,7 @@ bool follow(road_node &Road, double const T, bool const Forward, double const Di auto const here{station_at(lengths, from)}; auto const available{forward ? lengths.back() - here : here}; // what's left of a piece of a roundabout carries on round, so it can be shorter than a road of its own - auto const shortest{state.roundabout ? editor_ring::shortest_piece : kShortestRoad}; + auto const shortest{state.roundabout ? editor_ring::shortest_piece : road_limits_for(state.surfacetype).shortest_road}; if (remaining <= 0.0 || available >= remaining + shortest) { // the cut is put here; with nothing left to go the piece is kept whole @@ -1393,12 +1392,15 @@ editor_road::loose_end editor_road::find_end(glm::dvec3 const &Point, double con return result; } -std::vector editor_road::plan(glm::dvec3 const &Start, glm::dvec2 const *Direction, glm::dvec3 const &Target, glm::dvec2 const *Enddirection, bool const Straight, std::string &Error) +std::vector editor_road::plan(glm::dvec3 const &Start, glm::dvec2 const *Direction, glm::dvec3 const &Target, glm::dvec2 const *Enddirection, bool const Straight, + road_surface_type const Type, double const Halfwidth, std::string &Error) { std::vector pieces; glm::dvec2 const chord{Target.x - Start.x, Target.z - Start.z}; auto const span{glm::length(chord)}; - if (span < kShortestRoad) + auto const limits{road_limits_for(Type)}; + auto const tightest{editor_road_limits::tightest_bend(limits, Halfwidth)}; + if (span < limits.shortest_road) { Error = "Too short"; return pieces; @@ -1418,7 +1420,7 @@ std::vector editor_road::plan(glm::dvec3 const &Start, glm::dvec2 if (Direction != nullptr && Enddirection != nullptr) { // both ends are tied, which leaves a single curve with the tangents set - if (glm::dot(*Direction, chord) < 0.1 * span || glm::dot(*Enddirection, chord) < 0.1 * span) + if (glm::dot(*Direction, chord) < limits.tied_lead * span || glm::dot(*Enddirection, chord) < limits.tied_lead * span) { Error = "The road would have to turn back to meet the end"; return pieces; @@ -1436,7 +1438,7 @@ std::vector editor_road::plan(glm::dvec3 const &Start, glm::dvec2 straight(Target); return pieces; } - if (radius < kTightestRadius) + if (radius < tightest) { Error = "The bend is too tight"; return pieces; @@ -1449,7 +1451,7 @@ std::vector editor_road::plan(glm::dvec3 const &Start, glm::dvec2 { // only the far end is tied: the same road as the one leading back from there, turned around glm::dvec2 const back{-*Enddirection}; - auto reversed{plan(Target, &back, Start, nullptr, Straight, Error)}; + auto reversed{plan(Target, &back, Start, nullptr, Straight, Type, Halfwidth, Error)}; for (auto &piece : reversed) { std::swap(piece.points[segment_data::point::start], piece.points[segment_data::point::end]); @@ -1471,7 +1473,7 @@ std::vector editor_road::plan(glm::dvec3 const &Start, glm::dvec2 auto const side{glm::dot(chord, left)}; if (Straight || std::abs(side) < 0.02 * span) { - if (along < kShortestRoad) + if (along < limits.shortest_road) { Error = "The target is behind the start"; return pieces; @@ -1481,12 +1483,12 @@ std::vector editor_road::plan(glm::dvec3 const &Start, glm::dvec2 } auto const turn{2.0 * std::atan2(side, along)}; // positive to the left auto const radius{span * span / (2.0 * side)}; // likewise - if (std::abs(turn) > glm::radians(170.0)) + if (std::abs(turn) > limits.widest_turn) { Error = "The road would have to turn back to reach the target"; return pieces; } - if (std::abs(radius) < kTightestRadius) + if (std::abs(radius) < tightest) { Error = "The bend is too tight"; return pieces; @@ -1847,7 +1849,8 @@ bool editor_road::lane_width(road_node::state const &State, double const T, floa return true; } -bool editor_road::branch_from(road_node &Road, double const T, glm::dvec2 const &Direction, int const Incoming, int const Outgoing, float const Width, branch &Result, std::string &Error) +bool editor_road::branch_from(road_node &Road, double const T, glm::dvec2 const &Direction, int const Incoming, int const Outgoing, float const Width, road_surface_type const Type, branch &Result, + std::string &Error) { Result = branch{}; auto const &layout{Road.definition()}; @@ -1856,7 +1859,7 @@ bool editor_road::branch_from(road_node &Road, double const T, glm::dvec2 const auto const direction{glm::length(Direction) > 1e-9 ? glm::normalize(Direction) : glm::dvec2{0.0, 1.0}}; // the sharper the angle the road leaves at, the further from the centre the edges of the roads part auto const angle{std::acos(std::clamp(std::abs(glm::dot(direction, along)), 0.0, 1.0))}; - if (angle < kSharpestBranch) + if (angle < road_limits_for(Type).sharpest_branch) { Error = "The road would leave at too sharp an angle"; return false; @@ -1974,7 +1977,8 @@ bool editor_road::branch_from(road_node &Road, double const T, glm::dvec2 const return true; } -bool editor_road::branch_from(junction_node &Junction, glm::dvec2 const &Direction, int const Incoming, int const Outgoing, float const Width, branch &Result, std::string &Error) +bool editor_road::branch_from(junction_node &Junction, glm::dvec2 const &Direction, int const Incoming, int const Outgoing, float const Width, road_surface_type const Type, branch &Result, + std::string &Error) { Result = branch{}; auto const &layout{Junction.definition()}; @@ -1997,7 +2001,7 @@ bool editor_road::branch_from(junction_node &Junction, glm::dvec2 const &Directi { auto const &other{layout.arms[idx]}; auto const angle{std::acos(std::clamp(glm::dot(direction, other.direction), -1.0, 1.0))}; - if (angle < kSharpestBranch) + if (angle < road_limits_for(Type).sharpest_branch) { Error = "The road would leave too close to another road of the junction"; return false; diff --git a/editor/editorRoad.hpp b/editor/editorRoad.hpp index 51498b143..fc70f846f 100644 --- a/editor/editorRoad.hpp +++ b/editor/editorRoad.hpp @@ -142,11 +142,14 @@ class editor_road // width shared by all lanes of the road at specified value of the curve parameter of its axis. returns: false if the lanes differ in width static bool lane_width(road_node::state const &State, double const T, float &Width); // lays out a junction for a road leaving the side of specified piece at specified value of the curve parameter of its axis. - // Direction: the way the road leaves; Incoming, Outgoing: lanes of that road leading into the junction and out of it. + // Direction: the way the road leaves; Incoming, Outgoing: lanes of that road leading into the junction and out of it; + // Type: what that road is made of, which sets how sharp an angle it can leave at. // nothing is changed until the result is carried out. returns: false if it can't be done, with the reason in Error - static bool branch_from(road_node &Road, double const T, glm::dvec2 const &Direction, int const Incoming, int const Outgoing, float const Width, branch &Result, std::string &Error); + static bool branch_from(road_node &Road, double const T, glm::dvec2 const &Direction, int const Incoming, int const Outgoing, float const Width, road_surface_type const Type, branch &Result, + std::string &Error); // the same for a road leaving a junction between its arms, which gives the junction another arm - static bool branch_from(junction_node &Junction, glm::dvec2 const &Direction, int const Incoming, int const Outgoing, float const Width, branch &Result, std::string &Error); + static bool branch_from(junction_node &Junction, glm::dvec2 const &Direction, int const Incoming, int const Outgoing, float const Width, road_surface_type const Type, branch &Result, + std::string &Error); // makes the junction laid out for a branch, or gives the existing one its new arm, and cuts the roads to fit. what it does is added to Record. // returns: the junction static junction_node *carry_out(branch const &Branch, record &Record); @@ -156,8 +159,11 @@ class editor_road static loose_end find_end(glm::dvec3 const &Point, double const Radius, bool const Junctions = true); // lays out axes of the pieces for a road leading from a point to another. the directions are optional requirements // for the road at its ends; without them it starts straight at the target, with them it bends to meet them. + // Type: what the road is made of, which sets how tight it can bend and how short it can be; Halfwidth: of the road on each side + // of its axis, which no bend is tighter than (with some room). // returns: the axes in order, or nothing if there's no reasonable road to make, with the reason in Error - static std::vector plan(glm::dvec3 const &Start, glm::dvec2 const *Direction, glm::dvec3 const &Target, glm::dvec2 const *Enddirection, bool const Straight, std::string &Error); + static std::vector plan(glm::dvec3 const &Start, glm::dvec2 const *Direction, glm::dvec3 const &Target, glm::dvec2 const *Enddirection, bool const Straight, + road_surface_type const Type, double const Halfwidth, std::string &Error); // cuts the pieces so none is longer than specified static std::vector refine(std::vector const &Pieces, double const Length); // gives a string of pieces a smooth profile running through provided heights. diff --git a/editor/editorRoadLimits.hpp b/editor/editorRoadLimits.hpp new file mode 100644 index 000000000..11822c6a8 --- /dev/null +++ b/editor/editorRoadLimits.hpp @@ -0,0 +1,52 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include "world/RoadSurfaceType.h" + +#include +#include + +// how tight a road the road editor lays out, by what the road is made of +struct road_limits +{ + double tightest_radius; // smallest radius of a bend [m] + double shortest_road; // shortest road, and shortest piece left of a road cut for a junction [m] + double sharpest_branch; // smallest angle between two roads leaving a junction [rad] + // a road with both ends tied to a direction: the least part of the distance between the ends each end has to lead towards the other + double tied_lead; + double widest_turn; // a road with its start tied to a direction: the largest turn of the arc leading to the target [rad] +}; + +namespace editor_road_limits +{ + +inline constexpr double degree{std::numbers::pi / 180.0}; +// a paved road: the limits the editor had for every road before the types +inline constexpr road_limits paved{6.0, 2.0, 30.0 * degree, 0.1, 170.0 * degree}; +// a dirt road follows the ground between the fields: a tractor's bend, short stretches between the bends, a fork at a sharp angle, +// a hairpin, an end leading off square to the way to the other end +inline constexpr road_limits dirt{3.0, 1.0, 15.0 * degree, 0.0, 240.0 * degree}; +// room the inner edge of a bend keeps from the centre of the bend, as on a roundabout [m] +inline constexpr double inner_edge_room{1.0}; + +// smallest radius of a bend of a road with these limits, Halfwidth [m] wide on each side of its axis: the limit, and no less than +// leaves the inner edge of the road short of the centre of the bend, where the surface would fold over itself +inline double tightest_bend(road_limits const &Limits, double const Halfwidth) +{ + return std::max(Limits.tightest_radius, Halfwidth + inner_edge_room); +} + +} // namespace editor_road_limits + +inline constexpr road_limits road_limits_for(road_surface_type const Type) +{ + return Type == road_surface_type::dirt ? editor_road_limits::dirt : editor_road_limits::paved; +} diff --git a/lang/editor_pl.po b/lang/editor_pl.po index 6484fdd75..313742157 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -8073,6 +8073,18 @@ msgstr "Pas rozwidla się najwyżej na trzy: na pasy dodane ponad dwa nie da si msgid "Lane width [m]" msgstr "Szerokość pasa (m)" +msgid "paved" +msgstr "utwardzona" + +msgid "dirt" +msgstr "gruntowa" + +msgid "Road type" +msgstr "Rodzaj drogi" + +msgid "Paved: asphalt, concrete or setts, with the bends and the junction angles of a built road.\nDirt: a track between fields or through a forest. It bends tighter (3 m radius instead of 6 m), can be shorter (1 m instead of 2 m),\nleaves other roads at sharper angles (15 degrees instead of 30) and can turn back in a hairpin.\nMade dirt, a road with the default asphalt gets the field road texture and loses the white lines" +msgstr "Utwardzona: asfalt, beton albo kostka, z łukami i kątami skrzyżowań jak na drodze budowanej.\nGruntowa: droga polna albo leśna. Skręca ciaśniej (promień 3 m zamiast 6 m), może być krótsza (1 m zamiast 2 m),\nodchodzi od innych dróg pod ostrzejszym kątem (15 stopni zamiast 30) i może zawrócić serpentyną.\nDroga z domyślnym asfaltem zmieniona na gruntową dostaje teksturę drogi polnej i traci białe linie" + msgid "Left side" msgstr "Lewa strona" diff --git a/tests/unit/test_road_surface_type.cpp b/tests/unit/test_road_surface_type.cpp new file mode 100644 index 000000000..dfe7e14a1 --- /dev/null +++ b/tests/unit/test_road_surface_type.cpp @@ -0,0 +1,161 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "editor/editorRoadLimits.hpp" +#include "utilities/parser.h" + +#include +#include + +// the type of a road's surface (eu07/maszyna GH#347): a dirt road, a track between fields, can be laid out tighter than +// a paved one; the type is saved with the road, and the roads made before the types load and save as they did + +namespace { + +// what the scenery entry of a road says about its surface, read the way road_node::import_from() reads it: +// a road which doesn't say what it's made of is paved +struct surface_read +{ + std::string material{"asphaltdark1"}; + road_surface_type type{road_surface_type::paved}; + float texturelength{4.f}; + bool bad{false}; // an unknown type was named + std::string next; // the token which follows the read properties +}; + +surface_read read(std::string const &Entry) { + surface_read result; + cParser parser(Entry, cParser::buffer_TEXT); + auto token{parser.getToken()}; + while (false == token.empty() && token != "endroad") { + if (token == "surface") { + result.material = parser.getToken(); + } + else if (token == "surfacetype") { + if (false == road_surface::from_name(parser.getToken(), result.type)) + result.bad = true; + } + else if (token == "texlength") { + parser.getTokens(); + parser >> result.texturelength; + } + else { + result.next = token; + break; + } + token = parser.getToken(); + } + return result; +} + +// the appearance part of the scenery entry, written the way road_node::export_as_text_() writes it +std::string write(std::string const &Material, road_surface_type const Type, float const Texturelength) { + std::ostringstream output; + output << "surface " << Material << ' ' << "texlength " << Texturelength << ' '; + output << road_surface::entry(Type); + output << "side left shoulder 1.5 grass "; + return output.str(); +} + +} // namespace + +TEST_CASE("road surface type: a paved road keeps the limits every road had before the types") { + // the values editorRoad.cpp had as kTightestRadius, kShortestRoad, kSharpestBranch and in editor_road::plan() + auto const paved{road_limits_for(road_surface_type::paved)}; + CHECK(paved.tightest_radius == doctest::Approx(6.0)); + CHECK(paved.shortest_road == doctest::Approx(2.0)); + CHECK(paved.sharpest_branch == doctest::Approx(glm::radians(30.0))); + CHECK(paved.tied_lead == doctest::Approx(0.1)); + CHECK(paved.widest_turn == doctest::Approx(glm::radians(170.0))); +} + +TEST_CASE("road surface type: a dirt road is laid out more freely in every respect") { + auto const paved{road_limits_for(road_surface_type::paved)}; + auto const dirt{road_limits_for(road_surface_type::dirt)}; + // a bend a tractor makes on a single lane track + CHECK(dirt.tightest_radius < paved.tightest_radius); + CHECK(dirt.tightest_radius > 0.0); + CHECK(dirt.shortest_road < paved.shortest_road); + CHECK(dirt.shortest_road > 0.0); + CHECK(dirt.sharpest_branch < paved.sharpest_branch); + CHECK(dirt.sharpest_branch > 0.0); + // an end may lead off square to the way to the other end, but not away from it + CHECK(dirt.tied_lead < paved.tied_lead); + CHECK(dirt.tied_lead >= 0.0); + // a hairpin: the arc may turn past a half circle + CHECK(dirt.widest_turn > glm::radians(180.0)); + CHECK(dirt.widest_turn < glm::radians(360.0)); +} + +TEST_CASE("road surface type: no bend is tighter than the road is wide") { + auto const paved{road_limits_for(road_surface_type::paved)}; + auto const dirt{road_limits_for(road_surface_type::dirt)}; + // a single 3 m lane: the limit of the type + CHECK(editor_road_limits::tightest_bend(dirt, 1.5) == doctest::Approx(dirt.tightest_radius)); + // the layout the tool starts with, a 3.5 m lane each way: the inner edge 3.5 m from the axis keeps its room from the centre + CHECK(editor_road_limits::tightest_bend(dirt, 3.5) == doctest::Approx(3.5 + editor_road_limits::inner_edge_room)); + CHECK(editor_road_limits::tightest_bend(dirt, 3.5) > dirt.tightest_radius); + // a paved road of that layout keeps the limit it had + CHECK(editor_road_limits::tightest_bend(paved, 3.5) == doctest::Approx(paved.tightest_radius)); + // and a wide one is held to its width + CHECK(editor_road_limits::tightest_bend(paved, 7.0) == doctest::Approx(7.0 + editor_road_limits::inner_edge_room)); +} + +TEST_CASE("road surface type: the types go by their scenery names") { + for (auto const type : {road_surface_type::paved, road_surface_type::dirt}) { + CAPTURE(road_surface::name(type)); + road_surface_type read{type == road_surface_type::paved ? road_surface_type::dirt : road_surface_type::paved}; + CHECK(road_surface::from_name(road_surface::name(type), read)); + CHECK(read == type); + } + CHECK(std::string{road_surface::name(road_surface_type::paved)} == "paved"); + CHECK(std::string{road_surface::name(road_surface_type::dirt)} == "dirt"); + // an unknown name changes nothing + road_surface_type type{road_surface_type::dirt}; + CHECK_FALSE(road_surface::from_name("gravel", type)); + CHECK(type == road_surface_type::dirt); + CHECK_FALSE(road_surface::from_name("", type)); + CHECK(type == road_surface_type::dirt); +} + +TEST_CASE("road surface type: a paved road is saved as the roads were before the types") { + CHECK(road_surface::entry(road_surface_type::paved).empty()); + CHECK(write("asphaltdark1", road_surface_type::paved, 4.f) == "surface asphaltdark1 texlength 4 side left shoulder 1.5 grass "); + // and an entry of a road made before the types reads paved, with what follows read as before + auto const old{read("surface asphalt2 texlength 6 side left shoulder 1.5 grass endroad")}; + CHECK(old.type == road_surface_type::paved); + CHECK(old.material == "asphalt2"); + CHECK(old.texturelength == doctest::Approx(6.f)); + CHECK(old.next == "side"); + CHECK_FALSE(old.bad); +} + +TEST_CASE("road surface type: a dirt road is saved with its type and read back") { + auto const text{write(road_surface::default_material(road_surface_type::dirt), road_surface_type::dirt, 5.f)}; + CHECK(text == "surface droga_polna texlength 5 surfacetype dirt side left shoulder 1.5 grass "); + auto const back{read(text)}; + CHECK(back.type == road_surface_type::dirt); + CHECK(back.material == "droga_polna"); + CHECK(back.texturelength == doctest::Approx(5.f)); + CHECK(back.next == "side"); + CHECK_FALSE(back.bad); + // and written again it's the same + CHECK(write(back.material, back.type, back.texturelength) == text); + // the type is read wherever it stands among the properties, and an explicit paved reads as the default + CHECK(read("surfacetype dirt surface droga_polna endroad").type == road_surface_type::dirt); + CHECK(read("surface asphaltdark1 surfacetype paved endroad").type == road_surface_type::paved); +} + +TEST_CASE("road surface type: an unknown type leaves the road paved") { + auto const back{read("surface asphaltdark1 surfacetype cobbles texlength 4 side")}; + CHECK(back.bad); + CHECK(back.type == road_surface_type::paved); + // the unknown name is taken as the value of the type, not as the next property + CHECK(back.texturelength == doctest::Approx(4.f)); + CHECK(back.next == "side"); +} + +TEST_CASE("road surface type: a road made dirt or paved gets the surface of the type") { + CHECK(std::string{road_surface::default_material(road_surface_type::paved)} == "asphaltdark1"); + CHECK(std::string{road_surface::default_material(road_surface_type::dirt)} == "droga_polna"); +} diff --git a/world/Road.cpp b/world/Road.cpp index 79fc54f84..d389378da 100644 --- a/world/Road.cpp +++ b/world/Road.cpp @@ -956,6 +956,14 @@ void road_node::import_from(cParser &Input, glm::dvec3 const &Offset) m_state.surface = Input.getToken(); replace_slashes(m_state.surface); } + else if (token == "surfacetype") + { + auto const type{Input.getToken()}; + if (false == road_surface::from_name(type, m_state.surfacetype)) + { + ErrorLog("Bad road: unknown surface type \"" + type + "\" defined for " + label + ", paved is used instead"); + } + } else if (token == "texlength") { Input.getTokens(); @@ -4135,6 +4143,7 @@ void road_node::export_as_text_(std::ostream &Output) const } // appearance Output << "surface " << road.surface << ' ' << "texlength " << road.texturelength << ' '; + Output << road_surface::entry(road.surfacetype); char const *sidenames[]{"left", "right"}; for (int side = 0; side < 2; ++side) { diff --git a/world/Road.h b/world/Road.h index 93f4b4a11..139bbfad9 100644 --- a/world/Road.h +++ b/world/Road.h @@ -19,6 +19,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Names.h" #include "scene/scenenode.h" #include "world/Segment.h" +#include "world/RoadSurfaceType.h" namespace scene { @@ -59,6 +60,7 @@ class owned_shapes // medianround , // kerbs , bank , // bankmaterial , weight , roundabout, +// surfacetype : what the road is made of, which sets how tight the road editor lets it be laid out; paved unless told otherwise, // lanesto : lanes the piece has at the end of its axis, where these aren't the ones it starts with class road_node : public scene::basic_node { @@ -134,7 +136,8 @@ class road_node : public scene::basic_node std::vector lanes; std::vector changes; // permissions to change the lane, one for each pair of neighbouring lanes std::array taper{1.f, 1.f}; // what the widths of the lanes are multiplied by at the start and at the end of the axis - std::string surface{"asphaltdark1"}; + std::string surface{road_surface::default_material(road_surface_type::paved)}; + road_surface_type surfacetype{road_surface_type::paved}; // what the road is made of, as far as laying it out goes float texturelength{4.f}; std::array sides; // left, right float kerbheight{0.12f}; diff --git a/world/RoadSurfaceType.h b/world/RoadSurfaceType.h new file mode 100644 index 000000000..d71215ba2 --- /dev/null +++ b/world/RoadSurfaceType.h @@ -0,0 +1,63 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include + +// what a road is made of, as far as laying it out goes. a paved road (asphalt, concrete, setts) keeps to the bends and the angles +// of a built road; a dirt road (a track between fields, through a forest) turns tighter, comes in shorter stretches +// and leaves other roads at sharper angles. +// scenery entry: surfacetype , written for a dirt road only +enum class road_surface_type +{ + paved, + dirt +}; + +namespace road_surface +{ + +// the word the scenery uses for the type +inline char const *name(road_surface_type const Type) +{ + return Type == road_surface_type::dirt ? "dirt" : "paved"; +} + +// the type going by specified word. returns: false if there's no such type, with Type left as it was +inline bool from_name(std::string_view const Name, road_surface_type &Type) +{ + if (Name == "paved") + { + Type = road_surface_type::paved; + return true; + } + if (Name == "dirt") + { + Type = road_surface_type::dirt; + return true; + } + return false; +} + +// the scenery entry of the type, followed by a space. a paved road, which all the roads made before the types are, writes nothing, +// so the sceneries are saved as they were +inline std::string entry(road_surface_type const Type) +{ + return Type == road_surface_type::paved ? std::string{} : std::string{"surfacetype "} + name(Type) + ' '; +} + +// the material the surface of a road of the type gets unless told otherwise: the default asphalt, or the field road of the game's textures +inline char const *default_material(road_surface_type const Type) +{ + return Type == road_surface_type::dirt ? "droga_polna" : "asphaltdark1"; +} + +} // namespace road_surface From 919b4af043310e3fe02daf3e7518fa55bdf907e1 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 26 Nov 2026 22:29:09 +0100 Subject: [PATCH 133/136] feat(physics): dual-mode vehicles, stage 1: a genset as a second source of the traction circuit (GE#536) (#471) * test(scenarios): AI through a section without voltage and with interlocked line contactors Scenario cases for the parts of #272 (line breaker ahead of the pantographs, PantRequiresMain) and #276 (line contactors interlocked with the vehicle's own converter, LineContactorsInterlock) that had not been run in the simulator before. They all run the AI on the timetable run of td.scn. - ep05_td_dead_section: an EP05 runs under power into a 61 m span of overhead wire that has no voltage. Its line breaker stays closed, the traction force drops to 0, and behind the span the AI takes power again and stops at Przystanek. eu07_td_dead_section is the same run with an EU07, as a reference for the old behaviour: its line breaker opens after 0.2 s and the AI closes it again. - ep05_td_neutral_section: the same span, with the track under it marked overhead 0. The AI coasts from before the dead wire. - ep05_td_section_insulator: a 1 m section insulator, run under power. The 0.2 s voltage hold keeps the traction force up past it. - et42_td_converter_interlock(_cold): an ET42 with the interlock starts up and runs its timetable. - ep05_td_interlock_dead_section_cold: both keys on one EP05, starting cold, with the dead span on its way. - ep05_td_timetable: the plain timetable run of the EP05, as a reference. The runner gets vehicle_variants, a vehicle of the case's own made from one of the game's with .fiz replacements. The game's ET42 data doesn't have the interlock key yet. The runner also gets two new checks: traction (the traction force between two distances travelled) and master_controller. The local converter switch of #276 can't be covered: only the cab can set it, and in test mode nobody sits in a cab. * feat(physics): the genset of a dual-mode vehicle, a second source of the traction circuit (GE#536) A vehicle with induction motors and pantographs can have a diesel generator set as well (Power: GensetPower and the other Genset* keys, Cntrl. GensetStart). The traction selector picks the source of the traction circuit: the catenary through the pantographs, as before, or the genset. It moves only with the line breaker open. - the genset starts on request with the battery on, cranks for GensetStartTime, then runs at idle and up to full revolutions with the traction demand; stopped, it coasts down. It gives its regulated voltage from the idle revolutions up. - on the genset the line breaker closes only on a running genset, the undervoltage trip works at half its voltage, the traction power is capped at the genset's power at its present revolutions times GensetPmaxRatio, braking sends nothing back, and the pantographs' pressure switch is left out. The genset's voltage goes to the train's high voltage line as the pantographs' does. - the commands TractionMode and GensetSwitch pass along the train and can come from a scenery's PutValues. Nothing changes without GensetPower: the selector stays on the catenary and every new branch is unreachable. The keys are ignored, with a line in the log, on a vehicle which isn't an induction motor one fed by pantographs. * feat(cab): the traction selector and the genset switch of a dual-mode vehicle (GE#536) New commands tractionmodetoggle, tractionmodecatenary, tractionmodegenset (shift+G toggles) and gensettoggle, gensetenable, gensetdisable (ctrl+G toggles), and the two-state cab switches tractionmode_sw: and genset_sw:. The selector switch doesn't move while the line breaker is closed. Both act on the whole train, as the fuel pump switch does. A cab without the switches works as before. * test: the genset of a dual-mode vehicle (GE#536) The game's E6ACT with the genset of the E6ACTad "last mile" set in the test (520 kW, the rest assumed): the keys and their defaults, the selector's interlock with the line breaker, the start, the power cap at the wheels, the revolutions following the demand, the stop opening the line breaker, the automatic start, the battery, the pantographs' pressure switch, braking with nothing sent back, the genset feeding the next car through the high voltage coupling, the commands along the train and from a scenery. A run from the catenary is the same, step for step, with the genset keys as without them. * test(scenarios): traction_power check, and an E6ACTad timetable run on its genset (GE#536) traction_power checks the power at the wheels, the traction force times the vehicle speed, against a ceiling and optionally a peak to reach. e6actad_genset_td_timetable runs the td/rozklad timetable with an E6ACTad switched to its genset by the scenery (PutValues from event0 of its track); e6actad_catenary_td_timetable is the same vehicle left on the catenary. Both need a temporary vehicle variant in the game's data, which the README describes; it isn't in the SVN. * test(scenarios): the genset cases make their own E6ACTad variant The two E6ACTad cases needed a vehicle variant placed in the game's dynamic/ by hand. They now make it for the run with vehicle_variants. vehicle_variants takes an optional fiz_from: a file to copy instead of the vehicle's own .fiz, named in full, while the .mmd still comes from "from". e6actad.fiz only includes e6acta.fiz.inc, and the genset keys can't go on a second Power: line after the include, which would load the power source again; so the variant is e6acta.fiz.inc with the keys added to its Cntrl. and Power: lines. Cases without fiz_from work as before. * fix(physics): the genset's traction current isn't taken from the wire (GE#536) On the genset the pantographs still handed the traction current to the wire and the energy meter, so a dual-mode vehicle under a wire loaded the substation while its genset did the work. The current now comes from CatenaryCurrent(): on the catenary the expression DynObj had, on the genset only a heating fed straight from the pantographs. A selector command refused with the line breaker closed is no longer passed down the train, and a car whose genset starts on its own passes the start switch on to the cars behind. The cab's genset switch moves only when the request was taken, so it no longer sticks on an automatic-start car. --- McZapkie/MOVER.h | 36 + McZapkie/Mover.cpp | 226 +++++- input/command.cpp | 12 + input/command.h | 7 + input/driverkeyboardinput.cpp | 6 + input/drivermouseinput.cpp | 6 + tests/scenarios/README.md | 18 +- .../cases/e6actad_catenary_td_timetable.json | 25 + .../cases/e6actad_genset_td_timetable.json | 28 + tests/scenarios/cases/td_timetable_genset.scn | 18 + tests/scenarios/run.py | 27 +- tests/unit/test_genset.cpp | 662 ++++++++++++++++++ utilities/translation.cpp | 2 + vehicle/DynObj.cpp | 10 +- vehicle/Train.cpp | 107 +++ vehicle/Train.h | 8 + 16 files changed, 1179 insertions(+), 19 deletions(-) create mode 100644 tests/scenarios/cases/e6actad_catenary_td_timetable.json create mode 100644 tests/scenarios/cases/e6actad_genset_td_timetable.json create mode 100644 tests/scenarios/cases/td_timetable_genset.scn create mode 100644 tests/unit/test_genset.cpp diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 1458c632e..f70f577af 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -1480,6 +1480,28 @@ class TMoverParameters float pressure{0.f}; // current pressure }; + // the diesel generator set of a dual-mode vehicle: a second source of the traction circuit, next to the + // pantographs (eu07/maszyna#536). none unless the .fiz gives GensetPower + struct genset_device : public basic_device + { + // config (Power: Genset*), revolutions in rev/s, the .fiz gives rpm + double power{0.0}; // GensetPower, electric output at full revolutions [kW]; 0 = no genset + double voltage_nominal{0.0}; // GensetVoltage, regulated DC voltage from the idle revolutions up [V] + double revolutions_idle{0.0}; // GensetIdleRPM + double revolutions_max{0.0}; // GensetMaxRPM + double start_time{8.0}; // GensetStartTime, from the start request to running at idle [s] + double spinup_time{3.0}; // GensetSpinUpTime, time constant of the revolutions [s] + double traction_share{1.0}; // GensetPmaxRatio, part of the power the traction may take + // state + double timer{0.0}; // of the start [s] + bool is_cranking{false}; + // ld outputs + double revolutions{0.0}; // [rev/s] + double voltage{0.0}; // [V] + bool fitted() const { return power > 0.0; } + // the power the genset gives at its present revolutions [kW] + double available_power() const { return revolutions_max > 0.0 ? power * std::clamp(revolutions / revolutions_max, 0.0, 1.0) : 0.0; } + }; // basic approximation of a water pump struct water_pump : public basic_device { @@ -2212,6 +2234,11 @@ class TMoverParameters bool ConverterOverloadRelayOffWhenMainIsOff{false}; fuel_pump FuelPump; oil_pump OilPump; + genset_device Genset; // of a dual-mode vehicle, fitted() only with GensetPower + // the source the traction circuit takes its voltage from (the traction selector of a dual-mode vehicle) + enum class traction_mode { catenary, genset }; + traction_mode TractionMode{traction_mode::catenary}; + bool GensetSelected() const { return TractionMode == traction_mode::genset; } water_pump WaterPump; water_heater WaterHeater; bool WaterCircuitsLink{false}; // optional connection between water circuits @@ -2950,6 +2977,13 @@ class TMoverParameters bool HeatingSwitch(bool const State, range_t const Notify = range_t::consist); void HeatingSwitch_(bool const State); double EnginePowerSourceVoltage() const; // returns voltage of defined main engine power source + bool TractionModeSwitch(traction_mode const Mode, range_t const Notify = range_t::consist); // traction selector of a dual-mode vehicle + bool GensetSwitch(bool const State, range_t const Notify = range_t::consist); // genset start/stop request + double TractionSourceVoltage() const; // of the vehicle's own source the traction selector picks: the pantographs' or the genset's + double TractionSupplyVoltage() const; // what the traction circuit gets: the own source's, or the train's high voltage line's + double TractionSupplyMinVoltage() const; // below it the line breaker opens (undervoltage) + double GensetTractionPowerLimit() const; // [kW] at the wheels, the largest double unless running on the genset + double CatenaryCurrent() const; // [A] what the vehicle draws through its pantographs, if they touch the wire // whether the main circuit feeds what runs on it (the converter, a compressor, the heating, the motor and resistor // blowers, the traction motors): the line breaker closed, and where it closes ahead of the pantographs and holds // without traction voltage (PantographsRequireMains) also the voltage there, at least the one the undervoltage @@ -2975,6 +3009,7 @@ class TMoverParameters // whether the circuit a traction motor blower runs off has power: the battery, the converter or the main circuit, by its start type bool MotorBlowerPowerIsAvailable(cooling_fan const &Blower) const; void PantographsCheck(double const Timestep); + void GensetCheck(double const Deltatime); void LightsCheck(double const Timestep); bool FuseOn(range_t const Notify = range_t::consist); // bezpiecznik nadamiary bool FuseFlagCheck(void) const; // sprawdzanie flagi nadmiarowego @@ -3142,6 +3177,7 @@ class TMoverParameters void LoadFIZ_Headlights(std::string const &Line); void LoadFIZ_Clima(std::string const &line); void LoadFIZ_Power(std::string const &Line); + void LoadFIZ_Genset(std::string const &Line); void LoadFIZ_SpeedControl(std::string const &Line); void LoadFIZ_Engine(std::string const &Input); void LoadFIZ_EngineDiesel(std::string const &Input); diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 037e52fee..6b9c8dfa3 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1016,7 +1016,8 @@ void TMoverParameters::PantPressureSwitchTrip() if (TrainType != dt_EZT) { // pressure switch safety measure -- open the line breaker, unless there's alternate source of traction voltage - if (GetTrainsetHighVoltage() < EnginePowerSource.CollectorParameters.MinV) + // (the genset of a dual-mode vehicle, when the selector is on it, doesn't need the pantographs) + if (GetTrainsetHighVoltage() < EnginePowerSource.CollectorParameters.MinV && false == GensetSelected()) { // TODO: check whether line breaker should be open EMU-wide MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); @@ -2527,6 +2528,7 @@ void TMoverParameters::compute_movement_(double const Deltatime) LowVoltagePowerCheck(Deltatime); // power sources PantographsCheck(Deltatime); + GensetCheck(Deltatime); // main circuit MainsCheck(Deltatime); // traction motors @@ -2613,6 +2615,11 @@ void TMoverParameters::MainsCheck(double const Deltatime) break; } } + if (GensetSelected()) + { + // the traction selector of a dual-mode vehicle on the genset isolates the pantographs + localvoltage = Genset.voltage; + } // a line breaker closed ahead of the pantographs gets ready on the low voltage circuits auto const maincircuitpowersupply{std::abs(localvoltage) > 0.1 || GetTrainsetHighVoltage() > 0.1 || (PantographsRequireMains && (Power24vIsAvailable || Power110vIsAvailable))}; @@ -2730,7 +2737,8 @@ double TMoverParameters::LocalPowerVoltage(coupling const Coupling) case TPowerSource::Main: { // HACK: main circuit can be fed through couplers, so we explicitly check pantograph supply here - localvoltage = MainCircuitPowered() ? PantographVoltage : 0.0; + // (or the genset's, where the traction selector of a dual-mode vehicle is on it) + localvoltage = MainCircuitPowered() ? TractionSourceVoltage() : 0.0; break; } default: @@ -2739,10 +2747,10 @@ double TMoverParameters::LocalPowerVoltage(coupling const Coupling) } } } - // high voltage power sources + // high voltage power sources: the pantographs, or the genset of a dual-mode vehicle, by its traction selector if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector) { - localvoltage = std::max(localvoltage, PantographVoltage); + localvoltage = std::max(localvoltage, TractionSourceVoltage()); } break; } @@ -3049,7 +3057,7 @@ void TMoverParameters::HeatingCheck(double const /*Timestep*/) } case TPowerSource::Main: { - voltage = MainCircuitPowered() ? std::max(GetTrainsetHighVoltage(), PantographVoltage) : 0.0; + voltage = MainCircuitPowered() ? TractionSupplyVoltage() : 0.0; break; } default: @@ -3241,6 +3249,63 @@ void TMoverParameters::PantographsCheck(double const /*Timestep*/) } } +// the genset of a dual-mode vehicle: started on request with the battery on, it cranks for start_time, then runs at +// idle and up to full revolutions with the traction demand; stopped, it coasts down. regulated voltage from idle up +void TMoverParameters::GensetCheck(double const Deltatime) +{ + if (false == Genset.fitted()) + { + return; + } + auto &genset{Genset}; + auto const wasactive{genset.is_active}; + auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; + auto const requested{lowvoltagepower && false == genset.is_disabled && (genset.start_type == start_t::automatic ? GensetSelected() : genset.is_enabled)}; + if (false == requested) + { + genset.is_active = false; + genset.is_cranking = false; + genset.timer = 0.0; + } + else if (false == genset.is_active) + { + genset.is_cranking = true; + genset.timer += Deltatime; + if (genset.timer >= genset.start_time) + { + genset.is_cranking = false; + genset.is_active = true; + } + } + // revolutions: the start brings them up to idle in start_time; running they follow the traction demand, stopped + // they coast down to 0, both with the time constant spinup_time + if (genset.is_cranking) + { + genset.revolutions = std::max(genset.revolutions, genset.revolutions_idle * std::min(1.0, genset.timer / std::max(genset.start_time, 0.01))); + } + else if (genset.is_active && false == wasactive) + { + genset.revolutions = std::max(genset.revolutions, genset.revolutions_idle); + } + else + { + auto const demand{GensetSelected() && Mains ? std::clamp(eimv_pr, 0.0, 1.0) : 0.0}; + auto const target{genset.is_active ? genset.revolutions_idle + (genset.revolutions_max - genset.revolutions_idle) * demand : 0.0}; + genset.revolutions += (target - genset.revolutions) * std::min(1.0, Deltatime / genset.spinup_time); + if (genset.revolutions < 0.001) + { + genset.revolutions = 0.0; + } + } + // no excitation while cranking; running or coasting down, regulated from idle up, proportional below it + genset.voltage = genset.is_cranking ? 0.0 : genset.voltage_nominal * std::clamp(genset.revolutions / genset.revolutions_idle, 0.0, 1.0); + + if (genset.is_active != wasactive) + { + WriteLog("Genset of " + Name + (genset.is_active ? ": running" : ": stopped")); + } +} + void TMoverParameters::LightsCheck(double const /*Timestep*/) { @@ -4710,6 +4775,11 @@ bool TMoverParameters::MainSwitchCheck() const break; } } + if (GensetSelected()) + { + // on the genset of a dual-mode vehicle the line breaker closes only on a running one, whatever the pantographs give + powerisavailable = Genset.is_active && Genset.voltage >= TractionSupplyMinVoltage(); + } return powerisavailable && (ScndCtrlPos == 0 || EngineType == ElectricInductionMotor) && MainsInitTimeCountdown <= 0.0 && (ConvOvldFlag == false || ConverterOverloadRelayOffWhenMainIsOff) && true == GroundRelay && (true == NoVoltRelay || PantographsRequireMains) && true == OvervoltageRelay && @@ -4809,11 +4879,88 @@ void TMoverParameters::HeatingSwitch_(bool const State) HeatingAllow = State; } +// the traction selector of a dual-mode vehicle: moves only with the line breaker open, and only where a genset is +bool TMoverParameters::TractionModeSwitch(traction_mode const Mode, range_t const Notify) +{ + auto const initialstate{TractionMode}; + // refused with the line breaker closed, and then not passed on either, so the train stays on one source + auto const accepted{false == Mains}; + + if (Genset.fitted() && accepted) + { + TractionMode = Mode; + } + + if (Notify != range_t::local && accepted) + { + SendCtrlToNext("TractionMode", Mode == traction_mode::genset ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return TractionMode != initialstate; +} + +// the start request of the genset of a dual-mode vehicle; one which starts on its own ignores it, but passes it on to +// the cars behind, which may start theirs on request +bool TMoverParameters::GensetSwitch(bool const State, range_t const Notify) +{ + auto const initialstate{Genset.is_enabled}; + + if (Genset.start_type != start_t::automatic) + { + Genset.is_enabled = State; + } + + if (Notify != range_t::local) + { + SendCtrlToNext("GensetSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return Genset.is_enabled != initialstate; +} + +// the voltage of the vehicle's own source the traction selector picks: the catenary through the pantographs, or the +// genset of a dual-mode vehicle +double TMoverParameters::TractionSourceVoltage() const +{ + return GensetSelected() ? Genset.voltage : PantographVoltage; +} + +// the voltage the traction circuit gets: from the vehicle's own source, or through the train's high voltage line +double TMoverParameters::TractionSupplyVoltage() const +{ + return std::max(GetTrainsetHighVoltage(), TractionSourceVoltage()); +} + +// below it the undervoltage trip opens the line breaker +double TMoverParameters::TractionSupplyMinVoltage() const +{ + return GensetSelected() ? 0.5 * Genset.voltage_nominal : EnginePowerSource.CollectorParameters.MinV; +} + +// the power the traction may take [kW, at the wheels]: the genset's share at its present revolutions on the genset, +// no limit otherwise +double TMoverParameters::GensetTractionPowerLimit() const +{ + return GensetSelected() ? Genset.available_power() * Genset.traction_share : std::numeric_limits::max(); +} + +// the current the vehicle draws through its pantographs [A], if they touch the wire: the traction's (none while +// braking on the resistors) and the heating's. on the genset the genset feeds the traction circuit, so only a heating +// fed straight from the pantographs is left +double TMoverParameters::CatenaryCurrent() const +{ + if (GensetSelected()) + { + return HeatingPowerSource.SourceType == TPowerSource::CurrentCollector ? TotalCurrent : 0.0; + } + return (DynamicBrakeFlag && ResistorsFlag ? 0 : std::abs(Itot) * IsVehicleEIMBrakingFactor()) + TotalCurrent; +} + // returns voltage of defined main engine power source double TMoverParameters::EnginePowerSourceVoltage() const { - return EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? std::max(GetTrainsetHighVoltage(), PantographVoltage) : + return EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? TractionSupplyVoltage() : EnginePowerSource.SourceType == TPowerSource::Accumulator ? Power24vVoltage : 0.0; } @@ -4834,7 +4981,7 @@ bool TMoverParameters::MainCircuitPowered() const } // closed ahead of the pantographs the line breaker holds without the voltage, which the undervoltage trip isn't // there to vouch for - return EnginePowerSourceVoltage() >= EnginePowerSource.CollectorParameters.MinV; + return EnginePowerSourceVoltage() >= TractionSupplyMinVoltage(); } // ************************************************************************************************* @@ -6305,7 +6452,7 @@ void TMoverParameters::ComputeTotalForce(double dt) } // bo nie dzialalo else { - EngineVoltage = Power > 1.0 ? std::max(GetTrainsetHighVoltage(), PantographVoltage) : 0.0; + EngineVoltage = Power > 1.0 ? TractionSupplyVoltage() : 0.0; } FTrain = Power > 0 ? TractionForce(dt) : 0; @@ -7240,8 +7387,9 @@ void TMoverParameters::VoltageRelaysCheck() // TODO: check if we can use instead the code for electricseriesmotor // nie wchodzić w funkcję bez potrzeby // (a line breaker closed ahead of the pantographs holds without voltage) - if (Mains && ((std::max(GetTrainsetHighVoltage(), PantographVoltage) < EnginePowerSource.CollectorParameters.MinV && false == PantographsRequireMains) || - std::max(GetTrainsetHighVoltage(), PantographVoltage) > EnginePowerSource.CollectorParameters.MaxV + 200)) + // (the source by the traction selector of a dual-mode vehicle: the pantographs or the genset) + if (Mains && ((TractionSupplyVoltage() < TractionSupplyMinVoltage() && false == PantographsRequireMains) || + TractionSupplyVoltage() > EnginePowerSource.CollectorParameters.MaxV + 200)) { MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide } @@ -8059,6 +8207,11 @@ void TMoverParameters::InductionMotorDrive(double dt) else { eimv[eimv_Pmax] = std::min(eimc[eimc_p_Pmax], 0.001 * EngineVoltage * (eimc[eimc_p_Imax] - eimc[eimc_f_I0]) * Pirazy2 * eimc[eimc_s_cim] / eimc[eimc_s_p] / eimc[eimc_s_cfu]); + if (GensetSelected()) + { + // on the genset of a dual-mode vehicle the traction takes no more than the genset gives + eimv[eimv_Pmax] = std::min(eimv[eimv_Pmax], GensetTractionPowerLimit()); + } } eimv[eimv_FMAXMAX] = 0.001 * square(std::min(1.0, eimv[eimv_fkr] / std::max(abs(enrot) * eimc[eimc_s_p] + eimc[eimc_s_dfmax] * eimv[eimv_ks], eimc[eimc_s_dfmax])) * f_cfu / eimc[eimc_s_cfu]) * @@ -8091,6 +8244,8 @@ void TMoverParameters::InductionMotorDrive(double dt) Im = eimv[eimv_If]; if (eimv[eimv_Ipoj] >= 0) Vadd *= 1.0 - 2.0 * dt; + else if (GensetSelected()) + Vadd = 1.0; // the genset of a dual-mode vehicle takes nothing back: all the braking energy to the resistors else if (std::abs(EngineVoltage) < EnginePowerSource.CollectorParameters.MaxV) Vadd *= 1.0 - dt; else @@ -13438,6 +13593,11 @@ void TMoverParameters::LoadFIZ_CntrlStarts(std::string const &line) auto lookup = starts.find(extract_value("OilStart", line)); OilPump.start_type = lookup != starts.end() ? lookup->second : manual; } + // genset of a dual-mode vehicle: Manual (the default) needs GensetSwitch, Automatic runs whenever the selector is on it + { + auto lookup = starts.find(extract_value("GensetStart", line)); + Genset.start_type = lookup != starts.end() ? lookup->second : manual; + } // water pump { auto lookup = starts.find(extract_value("WaterStart", line)); @@ -13565,11 +13725,40 @@ void TMoverParameters::LoadFIZ_Power(std::string const &Line) // jeśli nie ma mocy, np. rozrządcze EZT EnginePowerSource.SourceType = TPowerSource::NotDefined; } + else + { + LoadFIZ_Genset(Line); + } SystemPowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("SystemPower", Line)); LoadFIZ_PowerParamsDecode(SystemPowerSource, "", Line); } +// the genset of a dual-mode vehicle (eu07/maszyna#536), on the Power: line; all optional, no genset without GensetPower +void TMoverParameters::LoadFIZ_Genset(std::string const &Line) +{ + extract_value(Genset.power, "GensetPower", Line, ""); + if (false == Genset.fitted()) + { + return; + } + extract_value(Genset.voltage_nominal, "GensetVoltage", Line, ""); + if (Genset.voltage_nominal <= 0.0) + { + Genset.voltage_nominal = EnginePowerSource.MaxVoltage > 0.0 ? 0.65 * EnginePowerSource.MaxVoltage : 3000.0; + } + extract_value(Genset.revolutions_idle, "GensetIdleRPM", Line, "600"); + extract_value(Genset.revolutions_max, "GensetMaxRPM", Line, "1800"); + Genset.revolutions_max = std::max(Genset.revolutions_max, 1.0) / 60.0; + Genset.revolutions_idle = std::clamp(Genset.revolutions_idle / 60.0, 1.0 / 60.0, Genset.revolutions_max); + extract_value(Genset.start_time, "GensetStartTime", Line, "8"); + extract_value(Genset.spinup_time, "GensetSpinUpTime", Line, "3"); + extract_value(Genset.traction_share, "GensetPmaxRatio", Line, "1"); + Genset.start_time = std::max(Genset.start_time, 0.0); + Genset.spinup_time = std::max(Genset.spinup_time, 0.01); + Genset.traction_share = std::clamp(Genset.traction_share, 0.0, 1.0); +} + void TMoverParameters::LoadFIZ_SpeedControl(std::string const &Line) { // speed control @@ -14332,6 +14521,13 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) if (CompressorListPosNo > 0) CompressorListPos = CompressorListDefPos; + // the genset of a dual-mode vehicle is a second source of the traction circuit of an induction motor vehicle + if (Genset.fitted() && (EngineType != TEngineType::ElectricInductionMotor || EnginePowerSource.SourceType != TPowerSource::CurrentCollector)) + { + WriteLog("GensetPower ignored: a genset works only with EngineType=ElectricInductionMotor and EnginePower=CurrentCollector"); + Genset = genset_device{}; + } + // NOTE: legacy compatibility behaviour for vehicles without defined heating power source if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector && HeatingPowerSource.SourceType == TPowerSource::NotDefined) { @@ -15289,6 +15485,16 @@ bool TMoverParameters::RunPowerCommand(std::string const &Command, double CValue DropAllPantographs(CValue1 == 1, range_t::local); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } + else if (Command == "TractionMode") + { + TractionModeSwitch(CValue1 > 0.5 ? traction_mode::genset : traction_mode::catenary, range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "GensetSwitch") + { + GensetSwitch(CValue1 > 0.5, range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } else { return false; diff --git a/input/command.cpp b/input/command.cpp index add272473..2c1cbd6e8 100644 --- a/input/command.cpp +++ b/input/command.cpp @@ -446,6 +446,12 @@ commanddescription_sequence Commands_descriptions = { {"genericset27", command_target::vehicle, command_mode::oneoff}, {"genericset28", command_target::vehicle, command_mode::oneoff}, {"genericset29", command_target::vehicle, command_mode::oneoff}, + {"tractionmodetoggle", command_target::vehicle, command_mode::oneoff}, + {"tractionmodecatenary", command_target::vehicle, command_mode::oneoff}, + {"tractionmodegenset", command_target::vehicle, command_mode::oneoff}, + {"gensettoggle", command_target::vehicle, command_mode::oneoff}, + {"gensetenable", command_target::vehicle, command_mode::oneoff}, + {"gensetdisable", command_target::vehicle, command_mode::oneoff}, }; // Maps of command and coresponding strings @@ -871,6 +877,12 @@ std::unordered_map const commandMap = { {"genericset27", user_command::genericset27}, {"genericset28", user_command::genericset28}, {"genericset29", user_command::genericset29}, + {"tractionmodetoggle", user_command::tractionmodetoggle}, + {"tractionmodecatenary", user_command::tractionmodecatenary}, + {"tractionmodegenset", user_command::tractionmodegenset}, + {"gensettoggle", user_command::gensettoggle}, + {"gensetenable", user_command::gensetenable}, + {"gensetdisable", user_command::gensetdisable}, {"none", user_command::none}}; } // namespace simulation diff --git a/input/command.h b/input/command.h index 9fb6021d0..7a9909686 100644 --- a/input/command.h +++ b/input/command.h @@ -445,6 +445,13 @@ enum class user_command genericset27, genericset28, genericset29, + // the traction selector and the genset of a dual-mode vehicle (eu07/maszyna#536) + tractionmodetoggle, + tractionmodecatenary, + tractionmodegenset, + gensettoggle, + gensetenable, + gensetdisable, none = -1 }; diff --git a/input/driverkeyboardinput.cpp b/input/driverkeyboardinput.cpp index 047f3678c..566a07192 100644 --- a/input/driverkeyboardinput.cpp +++ b/input/driverkeyboardinput.cpp @@ -103,6 +103,12 @@ driverkeyboard_input::default_bindings() { { fuelpumptoggle, {GLFW_KEY_F, ""} }, // fuelpumpenable, // fuelpumpdisable, + { tractionmodetoggle, {GLFW_KEY_G | keymodifier::shift, ""} }, + // tractionmodecatenary, + // tractionmodegenset, + { gensettoggle, {GLFW_KEY_G | keymodifier::control, ""} }, + // gensetenable, + // gensetdisable, { oilpumptoggle, {GLFW_KEY_F | keymodifier::shift, ""} }, // oilpumpenable, // oilpumpdisable, diff --git a/input/drivermouseinput.cpp b/input/drivermouseinput.cpp index 90414d312..788173759 100644 --- a/input/drivermouseinput.cpp +++ b/input/drivermouseinput.cpp @@ -640,6 +640,12 @@ drivermouse_input::default_bindings() { { "oilfuelpump_sw:", { oilfuelpumptoggle, none } }, + { "tractionmode_sw:", { + tractionmodetoggle, + none } }, + { "genset_sw:", { + gensettoggle, + none } }, { "motorblowersfront_sw:", { motorblowerstogglefront, none } }, diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index 600d8fa14..529fefea6 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -239,7 +239,7 @@ to `logs/`. | `fragment` | `.scn` file in `cases/` added to the scenery: trainsets after `FirstInit` (before it they derail on unlinked track), the rest before it (launchers read after it never fire). Optional when the case keeps the scenery's trainsets | | `vars` | values for `{{name}}` in the fragment; a list becomes one line per item | | `timetable` | a timetable file in `cases/` for a trainset of the fragment, for a train whose timetable no scenery of the game has: copied to the game's `scenery/` dir as `autotest_.txt` for the run and removed after it; the fragment names it `{{timetable}}` | -| `vehicle_variants` | vehicles of the case's own, made from those of the game, e.g. with a `.fiz` key the game's data doesn't have yet: a list of `{ "name": ..., "from": "/", "replace": [[old, new], ...] }`. For the run the vehicle's `.fiz`, with the literal replacements (an `old` it doesn't have is an error), and its `.mmd` are copied beside it in the game's `dynamic/` dir as `autotest__` and removed after it; the fragment names the type `{{variant_}}`, e.g. `dynamic pkp/et42_v2 112e-014-a {{variant_a}} ...`. The copy of the `.mmd` has the name of the vehicle it is made from in place of `(p2)`, the type name the simulator hands it, which some pass on to the include that names the model | +| `vehicle_variants` | vehicles of the case's own, made from those of the game, e.g. with a `.fiz` key the game's data doesn't have yet: a list of `{ "name": ..., "from": "/", "replace": [[old, new], ...] }`. For the run the vehicle's `.fiz`, with the literal replacements (an `old` it doesn't have is an error), and its `.mmd` are copied beside it in the game's `dynamic/` dir as `autotest__` and removed after it; the fragment names the type `{{variant_}}`, e.g. `dynamic pkp/et42_v2 112e-014-a {{variant_a}} ...`. The copy of the `.mmd` has the name of the vehicle it is made from in place of `(p2)`, the type name the simulator hands it, which some pass on to the include that names the model. An optional `"fiz_from": "/"` copies that file instead of the vehicle's own `.fiz`, named in full, e.g. `pkp/e6act_v2/e6acta.fiz.inc` for a vehicle whose `.fiz` only includes it (`e6actad.fiz`); the `.mmd` still comes from `from`. Keys for a section of the included file can't go after the include on a line of their own: a second `Power:` line loads the power source anew | | `expect` | the result the test mode should end with: `pass`, `fail`, `signal_passed_at_danger`, `timeout`, `standstill` or `error`, or `wall_timeout` for the timeout of the real time watchdog (the timeout code with a verdict saying it was the real time; a case expecting `timeout` fails on it). Default `timeout` for a case with `duration`, else `pass` | | `duration` | seconds of simulation to record: the test timeout of the run (`--test-timeout`) | | `timeout` | wall-clock seconds before giving up, loading included: the simulator's `--test-wall-timeout` (default 600) | @@ -299,6 +299,18 @@ starts on the level at the W4 of Gora, stops at the W4 of Dol 1500 m down the gr model), about 1590 m and 2690 m from the start. The three trains are the light EU07, the SN61 alone and the EU07 with three coaches. +`e6actad_genset_td_timetable` (fragment `td_timetable_genset.scn`) is the timetable run of a dual-mode vehicle on its +genset (eu07/maszyna#536): an E6ACTad, the Dragon 2 "last mile" with a 520 kW diesel generator set. The game data has no +genset for it yet, so the case makes its own E6ACTad (`vehicle_variants`, `{{variant_g6}}`): the `.mmd` of `e6actad`, and +as its `.fiz` the `e6acta.fiz.inc` that `e6actad.fiz` includes (`fiz_from`), with `GensetStart=Manual` added to the +`Cntrl.` line and `GensetPower=520 GensetVoltage=3000 GensetIdleRPM=700 GensetMaxRPM=1800 GensetStartTime=8 +GensetSpinUpTime=3 GensetPmaxRatio=0.85` to the `Power:` line. `event0` of the start track gives the standing vehicle, once, +`PutValues` `MainSwitch 0`, `TractionMode 1` (the selector on the genset) and `GensetSwitch 1`, a second apart, as the +vehicle holds one command at a time. The AI knows nothing of the genset: it closes the line breaker once the genset runs +and drives the timetable on it, at most 520 kW x 0.85 = 442 kW at the wheels (`traction_power`). +`e6actad_catenary_td_timetable` is the same variant without the events: it stays on the catenary and takes several +times that, which shows the check tells the two apart. + ### Heavy trains The heavy train cases (#187, #199, #263, #265) run on lines of their own beside the tracks of td.scn, at x = -3000, as @@ -643,6 +655,10 @@ the row instead, logged by builds from this branch on. after moving off, moves no more than `max_distance` metres, e.g. no creeping on locked wheels. - `ends_moving` `min_speed`: the last row of the physicslog is at `min_speed` or faster, e.g. the test ended without waiting for the train to stop. +- `traction_power` `max_kw`, optional `min_peak_kw` (*vehicle speed*): the power at the wheels, the + traction force times the vehicle speed, never goes above `max_kw` and, given `min_peak_kw`, reaches + it at least once; e.g. a dual-mode vehicle running on the power of its genset. The traction force + column is in N, whatever the header says. - `keeps_moving` `moving_speed`, `min_speed`, `until_distance`, optional `from_distance` (*vehicle speed*): once at `moving_speed`, the speed stays at or above `min_speed` between the two distances (metres travelled, from the vehicle speed), e.g. a heavy train doesn't come to a stand on a descent before a restriction. Reports the lowest speed. diff --git a/tests/scenarios/cases/e6actad_catenary_td_timetable.json b/tests/scenarios/cases/e6actad_catenary_td_timetable.json new file mode 100644 index 000000000..9e8ff5f72 --- /dev/null +++ b/tests/scenarios/cases/e6actad_catenary_td_timetable.json @@ -0,0 +1,25 @@ +{ + "description": "GE#536 stage 1, the twin of e6actad_genset_td_timetable without the switching events: the same E6ACTad variant stays on its catenary position and runs the td/rozklad timetable as the plain E6ACT does, on far more than the genset's 442 kW at the wheels, which shows the traction_power check tells the two apart. The same variant g6 as the genset case.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vehicle_variants": [ + { "name": "g6", "from": "pkp/e6act_v2/e6actad", "fiz_from": "pkp/e6act_v2/e6acta.fiz.inc", "replace": [ + ["InactiveCabFlag=15", "InactiveCabFlag=15 GensetStart=Manual"], + ["PhysicalLayout=3", "PhysicalLayout=3 GensetPower=520 GensetVoltage=3000 GensetIdleRPM=700 GensetMaxRPM=1800 GensetStartTime=8 GensetSpinUpTime=3 GensetPmaxRatio=0.85"] + ] } + ], + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\e6act_v2 e6actad-017 {{variant_g6}} 0 headdriver 0 0 enddynamic" + }, + "ini": ["gfxrenderer null"], + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "log_lacks", "pattern": "Genset of" }, + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "traction_power", "max_kw": 6000, "min_peak_kw": 1000 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/scenarios/cases/e6actad_genset_td_timetable.json b/tests/scenarios/cases/e6actad_genset_td_timetable.json new file mode 100644 index 000000000..92338d49d --- /dev/null +++ b/tests/scenarios/cases/e6actad_genset_td_timetable.json @@ -0,0 +1,28 @@ +{ + "description": "GE#536 stage 1: an E6ACTad (Dragon 2 last mile) on the td/rozklad timetable of td.scn, switched to its genset by the scenery before it leaves: PutValues MainSwitch 0, TractionMode 1, GensetSwitch 1 from event0 of its track, 1 s apart. The AI, which knows nothing of the genset, closes the line breaker once the genset runs and drives to Przystanek on at most 442 kW at the wheels (520 kW x 0.85). Makes its own E6ACTad for the run (vehicle_variants g6: e6acta.fiz.inc with the genset keys, the .mmd of e6actad).", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable_genset.scn", + "vehicle_variants": [ + { "name": "g6", "from": "pkp/e6act_v2/e6actad", "fiz_from": "pkp/e6act_v2/e6acta.fiz.inc", "replace": [ + ["InactiveCabFlag=15", "InactiveCabFlag=15 GensetStart=Manual"], + ["PhysicalLayout=3", "PhysicalLayout=3 GensetPower=520 GensetVoltage=3000 GensetIdleRPM=700 GensetMaxRPM=1800 GensetStartTime=8 GensetSpinUpTime=3 GensetPmaxRatio=0.85"] + ] } + ], + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\e6act_v2 e6actad-017 {{variant_g6}} 0 headdriver 0 0 enddynamic" + }, + "ini": ["gfxrenderer null"], + "track_events": { + "tdo_n1734": "event0 autotest_genset" + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Genset of autotest_e6actad_genset_td_timetable: running" }, + { "type": "starts", "min_speed": 20, "within": 180 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "traction_power", "max_kw": 451, "min_peak_kw": 380 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/scenarios/cases/td_timetable_genset.scn b/tests/scenarios/cases/td_timetable_genset.scn new file mode 100644 index 000000000..0918dc1bc --- /dev/null +++ b/tests/scenarios/cases/td_timetable_genset.scn @@ -0,0 +1,18 @@ +// td_timetable.scn (the timetable train on track 1 of Stacja1, route out at 10:34) with the train switched to its +// genset by the scenery before it leaves (eu07/maszyna#536, a dual-mode vehicle): event0 of the start track (the +// track_events of the case) runs while the vehicle with a driver stands there and gives it, once, PutValues +// MainSwitch 0, TractionMode 1 and GensetSwitch 1, a second apart, as the vehicle holds one command at a time. +// the AI knows nothing of the genset: it closes the line breaker once the genset runs and drives on its power +trainset td/rozklad tdo_n1734 0.0 0.1 +{{consist}} +endtrainset + +// the way out of track 1, see td_timetable.scn +node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end + +node -1 0 autotest_genset_done memcell 0 0 0 done 0 0 none endmemcell +event autotest_genset multiple 0 autotest_genset_done autotest_genset_ws autotest_genset_mode autotest_genset_on autotest_genset_mark condition memcompare * 0 * endevent +event autotest_genset_ws PutValues 0 none 0 0 0 MainSwitch 0 0 endevent +event autotest_genset_mode PutValues 1 none 0 0 0 TractionMode 1 0 endevent +event autotest_genset_on PutValues 2 none 0 0 0 GensetSwitch 1 0 endevent +event autotest_genset_mark UpdateValues 0 autotest_genset_done * 1 * endevent diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py index c83899d40..ad7ac5bcb 100644 --- a/tests/scenarios/run.py +++ b/tests/scenarios/run.py @@ -178,11 +178,16 @@ def write_vehicle_variants(case: dict, game_dir: Path, case_name: str) -> None: files = {} for variant in case.get("vehicle_variants", []): source = game_dir / "dynamic" / variant["from"] + # the .fiz to copy: the vehicle's own, or another file named in full (fiz_from), e.g. the .fiz.inc a + # vehicle's .fiz only includes, as keys added after the include on a second line of the same section + # would load that section again + fiz_source = game_dir / "dynamic" / variant["fiz_from"] if "fiz_from" in variant else source.with_name(source.name + ".fiz") + fiz_name = variant.get("fiz_from", f"{variant['from']}.fiz") # .fiz files are cp1250 like the sceneries; latin-1 round-trips every byte - fiz = source.with_name(source.name + ".fiz").read_bytes().decode("latin-1") + fiz = fiz_source.read_bytes().decode("latin-1") for old, new in variant.get("replace", []): if old not in fiz: - sys.exit(f"vehicle_variants: {variant['from']}.fiz has no {old!r}") + sys.exit(f"vehicle_variants: {fiz_name} has no {old!r}") fiz = fiz.replace(old, new) mmd = source.with_name(source.name + ".mmd").read_bytes().decode("latin-1").replace("(p2)", source.name) fiz_path, mmd_path = variant_paths(game_dir, case_name, variant) @@ -794,6 +799,23 @@ def check_master_controller(rows, from_distance, to_distance, at_most): return True, detail +def check_traction_power(rows, max_kw, min_peak_kw=None): + """The power at the wheels, the traction force times the vehicle speed, stays at or below max_kw + and, given min_peak_kw, reaches it, e.g. a dual-mode vehicle on its genset (eu07/maszyna#536).""" + if not rows or len(rows[0]) <= COL_VEHICLE_VELOCITY or rows[0][COL_VEHICLE_VELOCITY] is None: + return False, "the physicslog has no vehicle speed column" + power = [abs(r[COL_TRACTION_FORCE]) * abs(r[COL_VEHICLE_VELOCITY]) / 3.6 / 1000 for r in rows] + peak = max(range(len(rows)), key=power.__getitem__) + r = rows[peak] + detail = (f"peak {power[peak]:.0f} kW at t={r[COL_TIME]:.1f}s, v={r[COL_VEHICLE_VELOCITY]:.1f} km/h, " + f"Ft={r[COL_TRACTION_FORCE] / 1000:.1f} kN") + if power[peak] > max_kw: + return False, f"{detail}, above {max_kw} kW" + if min_peak_kw is not None and power[peak] < min_peak_kw: + return False, f"{detail}, below {min_peak_kw} kW" + return True, detail + + CHECKS = { "master_controller": check_master_controller, "traction": check_traction, @@ -807,6 +829,7 @@ CHECKS = { "stays_stopped": check_stays_stopped, "distance": check_distance, "ends_moving": check_ends_moving, + "traction_power": check_traction_power, "keeps_moving": check_keeps_moving, "starts_again": check_starts_again, } diff --git a/tests/unit/test_genset.cpp b/tests/unit/test_genset.cpp new file mode 100644 index 000000000..c3b4f3015 --- /dev/null +++ b/tests/unit/test_genset.cpp @@ -0,0 +1,662 @@ +#include "stdafx.h" +#include "doctest.h" +#include "consist.h" +#include "drive.h" +#include "golden.h" + +#include "McZapkie/hamulce.h" + +// the genset of a dual-mode vehicle (eu07/maszyna#536): a second source of the traction circuit of an induction +// motor vehicle next to its pantographs, which the traction selector picks. the vehicle is the game's E6ACT +// (Dragon 2) with the genset of the E6ACTad "last mile" set in the test: 520 kW, the rest assumed + +using test::consist; +using test::definition; +using test::track; +using test::vehicle; +using traction_mode = TMoverParameters::traction_mode; + +namespace { + +definition dragon() { + return definition::fiz("e6act_v2/e6acta"); +} + +definition dragon_genset() { + return dragon() + .set("Power", "GensetPower", 520) + .set("Power", "GensetVoltage", 3000) + .set("Power", "GensetIdleRPM", 700) + .set("Power", "GensetMaxRPM", 1800) + .set("Power", "GensetStartTime", 8) + .set("Power", "GensetSpinUpTime", 3) + .set("Power", "GensetPmaxRatio", 0.85); +} + +// the power the traction of dragon_genset() may take at full revolutions [kW] +double const genset_traction_power{520.0 * 0.85}; + +track const no_wire{0.15, 0.0, 0.0}; +track const wire{0.15, 0.0, test::catenary_3kv}; + +// the battery, the cab and a direction, as the driver begins +void wake(TMoverParameters &Cab) { + Cab.BatterySwitch(true); + Cab.CabActivisation(); + for (int i = 0; i < 3 && Cab.DirActive <= 0; ++i) { + Cab.DirectionForward(); + } +} + +// the vigilance and the cab signalling acknowledged, as test::drive() does once a second +void attend(TMoverParameters &Cab) { + if (Cab.SecuritySystem.is_cabsignal_blinking() && Cab.SecuritySystem.has_separate_acknowledge()) { + Cab.SecuritySystem.cabsignal_reset(); + } + if (Cab.SecuritySystem.is_blinking()) { + Cab.SecuritySystemReset(); + } +} + +void run(vehicle &Vehicle, double const Seconds, track const &Track = no_wire) { + test::drive(test::driving(Vehicle), Track, Seconds); +} + +// the line breaker closed, which it does only with the controller at zero, and after the relays are reset +void close_line_breaker(TMoverParameters &Cab) { + while (Cab.DecMainCtrl(2)) { + // down to zero + } + Cab.RelayReset(relay_t::maincircuitground | relay_t::tractionnmotoroverload | relay_t::primaryconverteroverload); + Cab.MainSwitch(true); +} + +// gets the vehicle ready to run on its genset, as test::start_up() does on the pantographs: the selector on the +// genset, the genset started, the line breaker closed once it runs, the converter and the compressor, the air, the +// brakes released. one round of the driver's actions a second; returns whether the vehicle got ready +bool start_on_genset(vehicle &Vehicle, track const &Track = no_wire, double const Seconds = 300.0) { + auto &cab{Vehicle.mover()}; + for (auto second = 0; second < Seconds; ++second) { + wake(cab); + cab.TractionModeSwitch(traction_mode::genset); + cab.GensetSwitch(true); + if (false == cab.Mains) { + if (cab.MainSwitchCheck()) { + close_line_breaker(cab); + } + } + else { + cab.ConverterSwitch(true); + cab.CompressorSwitch(true); + } + run(Vehicle, 1.0, Track); + if (cab.Mains && cab.ConverterFlag && cab.ScndPipePress >= 4.5) { + // and the brakes let go + test::release_brakes(cab); + for (auto wait = 0; wait < 120 && cab.BrakePress > 0.05; ++wait) { + run(Vehicle, 1.0, Track); + } + return cab.BrakePress <= 0.05; + } + } + return false; +} + +// the main controller to its full power position +void notch_up(TMoverParameters &Cab) { + for (int i = 0; i < 60 && false == Cab.IsMainCtrlMaxPowerPos(); ++i) { + Cab.IncMainCtrl(1); + } +} + +// the power at the wheels [kW] +double wheel_power(TMoverParameters const &Vehicle) { + return std::abs(Vehicle.Ft * Vehicle.V) / 1000.0; +} + +// one step of 0.01 s, acknowledging the vigilance once a second +void step(vehicle &Vehicle, long const Step, track const &Track = no_wire) { + if (Step % 100 == 0) { + attend(Vehicle.mover()); + } + Vehicle.step(Track); +} + +} // namespace + +TEST_CASE("genset: a vehicle without the keys has none and stays on the catenary") { + vehicle dragon6{dragon(), 0.0, "plain", 1}; + auto &cab{dragon6.mover()}; + CHECK(cab.Genset.power == 0.0); + CHECK_FALSE(cab.Genset.fitted()); + CHECK_FALSE(cab.TractionModeSwitch(traction_mode::genset)); + CHECK(cab.TractionMode == traction_mode::catenary); + CHECK_FALSE(cab.GensetSelected()); + REQUIRE(test::start_up(test::driving(dragon6), wire)); + CHECK(cab.PantographVoltage > 2900.0); + CHECK(cab.TractionSupplyVoltage() == std::max(cab.GetTrainsetHighVoltage(), cab.PantographVoltage)); + CHECK(cab.TractionSupplyMinVoltage() == cab.EnginePowerSource.CollectorParameters.MinV); + CHECK(cab.GensetTractionPowerLimit() == std::numeric_limits::max()); + // a start request does nothing without a genset + cab.GensetSwitch(true); + run(dragon6, 20.0, wire); + CHECK_FALSE(cab.Genset.is_active); + CHECK(cab.Genset.voltage == 0.0); + CHECK(cab.TractionMode == traction_mode::catenary); +} + +TEST_CASE("genset: the keys reach the vehicle") { + vehicle dragon6{dragon_genset()}; + auto const &genset{dragon6->Genset}; + CHECK(genset.fitted()); + CHECK(genset.power == 520.0); + CHECK(genset.voltage_nominal == 3000.0); + CHECK(genset.revolutions_idle == doctest::Approx(700.0 / 60.0)); + CHECK(genset.revolutions_max == doctest::Approx(30.0)); + CHECK(genset.start_time == 8.0); + CHECK(genset.spinup_time == 3.0); + CHECK(genset.traction_share == 0.85); + CHECK(genset.start_type == start_t::manual); + CHECK(dragon6->TractionMode == traction_mode::catenary); + // the pantographs stay what they were + CHECK(dragon6->EnginePowerSource.SourceType == TPowerSource::CurrentCollector); + CHECK(dragon6->EnginePowerSource.CollectorParameters.MinV == 2000.0); + + SUBCASE("started on its own") { + vehicle automatic{dragon_genset().set("Cntrl", "GensetStart", "Automatic")}; + CHECK(automatic->Genset.start_type == start_t::automatic); + } + SUBCASE("the defaults") { + vehicle defaults{dragon().set("Power", "GensetPower", 520)}; + auto const &plain{defaults->Genset}; + CHECK(plain.fitted()); + CHECK(plain.voltage_nominal == doctest::Approx(0.65 * 4600.0)); // of the pantographs' MaxVoltage + CHECK(plain.revolutions_idle == doctest::Approx(10.0)); + CHECK(plain.revolutions_max == doctest::Approx(30.0)); + CHECK(plain.start_time == 8.0); + CHECK(plain.spinup_time == 3.0); + CHECK(plain.traction_share == 1.0); + } +} + +TEST_CASE("genset: the keys are ignored on other than induction motor vehicles") { + for (auto const *path : {"4e_v1/4e", "br285_v1/br285"}) { + CAPTURE(path); + vehicle other{definition::fiz(path).set("Power", "GensetPower", 520)}; + CHECK_FALSE(other->Genset.fitted()); + CHECK_FALSE(other->TractionModeSwitch(traction_mode::genset)); + CHECK(other->TractionMode == traction_mode::catenary); + } +} + +TEST_CASE("genset: the selector moves only with the line breaker open") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + REQUIRE(test::start_up(test::driving(dragon6), wire)); + REQUIRE(cab.Mains); + CHECK_FALSE(cab.TractionModeSwitch(traction_mode::genset)); + CHECK(cab.TractionMode == traction_mode::catenary); + run(dragon6, 2.0, wire); + CHECK(cab.Mains); + cab.MainSwitch(false); + REQUIRE_FALSE(cab.Mains); + CHECK(cab.TractionModeSwitch(traction_mode::genset)); + CHECK(cab.GensetSelected()); + CHECK(cab.TractionModeSwitch(traction_mode::catenary)); + CHECK(cab.TractionMode == traction_mode::catenary); +} + +TEST_CASE("genset: started, it closes the line breaker without a catenary") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + wake(cab); + REQUIRE(cab.TractionModeSwitch(traction_mode::genset)); + cab.GensetSwitch(true); + run(dragon6, 7.0); + CHECK(cab.Genset.is_cranking); + CHECK_FALSE(cab.Genset.is_active); + CHECK(cab.Genset.voltage == 0.0); + CHECK_FALSE(cab.MainSwitchCheck()); + run(dragon6, 2.0); + CHECK(cab.Genset.is_active); + CHECK_FALSE(cab.Genset.is_cranking); + CHECK(cab.Genset.revolutions == cab.Genset.revolutions_idle); + CHECK(cab.Genset.voltage == 3000.0); + // the line breaker gets ready MainInitTime after the voltage came + for (auto second = 0; second < 10 && false == cab.Mains; ++second) { + if (cab.MainSwitchCheck()) { + close_line_breaker(cab); + } + run(dragon6, 1.0); + } + REQUIRE(cab.Mains); + CHECK(cab.PantographVoltage == 0.0); + dragon6.step(no_wire); + CHECK(cab.EngineVoltage == 3000.0); + CHECK(cab.MainCircuitPowered()); + run(dragon6, 5.0); + CHECK(cab.Mains); +} + +TEST_CASE("genset: on the catenary position the genset feeds nothing") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + wake(cab); + cab.GensetSwitch(true); + run(dragon6, 20.0); + REQUIRE(cab.Genset.is_active); + CHECK(cab.TractionMode == traction_mode::catenary); + CHECK_FALSE(cab.MainSwitchCheck()); + close_line_breaker(cab); + CHECK_FALSE(cab.Mains); + dragon6.step(no_wire); + CHECK(cab.EngineVoltage == 0.0); + CHECK(cab.TractionSupplyVoltage() == 0.0); + // running isolated, at idle + CHECK(cab.Genset.revolutions == cab.Genset.revolutions_idle); +} + +TEST_CASE("genset: on the genset position the catenary feeds nothing") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + wake(cab); + REQUIRE(cab.TractionModeSwitch(traction_mode::genset)); + // the pantographs up under the wire, the genset stopped: the line breaker never closes + CHECK_FALSE(test::start_up(test::driving(dragon6), wire, 120.0)); + REQUIRE(cab.PantographVoltage > 2900.0); + CHECK_FALSE(cab.Mains); + CHECK_FALSE(cab.MainSwitchCheck()); + dragon6.step(wire); + CHECK(cab.EngineVoltage == 0.0); + CHECK(cab.TractionSupplyVoltage() == 0.0); +} + +TEST_CASE("genset: the power at the wheels stays within the genset's") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + REQUIRE(start_on_genset(dragon6)); + notch_up(cab); + auto peak{0.0}; + auto revolutions{0.0}; + auto over{0L}; + auto step_count{0L}; + for (; step_count < 60000 && cab.Vel < 80.0 && cab.Mains; ++step_count) { + step(dragon6, step_count); + auto const power{wheel_power(cab)}; + peak = std::max(peak, power); + revolutions = std::max(revolutions, cab.Genset.revolutions); + if (power > genset_traction_power * 1.02) { + ++over; + } + } + CAPTURE(step_count); + CAPTURE(peak); + CHECK(cab.Mains); + CHECK(cab.Vel >= 80.0); + CHECK(over == 0); + CHECK(peak <= genset_traction_power * 1.02); + CHECK(peak >= genset_traction_power * 0.95); // the limit bites + CHECK(revolutions >= 0.95 * cab.Genset.revolutions_max); +} + +TEST_CASE("genset: the revolutions follow the demand, so the power builds up") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + REQUIRE(start_on_genset(dragon6)); + // at idle with nothing asked of it + CHECK(cab.Genset.revolutions == doctest::Approx(cab.Genset.revolutions_idle)); + CHECK(cab.GensetTractionPowerLimit() == doctest::Approx(genset_traction_power * 700.0 / 1800.0).epsilon(0.001)); + notch_up(cab); + // the demand of the traction builds up at the pace of the inverters, the revolutions follow it + auto step_count{0L}; + for (; step_count < 3000 && cab.eimv_pr < 0.99; ++step_count) { + step(dragon6, step_count); + } + CAPTURE(step_count); + REQUIRE(cab.eimv_pr >= 0.99); + run(dragon6, 3.0); + auto const after3{cab.Genset.available_power()}; + CAPTURE(after3); + // first order: 1 - exp(-1) of the way from idle to full in the time constant at the least + CHECK(after3 > 520.0 * 0.75); + run(dragon6, 9.0); + CHECK(cab.Genset.available_power() > 520.0 * 0.95); + CHECK(cab.GensetTractionPowerLimit() == doctest::Approx(cab.Genset.available_power() * 0.85)); + // notched down it goes back to idle + while (cab.DecMainCtrl(2)) { + // down to zero + } + run(dragon6, 20.0); + CHECK(cab.Genset.revolutions == doctest::Approx(cab.Genset.revolutions_idle).epsilon(0.01)); +} + +TEST_CASE("genset: running from the catenary is the same with the keys") { + // the values of a run of each one, every step + struct values { + std::vector force; + std::vector speed; + std::vector voltage; + std::vector current; + std::vector demand; + }; + auto const record = [](values &Values) { + return std::vector{ + {"Ft", [&Values](TMoverParameters const &Vehicle) { Values.force.push_back(Vehicle.Ft); return Vehicle.Ft; }}, + {"V", [&Values](TMoverParameters const &Vehicle) { Values.speed.push_back(Vehicle.V); return Vehicle.V; }}, + {"EngineVoltage", [&Values](TMoverParameters const &Vehicle) { Values.voltage.push_back(Vehicle.EngineVoltage); return Vehicle.EngineVoltage; }}, + {"Itot", [&Values](TMoverParameters const &Vehicle) { Values.current.push_back(Vehicle.Itot); return Vehicle.Itot; }}, + {"eimv_pr", [&Values](TMoverParameters const &Vehicle) { Values.demand.push_back(Vehicle.eimv_pr); return Vehicle.eimv_pr; }}, + }; + }; + auto const drive = [&record](definition const &Definition, values &Values) { + test::reseed_random(); + vehicle dragon6{Definition, 0.0, "test", 1}; + // not checked against a recorded one: the runs are compared with each other + test::trace trace{"genset/catenary", record(Values), 1, false}; + dragon6.record(trace); + test::drive_cycle(test::driving(dragon6), wire, trace); + }; + values plain; + values genset; + drive(dragon(), plain); + drive(dragon_genset(), genset); + REQUIRE(plain.speed.size() > 10000); + REQUIRE(genset.speed.size() == plain.speed.size()); + CHECK(*std::ranges::max_element(plain.speed) > 10.0); + // the first step they differ in, if any + auto const first_difference = [](std::vector const &Left, std::vector const &Right) { + return std::ranges::mismatch(Left, Right).in1 - Left.begin(); + }; + auto const size{static_cast(plain.speed.size())}; + CHECK(first_difference(plain.force, genset.force) == size); + CHECK(first_difference(plain.speed, genset.speed) == size); + CHECK(first_difference(plain.voltage, genset.voltage) == size); + CHECK(first_difference(plain.current, genset.current) == size); + CHECK(first_difference(plain.demand, genset.demand) == size); +} + +TEST_CASE("genset: stopped, it opens the line breaker") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + REQUIRE(start_on_genset(dragon6)); + REQUIRE(cab.Genset.revolutions == doctest::Approx(cab.Genset.revolutions_idle)); + cab.GensetSwitch(false); + auto step_count{0L}; + for (; step_count < 1000 && cab.Mains; ++step_count) { + step(dragon6, step_count); + } + // coasting down from idle, the voltage falls to half, the undervoltage limit, in spinup_time * ln 2 + auto const seconds{step_count * 0.01}; + CAPTURE(seconds); + CHECK_FALSE(cab.Mains); + CHECK(seconds == doctest::Approx(3.0 * std::log(2.0)).epsilon(0.05)); + CHECK_FALSE(cab.Genset.is_active); + // and it doesn't close again + for (auto second = 0; second < 20; ++second) { + close_line_breaker(cab); + run(dragon6, 1.0); + } + CHECK_FALSE(cab.Mains); + // coasting down to a stop, with the time constant spinup_time + CHECK(cab.Genset.revolutions < 0.01 * cab.Genset.revolutions_idle); + CHECK(cab.Genset.voltage < 0.01 * cab.Genset.voltage_nominal); +} + +TEST_CASE("genset: automatic start follows the selector") { + vehicle dragon6{dragon_genset().set("Cntrl", "GensetStart", "Automatic"), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + wake(cab); + run(dragon6, 10.0); + CHECK_FALSE(cab.Genset.is_cranking); + CHECK_FALSE(cab.Genset.is_active); + REQUIRE(cab.TractionModeSwitch(traction_mode::genset)); + run(dragon6, 1.0); + CHECK(cab.Genset.is_cranking); + run(dragon6, 8.0); + CHECK(cab.Genset.is_active); + // the start switch does nothing to it + CHECK_FALSE(cab.GensetSwitch(false)); + run(dragon6, 1.0); + CHECK(cab.Genset.is_active); + REQUIRE(cab.TractionModeSwitch(traction_mode::catenary)); + dragon6.step(no_wire); + CHECK_FALSE(cab.Genset.is_active); +} + +TEST_CASE("genset: no battery, no start") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + cab.BatterySwitch(false); + REQUIRE(cab.TractionModeSwitch(traction_mode::genset)); + cab.GensetSwitch(true); + run(dragon6, 20.0); + CHECK_FALSE(cab.Power24vIsAvailable); + CHECK_FALSE(cab.Genset.is_cranking); + CHECK_FALSE(cab.Genset.is_active); + CHECK(cab.Genset.revolutions == 0.0); + // and with it, it starts + wake(cab); + run(dragon6, 10.0); + CHECK(cab.Genset.is_active); +} + +TEST_CASE("genset: the pantographs' pressure switch leaves the genset's line breaker alone") { + SUBCASE("on the genset") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + REQUIRE(start_on_genset(dragon6)); + cab.PantPressSwitchActive = true; + cab.PantPress = 0.0; + cab.PantPressureSwitchCheck(); + CHECK(cab.Mains); + } + SUBCASE("on the pantographs it opens the line breaker, the check the genset is spared") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + REQUIRE(test::start_up(test::driving(dragon6), wire)); + REQUIRE(cab.Mains); + // the pressure switch looks at the voltage through the couplers, not the pantographs' + cab.PantPressSwitchActive = true; + cab.PantPress = 0.0; + cab.PantPressureSwitchCheck(); + CHECK_FALSE(cab.Mains); + } +} + +namespace { + +// what braking showed of the current of the traction circuit +struct braking { + double lowest_current{0.0}; // [A], negative going back to the source + bool electrodynamic{false}; // whether the electrodynamic brake took part + double speed_lost{0.0}; // [km/h] in the 20 s of braking +}; + +// up to 60 km/h at full power, then braking with the train brake for 20 s, which the E6ACT blends with the +// electrodynamic one +braking brake_from_60(vehicle &Dragon, track const &Track) { + auto &cab{Dragon.mover()}; + notch_up(cab); + for (auto step_count = 0L; step_count < 60000 && cab.Vel < 60.0; ++step_count) { + step(Dragon, step_count, Track); + } + REQUIRE(cab.Vel >= 60.0); + while (cab.DecMainCtrl(2)) { + // down to zero + } + run(Dragon, 2.0, Track); + cab.DynamicBrakeSwitch(true); + cab.BrakeLevelSet(cab.Handle->GetPos(bh_FB)); + braking result; + auto const speed{cab.Vel}; + for (auto step_count = 0L; step_count < 2000; ++step_count) { + step(Dragon, step_count, Track); + result.lowest_current = std::min(result.lowest_current, cab.Itot); + result.electrodynamic |= cab.eimv_pr < 0.0 && cab.eimv[eimv_Ipoj] < 0.0; + } + result.speed_lost = speed - cab.Vel; + return result; +} + +} // namespace + +TEST_CASE("genset: braking electrodynamically on the genset sends nothing back") { + SUBCASE("on the genset") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + REQUIRE(start_on_genset(dragon6)); + auto const braked{brake_from_60(dragon6, no_wire)}; + REQUIRE(braked.electrodynamic); + CHECK(braked.lowest_current >= -1e-6); + CHECK(braked.speed_lost > 5.0); + CHECK(dragon6->Mains); + } + SUBCASE("on the catenary the same braking feeds the line, the check the genset is spared") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + REQUIRE(test::start_up(test::driving(dragon6), wire)); + test::release_brakes(dragon6.mover()); + run(dragon6, 5.0, wire); + auto const braked{brake_from_60(dragon6, wire)}; + REQUIRE(braked.electrodynamic); + CHECK(braked.lowest_current < -10.0); + CHECK(braked.speed_lost > 5.0); + } +} + +TEST_CASE("genset: one genset feeds the next car through the high voltage coupling") { + // both able to join the control and the high voltage lines: 35 of the E6ACT, + control 4 + high voltage 8 + consist train; + auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 1).mover()}; + auto &second{train.add(dragon().set("BuffCoupl", "AllowedFlag", 47)).mover()}; + REQUIRE((first.Couplers[end::rear].CouplingFlag & coupling::highvoltage) != 0); + wake(first); + REQUIRE(first.TractionModeSwitch(traction_mode::genset)); + first.GensetSwitch(true); + train.run(5.0, no_wire); + CHECK(second.GetTrainsetHighVoltage() == 0.0); + train.run(10.0, no_wire); + REQUIRE(first.Genset.is_active); + CHECK(second.GetTrainsetHighVoltage() > 2900.0); + CHECK(second.PantographVoltage == 0.0); + // the second one, on its catenary position with the pantographs down, takes it as the catenary's + second.BatterySwitch(true); + train.run(10.0, no_wire); + second.RelayReset(relay_t::maincircuitground | relay_t::tractionnmotoroverload | relay_t::primaryconverteroverload, range_t::local); + CHECK(second.MainSwitchCheck()); + second.MainSwitch(true, range_t::local); + CHECK(second.Mains); + // stopped, the genset takes the voltage away + first.GensetSwitch(false); + train.run(30.0, no_wire); + CHECK(second.GetTrainsetHighVoltage() < 1.0); + CHECK_FALSE(second.Mains); +} + +TEST_CASE("genset: the selector command travels along the train") { + // two locomotives in multiple: the control line, no permanent coupling + auto const coupling{coupling::coupler | coupling::brakehose | coupling::mainhose | coupling::control}; + consist train; + auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 1).mover()}; + auto &second{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 0, coupling).mover()}; + REQUIRE((first.Couplers[end::rear].CouplingFlag & coupling::control) != 0); + wake(first); + train.run(1.0, no_wire); + CHECK(first.TractionModeSwitch(traction_mode::genset, range_t::consist)); + CHECK(first.GensetSelected()); + CHECK(second.GensetSelected()); + first.GensetSwitch(true, range_t::consist); + CHECK(first.Genset.is_enabled); + CHECK(second.Genset.is_enabled); + first.TractionModeSwitch(traction_mode::catenary, range_t::consist); + CHECK_FALSE(second.GensetSelected()); + // the unit range keeps to the permanent couplings, which locomotives in multiple don't have + first.TractionModeSwitch(traction_mode::genset, range_t::unit); + CHECK(first.GensetSelected()); + CHECK_FALSE(second.GensetSelected()); +} + +TEST_CASE("genset: a selector command refused with the line breaker closed isn't passed on") { + auto const coupling{coupling::coupler | coupling::brakehose | coupling::mainhose | coupling::control}; + consist train; + auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 1).mover()}; + auto &second{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 0, coupling).mover()}; + REQUIRE(test::start_up(test::driving(train), wire)); + REQUIRE(first.Mains); + // the second one's line breaker opened by itself, the lead's is closed + second.MainSwitch(false, range_t::local); + REQUIRE_FALSE(second.Mains); + CHECK_FALSE(first.TractionModeSwitch(traction_mode::genset, range_t::consist)); + CHECK_FALSE(first.GensetSelected()); + CHECK_FALSE(second.GensetSelected()); + // with the lead's open it goes along + first.MainSwitch(false, range_t::local); + CHECK(first.TractionModeSwitch(traction_mode::genset, range_t::consist)); + CHECK(first.GensetSelected()); + CHECK(second.GensetSelected()); +} + +TEST_CASE("genset: a lead which starts its genset on its own passes the start switch on") { + auto const coupling{coupling::coupler | coupling::brakehose | coupling::mainhose | coupling::control}; + consist train; + auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47).set("Cntrl", "GensetStart", "Automatic"), 1).mover()}; + auto &second{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 0, coupling).mover()}; + wake(first); + train.run(1.0, no_wire); + // ignored by the lead, so its cab switch doesn't move, but the car behind starts on it + CHECK_FALSE(first.GensetSwitch(true, range_t::consist)); + CHECK_FALSE(first.Genset.is_enabled); + CHECK(second.Genset.is_enabled); + CHECK_FALSE(first.GensetSwitch(false, range_t::consist)); + CHECK_FALSE(second.Genset.is_enabled); +} + +TEST_CASE("genset: on the genset the pantographs carry no traction current") { + SUBCASE("on the genset") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + REQUIRE(start_on_genset(dragon6)); + notch_up(cab); + run(dragon6, 10.0); + REQUIRE(cab.Itot > 50.0); + CHECK(cab.CatenaryCurrent() == 0.0); + // only a heating fed straight from the pantographs takes from the wire + cab.TotalCurrent = 40.0; + cab.HeatingPowerSource.SourceType = TPowerSource::CurrentCollector; + CHECK(cab.CatenaryCurrent() == 40.0); + cab.HeatingPowerSource.SourceType = TPowerSource::Main; + CHECK(cab.CatenaryCurrent() == 0.0); + } + SUBCASE("on the catenary the traction current goes through them, the check the genset is spared") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + REQUIRE(test::start_up(test::driving(dragon6), wire)); + test::release_brakes(cab); + run(dragon6, 5.0, wire); + notch_up(cab); + for (auto step_count = 0L; step_count < 60000 && cab.Vel < 30.0; ++step_count) { + step(dragon6, step_count, wire); + } + CAPTURE(cab.Vel); + REQUIRE(cab.Itot > 50.0); + CHECK(cab.CatenaryCurrent() == std::abs(cab.Itot) * cab.IsVehicleEIMBrakingFactor() + cab.TotalCurrent); + CHECK(cab.CatenaryCurrent() > 50.0); + } +} + +TEST_CASE("genset: a scenery command reaches the selector") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + wake(cab); + // as a scenery's PutValues event gives it, one at a time + cab.PutCommand("TractionMode", 1, 0, cab.Loc); + dragon6.step(no_wire); + CHECK(cab.GensetSelected()); + CHECK(cab.CommandIn.Command.empty()); + cab.PutCommand("GensetSwitch", 1, 0, cab.Loc); + dragon6.step(no_wire); + CHECK(cab.Genset.is_enabled); + run(dragon6, 10.0); + CHECK(cab.Genset.is_active); + cab.PutCommand("TractionMode", 0, 0, cab.Loc); + dragon6.step(no_wire); + CHECK_FALSE(cab.GensetSelected()); +} diff --git a/utilities/translation.cpp b/utilities/translation.cpp index 1048dcfb8..58c9746ab 100644 --- a/utilities/translation.cpp +++ b/utilities/translation.cpp @@ -267,6 +267,8 @@ std::string locale::label_cab_control(std::string const &Label) { "fuelpump_sw:", STRN("fuel pump") }, { "oilpump_sw:", STRN("oil pump") }, { "oilfuelpump_sw:", STRN("oil and fuel pumps") }, + { "tractionmode_sw:", STRN("traction mode selector") }, + { "genset_sw:", STRN("diesel generator") }, { "motorblowersfront_sw:", STRN("motor blowers A") }, { "motorblowersrear_sw:", STRN("motor blowers B") }, { "motorblowersalloff_sw:", STRN("all motor blowers") }, diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index f057ae917..bbaaf9bb7 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -3878,7 +3878,8 @@ bool TDynamicObject::Update(double dt, double dt1) if( MoverParameters->Pantographs[end::front].is_active || MoverParameters->Pantographs[end::rear].is_active ) { if( MoverParameters->Mains // Ra 15-01: logować tylko, jeśli WS załączony - && MoverParameters->GetTrainsetHighVoltage() < 0.1f ) { // yB 16-03: i nie jest to asynchron zasilany z daleka + && MoverParameters->GetTrainsetHighVoltage() < 0.1f // yB 16-03: i nie jest to asynchron zasilany z daleka + && false == MoverParameters->GensetSelected() ) { // nor a dual-mode vehicle running on its genset // Ra 15-01: bezwzględne współrzędne pantografu nie są dostępne więc lepiej się tego nie zaloguje ErrorLog( "Bad traction: " + MoverParameters->Name @@ -4444,12 +4445,9 @@ bool TDynamicObject::Update(double dt, double dt1) double k; // tymczasowy kąt double PantDiff; TAnimPant *p; // wskaźnik do obiektu danych pantografu - double fCurrent = ( - MoverParameters->DynamicBrakeFlag && MoverParameters->ResistorsFlag ? - 0 : - std::abs( MoverParameters->Itot ) * MoverParameters->IsVehicleEIMBrakingFactor() ) - + MoverParameters->TotalCurrent; // prąd pobierany przez pojazd - bez sensu z tym (TotalCurrent) + // prąd pobierany przez pojazd z sieci: trakcyjny (on the genset of a dual-mode vehicle none) i TotalCurrent // TotalCurrent to bedzie prad nietrakcyjny (niezwiazany z napedem) + double fCurrent = MoverParameters->CatenaryCurrent(); // fCurrent+=fabs(MoverParameters->Voltage)*1e-6; //prąd płynący przez woltomierz, rozładowuje kondensator orgromowy 4µF /* double fPantCurrent = fCurrent; // normalnie cały prąd przez jeden pantograf diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 2c5a8d560..2a5634cd7 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -362,6 +362,12 @@ TTrain::commandhandler_map const TTrain::m_commandhandlers = { {user_command::oilfuelpumptoggle, &TTrain::OnCommand_oilfuelpumptoggle}, {user_command::oilpumpenable, &TTrain::OnCommand_oilpumpenable}, {user_command::oilpumpdisable, &TTrain::OnCommand_oilpumpdisable}, + {user_command::tractionmodetoggle, &TTrain::OnCommand_tractionmodetoggle}, + {user_command::tractionmodecatenary, &TTrain::OnCommand_tractionmodecatenary}, + {user_command::tractionmodegenset, &TTrain::OnCommand_tractionmodegenset}, + {user_command::gensettoggle, &TTrain::OnCommand_gensettoggle}, + {user_command::gensetenable, &TTrain::OnCommand_gensetenable}, + {user_command::gensetdisable, &TTrain::OnCommand_gensetdisable}, {user_command::waterheaterbreakertoggle, &TTrain::OnCommand_waterheaterbreakertoggle}, {user_command::waterheaterbreakerclose, &TTrain::OnCommand_waterheaterbreakerclose}, {user_command::waterheaterbreakeropen, &TTrain::OnCommand_waterheaterbreakeropen}, @@ -4276,6 +4282,95 @@ void TTrain::OnCommand_oilfuelpumptoggle(TTrain *Train, command_data const &Comm vehicle->OilPumpSwitchOff(false == enable); } +// the traction selector of a dual-mode vehicle (eu07/maszyna#536), a two-state switch +void TTrain::OnCommand_tractionmodetoggle(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + if (Train->mvControlled->GensetSelected()) + { + OnCommand_tractionmodecatenary(Train, Command); + } + else + { + OnCommand_tractionmodegenset(Train, Command); + } +} + +void TTrain::OnCommand_tractionmodecatenary(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + // refused with the line breaker closed: then the switch doesn't move + Train->mvControlled->TractionModeSwitch(TMoverParameters::traction_mode::catenary, range_t::consist); + if (false == Train->mvControlled->GensetSelected()) + { + Train->ggTractionModeSwitch.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_tractionmodegenset(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + // refused with the line breaker closed, or without a genset: then the switch doesn't move + Train->mvControlled->TractionModeSwitch(TMoverParameters::traction_mode::genset, range_t::consist); + if (Train->mvControlled->GensetSelected()) + { + Train->ggTractionModeSwitch.UpdateValue(1.0, Train->dsbSwitch); + } +} + +// the start request of the genset of a dual-mode vehicle, a two-state switch +void TTrain::OnCommand_gensettoggle(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + if (false == Train->mvControlled->Genset.is_enabled) + { + OnCommand_gensetenable(Train, Command); + } + else + { + OnCommand_gensetdisable(Train, Command); + } +} + +void TTrain::OnCommand_gensetenable(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + // ignored by a genset which starts on its own: then the switch doesn't move + Train->mvControlled->GensetSwitch(true, range_t::consist); + if (Train->mvControlled->Genset.is_enabled) + { + Train->ggGensetButton.UpdateValue(1.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_gensetdisable(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + Train->mvControlled->GensetSwitch(false, range_t::consist); + if (false == Train->mvControlled->Genset.is_enabled) + { + Train->ggGensetButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + void TTrain::OnCommand_waterheaterbreakertoggle(TTrain *Train, command_data const &Command) { @@ -10087,6 +10182,8 @@ bool TTrain::Update(double const Deltatime) ggFuelPumpButton.Update(); ggOilPumpButton.Update(); ggOilFuelPumpButton.Update(); + ggTractionModeSwitch.Update(); + ggGensetButton.Update(); ggMotorBlowersFrontButton.Update(); ggMotorBlowersRearButton.Update(); ggMotorBlowersAllOffButton.Update(); @@ -11703,6 +11800,8 @@ void TTrain::clear_cab_controls() ggFuelPumpButton.Clear(); ggOilPumpButton.Clear(); ggOilFuelPumpButton.Clear(); + ggTractionModeSwitch.Clear(); + ggGensetButton.Clear(); ggMotorBlowersFrontButton.Clear(); ggMotorBlowersRearButton.Clear(); ggMotorBlowersAllOffButton.Clear(); @@ -12064,6 +12163,12 @@ void TTrain::set_cab_controls(int const Cab) { ggOilFuelPumpButton.PutValue(mvControlled->OilFuelPumpsEnabled() ? 1.f : 0.f); } + // traction selector and genset of a dual-mode vehicle + ggTractionModeSwitch.PutValue(mvControlled->GensetSelected() ? 1.f : 0.f); + if (ggGensetButton.type() != TGaugeType::push) + { + ggGensetButton.PutValue(mvControlled->Genset.is_enabled ? 1.f : 0.f); + } // traction motor fans if (ggMotorBlowersFrontButton.type() != TGaugeType::push) { @@ -12403,6 +12508,8 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con {"fuelpump_sw:", ggFuelPumpButton}, {"oilpump_sw:", ggOilPumpButton}, {"oilfuelpump_sw:", ggOilFuelPumpButton}, + {"tractionmode_sw:", ggTractionModeSwitch}, + {"genset_sw:", ggGensetButton}, {"oilpressb:", ggOilPressB}, {"motorblowersfront_sw:", ggMotorBlowersFrontButton}, {"motorblowersrear_sw:", ggMotorBlowersRearButton}, diff --git a/vehicle/Train.h b/vehicle/Train.h index d0c3aaa8b..932e9a78a 100644 --- a/vehicle/Train.h +++ b/vehicle/Train.h @@ -374,6 +374,12 @@ class TTrain { static void OnCommand_oilfuelpumptoggle( TTrain *Train, command_data const &Command ); static void OnCommand_oilpumpenable( TTrain *Train, command_data const &Command ); static void OnCommand_oilpumpdisable( TTrain *Train, command_data const &Command ); + static void OnCommand_tractionmodetoggle( TTrain *Train, command_data const &Command ); + static void OnCommand_tractionmodecatenary( TTrain *Train, command_data const &Command ); + static void OnCommand_tractionmodegenset( TTrain *Train, command_data const &Command ); + static void OnCommand_gensettoggle( TTrain *Train, command_data const &Command ); + static void OnCommand_gensetenable( TTrain *Train, command_data const &Command ); + static void OnCommand_gensetdisable( TTrain *Train, command_data const &Command ); static void OnCommand_waterheaterbreakertoggle( TTrain *Train, command_data const &Command ); static void OnCommand_waterheaterbreakerclose( TTrain *Train, command_data const &Command ); static void OnCommand_waterheaterbreakeropen( TTrain *Train, command_data const &Command ); @@ -745,6 +751,8 @@ public: // reszta może by?publiczna TGauge ggFuelPumpButton; // fuel pump switch TGauge ggOilPumpButton; // oil pump switch TGauge ggOilFuelPumpButton; // joint oil and fuel pump switch + TGauge ggTractionModeSwitch; // traction selector of a dual-mode vehicle (catenary/genset) + TGauge ggGensetButton; // genset start switch of a dual-mode vehicle TGauge ggMotorBlowersFrontButton; // front traction motor fan switch TGauge ggMotorBlowersRearButton; // rear traction motor fan switch TGauge ggMotorBlowersAllOffButton; // motor fans shutdown switch From bc6df7ea615f497a3cd6ee7c5bd36014d5279148 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 26 Nov 2026 22:29:18 +0100 Subject: [PATCH 134/136] fix: a seed is the whole text and 0 is a seed; Linux honours XDG_CONFIG_HOME and XDG_CACHE_HOME (#469) * fix(settings): a seed is the whole text as a number, and 0 is a seed seed_of() took the digits in front of a word for the number, so 4242abc was seed 4242, and 12abc and 12xyz were the same seed. Now the whole text has to be the number; anything else is hashed as a word, and a word that starts with digits is said in the log. A seed of 0 also stood for no seed, so -seed 0 and randomseed 0 drew a random one. Whether a seed was given is now kept apart, in random_seed_given, set by -seed, randomseed, the test mode and the server of a network session. random_seed keeps its type. randomseed with nothing after it still gives no seed. Follows up #176. * fix(paths): Linux keeps the settings and the cache where XDG says user_config_path() ignored XDG_CONFIG_HOME, and user_cache_path() took XDG_CACHE_HOME even when it held a relative path. Both now follow the XDG base directory spec: the variable when it is set to an absolute path, else .config or .cache in the home folder. The choice is made by xdg_base_directory(), which takes the values of the variables, so it is tested on every system. Windows and macOS are unchanged. Follows up #29 and #124. * fix(paths): Linux keeps the settings in ~/.config/MaSzyna until XDG_CONFIG_HOME has its own With XDG_CONFIG_HOME set (or under Flatpak), the settings of earlier releases in ~/.config/MaSzyna were silently left behind: the profile eu07.ini, the bindings, the odometers, the editor's settings. The old folder is now used while it exists and $XDG_CONFIG_HOME/MaSzyna doesn't, said once in the log; the one-time move of the orthophoto cache finds the old cache there too. * test: keep the XDG settings test folder out of the shared temp folder --- application/application.cpp | 13 ++-- network/network.cpp | 1 + simulation/simulationtest.cpp | 4 +- tests/unit/COVERAGE.md | 4 +- tests/unit/test_utilities.cpp | 110 +++++++++++++++++++++++++++++++++- utilities/Globals.cpp | 7 ++- utilities/Globals.h | 3 + utilities/utilities.cpp | 67 ++++++++++++++++++--- utilities/utilities.h | 19 +++++- 9 files changed, 208 insertions(+), 20 deletions(-) diff --git a/application/application.cpp b/application/application.cpp index 0ac02c4fe..bca673a1f 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -419,7 +419,7 @@ int eu07_application::init(int Argc, char *Argv[]) // the run's seed, settled once and kept in Globals: the engines come out of it. // narrowed on purpose - mt19937 and seed_of() both work on 32 bits, and that is // the seed somebody can write down and pass on - if (!Global.random_seed) + if (false == Global.random_seed_given) Global.random_seed = static_cast(true_random_seed()); Global.random_engine.seed(Global.random_seed); Global.local_random_engine.seed(Global.random_seed); @@ -1360,11 +1360,16 @@ int eu07_application::init_settings(int Argc, char *Argv[]) else if (token == "-seed") { // a number is the seed; anything else is a word that stands for one. said in the - // log as it was given, because that is what gets passed on to somebody else + // log as it was given, because that is what gets passed on to somebody else. 0 is a seed + // too; an empty word gives none, as randomseed with nothing after it if (i + 1 < Argc) { - Global.random_seed = seed_of(Argv[++i]); - WriteLog(std::format("seed given on the command line: {} -> {}", Argv[i], Global.random_seed)); + if (auto const seed{seed_given(Argv[++i])}) + { + Global.random_seed = *seed; + Global.random_seed_given = true; + WriteLog(std::format("seed given on the command line: {} -> {}", Argv[i], Global.random_seed)); + } } } else if (token == "--test") diff --git a/network/network.cpp b/network/network.cpp index b5eeced42..1bd02267d 100644 --- a/network/network.cpp +++ b/network/network.cpp @@ -244,6 +244,7 @@ void network::client::handle_message(std::shared_ptr Connection, con if (!Global.ready_to_load) { Global.random_seed = cmd.seed; + Global.random_seed_given = true; Global.random_engine.seed(Global.random_seed); Global.starting_timestamp = cmd.timestamp; // TODO: configure simulation settings according to received cmd.config diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp index d32fd0e72..169e0883c 100644 --- a/simulation/simulationtest.cpp +++ b/simulation/simulationtest.cpp @@ -92,8 +92,10 @@ void apply_test_mode_settings() Global.iMultiplayer = 0; Global.exec_on_exit.clear(); // and the same way every time, unless given another seed (-seed, or randomseed in the settings) - if (!Global.random_seed) + if (false == Global.random_seed_given) { Global.random_seed = seed_of("test"); + Global.random_seed_given = true; + } // the real time limit, which the scenery may set too test().watch_wall_clock(wall_clock_limit(Global.test.wall_timeout, Global.test.timeout)); } diff --git a/tests/unit/COVERAGE.md b/tests/unit/COVERAGE.md index 4f7f4d657..71870c892 100644 --- a/tests/unit/COVERAGE.md +++ b/tests/unit/COVERAGE.md @@ -147,7 +147,7 @@ The tests are written for the first two columns, and for what the game doesn't c - The messages of the log (`Failed to open file`, `Bad include`) are run, and not checked: the log of the tests is a stub. - A buffer type which is neither a file nor a text (the `default:` of the constructor) can't be given without an invalid value of the type. - **`utilities.cpp`:** - - `Now()`, `user_config_path()`, `user_cache_path()` and `true_random_seed()` depend on the clock, the environment and the entropy source of the system. The tests call them and check the shape of the result. The branches for a system without the variables or without an entropy source aren't run, and those of the other systems aren't compiled. + - `Now()`, `user_config_path()`, `user_cache_path()` and `true_random_seed()` depend on the clock, the environment and the entropy source of the system. The tests call them and check the shape of the result. The branches for a system without the variables or without an entropy source aren't run, and those of the other systems aren't compiled. The choice among the XDG variables and the home folder which Linux makes is apart from the environment (`xdg_base_directory()`) and tested on every system. - `FileCased()` looks through the working folder for a name given without a folder, and through the folder of the file elsewhere; on Windows it only asks whether the file is there. The search is run on Linux only. - **`ladderlogic.cpp`:** the two `return`s marked "not reachable" after the switches over the kind of an element. @@ -215,7 +215,7 @@ The tests record the behaviour as it is. The following points may deserve a look - `stol_def()` gives its default only for an empty text. A text which isn't a number gives 0 (the flags of an event, the log setting). - `split_string_and_number()` throws for a name with a hyphen which no digit follows (`a-b`), and for a number too big. The gamepad bindings and the PLC use it on names from files. - `extract_value()` throws `std::out_of_range` when the key is the last thing in the text with nothing after its `=`. With a space after the `=`, the next `key=value` is taken for the value. - - `seed_of()` takes a word starting with digits for the number in front (`12abc` is 12), so different words can stand for the same seed. + - `seed_of()` took a word starting with digits for the number in front (`12abc` was 12), so different words could stand for the same seed, and a seed of 0 stood for none. Fixed: the whole text has to be the number, anything else is a word, and whether a seed was given is kept apart (`random_seed_given`). - `erase_extension()` cuts at the dot of a folder when the file has none (`dir.d/file` becomes `dir`). - `Round()` adds a half and cuts the fraction, which rounds the negative numbers up: -1.6 becomes -1. - **The PLC (`ladderlogic.cpp`):** diff --git a/tests/unit/test_utilities.cpp b/tests/unit/test_utilities.cpp index 458b79eed..1b12f1b9a 100644 --- a/tests/unit/test_utilities.cpp +++ b/tests/unit/test_utilities.cpp @@ -9,6 +9,8 @@ #include "utilities/utilities.h" #include +#include +#include #include // the helpers of utilities/utilities.cpp and utilities.h as they behave now: the numbers and texts they give, their @@ -234,10 +236,39 @@ TEST_CASE("utilities: the seed a text stands for is its number, or its hash the // a number which isn't a seed is a word: negative, or too big CHECK(seed_of("-5") == 1448u); CHECK(seed_of("4294967296") == 3632702254u); + CHECK(seed_of("+5") == 1386u); + CHECK(seed_of("-0") == 1443u); // the bytes over ascii count as positive CHECK(seed_of("\xB9") == 185u); - // a word starting with digits is taken for the number in front of it - CHECK(seed_of("12abc") == 12u); + // leading zeros are the same number + CHECK(seed_of("007") == 7u); + CHECK(seed_of("00") == 0u); +} + +TEST_CASE("utilities: a seed is the whole text as a number, or the whole text as a word") { + // digits with something after them are a word, not the number in front of them + CHECK(seed_of("4242abc") == 386617702u); + CHECK(seed_of("4242abc") != 4242u); + CHECK(seed_of("12abc") == 46838433u); + CHECK(seed_of("0x10") == 1546855u); + // a space is part of the word as well: the settings and the command line give the seed without them + CHECK(seed_of("4242 ") == 49564196u); + CHECK(seed_of(" 4242") == 31151516u); + // so two words starting with the same digits stand for two seeds + CHECK(seed_of("12abc") != seed_of("12xyz")); +} + +TEST_CASE("utilities: randomseed and -seed give a seed, 0 too, and an empty text none") { + CHECK(seed_given("0") == std::optional{0u}); + CHECK(seed_given("00") == std::optional{0u}); + CHECK(seed_given("4242") == std::optional{4242u}); + CHECK(seed_given("hello") == std::optional{99162322u}); + CHECK(seed_given("4242abc") == std::optional{386617702u}); + CHECK_FALSE(seed_given("").has_value()); + // a seed which is given is not the same as none, whatever its number + CHECK(seed_given("0").has_value()); + // and the settings start without one, to be drawn + CHECK(std::make_unique()->random_seed_given == false); } TEST_CASE("utilities: a version 4 uuid is drawn from the random numbers of the simulation") { @@ -697,11 +728,84 @@ TEST_CASE("utilities: the folders of the user's settings and of the cache are na #if defined(_WIN32) CHECK(user_config_path("eu07.ini").empty() == (std::getenv("APPDATA") == nullptr)); CHECK(user_cache_path("x").empty() == (std::getenv("LOCALAPPDATA") == nullptr)); -#else +#elif defined(__APPLE__) CHECK(user_config_path("eu07.ini").empty() == (std::getenv("HOME") == nullptr)); +#else + // the folders the XDG variables of this environment give, or the ones in the home folder + auto const expected{[](char const *Variable, char const *Fallback, char const *Filename) { + auto const base{xdg_base_directory(std::getenv(Variable), std::getenv("HOME"), Fallback)}; + return base.empty() ? std::filesystem::path{} : base / "MaSzyna" / Filename; + }}; + auto const config{xdg_config_folder(std::getenv("XDG_CONFIG_HOME"), std::getenv("HOME"))}; + CHECK(user_config_path("eu07.ini") == (config.empty() ? std::filesystem::path{} : config / "eu07.ini")); + CHECK(user_cache_path("geoportal") == expected("XDG_CACHE_HOME", ".cache", "geoportal")); #endif } +TEST_CASE("utilities: the folders of the XDG base directory spec, as Linux finds them") { + using path = std::filesystem::path; + SUBCASE("the variable, when it is set to an absolute path") { + CHECK(xdg_base_directory("/srv/config", "/home/user", ".config") == path{"/srv/config"}); + CHECK(xdg_base_directory("/srv/config", nullptr, ".config") == path{"/srv/config"}); + CHECK(xdg_base_directory("/srv/config", "", ".config") == path{"/srv/config"}); + CHECK(xdg_base_directory("/", "/home/user", ".cache") == path{"/"}); + } + SUBCASE("the folder in the home one, when the variable isn't set, is empty or holds a relative path") { + CHECK(xdg_base_directory(nullptr, "/home/user", ".config") == path{"/home/user"} / ".config"); + CHECK(xdg_base_directory("", "/home/user", ".config") == path{"/home/user"} / ".config"); + CHECK(xdg_base_directory("config", "/home/user", ".config") == path{"/home/user"} / ".config"); + CHECK(xdg_base_directory("./cache", "/home/user", ".cache") == path{"/home/user"} / ".cache"); + CHECK(xdg_base_directory("~/cache", "/home/user", ".cache") == path{"/home/user"} / ".cache"); + } + SUBCASE("none, without the variable and without the home folder") { + CHECK(xdg_base_directory(nullptr, nullptr, ".config").empty()); + CHECK(xdg_base_directory("", "", ".cache").empty()); + CHECK(xdg_base_directory("relative", nullptr, ".cache").empty()); + } + SUBCASE("the settings and the cache: each of its own variable, the same home") { + auto const config{xdg_base_directory("/xdg/config", "/home/user", ".config")}; + auto const cache{xdg_base_directory(nullptr, "/home/user", ".cache")}; + CHECK(config / "MaSzyna" / "eu07.ini" == path{"/xdg/config/MaSzyna/eu07.ini"}); + CHECK(cache / "MaSzyna" / "geoportal" == path{"/home/user/.cache/MaSzyna/geoportal"}); + } +} + +TEST_CASE("utilities: the settings stay in ~/.config/MaSzyna while XDG_CONFIG_HOME has no MaSzyna folder") { + using path = std::filesystem::path; + // in the working folder, as the other tests do: a fixed name in the shared temp folder could be taken over by another user + auto const home{std::filesystem::current_path() / "eu07_unit_xdg_config_home"}; + std::filesystem::remove_all(home); + auto const homename{home.string()}; + // an absolute posix path which doesn't exist, on every system the tests run on + char const *const xdg{"/eu07_test_xdg_config_nowhere"}; + SUBCASE("without the old folder the settings go where XDG says") { + CHECK(xdg_config_folder(xdg, homename.c_str()) == path{xdg} / "MaSzyna"); + CHECK(xdg_config_folder(nullptr, homename.c_str()) == home / ".config" / "MaSzyna"); + } + SUBCASE("the old folder is kept while the new one doesn't exist") { + std::filesystem::create_directories(home / ".config" / "MaSzyna"); + CHECK(xdg_config_folder(xdg, homename.c_str()) == home / ".config" / "MaSzyna"); + CHECK(xdg_config_folder(nullptr, homename.c_str()) == home / ".config" / "MaSzyna"); + // the old folder needs the home folder to be found + CHECK(xdg_config_folder(xdg, nullptr) == path{xdg} / "MaSzyna"); + } + SUBCASE("a file of that name isn't the old folder") { + std::filesystem::create_directories(home / ".config"); + std::ofstream{home / ".config" / "MaSzyna"} << "x"; + CHECK(xdg_config_folder(xdg, homename.c_str()) == path{xdg} / "MaSzyna"); + } +#ifndef _WIN32 + SUBCASE("the new folder is taken once it exists") { + auto const config{home / "xdg"}; + std::filesystem::create_directories(config / "MaSzyna"); + std::filesystem::create_directories(home / ".config" / "MaSzyna"); + auto const configname{config.string()}; + CHECK(xdg_config_folder(configname.c_str(), homename.c_str()) == config / "MaSzyna"); + } +#endif + std::filesystem::remove_all(home); +} + // numbers ------------------------------------------------------------------------------------------------------------- TEST_CASE("utilities: the sign of a number, and a number rounded to a whole one") { diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 5e64e40c4..3ac6b8f99 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -936,7 +936,12 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& { std::string text; ParseOne(Parser, text); - Global.random_seed = seed_of(text); + // nothing after the key gives no seed; anything else does, 0 too + if (auto const seed{seed_given(text)}) + { + Global.random_seed = *seed; + Global.random_seed_given = true; + } return true; } diff --git a/utilities/Globals.h b/utilities/Globals.h index d37535778..a5c0bad67 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -56,6 +56,9 @@ struct global_settings { bool ready_to_load{ false }; std::time_t starting_timestamp = 0; // starting time, in local timezone uint32_t random_seed = 0; + // whether random_seed was given (-seed, randomseed, the server of a network session) or is still to be drawn: + // 0 is a seed like any other, so it can't stand for none + bool random_seed_given{ false }; TCamera pCamera; // parametry kamery TCamera pDebugCamera; std::array FreeCameraInit; // pozycje kamery diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index 61a059e35..ccc18cbed 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -16,6 +16,7 @@ Copyright (C) 2007-2014 Maciej Cierniak //#include //#include #include +#include #include #include //#ifndef WIN32 @@ -57,6 +58,33 @@ std::string Now() #endif } +std::filesystem::path xdg_base_directory(char const *Variable, char const *Home, char const *Fallback) +{ + // as the spec has it: a variable which isn't set, is empty or holds a relative path counts as not set. absolute is + // said the way a posix system says it, so the answer is the same on every system the tests run on + if (Variable != nullptr && Variable[0] == '/') + return std::filesystem::path(Variable); + if (Home != nullptr && Home[0] != '\0') + return std::filesystem::path(Home) / Fallback; + return {}; +} + +std::filesystem::path xdg_config_folder(char const *Variable, char const *Home) +{ + auto const base{xdg_base_directory(Variable, Home, ".config")}; + if (base.empty()) + return {}; + auto folder{base / "MaSzyna"}; + if (Home != nullptr && Home[0] != '\0') + { + auto legacy{std::filesystem::path(Home) / ".config" / "MaSzyna"}; + std::error_code error; + if (legacy != folder && false == std::filesystem::exists(folder, error) && std::filesystem::is_directory(legacy, error)) + return legacy; + } + return folder; +} + std::filesystem::path user_config_path(const std::string &filename) { namespace fs = std::filesystem; @@ -67,8 +95,17 @@ std::filesystem::path user_config_path(const std::string &filename) if (const char *home = std::getenv("HOME")) return fs::path(home) / "Library" / "Application Support" / "MaSzyna" / filename; #else - if (const char *home = std::getenv("HOME")) - return fs::path(home) / ".config" / "MaSzyna" / filename; + if (auto const folder{xdg_config_folder(std::getenv("XDG_CONFIG_HOME"), std::getenv("HOME"))}; false == folder.empty()) + { + if (auto const wanted{xdg_base_directory(std::getenv("XDG_CONFIG_HOME"), std::getenv("HOME"), ".config") / "MaSzyna"}; + folder != wanted) + { + // said once, so whoever set XDG_CONFIG_HOME knows why the settings aren't there + static std::once_flag told; + std::call_once(told, [&] { WriteLog(std::format("Settings kept in \"{}\", the folder of the earlier releases, since \"{}\" doesn't exist", folder.string(), wanted.string())); }); + } + return folder / filename; + } #endif return {}; // env var missing → caller falls back to CWD-relative filename } @@ -83,10 +120,8 @@ std::filesystem::path user_cache_path(const std::string &filename) if (const char *home = std::getenv("HOME")) return fs::path(home) / "Library" / "Caches" / "MaSzyna" / filename; #else - if (const char *cache = std::getenv("XDG_CACHE_HOME"); cache != nullptr && *cache != '\0') - return fs::path(cache) / "MaSzyna" / filename; - if (const char *home = std::getenv("HOME")) - return fs::path(home) / ".cache" / "MaSzyna" / filename; + if (auto const base{xdg_base_directory(std::getenv("XDG_CACHE_HOME"), std::getenv("HOME"), ".cache")}; false == base.empty()) + return base / "MaSzyna" / filename; #endif return {}; } @@ -183,10 +218,19 @@ std::uint64_t true_random_seed() std::uint32_t seed_of(std::string const &Text) { - if (std::uint32_t number{}; std::from_chars(Text.data(), Text.data() + Text.size(), number).ec == std::errc{}) + auto const *const end{Text.data() + Text.size()}; + std::uint32_t number{}; + auto const [last, error]{std::from_chars(Text.data(), end, number)}; + if (error == std::errc{} && last == end) { return number; } + if (error == std::errc{}) + { + // digits with something after them are a word like any other, not the number in front of them: "4242abc" + // isn't seed 4242. said in the log, since whoever wrote it most likely meant a number + WriteLog(std::format("seed \"{}\" isn't a number, taken as a word", Text)); + } std::uint32_t hash{}; for (auto const character : Text) { @@ -195,6 +239,15 @@ std::uint32_t seed_of(std::string const &Text) return hash; } +std::optional seed_given(std::string const &Text) +{ + if (Text.empty()) + { + return std::nullopt; + } + return seed_of(Text); +} + std::string generate_uuid_v4() { std::uniform_int_distribution dist(0, 255); diff --git a/utilities/utilities.h b/utilities/utilities.h index 0cefb6c11..db5b6b4cb 100644 --- a/utilities/utilities.h +++ b/utilities/utilities.h @@ -12,6 +12,8 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "utilities/parser.h" +#include + /*rozne takie duperele do operacji na stringach w paszczalu, pewnie w delfi sa lepsze*/ /*konwersja zmiennych na stringi, funkcje matematyczne, logiczne, lancuchowe, I/O etc*/ @@ -25,7 +27,16 @@ template constexpr T sq(T v) return v * v; } -// returns the per-user config path for `filename` (platform-specific dir), +// a base folder of the XDG base directory spec, of the values of its variable (XDG_CONFIG_HOME, XDG_CACHE_HOME) and +// of HOME, either of them null when not set: the variable when it holds an absolute path, else `Fallback` (.config, +// .cache) in the home folder, else an empty path. what Linux uses; apart from the environment, so tests can call it +std::filesystem::path xdg_base_directory(char const *Variable, char const *Home, char const *Fallback); +// the folder of the settings on Linux, of the values of XDG_CONFIG_HOME and HOME: MaSzyna in the base folder of the +// settings, but ~/.config/MaSzyna, where the releases which didn't read XDG_CONFIG_HOME kept them, while it exists and +// the new one doesn't, so the settings already there keep working. an empty path as xdg_base_directory +std::filesystem::path xdg_config_folder(char const *Variable, char const *Home); +// returns the per-user config path for `filename` (platform-specific dir: %APPDATA%\MaSzyna, +// ~/Library/Application Support/MaSzyna, $XDG_CONFIG_HOME/MaSzyna or ~/.config/MaSzyna), // or an empty path if the home/appdata env var is unavailable std::filesystem::path user_config_path(const std::string &filename); // the per-user path for `filename` among the files kept only to be fetched again faster, which don't roam with the profile: @@ -76,11 +87,15 @@ int RandomInt(int min, int max); /// @return A random seed as 64 bit unsigned integer std::uint64_t true_random_seed(); -// The seed a word stands for. A number is taken as it is written; anything else is +// The seed a word stands for. A number is taken as it is written - the whole text, so +// "4242abc" is a word, not 4242 - and 0 is a seed like any other; anything else is // hashed the way Java's String.hashCode does it, so the same word gives the same // world on every platform and every build - which is the whole point of telling // somebody a seed. std::uint32_t seed_of(std::string const &Text); +// the seed a text of the settings (randomseed) or of the command line (-seed) gives: none for +// an empty text, else seed_of() it, 0 included +std::optional seed_given(std::string const &Text); std::string generate_uuid_v4(); double LocalRandom(double a, double b); From 2ebb10b3b237f915ffda550ac16da5d6c197df4c Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 26 Nov 2026 22:29:27 +0100 Subject: [PATCH 135/136] build(linux): leave libcurl and its TLS stack out of the bundled libraries (#439) * build(linux): leave libcurl and its TLS stack out of the bundled libraries (refs #320) * fix(editor): libcurl is loaded at run time, so the game starts without it on Linux The game was linked with libcurl, so with libcurl left out of the bundle it needed the system's libcurl.so.4 to start, although only the editor's downloads use it. Now only the headers are used at build time, and the editor opens the system's libcurl with dlopen() when it first needs it: libcurl.so.4, libcurl-gnutls.so.4, then libcurl.so. It looks up the eight functions it calls and checks each one. Without libcurl, or with one missing a function, the game runs as usual and only the editor's downloads are off, as in a build without libcurl; one log line says why. A libcurl older than the headers (before 7.85.0) gets the protocols as bit masks. Windows is unchanged: the editor uses WinHTTP there. --- CMakeLists.txt | 7 +- CMake_modules/bundle_runtime_libs.cmake | 16 ++- editor/editorHttp.cpp | 156 ++++++++++++++++++------ editor/editorOrthophoto.cpp | 7 +- tests/unit/test_editor_http.cpp | 15 +++ 5 files changed, 158 insertions(+), 43 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 93d374b94..faa6ef86d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -777,13 +777,16 @@ if (WIN32) endif() # http client of the editor, for the orthophoto, the terrain model and the topo map of geoportal.gov.pl: WinHTTP on Windows, -# libcurl elsewhere when available +# libcurl elsewhere when available. libcurl isn't linked: only its headers are used, and editor/editorHttp.cpp loads the +# system's libcurl at run time (dlopen), so the game starts on a system without it and only the editor's downloads are off +# there. the package doesn't bundle it either (CMake_modules/bundle_runtime_libs.cmake) if (WIN32) target_link_libraries(eu07_settings INTERFACE winhttp) else() find_package(CURL QUIET) if (CURL_FOUND) - target_link_libraries(eu07_settings INTERFACE CURL::libcurl) + target_include_directories(eu07_settings INTERFACE $) + target_link_libraries(eu07_settings INTERFACE ${CMAKE_DL_LIBS}) target_compile_definitions(eu07_settings INTERFACE EU07_WITH_CURL) else() message(STATUS "libcurl not found: the editor's orthophoto and terrain model will only show what's cached, its topo map nothing") diff --git a/CMake_modules/bundle_runtime_libs.cmake b/CMake_modules/bundle_runtime_libs.cmake index a0f71543e..5b95c50e8 100644 --- a/CMake_modules/bundle_runtime_libs.cmake +++ b/CMake_modules/bundle_runtime_libs.cmake @@ -4,6 +4,12 @@ # the libraries of the system itself stay out: the C library and the loader, the GPU driver stack (libGL and its # kin come with the driver), X11 / Wayland, the sound servers, libstdc++ (the GPU drivers bring their own need of a # newer one) and a few more every distribution has. what a library left out depends on isn't bundled either +# +# libcurl and everything it pulls in (TLS, Kerberos, LDAP, HTTP/2, compression, name handling) stay out too: the +# build machine's copy knows the CA bundle path of the build machine's distribution (Debian), so shipped next to +# the game it breaks the certificate checks on Fedora or openSUSE, and the security updates of the TLS stack come +# from the user's system, not from our package. the game isn't linked with libcurl: the editor loads the system's one +# at run time (editor/editorHttp.cpp), and without it only the editor's downloads are off get_filename_component(game_folder "${GAME}" DIRECTORY) set(manifest "${game_folder}/bundled_libs.txt") @@ -43,7 +49,15 @@ set(system_libraries "^lib(asound|pulse|pulse-simple|jack|pipewire-[0-9.]+)\\.so" "^lib(udev|systemd|dbus-1)\\.so" "^libz\\.so" - "^lib(fontconfig|freetype|harfbuzz|expat|uuid)\\.so") + "^lib(fontconfig|freetype|harfbuzz|expat|uuid)\\.so" + "^libcurl" + "^lib(ssl|crypto)\\.so" + "^lib(gssapi_krb5|krb5|k5crypto|krb5support|com_err|keyutils)\\.so" + "^lib(ldap|lber|sasl2)" + "^lib(nghttp2|nghttp3|ngtcp2|rtmp|ssh2?|psl|idn2|unistring)\\.so" + "^libbrotli(dec|enc|common)\\.so" + "^libzstd\\.so" + "^lib(gnutls|hogweed|nettle|gmp|p11-kit|tasn1|ffi)\\.so") file(GET_RUNTIME_DEPENDENCIES EXECUTABLES "${GAME}" diff --git a/editor/editorHttp.cpp b/editor/editorHttp.cpp index cbda581f0..2a8c90c00 100644 --- a/editor/editorHttp.cpp +++ b/editor/editorHttp.cpp @@ -13,12 +13,20 @@ http://mozilla.org/MPL/2.0/. #if defined(_WIN32) #include #elif defined(EU07_WITH_CURL) +// of libcurl only the types and the constants: its functions are looked up at run time (libcurl() below), so the game +// starts on a system without libcurl and only the editor's downloads are off there. no deprecation warnings for the +// options kept for a libcurl older than these headers +#ifndef CURL_DISABLE_DEPRECATION +#define CURL_DISABLE_DEPRECATION +#endif #include +#include +#include +#include "utilities/Logs.h" #endif #include #include -#include #include namespace editor_http @@ -308,9 +316,10 @@ bool client::get(std::string const &Url, std::vector &Out, std::st namespace { -// the file of the certificates https is checked with. the libcurl bundled with the game knows only the one of the system it -// was built on (/etc/ssl/certs/ca-certificates.crt of Debian and Ubuntu), which Fedora, RHEL and openSUSE don't have: there -// every download failed. the file named by the user first, then the ones the distributions keep; empty leaves libcurl's own +// the file of the certificates https is checked with. a libcurl built elsewhere (as the one once bundled with the game) knows +// only the one of the system it was built on (/etc/ssl/certs/ca-certificates.crt of Debian and Ubuntu), which Fedora, RHEL +// and openSUSE don't have: there every download failed. the file named by the user first, then the ones the distributions +// keep; empty leaves libcurl's own std::string const &certificates_file() { static std::string const file{[]() { @@ -335,30 +344,99 @@ std::string const &certificates_file() }()}; return file; } + +// the functions of libcurl the client uses, looked up in the system's libcurl. their types are those the headers declare +// them with, so a call through them is the call of the function itself +struct curl_library +{ + decltype(&::curl_global_init) global_init{nullptr}; + decltype(&::curl_easy_init) easy_init{nullptr}; + decltype(&::curl_easy_cleanup) easy_cleanup{nullptr}; + decltype(&::curl_easy_reset) easy_reset{nullptr}; + decltype(&::curl_easy_setopt) easy_setopt{nullptr}; + decltype(&::curl_easy_perform) easy_perform{nullptr}; + decltype(&::curl_easy_getinfo) easy_getinfo{nullptr}; + decltype(&::curl_easy_strerror) easy_strerror{nullptr}; + bool loaded{false}; // all of them found +}; + +// the system's libcurl: the name of its runtime package (libcurl4 of Debian and Ubuntu, libcurl of Fedora and Arch), that of +// the GnuTLS build of Debian and Ubuntu, then that of its development files. null when there's none +void *open_curl() +{ + for (char const *const name : {"libcurl.so.4", "libcurl-gnutls.so.4", "libcurl.so"}) + { + if (void *const library{::dlopen(name, RTLD_NOW | RTLD_LOCAL)}; library != nullptr) + return library; + } + return nullptr; +} + +// the function Name of the library into Function, false when the library has none +template +bool resolve(void *const Library, char const *const Name, Function &Into) +{ + // dlsym() gives a function's address as void *, which POSIX lets be converted back to the function's type + Into = reinterpret_cast(::dlsym(Library, Name)); + if (Into == nullptr) + WriteLog(std::format("Editor: the libcurl of the system has no {}, the downloads of the editor are off", Name)); + return Into != nullptr; +} + +// the system's libcurl, opened and initialised once, when the editor first needs it, and kept for the rest of the run +curl_library load_curl() +{ + curl_library curl; + void *const library{open_curl()}; + if (library == nullptr) + { + WriteLog("Editor: no libcurl (libcurl.so.4) on this system, the downloads of the editor (orthophoto, terrain model, topo map) are off"); + return curl; + } + curl.loaded = resolve(library, "curl_global_init", curl.global_init) && resolve(library, "curl_easy_init", curl.easy_init) && + resolve(library, "curl_easy_cleanup", curl.easy_cleanup) && resolve(library, "curl_easy_reset", curl.easy_reset) && + resolve(library, "curl_easy_setopt", curl.easy_setopt) && resolve(library, "curl_easy_perform", curl.easy_perform) && + resolve(library, "curl_easy_getinfo", curl.easy_getinfo) && resolve(library, "curl_easy_strerror", curl.easy_strerror); + if (false == curl.loaded) + { + ::dlclose(library); + return curl_library{}; + } + curl.global_init(CURL_GLOBAL_DEFAULT); + return curl; +} + +curl_library const &libcurl() +{ + static curl_library const curl{load_curl()}; + return curl; +} } // namespace client::client() : m_platform(std::make_unique()) { - static std::once_flag initialized; - std::call_once(initialized, []() { ::curl_global_init(CURL_GLOBAL_DEFAULT); }); - m_platform->curl = ::curl_easy_init(); + if (auto const &curl{libcurl()}; curl.loaded) + m_platform->curl = curl.easy_init(); } client::~client() { + // set only with libcurl loaded if (m_platform->curl != nullptr) - ::curl_easy_cleanup(m_platform->curl); + libcurl().easy_cleanup(m_platform->curl); } bool client::get(std::string const &Url, std::vector &Out, std::string &Error, stop_check const &Stop) { Out.clear(); + auto const &curl{libcurl()}; if (m_platform->curl == nullptr) { - Error = "curl_easy_init failed"; + Error = (curl.loaded ? "curl_easy_init failed" : "no libcurl on this system"); return false; } + CURL *const handle{m_platform->curl}; struct sink { @@ -378,47 +456,52 @@ bool client::get(std::string const &Url, std::vector &Out, std::st }; auto const progress = +[](void *User, curl_off_t, curl_off_t, curl_off_t, curl_off_t) -> int { return (*static_cast(User))() ? 1 : 0; }; - ::curl_easy_reset(m_platform->curl); - ::curl_easy_setopt(m_platform->curl, CURLOPT_URL, Url.c_str()); - ::curl_easy_setopt(m_platform->curl, CURLOPT_USERAGENT, "MaSzyna-editor"); + curl.easy_reset(handle); + curl.easy_setopt(handle, CURLOPT_URL, Url.c_str()); + curl.easy_setopt(handle, CURLOPT_USERAGENT, "MaSzyna-editor"); if (auto const &certificates{certificates_file()}; false == certificates.empty()) { - ::curl_easy_setopt(m_platform->curl, CURLOPT_CAINFO, certificates.c_str()); + curl.easy_setopt(handle, CURLOPT_CAINFO, certificates.c_str()); #if LIBCURL_VERSION_NUM >= 0x073400 // an https proxy is checked with the same file - ::curl_easy_setopt(m_platform->curl, CURLOPT_PROXY_CAINFO, certificates.c_str()); + curl.easy_setopt(handle, CURLOPT_PROXY_CAINFO, certificates.c_str()); #endif } - ::curl_easy_setopt(m_platform->curl, CURLOPT_FOLLOWLOCATION, 1L); - ::curl_easy_setopt(m_platform->curl, CURLOPT_MAXREDIRS, 10L); - // http kept for the services the user types; nothing else, also where a redirect leads + curl.easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1L); + curl.easy_setopt(handle, CURLOPT_MAXREDIRS, 10L); + // http kept for the services the user types; nothing else, also where a redirect leads. the system's libcurl can be older + // than the headers: one without the options by name (before 7.85.0) refuses them, and takes the bit masks #if LIBCURL_VERSION_NUM >= 0x075500 - ::curl_easy_setopt(m_platform->curl, CURLOPT_PROTOCOLS_STR, "https,http"); - ::curl_easy_setopt(m_platform->curl, CURLOPT_REDIR_PROTOCOLS_STR, "https,http"); + bool const named{(curl.easy_setopt(handle, CURLOPT_PROTOCOLS_STR, "https,http") == CURLE_OK) && + (curl.easy_setopt(handle, CURLOPT_REDIR_PROTOCOLS_STR, "https,http") == CURLE_OK)}; #else - ::curl_easy_setopt(m_platform->curl, CURLOPT_PROTOCOLS, static_cast(CURLPROTO_HTTPS | CURLPROTO_HTTP)); - ::curl_easy_setopt(m_platform->curl, CURLOPT_REDIR_PROTOCOLS, static_cast(CURLPROTO_HTTPS | CURLPROTO_HTTP)); + bool const named{false}; #endif - ::curl_easy_setopt(m_platform->curl, CURLOPT_MAXFILESIZE_LARGE, static_cast(kLargest)); - ::curl_easy_setopt(m_platform->curl, CURLOPT_NOSIGNAL, 1L); - ::curl_easy_setopt(m_platform->curl, CURLOPT_CONNECTTIMEOUT, 10L); - ::curl_easy_setopt(m_platform->curl, CURLOPT_LOW_SPEED_LIMIT, 1L); - ::curl_easy_setopt(m_platform->curl, CURLOPT_LOW_SPEED_TIME, 20L); - ::curl_easy_setopt(m_platform->curl, CURLOPT_WRITEFUNCTION, write); - ::curl_easy_setopt(m_platform->curl, CURLOPT_WRITEDATA, &received); - ::curl_easy_setopt(m_platform->curl, CURLOPT_NOPROGRESS, 0L); - ::curl_easy_setopt(m_platform->curl, CURLOPT_XFERINFOFUNCTION, progress); - ::curl_easy_setopt(m_platform->curl, CURLOPT_XFERINFODATA, const_cast(&Stop)); + if (false == named) + { + curl.easy_setopt(handle, CURLOPT_PROTOCOLS, static_cast(CURLPROTO_HTTPS | CURLPROTO_HTTP)); + curl.easy_setopt(handle, CURLOPT_REDIR_PROTOCOLS, static_cast(CURLPROTO_HTTPS | CURLPROTO_HTTP)); + } + curl.easy_setopt(handle, CURLOPT_MAXFILESIZE_LARGE, static_cast(kLargest)); + curl.easy_setopt(handle, CURLOPT_NOSIGNAL, 1L); + curl.easy_setopt(handle, CURLOPT_CONNECTTIMEOUT, 10L); + curl.easy_setopt(handle, CURLOPT_LOW_SPEED_LIMIT, 1L); + curl.easy_setopt(handle, CURLOPT_LOW_SPEED_TIME, 20L); + curl.easy_setopt(handle, CURLOPT_WRITEFUNCTION, write); + curl.easy_setopt(handle, CURLOPT_WRITEDATA, &received); + curl.easy_setopt(handle, CURLOPT_NOPROGRESS, 0L); + curl.easy_setopt(handle, CURLOPT_XFERINFOFUNCTION, progress); + curl.easy_setopt(handle, CURLOPT_XFERINFODATA, const_cast(&Stop)); - CURLcode const code = ::curl_easy_perform(m_platform->curl); + CURLcode const code = curl.easy_perform(handle); if (code != CURLE_OK) { - Error = (received.over || code == CURLE_FILESIZE_EXCEEDED ? kTooLarge : ::curl_easy_strerror(code)); + Error = (received.over || code == CURLE_FILESIZE_EXCEEDED ? kTooLarge : curl.easy_strerror(code)); Out.clear(); return false; } long status{0}; - ::curl_easy_getinfo(m_platform->curl, CURLINFO_RESPONSE_CODE, &status); + curl.easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &status); if (status != 200) { Error = "HTTP " + std::to_string(status); @@ -443,8 +526,11 @@ bool client::get(std::string const &, std::vector &Out, std::strin bool available() { -#if defined(_WIN32) || defined(EU07_WITH_CURL) +#if defined(_WIN32) return true; +#elif defined(EU07_WITH_CURL) + // libcurl opened here when nothing needed it yet + return libcurl().loaded; #else return false; #endif diff --git a/editor/editorOrthophoto.cpp b/editor/editorOrthophoto.cpp index d3254a2c1..7ea68acae 100644 --- a/editor/editorOrthophoto.cpp +++ b/editor/editorOrthophoto.cpp @@ -739,11 +739,8 @@ editor_orthophoto::service_info editor_orthophoto::describe(std::string const &S bool editor_orthophoto::can_download() { -#if defined(_WIN32) || defined(EU07_WITH_CURL) - return true; -#else - return false; -#endif + // on Linux, whether the system has libcurl as well + return editor_http::available(); } std::string editor_orthophoto::cache_directory() diff --git a/tests/unit/test_editor_http.cpp b/tests/unit/test_editor_http.cpp index ffdfe9959..a3abfc6b7 100644 --- a/tests/unit/test_editor_http.cpp +++ b/tests/unit/test_editor_http.cpp @@ -91,6 +91,21 @@ bool proxied() { } // namespace +TEST_CASE("editor http: a build with an http client has it at run time") { +#if defined(_WIN32) || defined(EU07_WITH_CURL) + // WinHTTP comes with Windows. libcurl isn't linked, it's loaded when first needed: a build made with its headers runs + // on a system that has it, so the tests below don't quietly skip a libcurl that failed to load + CHECK(editor_http::available()); +#else + CHECK_FALSE(editor_http::available()); + editor_http::client client; + std::vector data; + std::string error; + CHECK_FALSE(client.get("http://127.0.0.1/", data, error, []() { return false; })); + CHECK_FALSE(error.empty()); +#endif +} + TEST_CASE("editor http: a request a service doesn't answer is given up as soon as a stop is asked for") { if (false == editor_http::available() || proxied()) return; // a build with no http client, or a proxy in the way From 7ac2472c376e68fef862612420296e8a56b589ae Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 27 Nov 2026 04:05:40 +0100 Subject: [PATCH 136/136] Merge master into staging (#514) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Enhance Windows build matrix with AVX2 variants * fix(lang): the two Polish lines of the download area written with \n, so they match the tooltip and the hint * fix(files): data named in another case is found on Linux, folders included The parser and the loaders lowercase every name they read, while the data made on Windows has files and folders named in any case (scenery/Braniewo, textures/siec_trakcyjna_ph/.../STS_*.tga, sounds/sip/Gorki.wav). FileCased matched the file name only, so a folder in another case wasn't found. - FileCased walks every part of the path on Linux, the folder listings kept by their lowercase and read again once the folder changed; Windows as it was - FileExists finds the file in any case on Linux, and the variant with names and extensions gives back the name as it's on the disk, so textures, materials, sounds, station announcements and scripts open that name - models, sound captions, timetables and nodebank previews open the file as it's named on the disk; the texture format is told by the extension in any case * fix(files): the banks keep the names asked for, only the opening takes the case of the disk The textures, materials and sounds are kept by the names they're asked for. Given back as named on the disk, a file in another case missed the bank and was loaded again on every request. - FileExists with names and extensions finds the file in any case but gives back the name asked for; FileOnDisk gives the file to open, used where textures, sounds and scripts are opened - FileExists of a single name is a plain check again, the places checking it and opening the same name stay as they were - the texture format is told by the extension asked for again - a folder changed shortly before it was read is read again for a name missing from it, the time of a change being as coarse as the clock of the file system; a listing cut short isn't kept * fix(files): a folder changed in the future isn't read again on every name missing from it * perf(files): a file missing costs a single check, as before Measured in a case sensitive folder (3000 textures, every 20th in mixed case, looked up the way Texture.cpp does), the walk over every part of the path made a texture lookup 4-5 times slower than master: each name tried and missing checked every folder of its path. - the folders found are kept by the name they're given with, the missing ones for a second, so a missing file checks its folder alone - a folder named as it is on the disk is taken without its listing - the time a folder was changed is looked at once a second at most The lookup is now as fast as master's (about 180 us per texture on NTFS in both) while finding the files named in another case too. * fix(files): terrain files named in another case are found on Linux The terrain directive names .txtf/.btf files in lowercase, as the parser gives every token. The name is now taken as it is on disk, from the text file first, so the binary file is made next to the text and the editor's references and layers keep one name. * fix(files): models named in another case are found on Linux The manager of the models looked for the file with FileExists of a single name, a plain check again since the banks keep the names asked for, so a model named in another case (models/przejazdy/plyty3_L, dynamic/pkp/st44_v2/main/2M62-0685-A) was reported missing before TModel3d::LoadFromFile() could open it as it's named on the disk. find_on_disk() finds the file in any case and gives back the name asked for, the key of the bank. * refactor(files): named functions instead of the lambdas of the folder cache (Sonar S2259, S3608, S6004) Sonar took the folder captured by the lambda reading it for a reference to null, failing the quality gate on reliability. The folder is read and the path kept by functions in the anonymous namespace, the age of the listing declared in its if. * fix: the simulator opens more than 512 files at once, and a shader it can't open says why With "physicslog yes" every driver keeps its .dat open, and a large scenery (Tomaszewo: some 500 vehicles, cars of the roads included) took all 512 streams the MSVC runtime gives: the next fopen failed and the simulator stopped at "cannot read shader: shaders/map.vert" on opening the map. The limit is raised to 8192 at the start (the soft limit of open files up to the hard one on Linux), and a shader file that doesn't open is told as such, with the system's reason, rather than as one that can't be read. * feat(blackbox): the black box on its own, writing the tapes of the user's vehicles at the end "blackbox yes" in eu07.ini records the black box with the physics logs on or off, "blackbox no" never; with no entry it goes with "physicslog yes" as before. With the physics logs off, the recorder keeps the line of the physics log of the driver the user is with, every 0.05 s, and writes it to physicslog/.dat when the recording closes: the speed recorder's tape of the vehicles the user was in, without every vehicle keeping a log open and written twenty times a second. The line and the header of the log are made by one function of the driver, which its own log writes too, and the file is opened the same way, so the two are the same to the byte: the readers of these logs (the old Hasler tape viewer, the starter) read them as before. * feat(physicslog): the logs written every two seconds by a thread of their own, no file kept open; the black box's tapes as it goes "physicslog yes" kept the .dat of every vehicle with a driver open for the whole run and flushed it twenty times a second from the simulation's thread: some 580 open files on Tomaszewo. The lines are kept now and a thread of their own writes them every two seconds, each file opened only for the moment it is written to. The files, their lines and their text mode stay as they were. - The black box, with the physics logs off, writes the tapes of the user's vehicles through the same writer as it goes, not at the end. A log begins when the user is first in the vehicle and goes on while the user looks around outside, until another vehicle is taken; back in it, the log goes on after the gap. The vehicle's own driver keeps the log only if it is the primary one, as a passive one's clock stands still; otherwise the driver of its train does. - What is kept is written when the simulator closes, after the black box, at the end of a test run, and when the test watchdog ends a run. A crash loses the last two seconds. - On Tomaszewo with the black box alone, the one tape grows every two seconds. With "physicslog yes", the 581 logs grow and the simulator holds as many handles as without them; writing them takes the thread about 1.9 s, which the closing waits for once. * feat(blackbox): the cab record holds the speed of the wheels, apart from the vehicle's when they slip The speed of the cab record is the vehicle's. The speedometer, and a speed recorder's tape with it, shows the speed of the wheels as they turn, which runs away from it while they slip and drops to 0 while they are locked in a skid. It is added at the end of the record (194 bytes), where the readers skip what they don't know; the .dat tapes have it already, in their second column. * fix(ci): build OpenAL Soft with the PipeWire, PulseAudio and ALSA backends, so the Linux game has sound The Linux job builds OpenAL Soft 1.24.2 from source, but the runner had none of the headers of its audio backends, and OpenAL Soft's CMake leaves out every backend it can't find. The bundled libopenal.so.1 had only OSS, Null, Wave and Loopback. Modern distributions and the Steam Linux Runtime have no /dev/dsp, so the game logged "Failed to obtain audio device" and played nothing, with any Steam Linux Runtime and without one. - install libasound2-dev, libpulse-dev and libpipewire-0.3-dev before building OpenAL Soft - configure it with ALSOFT_REQUIRE_PIPEWIRE/PULSEAUDIO/ALSA, so a missing header fails the build instead of shipping a library without sound The backends are loaded with dlopen at run time (ALSOFT_DLOPEN is on by default), so the bundled library gains no new dependency. Tested by putting an OpenAL Soft 1.24.2 with these backends next to the game from the Steam depot: under Steam Linux Runtime 4.0 the sound works. Co-Authored-By: Claude Opus 5.5 * fix(editor): the certificates of https looked for where the distribution keeps them The Linux game bundles the libcurl of Ubuntu, which knows only Ubuntu's /etc/ssl/certs/ca-certificates.crt. Fedora, RHEL and openSUSE keep the certificates elsewhere, so every download of the editor (orthophoto, terrain model, topo map) failed there with a certificate error. The file is taken from SSL_CERT_FILE or CURL_CA_BUNDLE when set, else the first of the files the distributions keep, and passed as CURLOPT_CAINFO. With none found libcurl keeps its own. * fix(editor): an https proxy checked with the same certificates CURLOPT_PROXY_CAINFO gets the file found for CURLOPT_CAINFO, so a download through an https:// proxy on Fedora or RHEL doesn't fail on the proxy's certificate. * fix(ci): the no-AVX2 Windows build has its own concurrency group and its own public download After master was merged the two Windows variants shared one concurrency group with cancel-in-progress, so one cancelled the other, and the publish job looked for an artifact name the matrix no longer produces. Each variant now has its own group, the publish job downloads both, and the release carries maszyna-windows-x64.zip (AVX2, the old name, so the links already handed out still work) and maszyna-windows-x64-noavx2.zip. The AVX2 variant passes -DENABLE_AVX2=ON explicitly instead of an empty flag. * build: a build without AVX2 has _noavx2 at the end of its executable name With ENABLE_AVX2=OFF the executable is eu07-x64___noavx2.exe (eu07-x64_noavx2.exe without ADD_VERSION_SUFFIX), so a starter can tell the two builds apart by the name alone and pick this one on a CPU without AVX2. The AVX2 build keeps its name. * ci: Linux is built without AVX2 too, published as maszyna-linux-x64-noavx2.tar.gz The Linux job becomes the same two-variant matrix as Windows (ENABLE_AVX2=ON/OFF), each variant with a concurrency group of its own. The publish job downloads both Linux artifacts, restores the executable bits in both and releases maszyna-linux-x64.tar.gz (AVX2, the old name) next to maszyna-linux-x64-noavx2.tar.gz. The no-AVX2 executable is eu07___noavx2. * fix(renderer): the legacy renderer clears the arrays the scene left before it draws the ui The legacy renderer drew the ui with the client arrays of the last scene draw still enabled: the texture coordinates of the normal map unit and the normals, pointing into the vertex buffer of whatever was drawn last, 48 bytes a vertex. The ImGui backend sets up the vertex, colour and texture coordinates of the active unit only, so the driver read the stale arrays with the indices of the ui. Once the ui had more vertices than that buffer, the NVIDIA driver read past its end and the game crashed; a crash dump of the editor (an area selected, a track being laid) shows the read of vertex 15113 at a 48-byte stride in ImGui_ImplOpenGL2_RenderDrawData. The arrays are now disabled on every texture unit the geometry uses, with the normal and colour arrays, inside the glPushClientAttrib already there, so the scene gets its state back after the ui. The default and the experimental renderers don't go through this code. * fix(app): a renderer this build doesn't have starts the full one, not the legacy one The starter writes "gfxrenderer vulkan" for the Vulkan renderer of the builds that have it. This exe doesn't know the word, and every word other than default/experimental fell to the legacy renderer: a player who picked Vulkan got the slowest renderer, the one whose ui crashes on NVIDIA (the arrays left by the scene). "experimental" in a build without the NVRHI renderer ended with "no renderer found!" and no game at all. After the settings are read, a gfxrenderer word this build has no renderer for becomes "default", with a line in the log saying so. The words it knows stay as they were: full/default, legacy, simple, null, the older starters' simpleshader and off (legacy as before), and experimental where it is built. * fix(settings): the gfxrenderer word read in any case, as the starter reads it A hand-written "gfxrenderer Legacy" started the legacy renderer only because every unknown word did; with unknown words going to the full renderer it would have changed. The word is lowercased when read, as StarterNG's RenderEngineOf does, so Legacy, Simple or Full mean what they say. * fix(physicslog): a log whose file can't be written keeps its lines and header, and the writer is stopped once on every way out A failed write put its lines back, ahead of those since, so a file held by another program for a while gets its header and every line once it can be written; up to 4 MB kept per log. Stopping is joined once, and not from the writer's own thread. main stops the logs after an error it caught too, and the test watchdog flushes with a time limit, so a disk that doesn't answer doesn't keep the run from ending. * fix(blackbox): the wheels of the powered vehicle, as the speedometer has them, and the logs described as the drivers' they are In a unit driven from an unpowered car, the speed of the wheels was of the car the user is in, whose wheels never slip; now of the motor car, signed as the occupied vehicle's speed. The doc tells of a log per driver, and of the two seconds of real time a crash loses. * fix(physicslog): failed logs kept within 64 MB in all, cut outside the lock, never written twice; the writer knows itself when stopped The lines kept while files can't be written are cut to their share of 64 MB before the lock the simulation waits on. A log written in part is cut back to its length, so the next try doesn't write its start twice. A stop from the writer itself is told by its id even after another thread took it to join, and the watchdog's flush waits at most its time, the writing on a thread of its own. * feat(physicslog): the logs of the trains only, physicslog.trains "physicslog.trains yes" in eu07.ini writes the .dat log of each driver who drives rail vehicles, not of the passengers nor of the road vehicles that make "physicslog yes" hundreds of files on a big scenery: the tape of every train. A driver made primary later begins its log then, and isn't counted while it doesn't log. The black box goes with it when the ini says nothing of its own, and doesn't write a second log of a driver writing its own. The doc tells the doors' sides are the vehicle's, the driver's swapped in the rear cab. * fix(physicslog): a train's log begun at its first line, so passive crews get no file Every crew is primary in the constructor and the drivers but one of a train with crews in more vehicles are made passive only before it starts, so a log begun there left files with only the header. With physicslog on all logs begin at once as before; one of a train waits for update_logs. * fix(editor): the texture pickers let go of the images scrolled past, the memory no longer runs out The picker of the textures of a track offers every texture of the textures folder, and each tile that came into sight read its texture full size, into the graphics card and the memory, and kept it there for good. Scrolling through the list for a trackbed texture took about 2.5 MB a tile: some 900 tiles made 3.5 GB, the whole folder 28 GB, and the game went down once the memory ran out. An image out of sight for 3 seconds is now taken out of both again (texture_manager::unload, Unload_Texture of the renderers) and read anew when it's shown once more, a few a frame as before. Only a texture the scene has never drawn is let go; those of the scene stay to the resource sweep. The texture browser lets go of its images on Refresh too. The picker no longer lists textures/previews: the 4100 previews of the node bank are images of models, not textures of anything. Checked on td.scn by a scripted run: 8000 images of the picker read one batch a few frames after another held the game at 2-3 GB, where it went to 28 GB and fell before; images shown again after they were let go come back; a trackbed texture picked from the folder is drawn on the track after its image was let go. * fix(physicslog): the writer's destructor throws nothing, its wait a plain condition variable woken to stop; a driver of no vehicle controls nothing * fix(editor): the images of the materials let go of with all their textures, the browser's Refresh a frame later An image of a material read the material with all its textures, the normal and specular maps and the variants, and only the first one was let go of: those stayed in the memory for every material scrolled past. They are let go of together now (Unload_Material). texture_manager::unload also takes the textures read and not made yet, waiting for a worker still reading one, and deletes the gl texture itself: release() would read it back from the card with gfx.resource.move only for it to be dropped. The Refresh of the texture browser let go of the images in the middle of the frame, while panels drawn before it could still refer to them; it now marks them, and they go at the start of the next frame. Checked on td.scn by a scripted run: 8040 images of the picker read a batch every few frames end at 2.0 GB, against 2.3-2.6 GB before this and 1.1 GB at the start; a trackbed material picked from the folder is drawn on the track after its image was let go. * fix(physicslog): every stop asked wakes the writer, the one from itself too; no psyche for a driver of no vehicle * fix(editor): the image of a material with no texture in its first slot is let go of too Its normal and specular maps were read with it and stayed in the memory: the trim passed over every image with no texture of its own, the material along with it. * fix(physicslog): nothing that goes wrong in the writing ends the simulator; a name in 1250 makes a path on a Windows set to UTF-8 The writer's thread called flush() with nothing around it, so an exception leaving write() ended the process with std::terminate, with no message. One that happens: the file of a log was made a std::filesystem::path of the vehicle's name, which MSVC converts in the code page of the system and throws for bytes not of it; on a Windows with "Use Unicode UTF-8 for worldwide language support" a vehicle named in 1250, as the sceneries have them (0xB3 for ł), isn't UTF-8. - the file of a log is made of the name with MultiByteToWideChar without MB_ERR_INVALID_CHARS: the same file as before for every name of the code page, U+FFFD for the bytes not of it instead of a throw. Elsewhere the bytes are the name of the file as they were - a log whose writing throws for any other reason (memory) is kept for the next try as one whose file can't be written, and the other logs are written still - the thread, flush_for() and stop() write through flush_safely(), which lets nothing out: what was taken for a writing failing as a whole is lost and told in the log, the next writing goes on - the messages name the file by the bytes of the name, not by path::string(), which converts back Tests: a log which can't be written doesn't keep the others from theirs; a vehicle named in 1250 has its log, read back by physicslog_writer::file(). Reported in the review of #385. Co-Authored-By: Claude Opus 5.5 * fix(blackbox): the tapes go on after the editor, with the physics logs off The tapes of the user's vehicles were written by update() after the check for the writer of the recording, which close() drops on entering the editor (F11). With "physicslog no", the speed recorder's tape ended at F11 while the drivers' own logs of "physicslog yes" went on. The tapes are files of their own: they are kept from the moment the recording was to be made, the file made or not, closed or not, until the simulator closes, after the gap of the time in the editor. Only the recording itself stops at F11, as before. Reported in the review of #385. Co-Authored-By: Claude Opus 5.5 * fix(physicslog): what no file name may have on Windows is replaced in the name of a log, on every system A spawned vehicle is named :, and its log went to physicslog/:.dat. On NTFS that isn't even an error: it is the stream .dat of the file , which nothing lists, so the log was written and no one could find it. On Linux the file was there, under a name Windows can't open. The name of the file of a log has < > : " / \ | ? * and the control characters replaced by _, on every system, so the logs are named alike everywhere (spawn_ezt:12 is spawn_ezt_12.dat), and a _ before a name Windows keeps for a device (con, nul, com1..., with an extension too). The bytes of 1250 stay. The black box tells the log it begins by the same name. Co-Authored-By: Claude Opus 5.5 * refactor(renderer): a material's textures let go of in one place, for every backend Unload_Material walked the textures of a material and of its variants the same way in both opengl renderers, and Sonar counted its declarations, set into the long run of overrides the two headers share, as duplicated: 5.2% of the new code, 3% allowed. The walk is gfx_renderer's now, over IMaterial::GetAllTextures and the backend's Unload_Texture. Materials that don't tell their textures, the Vulkan renderer's, give none, and are left alone as before. Co-Authored-By: Claude Opus 5.5 * AI: shunting brakes for a stop point again; test mode: no false SPAD for a train set across a signal (#409) * fix(ai): shunting AI brakes for a stop point again, the braking curve doesn't plan from a brake table left at zero The braking curve outside the final approach plans from the consist brake table since ce87aa0e (#187, merged with #264) whenever the brake is pneumatic. That table is worked out only for train running (Obey_train, Bank); in shunting it stays at zero, the planned full braking falls to its floor of 0.01 m/s2, and the demand comes out at a few hundredths of a m/s2, above the shunting brake threshold of -0.2. A shunting engine then rolled on without braking until the final approach, too late, and ran through the signal it was to stop at (seed 480873929 of l053_poranek: ep07p-2003 at sandomierz_g4_sem_info, sm42-1096, et22-654). With no worked out table the curve is again the constant deceleration over the distance left, as it was before ce87aa0e and as #187 meant to keep it for shunting. Train running is unchanged. The curve moves out of TController into vehicle/brakingcurve.{h,cpp} so that it is unit tested: tests/unit/test_braking_curve.cpp checks a shunting engine braking to a stop point with the zeroed table, and that a train with a worked out table gets the same demand as before. * test(ai): pin the train braking-curve demand to the results of the code before the move A brake table that grips harder as the train slows and a gradient, so that a wrong gravity sign, table index or a dropped term in the shaped demand shows; the expected values were worked out with the code removed from TController::adjust_desired_speed_for_braking_curve. * fix(test): a train set across a signal doesn't pass it at danger the moment the AI first looks at it The speed table takes in events up to a train length behind the head, so a signal the train stands across at the start of a scenario is found already behind the head, becomes elapsed on its first update, and the test mode reported it as passed at danger (calkowo_lotos: st43-189 at mac_daleko3_sem_info, manewrowo3: st43-100 at suw_szopa_a02_sem_info, both at 13.6 s with the train at a stand, the signal 20 m behind the head). A point now counts as passed only when the head of the train had it ahead once; the blackbox record of passed signals follows the same rule. * fix(test): a signal found up to 5 m behind the head still counts as seen ahead The distance to an event is found in steps of a metre from the position of its memory cell, so a signal just ahead of the head (a train stopped short of it when the autopilot takes over, or set right at it at the start) could come out slightly behind it, and passing it would not be reported. The trains set across a signal that the previous commit is about stood 20 m past it. Still not reported: a signal crossed while the speed table is being traced anew in motion (a Timetable: command to a running train, the autopilot taking over in motion), as it is found behind the head when the trace is made. * docs(test): say what the seen-ahead tolerance gives up A train set less than 5 m past a signal at stop is still reported to pass it at danger: standing that close it can't be told from a train stopped just short of the signal, which the tolerance is there for. --------- Co-authored-by: maj00r * fix(camera): the roll of the cab shake tilts the view about the line of sight again (#414) 623c4f82 (#97, in 26.05.1) changed the order of the camera rotations from Z, X, Y to X, Y, Z. The order matters only with a roll, which the cab shake gives (Angle.z, set in drivermode.cpp), or a camera entry of the scenery with a roll. Applied last, in the space of the cab, the roll nodded the view up and down when looking out of a side window instead of tilting it. The roll is multiplied in first again, as in 26.05. Co-authored-by: maj00r * fix(particles): the smoke of a cold diesel keeps the colour of its template (#413) bcb9e644 (#109) turned a comparison into an assignment: the smoke of a vehicle in air at 5 degrees or less, or with its engine under 45 degrees, got the colour 128,128,128. The emitter colour is on a 0-1 scale, so the smoke turned pure white, glowing at night, and stayed so once the engine warmed up. Up to 26.05 the line compared and did nothing; the smoke keeps the colour of its template again, as it did then. Co-authored-by: maj00r * Fix stutter with fpslimit on Windows and a texture unit cache race with threaded Python screens (#399) * fix(render): the python upload thread only marks the texture unit cache stale, the drawing thread clears it update_from_memory() runs on the python upload thread with python.threadedupload (the default), and since e230d7b9 it cleared opengl_texture::units there outright. That raced Bind_Material filling the same array for its multi-bind: a unit reset between the fill and glBindTextures() made the bind of that unit fail, and the object was drawn with the texture of the one drawn before it, for a frame, at the rate of the screens. The thread now sets an atomic flag, and the drawing thread clears the cache when it next binds textures (bind() and the multi-bind of Bind_Material), so a screen texture given a new gl name is still rebound. * fix(app): fpslimit asks Windows for the 1 ms timer, the frames no longer come in turns long and short The wait of fpslimit sleeps, and Windows wakes a process which didn't ask for a finer timer in steps of up to ~15.6 ms. A 10 ms slot of fpslimit 100 ended ~15.6 ms later, the pacer made it up with no wait in the next frame, and with vsync on the frames were shown for one or two refreshes in turn: visible stutter at a steady FPS. timeBeginPeriod(1) is held from the settings to the exit, only when fpslimit is set. * fix: the 1 ms timer also for an fpslimit set by the scenery, the stale unit cache checked with a plain load first A config block of the scenery is parsed after the settings and can set fpslimit, so the timer period is asked for at the first wait of the pacer too, once. bind() checks the stale flag of the unit cache with a relaxed load before the exchange, which it does for every texture. * fix(textures): the stale flag of the unit cache uses the default memory order (Sonar S8417) On x86 a sequentially consistent load and exchange cost the same as the relaxed and acq_rel ones; only the store in invalidate_unit_cache() becomes an xchg, and it runs rarely. --------- Co-authored-by: maj00r * fix(camera): the cab shake taken at the frame's moment between its fixed steps, it no longer moves in steps (#403) The shake of the cab camera (ShakeState) is stepped by update_shake at a fixed 1/50 s, while the camera read the raw state every frame. At any frame rate other than 50 the shake moved in steps: some frames showed the same state as the one before, others jumped one or two steps at once. Players with 144/165 Hz screens saw the cab jump around the camera. The vehicle now keeps the state from before the last step (ShakeStateBefore), and the camera takes the state between the two at the share of the step the simulation time has reached (shake_between). The offset and the velocity are blended, the angles worked out from the blended velocity. The shake itself is computed as before, with the same fixed step and the same springs; only what the camera shows of it changes. It lags the vehicle by a constant 1/50 s instead of 0 to 1/50 s. Measured with the same build and the blending switched off by a temporary environment variable (not in this commit), the EU07 on td.scn driven by the AI, frames over 30 km/h, two runs of each: - 60 fps: frames with the shake standing still 25% -> 0%, the change in its speed frame to frame 4-5 times smaller for the offset, a third smaller for the angles - ~144 fps: 65% -> 0%, 10-18 times smaller for the offset, 4 times for the angles - no fps limit (~520 fps): 90% -> 0% Co-authored-by: maj00r * fix: inverted clamp bounds give the upper bound again, as the old clamp did (#412) * fix: inverted clamp bounds give the upper bound again, as the old clamp did The project's own clamp() of 26.05 applied the lower bound first and the upper one last, so bounds given the wrong way round always gave the upper one. Its calls became std::clamp (undefined for such bounds) and, where the bounds can cross, safe_clamp, which swapped them instead. Neither gives the old result. - safe_clamp is the old clamp again, min(max(value, lo), hi). This restores 26.05 at every place it is used, among them the AI's dynamic brake test (its demand was fAccThreshold x1.21, the swap made it x1.01), the generator voltage, the heavy cargo acceleration of the AI and the EP correction of the brake. - The cab camera is kept inside the cab with safe_clamp. The bounds come from the .mmd as written and some cabs have them reversed (the B cars of SA134 and 21xM, ET40, 754); with std::clamp the camera jumped between the two bounds every frame on MSVC, as its result is fed back. * fix: every call of the old clamp gives what it gave up to 26.05.1 d1f16411 (#99) made every call of the project's clamp() std::clamp. Where the bounds come from the data or are computed at runtime they can cross, and then std::clamp gives another result (undefined behaviour; MSVC gives the lower bound unless the value is above the upper one) where the old clamp gave the upper bound. These calls use safe_clamp, the old clamp, too: - Mover: the pantograph pressure (MaxPress), the compressor switch (CompressorListPosNo), the coupler distance (DmaxB, DmaxC), the engine revolutions, the eimic ramp (CtrlDelay), the eimic limit (eimic_max), the speed control ramp (PowerUpSpeed, PowerDownSpeed), the load (MaxLoad), the magnet of the security system (Dim.L); - DynObj: the coupler distance of the buffers (DmaxB), the axle distance (Dim.L); - Train: the brake handle positions (BrakeCtrlPosNo, the range of the handle); - the legacy renderer: the mouse pick (the window size). With the bounds in order nothing changes. Calls whose bounds the code keeps in order (constants, SplineFidelity 1-4, the season table, the guarded output calibration) give the same result with std::clamp and stay as they are. The load offset takes its arguments in the 26.05.1 order again; fa2ed089 swapped them, which with the old clamp differs only for a negative load. The bump at a rail joint gives the old result again. Up to 26.05.1 its clamps had 0 in place of the value (since 96f43e11 and 4d72d352), and the old clamp made that the headroom Vmax - (Vel + 0.32 Vmax), negative above 68% of the top speed, capped from above only; d464628a and 03bfbb13 kept it at 0 or above. Only damaged track has the bump: a damage flag in the .scn, a derailer set by an event, a track made on a derailment. The interior light of the cab in the 3.3 renderer is computed in double again, as before d1f16411. The call added since (stepped_uc_value, 00955513) keeps what master does: bounds given the other way round are put in order. * fix: the alpha of a particle in the legacy renderer as up to 26.05.1, the NaN cases of the clamp tested Up to 26.05.1 the alpha was clamp( particle.opacity * 255, 0, 255 ): the float was made a byte first, so the clamp did nothing and an opacity over 1 (a smoke max_opacity over 1) wrapped round, 1.2 giving 50. The move to std::clamp made it 255. It's made a byte as then again, through int: the byte the x86-64 compilers gave, without the undefined behaviour of that conversion (MSVC makes the same two instructions of both). openglparticles.cpp goes with feat/gl46-migration; its opengl33 counterpart, std::clamp( opacity, 0, 1 ), already gives what 26.05.1 gave. The tests pin what the old clamp gave with NaN: a NaN value stays NaN, a NaN bound doesn't clamp. The checks named after the AI braking test and the bump at a rail joint say they test the helper with the arguments of those calls, not the calls. * test: the includes of the clamp tests before the project's headers and go up, after the test headers, so the change no longer touches the lines #416 adds its includes after. With both merged is included twice, which is harmless. --------- Co-authored-by: maj00r * Python screens: the worker's image goes in place only after its fence, not a bare glFlush (#411) * fix(python): a screen uploaded by the worker goes into a texture of its own, put in place after a fence With python.threadedupload (the default) the worker wrote the image into the texture the drawing thread draws from, with glTexImage2D and glGenerateMipmap from its own context, and only a glFlush after. Nothing ordered the two contexts: the drawing one could sample the texture while its storage was being made anew, its level 0 half written or its mipmaps not made yet, and on a change of size the worker deleted the texture and wrote a new name into `id` with no synchronisation. The worker now uploads each image into a new texture, sets a fence after it and flushes. The drawing thread, once per frame in python_taskqueue::update(), waits for that fence on the gpu (glWaitSync, the cpu goes on), deletes the old texture and puts the new one in place. The worker no longer touches the texture drawn from, nor `id`. An image the drawing thread didn't take yet is dropped by the next one. Without sync objects the worker waits for the upload with glFinish. The windows of python.displaywindows with python.sharectx bound the texture once; they now bind the name of the last image put in place, which python_rt keeps for them. Uploads on the drawing thread (python.threadedupload no, the Lua and WebAssembly screens, the editor) are as they were. * fix(python): the image of the worker goes in place once its fence is signalled, the viewer binds it each frame From the review of 8811ee5a: - glWaitSync ordered only the context of the main window. The extra viewports and the windows of python.displaywindows draw in contexts of their own and could bind the new texture before the upload was done. commit_thread_upload() now asks the fence without waiting (glClientWaitSync, timeout 0) and puts the image in place only once it is signalled, so every context binding it afterwards has it whole. Until then the task stays in the upload queue and is asked again the next frame. - The drawing thread chose between upload and commit by python.threadedupload, the worker by whether it got a context. With python.threadedupload on and no context made for the worker, the screens were no longer updated. The task now records that a worker uploaded it. - The viewer of python.displaywindows told a new image by its texture name, but a deleted name comes back for a later texture. It binds the name of the last image each frame, read under the lock of the render target, and the name it starts with is read on the drawing thread when it is made. * fix(python): the old texture deleted under the lock the viewers bind under, a fence not made waited for with glFinish From the review of #411: - finish_upload() deleted the old texture before it took the lock of the render target, and the windows of python.displaywindows read the name under that lock but bound it after letting go of it. A window could bind a name already deleted, or already given to the next upload. In a compatibility context (the legacy renderer) that makes a new empty texture: a black frame and a texture never deleted. The commit and the publishing of the new name now go under the lock, and the viewer binds under it too. A name bound before the deletion stays alive in that window's context while bound. - A glFenceSync that returns no fence was taken for a signalled one: the image went in place at once, with nothing ordering the contexts. The worker now waits for its upload with glFinish then, as without sync objects. * fix(python): the worker waits for the lock of the screen without the gil, no flush after a finish From the review of 939514ea: - The drawing thread now holds the lock of the render target for a whole upload with python.threadedupload off. The worker, copying the next image under that lock, waited for it holding the gil. It now lets the gil go around the lock and the copy: the bytes it copies stay valid, the object is immutable and held by the reference the worker has. - glFlush after glFinish did nothing; the worker flushes only when it made a fence. --------- Co-authored-by: maj00r * fix(models): a scenery light that is off no longer shows lit for a moment the first time it comes into view (#407) * fix(models): a scenery light that is off no longer shows lit for a moment the first time it comes into view Since d13c27a7 (the light blinking rework) the opacity of a light changes step by step from its last value, and the opacities start at 1. RaAnimate runs only for the instances that are drawn, so a model with "lights 0" (a W24 LED indicator, for one) was drawn lit when it first came into range and faded out over 0.45 s. Before d13c27a7 the opacity of a plain on/off light was worked out anew from a timer starting at 0, so a light that is off was off from the first frame. Now the first time an instance is animated its lights take their current state at once, whether it came from the definition or from an event since. Every later change fades as before. The light threshold modes (ls_Dark, ls_Home) are untouched. The only other difference from before d13c27a7: a light that is on no longer fades in the first time it is drawn. * fix(models): the light opacity step written without an implicit double to float conversion (Sonar S5276) The sum is still worked out in double and rounded to float once, as the compound assignment did, so the result is the same to the bit. --------- Co-authored-by: maj00r * Editor: switch drives with no switch listed and marked; a deleted switch takes its drives and ballast along (#330) * feat(track): the rail code split by concern, the blades of the switches with the key frogs shaped from their templates The rails are laid by code of their own instead of inside Track.cpp: gauge lines (GaugeLine), knot lines (Knots.h), crossings and check rails (RailCrossings), rail materials (RailMaterials), measuring the rail profile (RailProfile), planning the cuts (RailPlan), the carving scan (RailCarve) and laying the geometry (RailLayer). A switch with the key frogs draws its blades from the tip where their planed nose ends to the heel, bent as they're thrown, and the rail behind them from the heel on, where they were laid from the start of the switch before; on a switch of the catalogue they start at the cut tip of the tables, 1.248 m from the joint at R 190, 1.5 m at R 300 (track_features::blades). The frogs cut from the rails, the wing and the check rails are built but switched off (track_features::crossings), the rails laid whole as before. The switches without the key keep the blades they had. A switch path can be a chain of pieces: pieces1 and pieces2 keep the parts of each path after the classic bezier, which stays as the approximation older versions read. A path with its radius given is a curve however gently it bends, a plain track a straight only where both of its control vectors lie along it. A vehicle trailing through a switch with a movable nose set the other way runs off the rails at it (TRAILED_SWITCH). * feat(render): the shared treads of the rails and their cut faces drawn, the cut faces in the matte variants of the rail materials Both renderers draw the treads a track shares with the rails it crosses, in the pick pass too, and a pass of their own for the faces where the rails are cut, the ends of the blades among them, in the matte variants of the rail materials, so the cut faces don't shine like the head the wheels polish. * feat(vehicle): an axle on a switch keeps to the path it came on, and coming from the frog end trails the switch through where the wheels reach the blades The switch thrown under an axle no longer moves it over onto the other path; it runs on along the one it entered. Coming from the frog end, where the blades are shaped or the frog has a movable nose, the switch set the other way is trailed through (rozprucie) only where the wheels get to the blades or to the nose, not as the axle enters the track; the other switches are trailed through as it enters, as before. * fix(track): the tracks drawn straight before, which their second control vector bends now, written to the log The simulator told a straight by the first control vector of a path alone, so a track whose second control vector bent it was drawn straight; now it's a curve. Such a track is named in the log as it loads, so a scenery made counting on the straight can be found: 25 tracks of lk357. Paths with both control vectors along them bend a centimetre or so at most and aren't named. * feat(track): 3D sleepers and switch timbers laid where the simulator makes the ballast, switched off in the build The sleepers of a track running alone are laid square to it, the timbers of the switches and crossings across the tracks running over them, shared by them, of the models set with sleepers3d and sleepers3dplain in eu07.ini; sleepers3dbed tells whether the ballast is laid under them too, lowered so they stick out of it. The layout of a cluster of tracks is worked out once and kept till a track of it changes, in a thread of its own while the simulation runs. timbermodel of a track, read and written back before, takes the place of the model of sleepers3d there. All of it is off whatever eu07.ini sets (track_features::sleepers), the tracks keeping their ballast and their sleeper models. * feat(render): the 3D sleepers and switch timbers drawn in instanced batches Render_Timbers lays the beams of the tracks in range where they're out of date and draws those of a run of tracks of a cell gathered by the model and its part or its level of detail, in as few instanced batches as they fit in; in the shadow pass only those near the camera. A track with them leaves its old sleeper model out. OpenGL 3.3 renderer only. * fix(track): the counts of what's wrong with the sleepers kept safe from the thread laying them, and that thread stopped before what it works with goes The counts of the beams clipped, dropped and off the plane, of the slowest and the biggest cluster, are counted by the thread working out the layouts in the background as well as by the simulation laying a cluster itself, and were plain values written by both; they're atomic now. What the thread keeps the clusters in, their version and the counts were made after the worker, as it first asked for them, and so destroyed before it at the exit while its thread could still be laying a cluster; they're made first now, the worker stopping and joining its thread before they go. The tracks go with the paths of the simulation, made before the worker. * revert(track): a tributary and a track of an unknown type load as before They came in with the rail code from the guards of the editor against crashing, and don't belong with the blades: a track of an unknown type loaded as a normal track of the railway could be joined to it and run on, and a tributary loaded as a river with its first path lost the second one when the editor saved the scenery. Both load as on master again; the place where the editor crashed on them is to be guarded where it is. * fix(track): the tracks drawn straight before named in the log once, as they load, and the paths of the switches with no radius told a straight as before in one term The log of the tracks the second control vector bends now was written each time the segments of a track were made again, as a track with its unevenness loads and as the editor changes or drags a track; it's written only the first time, as the track loads. The paths of a switch or a crossing with no radius keep the rule of master, a straight told by the first control vector alone, its two terms being the same length; they're one term now, with the comment saying so. * fix(track): the thread laying the sleepers stopped as the application exits, and loading no models itself The thread reads the scenery, which the application deletes as it exits well before the statics go: it's stopped and joined first thing in exit() now, the worker destroyed with the statics only where the application exits some other way, and not started again after. The models the beams are made of were loaded by the thread where it didn't find them, through the renderer, out of the thread of the renderer, into a map read by the simulation meanwhile: they're found under a lock now and loaded only by the threads other than it, again for all the tracks whenever a track changed since, before a layout is asked of it. With the 3D sleepers off in the build their settings aren't exported, and a track changed doesn't look for the tracks around to lay their beams again. * feat(track): the 3D sleepers turned on with sleepers3d in eu07.ini, no longer switched off in the build track_features::sleepers is gone: sleepers3d in eu07.ini lays them, none (the default) lays nothing and the tracks keep their ballast, as before. The sleepers3d settings are written back with the others. The editor changes the tracks, so while it's open their sleepers are worked out on the main thread as they're needed, not in the background. * fix(render): only the part of a timber model drawn, not what else the model holds A timber model of parts may hold more than its begin, main and end, as the kits with the fastenings of the rails do. Those were drawn with each part of each timber, in the middle of the track; they aren't laid, so they're skipped now. * fix(track): the 3D sleepers laid only for a renderer which draws them Only the OpenGL 3.3 renderer draws the beams. With another one a track set to them lost its ballast to them, lowered or not laid at all with sleepers3dbed no, and nothing was drawn in its place. Draws_Timbers() of the renderer tells now, and where it's false the tracks keep their ballast, as with sleepers3d none. * fix(render): the submodels of a timber model left as they were after its parts are drawn They were all made visible after a part was drawn, the ones the model hides itself too, like Light_On, while the same model may stand in the scenery. The submodels of the top level besides the parts are listed as the model is loaded, hidden while a part is drawn and given back their own visibility after. The parts have to be at the top level of the model for that; a model with them deeper is logged and drawn whole. Render_Timbers no longer looks the model up under the lock for every run of tracks, the name set is enough there. * fix(render): a vertex whose faces give its texture no direction gets a tangent across its normal, not a NaN one The cut ends of the rails have one spot of the texture on all their corners, so their tangent came out of normalize() as NaN. The normal-mapped shaders then shaded them with a NaN normal: about half of the vertices of the cuts and frogs, and the end faces of the rails. * feat(track): the frogs cut from the rails turned on with frogs in eu07.ini, no longer switched off in the build frogs yes cuts the rails of the plain tracks and of the switches with the key frogs where they cross other rails, into frogs, wing rails and check rails. It's off by default: the rails are laid whole as before, the blades of the switches with the key are shaped still. * refactor(editor): the track mode file split into the files of its tools, the code as it was A pure move, so that the commits after it show what changes in each tool rather than a 4800-line file rewritten. The member functions of editor_mode go to the file the editor of this branch has them in: route, straights, lay, switchplace, switchdrive, switchtool, trackgizmo, and the rest stays in editormodetrack.cpp. The helpers of its anonymous namespace go to editormodetrackshared.h, as they were but inline, in namespace track_mode, which the files use. No line of code changes; the files add only their license, includes and the using line. * feat(editor): the groundwork the tools of the editor share - The tool interface (editortool.h), the gestures of the mouse (editorgestures.h) and what the modes share (editormodeshared.h); the projection, viewport, selection and texture picking taking them up. - Scripted input (scriptedinput): the input of a selftest script fed to the editor as if typed and clicked, the real mouse and keyboard ignored meanwhile; EU07_EDITOR_SELFTEST_HIDDEN draws into a window never shown nor focused. - The ui layers and panels of the editor, its settings, icons and the info of the includes; the layers of the scenery and their saving; the launcher mode. - utilities: user_cache_path (the cache folder of the system for the user) and the helpers of the translations. - stb_image: the gif loader takes the frame two back from the frames it decoded, not from before its buffer. - tools/editor: the scripts making the headers of the drives, the turntables, the editor and its usage. - Unit tests: test_area and the stubs of the editor the tests link. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the tracks laid along an alignment, to the PKP PLK norms, with their grade line and the ground - The alignment of the laying (editorAlignment, editorAlignmentStore): straights, transition curves and arcs with the cant of the norms for the speed, the radius below the minimum for it a warning; the lay, route and straights tools build on it, the route plan reading the curves going on from the tracks adjoining. - The grade line (editorProfile, the profile and gradeline tools): fitted to the terrain model or edited by hand, the tracks fitted marked in the scenery (//$f), the shared grade lines of nearly parallel tracks (//$n). - The ground under the tracks (editorGroundFollow, trackbed): the terrain drawn to the tracks and restored, the tracks put onto the terrain. - Connections between tracks (editorConnections, the connection and connection curve tools), the track presets, the shape of a track (editorTrackShape), digitizing tracks from the orthophoto, the properties sheet of the tracks (trackprops) and the track ux. - Unit tests: alignment, ground fit, heights, with the data of two fits. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the switches placed, slid and designed from their templates - The switch templates (editorSwitchStore, the template tool): the catalogue switches and the user's own, kept with the settings; the designer (editorSwitchDesign) with a drawing of the dimensions, a and b typed in with the shape making up the rest, a switch clicked off the orthophoto. - The curve of a switch laid into a curve (editorSwitchCurve), placement on a straight or into a curve, slide along it, crossovers and double slips (switchplace, switchslide), the drives of the switches (switchdrive) and the records of the switches placed (records). - Unit tests: test_switch_curve. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the tools of the infrastructure beside the tracks The gauge, speed, joints, lineside, parallel tracks, vehicles, signals, turntables, sweep and road tools with headers of their own; the kilometrage of the lines (editorKilometrage, the km tool); the infrastructure, roads and speeds behind them (editorInfra, editorRoad, editorSpeed). Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the terrain model of geoportal.gov.pl and the orthophoto downloaded for the editor - editorNmt: the squares of the terrain model at 1 m (NMT GRID1, the WCS service of geoportal.gov.pl) fetched by two workers, kept in editor/cache/nmt/grid1 of the game folder, the heights of the scenery taken from them; the nmt mode loads it along the tracks or around the camera. - editorHttp: the HTTP client of both, WinHTTP on Windows, libcurl elsewhere where it's built with it; without it the caches only. - The orthophoto: its cache moved to the cache folder of the system for the user, the download area a polygon on the topo map (//$a) filled in the background, the 4K imagery, the tiles waiting outlined on the ground. - editorGeoMap: the topo map of the top view; heightmapterrain and the terrain streamer grow the terrain made from the model around the camera. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(launcher): the scenery wizard picks the place of a new scenery on the topo map the editor shares The wizard drops its own map download and decoding for the topo map widget of the editor (editorGeoMap). The place clicked becomes the geographic reference of the new scenery (//$g PUWG1992), and the scenery starts with the orthophoto of the editor on (//$o), lying under it in place. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the tools wired into the editor mode and the build editor_mode takes the tools of the commits before: its header declares them, editormode.cpp and the track mode drive them, and the renderers draw their overlays (opengl33 and legacy). CMakeLists lists the new sources and adds WITH_EDITOR_SELFTESTS (off by default); the unit tests build the new test files. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the selftests of the editor split by what they test The scripts of EU07_EDITOR_SELFTEST run the commands of editormodeselftest*.cpp: scene, track, rails, join, switch, signal, sleepers, sweep, terrain, monkey. The code is in every build; only with WITH_EDITOR_SELFTESTS=ON does the editor read the variables and run a script. The selftests of master now need the option too. The tree builds again with this commit. * feat(editor): the Polish texts of the editor, all of them in one update of editor_pl.po * fix(editor): the marks of the editor moved off the letters the starters read, and its lines told by their words The starters read some letters in a scenery file: the Starter the title //$n, the attachments //$f and the old scenery //$a, StarterNG and the launcher of the game the attachments //$f and the title //$n. The editor wrote its download area, shared grade lines and fitted tracks under them, and took every line of those marks as its own: saved, a scenery lost its title and attachments, and the starters showed the lines of the editor as them. - The download area is //$z, the shared grade lines //$w, the fitted tracks //$t. - Their lines and those of //$o are told by their first words, as //$h, //$r and //$k were: //$o only as "on 0" or "on 1", the origin or the settings of older builds after it, so a trainset described as "on ..." isn't taken. - The lines older builds wrote under //$a, //$n and //$f are read only by the words the editor wrote in them, or by its own comment line before them, under the new mark. Each save writes them again with it, also when the editor didn't change them; the lines of the starters stay. * fix(editor): a square of the terrain model cut short isn't read, and the squares are kept in the user's cache The service puts the directory of its GeoTIFF before the pixels, so a file cut short by a write or a fetch broken off was read whole, the pixels missing coming out as heights of 0 m, for good. - The reader (editorGeoTiff.hpp, with unit tests) wants all the strips the rows need, each within the file. - A square is written under a name of its own and renamed. - The squares are kept in the user's cache folder (nmt/grid1), as the orthophoto, since the game folder may not be writable; without one, in the game folder as before. The ones older builds kept there are moved over as each is asked for, a damaged one deleted. - Capabilities that didn't come aren't kept as the fallback name for the session: the next square asks again. * chore(editor): the http client said to serve the terrain model and the topo map too, the gif fix of stb_image marked local - CMake names the orthophoto, the terrain model and the topo map as what goes without libcurl. - The fix of the gif frame two back in stb_image is ours, not upstream's (v2.30 still has the old line): a comment at the line says so, for an update of stb_image to keep it. * fix(editor): the lines moved off the letters of the starters in a merged layer written once, not again with each save A merged layer's text goes into the file of its target on save, and the target is read again; the marked lines of the merged layer were dropped only for the marks the editor had changed. The lines moved to the new letters stayed with their old places, and the next save of the session wrote them into the target once more. - After a save, the marked lines of every merged layer are dropped; those of its target are read again from its file. - The lines of a dead layer aren't written again. - The selftest layermerge merges the layer of one file into another's, as the layers panel does. * feat(editor): the station as the signalling sees it, found from a switch of it, and its schematic editorStation: the switches joined by plain track no longer than 1.5 km, the tracks between them and the lines leading out, 400 m of each beyond the outermost switch; laid out as a schematic along the main track through the station. The track circuits, the signals and their lights, the lengths of the station tracks and the lines to the next stations are worked out from it for the signalling tool. Nothing uses it yet: the signalling tool, wired in the next commit, does. It builds on its own. * feat(editor): the signalling of a station in the Signalling tab, laid out from a switch of it as on the lines of PKP PLK LMB on a switch in the Signalling tab opens its station: the schematic in a window of its own, the name, the code, the line and the km of the station, and the steps of its signalling, each one step of undo: - the switches numbered along the station after its code, bpd_1, the parts of a slip bpd_15a..d; the drives and the objects naming a switch follow it, events written by hand keep the old names; - the tracks cut at the joints of the track circuits, Ie-4, and the circuits named, bpd_iz1, bpd_it1; - the entry, exit and shunting signals placed and named, A, F1, Tm1, from the templates chosen; - the signals of the lines out: the automatic block of three or four aspects, the block sections no shorter than the braking distance, or the semi-automatic one with a warning disc; block boundaries drawn by hand; - the lights each signal needs for its routes, Ie-1 and Ie-4 § 8, its template fitted to them; - the SHP track resonators the signals lack, rezonator.inc; - the lengths of the station tracks as a table, and what the station and its lines still lack, with Repair. The stations described are kept as //$s lines in the files of their layers. * fix(editor): the signals of a station and of its lines not placed with no template for a kind, no track cut for them first - Set the signals and Set the line signals cut the tracks first, and only then found no template for a kind. They stopped there, but the cuts stayed as a step of undo. Now they ask for the templates first, by the lookup signal_batch() uses (signal_template_for(), behind editor_signals::signal_templates_missing()). Without one nothing is cut. - Set the signals and Set the track circuits again under Track lengths had the ids of the buttons of the steps above them. ImGui flagged them when hovered. Each now has an id of its own. * fix(utilities): win1250_to_utf8 turns the polish letters into utf-8, not into themselves utilities.cpp starts with a byte order mark, so the compiler reads it as utf-8. The game's targets don't get /utf-8, though: set_target_properties(... COMPILE_OPTIONS ...) in the MSVC block of CMakeLists.txt replaces the options add_compile_options gave them. So the string literals went into the program in the code page of the system, windows-1250 on a polish one, and the map of win1250_to_utf8 turned each letter into itself. What read windows-1250 through it got no utf-8: the names, descriptions and categories of the sceneries and the names of the textures in the launcher, and the descriptions of the templates in the editor. The editor writes such a description back through utf8_to_win1250, which makes a question mark of each byte that doesn't start a utf-8 sequence, so the letters it had read unchanged didn't come back. The utf-8 sequences are written as bytes now, the way utf8_to_win1250 has them, so they don't depend on the options. The options stay as they are: with /utf-8 other literals of the files with a byte order mark would change, the "±" of the table of Bezogonkow would take two bytes and move the letters after it. The unit tests check the letters and that the text given is valid utf-8. (cherry picked from commit 9ffed96ec1af6cdafd918ab1ca4c0d75bbd334f5) * fix(editor): the switches renamed only after the events by their old names are shown, the station records in windows-1250 and in the file the scenery had Number the switches renames the switches and what the editor writes along with them, but not the events written by hand: a switch event aiming at a switch, or :event0 and the others named after it, would keep the old name and lose its switch. Now the first click lists them in the status, up to six and how many more, and renames nothing. A second click with the same renames goes ahead. The name of a station is written in windows-1250, like the rest of the scenery file. A name read that isn't valid utf-8 is taken for windows-1250; the utf-8 the earlier builds wrote is read as it is. utf8_to_win1250 moves from editorIncludeInfo.cpp to the utilities, beside win1250_to_utf8, and the unit tests check both ways. The record of a station that had none goes beside the records of the other stations, in the file marked with them, so a scenery saved under another name keeps them in one file. output_layer takes, after _.scm, an included file of the part of another name, the one of the scenery it was copied from, before it makes a new one. The comments: the joints of the track circuits stand 4.2 m beyond the fouling points, where the axes are 3.5 m apart, as joints() counts them; the regulation of the lengths is cited with its date and title. * fix(editor): a scenery saved under another name keeps one file of the keys by the movable noses, not the old one beside its own The editor writes the keys by the movable noses on each save to _dzioby.scm and includes it. A copy of a scenery, saved under another name, still included the file of the scenery it came from, and its save wrote a file of its own and included it too, so each key stood twice. Now the save leaves out of the scenery the other files of such keys it includes, told by the line the editor writes at their start. Their files stay on the disk, for the scenery they were made for. A file made by hand, without that line, stays included. The turntable controls had the same, fixed the same way on their own. * fix(editor): a file of the scenery named like a part of a tool isn't taken for the one the tool made output_layer took, after _.scm, any included file named *_.scm, so that a scenery saved under another name goes on with the file of the scenery it was copied from. A file of the scenery named alike, written by hand, such as rejon_teren.scm, got the terrain directive, the hectometre posts or the new signals too. The files output_layer makes start with a line of their own now, "// scenery layer created in the editor for its part", and a file of another name is taken only with that line. A layer gets it through the new parameter of scene::node_layers::create(); the others start with the general line as before. _.scm of the scenery itself is taken without the line, as it was. A file made for a part by an earlier build has only the general line, so a copy saved from it gets a file of its own. * feat(editor): a player of GIF clips for the windows of the editor editor_clips::clip plays a GIF in an ImGui window, looped, from the time given. stb_image decodes the whole file on a thread of its own, so the window isn't held up; until then the clip says it's loading. The frames are kept as stb_image decoded them, and the one shown is a texture of the ImGui renderer (Create_Image), made again only when the frame changes. A file that isn't there is told missing at once, with no thread started. Nothing uses it yet; the tutorial of the next commit shows its clips with it. * feat(editor): Help > Tutorial, fifteen short lessons of the editor The lessons: looking around, laying track, curves, the radius of the curves at the bends, correcting a curve, joining tracks, switches, switch templates, signals and posts, selecting and fixing, editing with the gizmo, the grade line, terrain from the terrain model, sceneries made before, saving and driving. Each lesson has: - in eight lessons, a looping clip from lang/editor_tutorial/.gif, played from the start on a click; in six others, a moving drawing (the radius at a bend, a switch template clicked, the signals, the grade line, the terrain, a trainset); - the mouse buttons and keys drawn as pictures beside what they do; - ticks that fill in as the user does it, told by the tools through editor_guide::first_step_done(); - a button that turns the tool of the lesson on; - Back / Next and a dot per lesson, green when the lesson is done. The window follows the work: when the tool in use changes, it turns to the first lesson of that tool not done yet, and a page turned by hand stays until then. In a lesson of laying it warns when there's no ground under the cursor. Where it opens: - by itself when an editor session starts, until "Show when the editor opens" is unticked (first_steps in the editor's settings); - from the Help menu; - from a Tutorial button beside Lay a track in the hint of an empty scenery, which isn't drawn while the tutorial is open; - at its lesson, from a "?" by the radius at the bends in the lay panel. A lesson whose clip isn't there is shown without it; the clips aren't in this commit. editor_guide is a new role of the editor, given to the hekto-post and trainset tools. Selftest command tutorial : opens the tutorial at a lesson, from 0; -1 closes it. * fix(editor): the lessons of the tutorial say what the editor does The lesson texts checked one by one against the tools; the ones that told otherwise: - Switches: a connection isn't chosen at the top of the panel, its kind comes from where the drag is let go (a crossover onto the other track, over a crossover the other way a double one, or scissors where they overlap). - Switches: a ladder leads onto the parallel tracks it's dragged across, let go on the farthest, with the straights up to where they start; it lays no missing tracks. - Terrain: there is no step 3. Step 1 is Location, step 2 is Load around the camera while there are no tracks and Tracks and terrain with its three ways once there are. The rows had the step numbers in the keys column, and 1, 2 and 3 switch the edit modes in the Terrain field. Now the steps show the mouse, the terrain under some tracks only is a row of F3 (the line the terrain panel shows), and the rows that only tell what the fit does have no key. - Sceneries made before: a plain include can be changed; the row lists what can't: an include template (.inc), the binary terrain cache, a file included twice or with parameters, a locked or hidden layer. - Laying: the second Esc drops the points only within 3 s. - The radius at the bends: two transition curves from 6000 m down to 2000 m while they're long enough for the speed, then an arc; a label turns orange where the curve breaks the norms, not because it came out smaller; two transitions meeting read 2xL and R; the labels of each transition curve are on laid tracks, close up. - Signals and posts: the W17 markers go by the selected switch, around the camera or the whole scenery, not along a line. - Selecting and fixing: E lengthens the track, the control vectors bend it. - The gizmo: at a point Q moves the point alone, W turns the whole track about it. The tooltip of Help > Tutorial no longer speaks of clips: the tutorial goes without them. lang/editor_pl.po has the new texts. * fix(editor): the lessons of the tutorial in plain words Every row, goal and warning of the tutorial is said again for someone who has never laid a track, in English and in Polish: - the words of the railway and of the editor are said in everyday ones, or explained where they come: the radius (how big the curve is), the transition curve (the easing into it), the cant (the outer rail raised), the gizmo (handles on the track), the control vectors (points that bend it), the grade line (how the line goes up and down), the terrain model (the real ground), the orthophoto (the aerial photo), the hectometre posts (every 100 m), W17 (how far a wagon may stand); - what only a designer needs is left out: the 6000 and 2000 m of the radius ladder, the compound curve, the hump, the kinds of include that can't be changed; - the buttons are named as the panels name them: Apply to the scenery, Template editor..., the tiles of the switch tool; - the Polish names of three lessons say what they are about ("Uchwyty na torze (gizmo)", "Wzniesienia i spadki", "Prawdziwy teren"). Their English titles stay, the lessons are found by them; - the warning of no ground under the cursor tells what happens to the track; - two captions of the drawings say what they show (the tracks inside a box, posts every 100 m), and in Polish the button of the top view is "Widok z góry (O)", without "ortogonalny". What each row tells of is the same as before. The msgid of the length typed while laying stays, the window of the keys (F1) uses it. * feat(editor): the semaphores and the warning discs chosen by what their descriptions say they show The descriptions of the signal templates can now say what a semaphore shows and what a disc repeats, and the editor reads it: - signal: {arms: 2, aspects: {Sr1: ..., Sr2: ..., Sr3: ..., Sz: ...}, repeats: {stop: ..., vmax: ..., "40": ...}} is kept with the template, the events named for each aspect - the palette shows a template with arms as a semaphore of its arms, with 1 arm / 2 arms and Sz picking the template of the same tile that has them - the signals of SRK take a semaphore whose aspects cover what the signal needs (Sr3 where a speed is reduced, Sz on the main signals), the fewest arms that do it, and say which one does when the placed one hasn't them or has more than it needs - the warning disc before a semaphore is one whose repeats cover stop, the highest speed and 40 km/h when the semaphore shows Sr3; SRK writes no events of the routes, so this only chooses and checks the disc - the linked signal (parameter 7) is read for the role link as well as text - signal_headers.py keeps the keys written by hand in a description (arms, aspects, repeats, the description and the parameters from 6 on) when it writes the guessed ones again - signaltemplates of the self test lists what the templates say and the heads made of them * feat(editor): the shaped discs swapped and set by hand, the warning discs checked by what they repeat The shaped shunting and stop discs (mk1, tzm, z1) are known to the signalling, but it doesn't place them by itself: - a shaped disc chosen in the palette for the shunting or the stop signals is placed by hand only; the signalling of a station takes the light template of the kind there, and says so when there is none - the template of a shunting or a stop signal standing can be swapped for a light or a shaped one of another mount as well (dwarf and mast, not gantry) - a signal whose description lists its aspects shows a button for each under its card: it sets the signal to that aspect in the editor, by the animations, the lights and the submodels its event sets off, the time standing still; nothing of it is saved. TAnimContainer::Finish takes an animation to its end at once, giving the submodel its angles, multi_event::branches tells the events set off when the condition isn't met From the review of the descriptions: - a shaped warning disc standing before a semaphore described is checked by the events it repeats: stop, the highest speed and 40 km/h of a second arm told apart; one which doesn't is offered the disc which does, and Fit swaps it - the disc offered is of the mount of the disc chosen, taken from the template even when it isn't described - 1 arm / 2 arms / Sz of the palette pick the template leaning as the chosen one and most like it by its name - a semaphore described with its arms but not its aspects has Sr1, Sr2 and with a second arm Sr3 - Fit leaves a semaphore having what it needs with its arms, for the events written by hand to the aspects of a second one; the messages of the fitting speak of what the signals need, not of their lights - signal_headers.py warns of a signal map written as a block, whose keys it can't keep * fix(editor): an aspect shown by hand doesn't name a vehicle that may be gone The Show button runs the events of the aspect outside the queue. run() writes the vehicle that set the event off last into the log, and nothing clears that pointer, so a train deleted since would have been read after it was freed. The queue sets the activator anew each time, so it is cleared before the run. * fix(editor): a disc not described is only offered the one that tells, a light stand-in of the mount of the shaped one - A shaped warning disc whose template doesn't say what it repeats may tell all its semaphore shows as well. It is no longer marked as not fitting: the disc described is offered as a hint, and Fit leaves it be. A disc whose template isn't among the scanned, its mount not known, is offered nothing rather than discs of any mount. - A shaped disc chosen for shunting or stop is stood in for by a light template of its own mount first, a dwarf for a dwarf. - The tooltip of the aspect buttons says the trains read the signal as its events set it last, in a run started from the editor too. - The Polish texts of the fitting speak of signals, not semaphores, since it takes the discs too. * refactor: the Sonar remarks on the switch blades taken care of - the big functions of the rails split into helpers with one job each: the carving, the laying and the planning of the rails, their crossings, the blades, the lofted spans of a segment, the profile of a rail measured piece by piece, the joining of the switches - the floating-point loop counters are while loops doing the same additions, so the samples come out where they did - C arrays are std::array, the two sides of the paths path_sides; the ends of a cut are two parts of one struct, ending and starting - the rail laid by a course of its own, not eleven parameters - the globals kept in functions, the nested ternaries taken apart, one declaration per statement, explicit captures, ranges algorithms, std::format, std::numbers, emplace_back, structured bindings - the region finds the sections around a point into a list the caller gives, so the search for the rails around a track shares no list with another thread - check_rails and create_track_rail_profile are const, the pool of the reused chunks can't be copied The geometry of every chunk of lk357 and td_fog, with the frogs on and off, comes out the same as before. * refactor: the Sonar remarks on the 3D sleepers taken care of - the big functions of the sleepers split into helpers with one job each: the clusters and the lines of timbers, the gaps under the rails, the models and their parts, the check of the layout, the drawing of the timbers in instanced batches - the tracks near a track found into a list of their own, the region searched into a list the caller keeps, not the one the region shares with the main thread; the callbacks are templates, not std::function - the layout of a cluster takes a span of its tracks - the globals kept in functions, the parts of a beam int constants, beam_overhang no longer hidden by a field of the same name - scoped_lock, jthread, contains, ranges algorithms, std::format, emplace_back, structured bindings, explicit captures, upper-case literal suffixes, one declaration per statement - the uniform buffer takes a span of bytes * fix(editor): the editor core builds with GCC again - kCrossoverStraights is constexpr, so the connection curve can take it into a constant expression; GCC refused a double that was only const there. - the track_hover alias inside editor_mode dropped: declared after hovered_track had already used the name, it changed what the name meant in the class (-Wchanges-meaning); the definitions name the shared track_hover. - included where the rail self-test uses std::memcpy, which MSVC reached through other headers. * refactor: the second round of Sonar remarks on the switch blades - the carve of a throwable part takes the cut before it only where there is one, as only that cut makes it throwable - the splitting of a grooved profile by the floor of its groove moved out of the rail layer into a class of its own, which is given the profile, the size of the rail, the texture of the plates and the side - the rail drawing is made by a const function - the triangles of an ear-clipped outline go in as the arrays they are, the search for a corner within an ear is an any_of, the loop pruning thin corners keeps the count it started with, as it stops at the first - the bytes of the blocks of a texture are taken off the file through its buffer, with no cast of their storage - the log of a carved part takes the tracks around it as a span - the joint length of a switch, a constant, isn't captured, and the directions at the ends of a crossroads are tested in one condition each * refactor: the Sonar remarks on the tutorial - the window of the tutorial in smaller pieces: the steps reached, the lesson followed and its clip, the clip or the sketch of a lesson, its keys and steps, the button under it and the buttons of the pages; the lessons are a table of their own, the button of each kind of lesson picked from a switch - a clip whose delays add up to nothing shows no frame instead of dividing by them - the frames of a clip are decoded by a function of their own, on a thread kept with them and joined once it's done, or as the editor closes, instead of a detached one - the sleepers of the signal sketch counted by a whole number, the texts of the sketches made by std::format, their points kept in std::array, the whole numbers turned into floats where it's meant * fix: the bugs and vulnerabilities Sonar found in the editor core - the loops stepping along a track, a curve or the view count their steps by a whole number and take the station as so many steps from the first, instead of adding a fraction up, which drifts - the self-test of the guard rails keeps the plan of the rails of the track against while it goes through them: the range of the loop was in a plan made for it and gone before the loop began - the generators of the self-tests and of a unit test are seeded on purpose, so a run can be repeated: marked for Sonar as such - the tool writing the descriptions of the templates takes the names out of its tables only where they stay in the data folder * fix: the loops of the signalling stepping by a whole number the places of the block signals along a line and the marks of the chainage under the plan of a station are counted by a whole number and taken as so many steps from the first, instead of adding a fraction up, which drifts; Sonar took the counters of floats for bugs * refactor: the checks of the signal heads and the signal sheet in smaller pieces the remarks Sonar made on the signal descriptions: the warning about a disc on the mount of a signal is worked out by a function of its own, the fit and the aspects of a head, the swap of a template and its aspects in the sheet of a signal are drawn by members of their own, the walk over the events of a signal is a free function instead of a std::function held by a lambda, and the description of an include is read a part at a time; the names of the kinds are kept in a std::array and looked up by the algorithms of ranges, a name is taken as a std::string_view where it is only compared, and the locals named event, which hid the enumerator, are renamed * style: a space after a comma in the join self-test * style: a space after the question mark in the terrain sketch * style: a space after the question mark in the status of the fitting * refactor: the last Sonar remarks on the small fixes the opening of a scenario catches the exception the scenery throws when it can't be read, not any runtime error; the vehicle moved between trainsets keeps its source by a reference to const; the messages of a track of an unknown type and of a tributary are raw string literals; the parser opens a file by a std::filesystem::path, and the log of a file it can't open still names its folder and its name * refactor: the crossings of a track found without casting its const away the radius of a node can be read off a const one: radius_() is const across the nodes, the ones of the tracks and the models marked override, and a const radius() gives the radius worked out already, or works it out anew without keeping it; the helpers finding the crossings of a track only read it and take it const, its own run of rails typed apart from the ones of the tracks it crosses, which the crossings found name; the triangles of a filled outline are pushed as named corners * refactor: the paths around a track sampled without casting its const away the sampling of the paths and the clusters of tracks laid together only read the tracks, so they take and keep them const: the path sampled points at a const track, the tracks near one are found from a const one by its const radius, and a cluster holds const tracks; the shared zones of the timbers no longer cast the const of their track away * fix(editor): the Sonar blocker remarks on the stack, no side effects in the operands of && and ||, no local named final (S912, S1669) Counting the leftover signals, the pieces of a station walk, the places with nothing beside a run and the joints and fouling points logged by the self-tests no longer counts inside a condition; the last span of a straight is named tail. The counts and what they log are the same. * revert(vehicle): an axle on a switch follows the switch as it is set, as before the stack The axle kept to the path it came on, so a switch thrown under a moving train no longer sent the rest of it onto the other branch, and coming from the frog end it trailed shaped blades only where the wheels reached them. That changed the running of every switch in every scenery, and the AI still scans its route by the switch as set. TrkFoll is as on master again, and the trailing point of the blades it used is gone. * revert(track): a path is told a straight by its first control vector alone again, as the sceneries are made for A plain track was drawn bent where its second control vector was off the chord though the first lay along it, and a path with a radius given was never straightened. Tracks of existing sceneries drawn straight before would have been drawn bent, with their length, cant and the models along them. TTrack::straightened is the rule of master, for plain tracks and the paths of switches. The editor keeps a bend dragged with the second control vector, or set by joining the tangents, by moving the first one 2.5 cm off the chord to the side of the bend, past the tolerance, so the track is drawn, saved and read back bent, by older builds too; the second one dragged back along the chord takes the first one back onto it. * feat(track): the switches joined directly to other switches at load told in the log A switch right after another one is joined to it as the sceneries load, where its end was left open before and vehicles came off the track there. Each switch joined so is logged with its place and the number of ends, and the whole number once, so a scenery can be checked for places that run differently now. * fix(editor): a bend kept by lengthening the first control vector, not turning it keep_bent moved the first control vector 2.5 cm sideways, which turned the start tangent: a kink of 0.29 deg on a 15 m track, flagged by the joints check, and against the fixed direction at a switch or a locked track. Now the vector keeps its direction and gets 2.5 cm longer than a third of the chord, which the simulator no longer takes for a straight. It is also applied after an end is moved or snapped, since a new chord or a snap onto a neighbour could bring the vector back within the tolerance. With the second vector back on the chord, the first goes back to a third of it. * fix(track): each switch joined directly to another one logged with both names join_switches counted ends, while one join links both switches, and only the first switch of a pair was named. It now returns the switches joined to, and the log names both of each joint and gives the number of joints. * fix(editor): a path drawn bent is kept bent through every edit, one drawn straight is left as it is The first control vector is made longer past the 2 cm tolerance only where the path was drawn bent before the edit, or where the edit itself sets the second vector: the end of the path moved, its first vector, its second one, a neighbour followed or its grade taken, the controls aligned at a joint, an end snapped. A path drawn straight keeps being straight when its ends move, and the paths of a track that the edit doesn't bend aren't changed. Moving the second vector back along the chord takes the first one back to a third of the chord where it was made longer here. * fix(app): a scenery that can't be opened takes the game back to the launcher whatever the file system throws Catches std::runtime_error again, as master did: invalid_scenery_exception is one of them, and so is what the file system throws while the scenery is opened. * fix(track): the beams worked out in the background don't read the ends a switch is set to The ballast a switch trackbed takes is asked of the tracks joined to its main path, as the trackbed is made at the load, not of the ends the switch is set to now, which change as it's thrown while the thread runs. What the thread reads with no lock against the main thread is written down where it runs, with the two things driving can change: a switch thrown and a turntable turned. * perf(render): the cut faces of a track drawn with nothing put on the heap, a track with none passed over at once * chore(track): the switch drawing the cut faces in the unrolled material read only in the builds with the self-tests * docs(track): the blades flag said to be switched on, and what frogs in eu07.ini changes of it * fix(editor): a response over 64 MB is refused, curl kept to http and https, the address read as UTF-8 The body of a map or of a service the user typed is read into memory up to 64 MB and fails above that, with WinHTTP and with curl. curl follows at most 10 redirects and only to http or https. WinHTTP gets the address widened from UTF-8, so a pasted one with letters past ASCII isn't turned into garbage. * fix(editor): only the orthophoto an older editor kept is deleted from the settings folder, not all its cache The geoportal folder of the old cache is removed, and the cache folder itself only where nothing else is left in it. * fix(editor): the square metre of the outlined area written as its UTF-8 bytes, shown right where /utf-8 doesn't reach * docs(track): why the velocity read for a switch is put back after its segments are made * fix(track): the blade tips and the open ends of a track take the dark of the rail, not the colour of a worn tread No wheel runs over them, so their cut faces aren't drawn as worn: the beige the matte material gives a worn face is left to the cut faces of the frogs. * fix(editor): a neighbour followed or given its grade is bent only where its second vector really changed follow() and follow_grade() write the second vector of a track joined at its end back as it was when the joint didn't turn or keep its grade; a track the simulator draws straight with that vector off the chord was made bent then, though the edit never touched it. Its first vector is lengthened now only where the path was drawn bent or the second vector took another direction or grade. * fix(track): the open ends of a track laid with cuts take the dark of the rail too The rails a frog or a crossing cuts are laid piece by piece; the caps of their pieces at the open ends of the track were drawn worn with the cuts of the frogs. They aren't worn now, as the open ends of the other tracks. * fix(editor): a neighbour drawn straight is bent only where the edit took its second vector off the chord follow_grade() sets the height of the second vector anew on every graded joint, a fraction of a millimetre off the height the scenery has, so a change of the vector bent a track whose second vector stood off the chord sideways already, though the simulator draws it straight. follow() and follow_grade() keep a path drawn straight bent now only where its second vector lay along the chord before the edit and stands off it after; a path drawn bent is kept bent as before. How far the vector stands off the chord is measured in one place, keep_bent() uses it too. * docs(editor): the comment of keep_bent above keep_bent again, not above the measure of the chord * Editor: signal reads kept by the signal, level crossing discs, signals out of the gauge, indicators, the signalling tools split (#307) * fix(editor): the read of a signal stays by it as its track is split, on a switch and when it is moved, and a level crossing disc is placed The trains find a signal by its read, a passive event in a list of the track, and measure the way to the cell it reads along three tracks further at most. The editor let the read drift away from the signal, or put it where trains of another path read it. - A track split in two: a read the trains scan for (a passive event) goes to the piece by the point it reads, whatever its list; before, those of the runs towards the end stayed on the first piece. Five splits left the reads of A, B, C and J on the first piece while the signals stood on the sixth, out of the reach of the trains. The reads of signals placed since the scenery was opened, not bound to an event yet, go to the piece by their signal the same way. - A signal moved off its track jumped back to that track's end once the track was changed: the track had taken it up as its object and measured it again along itself. A moved signal is let go by the track it stood by, and an object of a single point moved off the side of its track no longer follows it. - A switch reads its events to the trains of both its paths. A signal past the frog of a path, where the axes are a gauge apart, is passed by the trains of that path only, so its read goes to the track joined to the far end of the path, in the list of the trains running from the switch onto it or the other way. Before the frog it stays on the switch. Moving the signal across the frog takes the read between the two. - A signal by a switch on the side of its other path stood on that path, in the way of its trains (0.45 m from its axis); it is refused there, placed or moved, with the reason. - The kind crossing of the descriptions (tsosp, tsospn) is known: the level crossing disc is listed in the palette and placed with its read. Checked in the editor on a hidden desktop: five splits of a track with bound and fresh reads, a signal moved to another track and the old one raised, signals placed before and past the frog of a switch on both paths, turned and moved across the frog, saved and opened again with the reads bound, the tracks raised, shifted and bent with the signals following. Unit tests pass. * fix(editor): a split keeps reads far off the path and bound objects up to 30 m by their pieces A read the trains scan for moves to the piece by the point it reads only from event1 and event2, only when it isn't ignored and only when that point is within 50 m of one of the pieces; a read at the station building stays in its list. An object bound by hand keeps its binding as its path moves up to 30 m from it, an adopted one up to 12 m as before. * feat(editor): the tracks that read a signal are drawn and can be picked, flipped or dropped The selected signal shows each read of its _sem_info as a thick band over the reading track, arrows in the way the read is scanned, a line from the foot of the signal and a plate with the list and the track; the hovered one shows them thinner and placing or moving a signal shows where it will be read. The panel lists the reads: each can be turned the other way or removed, "Pick the path" takes a click on a track (with Shift one read more or less) and "By the path it stands by" puts back the read the signal gets when it is placed. Each change is one step of the undo. The self-test gets signalread, signalreadflip, signalreaddrop and signalreaddefault, and the probe lists every read of a signal. * fix(editor): a moved or turned signal keeps the reads picked by hand, and a read set again isn't an undo step Moving a signal, taking it across the track or turning it put back only the read by the track it stands by and dropped the others: those stay on their tracks now, on the other list when the signal is turned. Setting the reads the signal has already says so and adds no step to the undo. Picking a reading track disarms the template, so a click after Esc doesn't place a signal, and the signals are listed again after any change of the history, also once it is full. * feat(editor): a signal is placed out of the gauge of the tracks around it As a signal is placed, moved, taken across or turned, its models are measured against the gauge chosen in the Gauge window along every path near it. One that enters it is taken sideways, away from the axis of the track whose gauge it enters, as deep as it went in and 3 cm more, in the same step of the undo; between two tracks too close for it, it stays where it was put and the status tells which gauge it enters and how deep. A gantry is only measured. The panel of the selected signal tells when it stands in the gauge, with a button to move it out, and the view marks the deepest place. The gauge tool measures any models against the paths around them for it. The self-test places a signal at a given offset and its probe tells the gauge. * fix(editor): a moved signal leaves only the read of the track it stood by, and the gauge is checked on its level The reads a moved signal keeps were all but the first one listed, which is the first track of the scenery having it, not the one the signal stood by: a read picked by hand could go and the track it left could keep it. It is the read of the track it stood by that goes with it now, and turned, eventall1 and eventall2 swap as well. A track more than 2 m above or below the foot doesn't push the signal aside, the status tells the real distance it went, the gauge is measured again when the signal follows a dragged track, and the marker in the view shows only what is up to date. * feat(editor): indicators put on a signal from the panel, they move and go with it The indicators of scenery/pkp/wskazniki described as "category: indicator" are offered under the selected signal, grouped by their sign. One is put in as an include named after the signal, on the srk layer: - a lit one (place: head) under the lowest lamp of the signal, 0.73 m below it and 5 cm ahead of the mast, each next one 0.45 m lower; a dwarf signal is refused, it has no mast for one; - a plate (place: foot) at the foot of the signal, its model has its place by the mast built in. The panel lists the indicators standing by the signal with a Remove button. They are found as the includes whose first parameter is the signal's name, within 1 m of it in plan. When the signal is flipped, turned or moved, they keep their place in its frame, in the same undo step; deleting the signal deletes them too. If the signal and the indicator both define an event, the status says so, since the scenery keeps only one of them. The self-test gets signalindicator and signalindicatordrop, and its signalprobe gives each indicator's height and the height of the lowest lamp. * feat(tools): indicator descriptions and the indicators taken out of the signal templates indicator_headers.py writes //$e descriptions into the LED indicators of scenery/pkp/wskazniki (W19, W20, W21, W24, W26) with the events each shows. It also makes the indicators that were so far only built into the signal templates: - W1 of the warning discs, new, old and with the light strip; - W1 and W18 (new and old) of the block signals; - the I, II and III plates of the repeaters. The plates fixed flat to the mast are moved 4 cm ahead. Their back is 5 cm from the mast's axis, while the mast is 6.1 cm thick and its clamp under them 8.3 cm, so the mast went through the plate, in the templates too. * fix(editor): a signal turned or moved by the gizmo is read and kept out of the gauge, its indicators go with it everywhere The gizmo of an include only rewrote the numbers of a signal. Its read stayed on the event it had, even when the signal was turned to the trains of the other direction. Its indicators stayed behind, its height could be dragged off the ground, and the gauge wasn't checked. Now: - the gizmo moves a signal in the plan only, at the height it has; - while it is dragged, its indicators keep their place by it; - once it is let go, the drag is made again as a move of the signal tool, one step of the history: the read goes to the event of the trains it faces on the path it stands by, and it is taken out of the gauge; - dropped away from every track, it goes back where it stood. The indicators of a signal are found in the scenery now, not in the list the signal tool keeps up only while it is open: - deleted from another tab, the signal takes them with it; - a signal renamed in the node properties gives its new name to them in the same step of the history; - in the station and line batches, a renamed signal renames them, and a removed one removes them; - the binding of objects to tracks puts them on the path reading their signal, not on the one nearest to them, and a signal moved by hand lets go of them too. Also: - a signal on a gantry takes no indicator from the list; - an indicator a signal has already isn't put on it twice; - the signals and their indicators are found in one pass over the includes, the indicators by the name of their signal; - a step of the history with tracks is always one of their edit, so they are taken back with the includes. The self-test gets signalgizmo, which turns and moves a signal as the gizmo does. * fix(tools): indicator_headers.py keeps the files it replaces, writes beside the data on request - An indicator it made, found changed, is put into a tar in editor_backup before it's written again. - --sidecar writes the descriptions of the lit indicators into editor/templates, as the other header scripts do, the files of the game left alone. - The indicators it makes are copies: the signal templates keep their own, and the docstring and the files say so. * fix(editor): a signal moved by the gizmo by another track is read by it, the templates known without the signal tool - At the end of a gizmo move the nearest track takes the signal when it is nearer than its own by more than 0.5 m; a track it was dropped onto, within 1.2 m of its axis, doesn't, so a signal only turned between two tracks or dropped onto one in a switch keeps its own. - The signal templates and indicators are looked for when a signal is renamed or its gizmo shown, so its indicators follow without the signal tool opened first. - A drop refused puts the gizmo and the node properties back where the signal stands. - The indicators follow only once the gizmo made its step, and the ones not changed are left alone: grabbed and let go it changes nothing. * fix(editor): a signal dropped by the gizmo onto a track keeps its own, the gizmo doesn't wait for the template scan - When the nearest path to the drop is within 1.2 m of its axis, the signal keeps its own track, instead of only that path being left out: dropped onto a middle track it no longer goes to the track beyond it. - The gizmo starts the signal template scan without waiting for it, so a rescan with a signal selected doesn't stop the editor; renaming a signal still waits. * feat(editor): the signalling split into Signals, Station, Station signals and Line block The one Signalling tool held the signals placed by hand, the whole wizard of a station and its checks; each is now a tool of its own in the toolbar: - Signals (I): the palette, a signal placed by a track, dragged along it, selected; a click on a switch no longer opens a station. - Station: LMB on a switch lays the station out; its name, code, line, km, speed and braking distance, the numbers of the switches, the track circuits, the number of the selected track, the list of the switches. - Station signals: the signals of the whole station placed at once, the template of each of their kinds (main, shunt) chosen in a table, and below what the signalling lacks: the repairs, the SHP resonators, the track lengths, the signal heads. - Line block: the block of each line, the block boundaries drawn by hand, the line signals, the templates of the block signals and warning discs. The station tools share the open station and its schematic; Station signals and Line block show what the Station tool set for it, the line and the km in red where the line block needs them. The template table replaces the palette in the station tools, so choosing a template there no longer arms placing. Two icons drawn for the new tools, in editor_icons.py too; the png is drawn by the same shapes, Pillow wasn't at hand. The tracktab self-test takes a tool by its name, and srkopen shows the Station tool. * feat(editor): a signal shows its distance from the track axis and to the switch ahead, and goes to 50, 100 m... from it - editor/editorTrackTrace: the track followed the way a train runs, shared by the W17 markers and the signals. The fouling point of a switch (where the axes of its tracks are 3.5 m apart) moved here… * fix: a failed start says why and ends with an error code; a small crash dump by default (#425) * fix: a failed start says why in the log and ends with an error code When the window could not be made, the log only said "Bad init: failed to create glfw window", without the reason glfw knows (no OpenGL driver, no pixel format that fits, no EGL). Sometimes it did not even say that: the log thread writes every 50 ms, and main() ended the process with std::_Exit(0) without stopping it, so a start that failed within that time left a log that ends at "// startup". - glfw's errors go to the log and errors.txt through glfwSetErrorCallback, set before glfwInit(); each distinct message once. - after a failed start (or an exception caught in main) the log thread is stopped and waited for, as the test runs already do, so nothing logged last is lost. - a failed start ends with exit code 1 instead of 0, so the starter can tell it from a closing. A start that worked ends as before. * fix: glfw's errors told during the start only, a closed crash dialog is no failed start After review of the previous commit: - the glfw error callback is taken off at the end of init(). Once the simulator runs, glfw would only repeat what the platform can't do (glfwSetCursorPos on Wayland, on every mouse-look) or what a scenery asks for in vain (launcher key codes below GLFW_KEY_SPACE, checked on every update), which would put new lines in errors.txt of existing sceneries and cost a format and a lock per call. - closing the crash-report window ends the simulator as before, but init() now returns 1 for it (above 0: closed by the player), and only a result below 0 gives exit code 1. - a start that throws from init() (bad_alloc, or a runtime_error on Windows) ends with exit code 1 too; an exception after a start that worked ends with 0 as before. * feat: a small crash dump by default, the full one with "crashdump.full yes" The dump written by the crash handler (Windows, WITHDUMPGEN) held all the memory of the simulator (MiniDumpWithFullMemory), so it was as large as the memory the simulator took: gigabytes on a large scenery, written to the game folder at the moment of the crash, on machines with 8 GB of RAM too. By default it now holds the stacks with the memory they point to, the threads, the modules, the handles, the memory map and the modules' data segments (MiniDumpWithDataSegs in place of MiniDumpWithFullMemory, the rest of the flags as before). The globals, Global among them, stay readable. "crashdump.full yes" in eu07.ini writes the full dump as before. Measured on td.scn with a ghostview camera (1.2 GB committed): the small dump 44 MB in 2 s, the full one 1.6 GB in 19 s. The key is new and optional: eu07.ini files without it read as before, and the setting is listed in the log at start. * fix: the small crash dump keeps the process and thread blocks MiniDumpWithProcessThreadData adds the PEB and the TEBs, a few KB: the command line (the scenery and the vehicle), the environment and the last error of each thread, which the small dump otherwise lacks, since the heap behind Global's longer strings is not in it. * fix: an exception that ends the simulator says what it was in the log After review of #425: - the exceptions main() catches are logged ("Critical error: ..."): on Windows the runtime_error that only showed a message box, and on the other systems any std::exception, which used to end the simulator through std::terminate with no word in the log. On Windows the others are still left to CrashHandler, whose dump shows where they were thrown. - every exception caught there ends with exit code 1, in the start or later, as a crash; it used to be 0 when caught, the abort code when not. - closing the crash-report window logs "Crash report window closed, closing" instead of the error "Failed to run crash gui!", which stays for a result below 0. * feat: the stack of a crash on Linux in the log and on the standard error On Linux no dump is written (the crash handler is Windows only, crashpad is off), so a crash left a log that just stopped. A handler of SIGSEGV, SIGBUS, SIGFPE, SIGILL and SIGABRT (installed at the start of main) now writes, with write() only: Crash: signal 11 (SIGSEGV) at address 0x... Version: EU07 (cmake), (...) Stack (addr2line -f -C -e ): to the end of the log file (its whole path, set when the log opens it) and to the standard error, which StarterNG shows first. The Linux builds carry their symbols (GENERATE_PDB adds -g, nothing strips them), so addr2line on the eu07 file of the same version gives the files and lines. Then the signal ends the process as before (SA_RESETHAND, raise): the same exit status, and a core dump where the system makes one. The handler runs on an alternate stack, so an overflow of the main thread's stack is reported too; backtrace() is warmed up at install so it doesn't allocate in the handler, and alarm(5) ends a handler that hangs (a crash in the allocator or the loader). WAMR is built without its hardware bound checks, so it installs no SIGSEGV handler of its own. Elsewhere crash_signals does nothing. A unit test (Linux only) crashes a child process and checks the report on its standard error and in the log, and that the child still ended by SIGSEGV. * fix: the crash report can't be cut by a second crash signal or end with SIGALRM After review: - the five crash signals are blocked while a report is written, so a second one waits rather than starting a second report in its middle (a fault that comes while blocked still ends the process). - a report that hangs past alarm(5) ends the process by the signal of the crash, not by SIGALRM: a SIGALRM handler, set only in the crash handler, raises the crash signal and unblocks it. - the child of the unit test calls alarm(10) first, so a child stuck before the crash can't hang the build. --------- Co-authored-by: maj00r * feat(track): unevenness waves shaped by the track spectra of FRA and ORE B176 (#426) * feat(track): unevenness waves shaped by the track spectra of FRA and ORE B176 The waves were 5-42 m sideways and 8-83 m vertically, with the long ones cut down, so a short wavelength carried a large share and the ride and the rails looked busy. They are now 7-90 m sideways and 8-110 m vertically, about the bands D1-D3 of EN 13848, each wave standing for a band of the spectrum S ~ Wc^2 / (W^2 (W^2 + Wc^2)), Wc = 0.8245 rad/m, the shape the FRA and the ORE B176 (German) spectra share: the longer a wave, the higher it is. The "uneven" value keeps its meaning, the peak deviation of a rail on a 10 m chord as PLK Id-14 measures it, so the values in sceneries stay as they are. Since the chord sees the long waves less, the amplitudes are calibrated again, and apart for the vertical and the sideways waves: stray_per_mm becomes stray_up_per_mm 0.00229 and stray_side_per_mm 0.0031, and cross_share 0.35. A track at "uneven 18" measures 18 mm vertically, 17 sideways, 15 of twist, +-10 of gauge, 21 of cross level and J 5.7 against the Id-14 limits for 80 km/h. A rail now goes up to about 5 cm off its design over the long waves, so the bound of the test goes from 40 to 60 mm; the short waves the cab shakes on are smaller, the sideways bend under the axles about 30% less. Every scenery with unevenness looks and rides differently after this. No release has unevenness yet. The grading tool follows the vertical waves; on Baltyk the pantograph keeps within 0.6 cm of the wire up to the product 1150 of the vertical value and the speed (925 before). * test(track): bound the sideways offset of an uneven track off its design The longer waves move the track about 4.5 cm sideways off its design at "uneven 18" (2 cm before), and nothing checked or stated it. The Id-14 test now bounds the peak sideways offset of the middle of the track below 5 cm, next to the vertical one, so a later change of the shares can't double it unnoticed. The doc gives the figure, and names platform edges and level crossing panels among what a rail moves away from. --------- Co-authored-by: maj00r * feat(editor): ~ shows or hides the orthophoto, Ctrl+~ downloads what the camera sees first; the speed of the camera in the View menu (#312) * feat(editor): ~ shows or hides the orthophoto, Ctrl+~ downloads what the camera sees first; the speed of the camera in the View menu ~ (the key left of 1) turns the orthophoto on and off. Ctrl+~ finds what of the ground the camera sees (rays through a grid over the screen down to the level of the ground under the camera, or as far as 2.5 km where they don't come down to it) and puts those tiles at the front of the queue of the downloads, the ones which failed tried again at once; the status line tells how many. Tab is not used, the laying and the switches have it. View > Camera speed: the speed of the free camera of the editor (x0.05 to x10, 1 as it was), how many times faster Ctrl makes it (1 to 30, 30 as it was), and in the top view as fast as the view is zoomed, so the map crosses the screen at the same pace zoomed in or out. Kept in the settings of the editor; the camera of the cab and of the free fly outside the editor unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * fix(editor): Ctrl+~ in the top view, over a scenery with no terrain under the camera and with the orthophoto off; "As it was" without the speed going with the zoom In the top view the box is the view itself, its corners on the ground. The ground under the camera is the terrain, else the scenery, else the rays go as far as the reach. The tile of the camera is taken anew by hurry(), it isn't followed while the layer is off. The top view is as fast zoomed in as out by default, as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * fix(editor): the corners of the top view on the ground put where the camera is (the view matrix is camera-relative) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * i18n(editor): Polish for the orthophoto keys and the camera speed, on top of the master's own translations Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * fix(editor): Ctrl+~ asks only for the tiles update() would ask for; the tooltip of "Track colours" back in its place After the reviews of #312: - hurry() skips the tiles outside the download area set and marks the ones outside the area the service covers as empty, as update() does, so Ctrl+~ no longer queues downloads update() drops at once (and the workers took anyway, into the disk cache, against the area set), nor requests the service can't answer. - A blank tile hurried takes the standard image first, as in update(); first_level() and outside_area() are shared by both loops, and the body of the loop of hurry() is hurry_tile(). - orthophoto_hurry() takes the level of the terrain only when it's below the camera, as the branch of the scenery already did: a camera under the terrain (a tunnel, under the heightmap) no longer flips the box of the view behind it. - The "Camera speed" menu goes after the tooltip of "Track colours", which it had taken. - #include once in editorOrthophoto.hpp. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QRgQ1K1Qu7TCsa74zsNURd --------- Co-authored-by: Claude * fix: whole-number bounds of Random() give a real number again (#416) * fix: whole-number bounds of Random() give a real number again ee3af0bf (#99, in 26.05.2) renamed RandomInt to an overload, Random(int, int). The calls with whole-number bounds that expect a real number in between took the overload and draw whole numbers since: - wheel flats given with P0 happen to 1 vehicle in 101 (before: none), the random part of a flat is a whole number of millimetres; - the chance of truck hunting is h/101 instead of h/100; - the wind starts with a whole azimuth, speed and rates of change, and its direction changes in whole degrees per second; - the tachometer below 5 km/h jumps to whole numbers. The whole-number draw is RandomInt again, keeping the shared engine and the swap of inverted bounds; the loading screen's trivia use it. Those calls take the real Random() again, as up to 26.05.1. * RandomInt: the comment says what it draws and why it has a name of its own The comment put the bug on the overloading. It was in the calls that pass whole-number bounds and expect a real number; the separate name keeps them on Random(double, double). * fix: RandomInt draws from the local engine, as up to 26.05.1 from one of its own From the review of #416: ee3af0bf moved RandomInt from an engine of its own (std::mt19937 seeded by std::random_device) to Global.random_engine, the engine of the run's seed, and only the name was taken back here. Its one caller draws the trivia of the loading screen, in init_modes, before a network client gets the seed of the session in server_hello: the server's engine was then one draw ahead of the client's, and with a fixed randomseed the trivia was the same on every start. It is drawn from Global.local_random_engine now, the engine of what one machine shows, seeded from a true random source in init_modes before the loader is made. The test of the same seed checks the shared engine with Random() and the local one with RandomInt(); a new test checks that RandomInt() doesn't move the engine of the run's seed. --------- Co-authored-by: maj00r * fix(editor): the orthophoto only on the chunks of the heightmap terrain in memory, and laid onto the ground again once it comes (#417) * fix(editor): the orthophoto only on the chunks of the heightmap terrain in memory, and laid onto the ground again once it comes Right after the editor started, the tiles of the orthophoto came from the disk cache at once and were fitted to the ground before the chunks of the heightmap terrain had come (on IRT the orthophoto was on at 24.5 s, the first chunk came at 24.5 s, the last one at 85 s). A tile with no ground under it, and none beside, stayed flat at the height of the layer (0 m, some 230 m under IRT); one partly over the ground had its holes filled from the points beside. Neither was fitted again when the ground came: only the guessed tiles were, by their middle and corners alone, and a tile with no chunk under it at all never got any. The overlay, drawn over everything, then slid with the camera (WASD, turning) instead of lying on the ground. Turning the orthophoto off and on hid it: by then the terrain was in and the tiles took their heights from it or from the edges of the tiles beside. - With the heightmap terrain (the terrain streamer active), a tile of the orthophoto, of the WMS layers and of Ctrl+~ is asked for and shown only where its chunks are in memory (terrain_streamer::ground_under): it waits while one is still to come, and where no chunk is nor will be there's no imagery at all. A scenery without the heightmap terrain is as before. - A tile remembers the points of its grid the ground didn't answer and is fitted again once the ground comes under any of them (every second point and the edges), not only the guessed tiles. No asset changes. Co-Authored-By: Claude Opus 5.5 * fix(editor): the orthophoto waits only for the chunks that will come at this distance, and lies on the other ground or the guess elsewhere After the reviews of maj00r and jerrrrycho on #417: - A tile is no longer dropped where no chunk of the heightmap terrain is nor will be. There it lies on whatever ground there is (terrain models) or on the NMT guess, as on master; a scenery with a few chunks, or with chunks removed, keeps its imagery around them. - A chunk counts as still to come only while it's being loaded or lies within the circle the streamer walks around the camera. The corners of the imagery in the 3D view, beyond that circle, no longer wait for chunks that won't load there: they lie on the guess and are sampled again when the camera comes near and the chunk loads. - terrain_streamer::ground_under() (true / false / empty) became ground_coming() (bool), the cover source of the orthophoto the coming source, and on_ground() waits_for_ground(), which only holds back a new tile. - In the scene (in_scene), the points a steep triangle leaves without a height but the heightmap terrain answers aren't kept as unanswered, so the tile isn't sampled again on every chunk that comes. The holes are counted from the heights again, as on master. --------- Co-authored-by: Claude Opus 5.5 * fix(editor): the closing doesn't wait for a geoportal service that doesn't answer (#432) * fix(editor): the closing doesn't wait for a geoportal service that doesn't answer When geoportal.gov.pl took the connection and never answered, the editor's closing stood still for tens of seconds and was killed: the WinHTTP client was synchronous and looked at the stop only between the reads of a body, so a request waiting for the answer held the closing for the timeouts (up to 20 s for the answer, a few tries a square), and the map of the place-picker downloaded with no stop at all, its std::async future waited for to the end. On Windows the client now uses WinHTTP asynchronously: each step is waited for while the stop is looked at every 50 ms, and a stop closes the request at once. The timeouts, the user agent, the size limit, the errors and the body of a response with an error status stay as they were. The map of the place-picker is given up when it goes. libcurl looked at the stop during the whole transfer already. The unit tests run the client against a local server that never answers (given up within 0.4 s of the stop), one with a body of 100 kB and one with an error status. * fix(editor): the capabilities of a WMS service being added don't hold the closing either The reading of the layers of a WMS service the user adds ran on a std::async future of the editor with no stop: closing the editor while such a service didn't answer waited for its three tries. The reading is given up when the editor goes, as the other downloads now are, and editor_http_get, left with no callers, goes. The unit test's silent server no longer waits for the client to close its connection, and the requests to the local server are skipped when the environment names a proxy, which couldn't reach it. * fix(editor): the stop of the WMS reading outlives the future waiting for it The flag was declared after the future of the reading, so it was destroyed first while the future's destructor still waited for the task reading it. --------- Co-authored-by: maj00r * revert(environment): the turbidity of the sky as it was before #227 (#410) #227 (842b7688) raised the turbidity of the sky dome for most cloud covers (3 -> 4 for a clear sky, 5 -> 6 at 0.41-0.60, one more from 0.61 up to 0.90). In the Preetham model a higher turbidity darkens the sky a lot once the sun is below the horizon: with a cover of 0.47 the zenith is about a third darker 1.4 degrees below it and half as bright 3 degrees below, the stars come out right after the sunset and the ambient light taken from the sky dome drops with it. Players report the dusk as too dark since the update. The values are put back as they were before #227, in the turbidity_of() that #323 made of the old chain of conditionals. A clear sky gets the turbidity 3 again, which #227 said breaks the model at night. Co-authored-by: maj00r * fix(render): the free camera blurs with its own movement, the grass racing under it no longer strobes in rings (#441) The motion blur took the movement of the vehicle the camera sits in and nothing else, so in freefly (and the debug camera) the world got no blur from the camera at all. Low over grass the texture under the camera then moved tens of pixels a frame and strobed: rings around the camera, at the distances its pattern repeats, stronger with shift and ctrl, gone above about 20 m, worst on a 165 Hz screen. * the camera with no vehicle of its own blurs the world with its movement since the frame before, as a vehicle does with get_future_movement(); a jump of 50 m or more (a camera preset) is no movement * that movement is held to half a metre a frame: the blur takes the scene where the camera will be, and a camera faster than that passes the ground at the bottom of the screen within a frame, where its motion turned over into a bright band. with the shutter of the blur it still smears metres * the blur shader skips samples off the picture instead of reading its edge row again and again * fix(ai): an uphill start keeps the power on until the train brake is off (#396) * fix(ai): an uphill start keeps the power on until the train brake is off The uphill start of #265 ended as soon as the power held the train (or the head of the train moved back 0.5 km/h). From then on the brake still on in the wagons made Ready false, the power went off, the train rolled back, was braked again and the start began anew; only the cylinders falling below 0.8 bar let the train get away. - Once the power holds the train, the start goes on while the train brake is released: Ready holds, the power stays on, bounded to 1.5 x the grade force. It ends when the consist is released (the same test as Ready, without the hold) or after 60 s. - A start is given up for rolling back on the mass-weighted speed of the consist, not on the speed of the locomotive, which runs back into the slack of the train held by its brake. - A train slipping back uphill is not released by the rule for a train to go on. * fix(ai): an uphill start begins only with the whole train at a stand * fix(ai): an uphill start applies the train brake further while it doesn't hold the train without the locomotive brake * fix(ai): the speed and the tractive force of an uphill start in the direction of travel also from cab 2 * fix(ai): an uphill start tops up the train brake a full application time a step, at most to full service, and keeps the power between 1.1 and 1.5 times the grade force while the brake releases * fix(ai): an uphill start no longer takes a notch back in the release phase: the notch below doesn't hold the train * refactor(ai): the train brake top-up of an uphill start in uphill_start::brake_top_up(), with unit tests * fix(ai): a standing train starts only with its brakes charged, held on the locomotive brake while it charges (#444) * fix(ai): a standing train starts only with its brakes charged, held on the locomotive brake while it charges Prepared from cold, the AI filled the brake pipe at once with the locomotive brake off: the distributors released while the auxiliary reservoirs were still empty, so the train had no air to brake with, and on a gradient it rolled as it released. The train counted as ready as soon as it was released. A train placed cold with its pipe below the lock of the FV4a driver's brake valve (2.75 bar) wasn't unlocked until the order to go, and went on what its reservoirs got meanwhile (TMS77185 in linia_107_objazdy: 40 minutes at 1.2-1.9 bar, the last wagon at 4.3 bar at the start). - Standing, PrepareEngine() applies the locomotive brake first, then fills the pipe. Where the locomotive brake alone doesn't hold the train (1.1 x the grade force), the train brake goes to the first service position instead, so the reservoirs charge with the train held. Multiple units with the electro-pneumatic brake are released as before. - Standing to charge, the AI unlocks the pipe as it does to go (the releaser, or the unlock button). A handle which has to be moved to unlock is left where the light application holds the train. - A train is ready only once the pipe and the auxiliary reservoir of every vehicle with a working brake are within 0.5 bar of the working pressure (4.5 of 5.0: the last wagon of a long train stays at about 4.6-4.7 from what leaks along the pipe), with the pipe fed at the head of the train. Brakes cut out don't count. - The locomotive brake comes off only once the train is charged, also against DecBrakeEIM(), which for a vehicle without the integrated handle releases it too; an uphill start begins only then. - A human driver gets the same wait as a hint: "Wait for the train brakes to charge" (driver_hint::waitbrakecharge), and the hint to release the brakes waits with it once the train brake is off (brake_charge::release_waits()). The train brake may still come off: released, it fills the pipe. - A charge that rises by less than 0.02 bar in 60 s lets the train go all the same, with a line in the log. The time counts only while there is air to charge with (the engine prepared, the main reservoir above what the pipe charges to, the pipe fed at the head): a train with its compressor not running yet or a locked pipe is waited out. Once let go, a train stays so until it is to stand again: otherwise the pipe refilling behind the release held it at a crawl (et22-1075 with 36 wagons, baltyk_interregio). - The check applies to the pneumatic brake only, to the first start of a train that hasn't run (above 1 km/h) since it was placed, and to a start with the pipe below 2.5 bar (near empty, after an emergency application). A start after an ordinary stop, a service stop (3.0-3.5 bar), a change of direction or a shunting move isn't held: waiting there only delayed the train, and the scenery set the routes of the others later. - The release of the train brake in PrepareEngine() had a stray semicolon after its condition; the condition applies again in motion. - Unit tests for the charge check (brake_charge::charged(), locomotive_brake_holds(), release_waits()). Run on all 174 shipped sceneries (20 minutes each, against master): no train stuck that moved on master, 466 timetable departures compared, 459 within 15 s, mean -1.2 s. Waits for the charge: median 4 s, 90% 39 s, longest 106 s (a heavy freight train charged from 2.2 bar). * test(ai): the brake charge test counts its looks in whole numbers, not in a floating-point time SonarCloud took the loop of the test of a train with nothing to charge with yet for a bug (cpp:S2193, a counter of type double). The same 120 looks, 5 s apart. * fix(ai): the light application that holds a charging train stays on, and an empty pipe is no charge Runs of a cold train on a gradient (P33000 at Lupkow in linia_107_objazdy, 13-16 per mille, with an SM42 and 32 wagons, 1556 t) showed three faults of the charged-brakes start: - The locomotive brake was taken to hold the train with the force of its brake blocks alone, 1031 kN for an ST43: several times what its wheels pass on to the rails. It is limited to a quarter of the locomotive's weight (brake_charge::adhesion), so a light locomotive with a heavy train gets the light application of the train brake. - That application was taken off again as soon as the order to go came, by the rule that puts the handle back to running with the main reservoir below 5 bar, and by DecBrake(). The train then stood on the locomotive brake that doesn't hold it, and moved as its wagons let go (to 0.3 km/h). It stays on until the train is charged (brake_charge::holds_application()). - With the train brake applied the train counted as charged to what the head of the pipe has, which is nothing with the pipe empty: charged at 0.02 bar the moment the brake was applied. The pipe at the head counts no lower than a full service application leaves (brake_charge::reference()). The SM42 with the 32 wagons now stands still while it charges and starts without rolling back, 2 min 30 s after it was prepared (4 min 40 s before, with a start that rolled back at 0.3 km/h). An ST43 with 33 wagons and a 754 with 8 coaches there are as before, their locomotive brake holds them. In eight of the sceneries run before (l053_poranek, calkowo_v2_cementa, calkowo_v2_ctl-wegiela, calkowo_v2_osoba_jar_poranek, calkowo_retro_zima, linia61_towarowy2, l053-sluzba-brutto-posp, baltyk_interregio) the 60 timetable departures compared are the same, within 15 s, mean 0.0 s. Unit tests for the two new decisions. * fix(ai): the locomotive brake counted of the occupied vehicle alone locomotive_brake_force() added the brake of every powered vehicle of the train. The locomotive brake handle acts on the occupied vehicle only (LocalBrakePosA is set on mvOccupied and passed to no other vehicle), so a second locomotive, in multiple control or hauled dead, made the brake count as holding a train it doesn't hold, and the train brake was released on a gradient with the leading locomotive alone holding. The estimate of one vehicle is brake_charge::locomotive_brake_force(), with a test. brakecharge.h named TController::control_brake_charge(), which doesn't exist: the logic is in determine_consist_state(). * fix(sky): the legacy renderer gets the sky, ambient and fog of 26.05 again (#415) * fix(sky): the legacy renderer gets the sky, ambient and fog of 26.05 again The colours of the sky dome were made for the full renderer, which tonemaps them and draws to an sRGB framebuffer: the sRGB matrix, the gamma put on the brightness, a lighter gradient and a band of light at the horizon (40c21bd4, b46c8c76, 8df81eb4), and the fog no longer dimmed by the diffuse level (#229). The legacy and simple renderers draw these colours as they are, and the ambient light and the fog are taken from them, so all three differed from 26.05 there. With Global.LegacyRenderer the dome is computed as in 26.05: the Adobe RGB matrix, the brightness knee at 0.85, the sky tone saturated as the colour, the plain gradient and the gamma of 0.45 by day at the end; the fog is lit by the key light at its diffuse level. The full renderer is unchanged. The turbidity under overcast is a separate fix (#410). * fix(test): a test run takes the legacy and the simple renderer flag off with the renderer From the review of #415: apply_test_mode_settings() sets the null renderer but left Global.LegacyRenderer and Global.BasicRenderer as the gfxrenderer line of eu07.ini made them. With this PR the legacy flag picks the colours of the sky dome, and their average is the light level the scenery lamps, the AI's compartment lights and Python's light_level go by. The same --test run on a machine with "gfxrenderer legacy" and on one with the default renderer computed different skies and could switch those lights at other times. A test run now always takes the sky of the full renderer, as on master. The context of a test run doesn't depend on the flag (it asks for none in particular), and its multisampling is off, so nothing else changes. --------- Co-authored-by: maj00r * fix(python): the files a screen opens itself are found on Linux when named in another case (#449) #362 made the simulator find the data named in another case of its letters, through FileOnDisk(), the script of a screen included. What the script opens itself goes past it: Image.open(), ImageFont.truetype(), open() and the openimage() of the screens go straight to the system. The data is made on Windows, so on Linux a screen that asks for "WS_on.png" where the disk has "ws_on.png" doesn't start at all, e.g. the left screens of the EN57AL/AKM (WS_gotowosc.png), EN57AKL and EN71AKS (WN_off.png, M1M2_on.png and more). abstractscreenrenderer.py, run in __main__ before any screen, now finds those files as FileCased() does: the name given when it's on the disk, otherwise the one differing from it only in case, of the file or of its folders, a folder listed again for a name missing at most once a second. builtins.open() (which Image.open() goes through) and ImageFont.truetype() take the name so found, and openimage() looks for it. A file not there yet goes into its folder as named on the disk, so a screen writing its state for the first time doesn't make a second folder. A name with no such file is passed on as given, so a file missing fails as before. On Windows, which finds the names in any case itself, nothing is wrapped and nothing changes. No change to the game data is needed. Checked on a case-sensitive folder (a Windows folder with the case-sensitive attribute) with the scripts as they are in the data: with the file of master the EN57AL, EN57AKL and EN71AKS screens fail to start, with this one they start and render; plus the cases of the lookup (folders, ./, .., backslashes, a new file, a missing one, the module run twice, a screen's global named like the module's own). Co-authored-by: Claude Opus 5.5 * fix(render): old assets drawn as 26.05 drew them; the headlight beam spread sideways (#481) * fix(render): old assets drawn as 26.05 drew them: metal, sun highlight, tonemapping, sun scale, diffuse colour The shader changes since 26.05.2 were made for PBR-authored assets; the assets in the game data were tuned for 26.05, and none of them is authored for the new combine. - Metal keeps its diffuse term as far as its reflection mask is low (metal_diffuse_loss = metalic * reflectivity). Assets marking metal in the specgloss with a low mask went almost black (the gold EN63A-031); a full mask is drawn as before. - The direct sun highlight is tinted by the albedo again, for dielectrics too. Old assets tuned param_specular / specgloss R with that multiply; untinted, dark glossy plastic broke into white glints along edges (Impuls fronts) and speckles on cab desks (SA132). - ACES instead of AgX: AgX with its look crushed the dark end, a night scene lost half its brightness and the ground beside the track went black. - SUN_DIFFUSE_SCALE 2.5 again (1.5 dimmed the moon at night as well). - The Diffuse colour of submodels and shapes scales the light as it is, as in 26.05, not raised to 2.2: that took a quarter off the default 0.8 of every scenery shape and more off the ~64 000 textured submodels with a darker Diffuse. Checked on screenshots of 10 vehicles by day (Ultra preset) and from cabs at night against the 26.05.2 shaders on the same executable. No game data changes. * feat(render): the headlight beam spread sideways, gfx.headlights.beamwidth (default 1.7) The projected beam texture lit the track and the ballast, and the ground beside them only with its dark edge (24-45 against 116 on the ballast close ahead, nearly 0 further on), so at night only the ballast showed. The beam is spread sideways around its middle by gfx.headlights.beamwidth: at 1.7 the ground gets most of the light of the ballast, the brightness along the track stays as it was. 1 draws the narrow beam of 26.05; range 1-4. The value reaches the shaders as HEADLIGHT_BEAM_WIDTH, written with the classic locale so that a decimal comma can't break the glsl; the shader validator compiles them with and without the spread. The key is written to the log with the other settings. * fix(render): the sunless specgloss shader combines metal as apply_lights does * fix(render): an untextured submodel takes its linearised colour as the texture again, as 26.05 did mat_colored.frag gave apply_lights() a white base, so the albedo of a Map: none submodel was its diffuse colour c, where 26.05.2 drew c^2.2 * c. A dark grey came out tens of times lighter: on the road vehicles of pctga the tyres (25-40 grey) 60-165x, the glass 23x, whole untextured cars (a4, golf, passat, ka, arosa) 1.5-3x. With the linearised colour as the texture a grey matches 26.05 in the ambient and the sun; a saturated colour is up to a third darker in the sun, as 26.05 scaled the sun by the value of the colour, not by the colour. * fix(render): the sun highlight is tinted by the texture alone, as 26.05 drew it --------- Co-authored-by: maj00r <73280030+maj00r@users.noreply.github.com> Co-authored-by: maj00r Co-authored-by: Claude Opus 5.5 Co-authored-by: Hirek193 Co-authored-by: pol102 Co-authored-by: pawelw --- CMakeLists.txt | 2 + application/driverhints.cpp | 8 + application/driverhints_def.h | 1 + ci_shadervalidator/main.cpp | 2 + ci_shadervalidator/utilities/Globals.h | 1 + environment/skydome.cpp | 56 ++- gl/glsl_common.cpp | 18 + rendering/opengl33renderer.cpp | 25 ++ rendering/opengl33renderer.h | 2 + shaders/light_common.glsl | 45 ++- shaders/mat_colored.frag | 8 +- shaders/mat_sunlessnormalmap_specgloss.frag | 16 +- shaders/postfx_motionblur.frag | 4 + shaders/tonemapping.glsl | 7 +- simulation/simulationenvironment.cpp | 4 +- simulation/simulationtest.cpp | 4 + .../python/local/abstractscreenrenderer.py | 69 +++- tests/unit/test_brake_charge.cpp | 169 +++++++++ tests/unit/test_brake_releaser.cpp | 17 + tests/unit/test_uphill_start.cpp | 103 ++++++ utilities/Globals.cpp | 7 + utilities/Globals.h | 3 + vehicle/Driver.cpp | 328 +++++++++++++++--- vehicle/Driver.h | 22 ++ vehicle/brakecharge.cpp | 65 ++++ vehicle/brakecharge.h | 76 ++++ vehicle/brakereleaser.cpp | 5 + vehicle/brakereleaser.h | 3 + vehicle/uphillstart.cpp | 36 ++ vehicle/uphillstart.h | 41 +++ 30 files changed, 1068 insertions(+), 79 deletions(-) create mode 100644 tests/unit/test_brake_charge.cpp create mode 100644 tests/unit/test_uphill_start.cpp create mode 100644 vehicle/brakecharge.cpp create mode 100644 vehicle/brakecharge.h create mode 100644 vehicle/uphillstart.cpp create mode 100644 vehicle/uphillstart.h diff --git a/CMakeLists.txt b/CMakeLists.txt index faa6ef86d..57ace8499 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -582,6 +582,8 @@ set(CORE_SOURCES "vehicle/brakereleaser.cpp" "vehicle/handover.cpp" "vehicle/crew.cpp" +"vehicle/uphillstart.cpp" +"vehicle/brakecharge.cpp" "vehicle/horn.cpp" "vehicle/cameraviews.cpp" "vehicle/linebreaker.cpp" diff --git a/application/driverhints.cpp b/application/driverhints.cpp index 2c3fbd66b..cd1967aa2 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -762,6 +762,14 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) return mvPantographUnit->PantPress >= (is_emu() ? (mvPantographUnit->PantPressLockActive ? 4.6 : 2.6) : 4.2); } ); break; } + case driver_hint::waitbrakecharge: { + // NOTE: this action doesn't have AI component: the ai waits through Ready and DecBrake() + hint( + Action, + [this](float const /*Parameter*/) { + return IsConsistCharged; } ); + break; + } case driver_hint::waitloadexchange: { // NOTE: this action doesn't have AI component hint( diff --git a/application/driverhints_def.h b/application/driverhints_def.h index 6f5c86474..2e0556968 100644 --- a/application/driverhints_def.h +++ b/application/driverhints_def.h @@ -59,6 +59,7 @@ DRIVER_HINT_DEF(directionother, STRN("Switch reverser to opposite direction")) DRIVER_HINT_DEF(directionnone, STRN("Set reverser to neutral")) DRIVER_HINT_DEF(waitpressuretoolow, STRN("Wait for main reservoir to fill")) DRIVER_HINT_DEF(waitpantographpressuretoolow, STRN("Wait for sufficient air pressure in pantograph subsystem")) +DRIVER_HINT_DEF(waitbrakecharge, STRN("Wait for the train brakes to charge")) DRIVER_HINT_DEF(sandingon, STRN("Switch on sanding")) DRIVER_HINT_DEF(sandingoff, STRN("Switch off sanding")) DRIVER_HINT_DEF(consistdoorlockson, STRN("Switch on door locks")) diff --git a/ci_shadervalidator/main.cpp b/ci_shadervalidator/main.cpp index bd7db0523..bdc1a9ef4 100644 --- a/ci_shadervalidator/main.cpp +++ b/ci_shadervalidator/main.cpp @@ -113,6 +113,7 @@ bool check_shader_allopts(std::string filename) Global.gfx_shadergamma = true; // the default of the simulator, which compiles the alpha to coverage branches of the shaders Global.iMultisampling = 2; + Global.gfx_headlights_beamwidth = 2.f; if (!check_shader(filename)) suc = false; @@ -124,6 +125,7 @@ bool check_shader_allopts(std::string filename) Global.gfx_extraeffects = false; Global.gfx_shadergamma = false; Global.iMultisampling = 0; + Global.gfx_headlights_beamwidth = 1.f; if (!check_shader(filename)) suc = false; diff --git a/ci_shadervalidator/utilities/Globals.h b/ci_shadervalidator/utilities/Globals.h index e8f548dc3..943ff0adc 100644 --- a/ci_shadervalidator/utilities/Globals.h +++ b/ci_shadervalidator/utilities/Globals.h @@ -9,6 +9,7 @@ struct _global bool gfx_shadergamma; bool gfx_usegles; int iMultisampling; + float gfx_headlights_beamwidth; }; extern _global Global; diff --git a/environment/skydome.cpp b/environment/skydome.cpp index 654b3a345..2a12695d9 100644 --- a/environment/skydome.cpp +++ b/environment/skydome.cpp @@ -5,6 +5,27 @@ #include "simulation/simulationenvironment.h" #include "utilities/Globals.h" +namespace { + +// XYZ to Adobe RGB, as the sky was converted up to 26.05. the legacy renderer still gets its sky this way: +// it draws the colours of the dome as they are, with no tonemapping of its own +glm::vec3 +xyz_to_adobe_rgb( glm::vec3 const &XYZ ) { + + // M^-1 for Adobe RGB from http://www.brucelindbloom.com/Eqn_RGB_XYZ_Matrix.html + std::array const mi{ + glm::vec3{ 2.041369f, -0.969266f, 0.0134474f }, + glm::vec3{ -0.5649464f, 1.8760108f, -0.1183897f }, + glm::vec3{ -0.3446944f, 0.041556f, 1.0154096f } }; + + return glm::vec3{ + XYZ.x * mi[ 0 ].x + XYZ.y * mi[ 1 ].x + XYZ.z * mi[ 2 ].x, + XYZ.x * mi[ 0 ].y + XYZ.y * mi[ 1 ].y + XYZ.z * mi[ 2 ].y, + XYZ.x * mi[ 0 ].z + XYZ.y * mi[ 1 ].z + XYZ.z * mi[ 2 ].z }; +} + +} // namespace + // sky gradient based on "A practical analytic model for daylight" // by A. J. Preetham Peter Shirley Brian Smits (University of Utah) @@ -185,6 +206,11 @@ void CSkyDome::RebuildColors() { float twilightfactor = std::clamp( -simulation::Environment.sun().getAngle(), 0.0f, 18.0f ) / 18.0f; auto gammacorrection = glm::mix( glm::vec3( 1.0f ), glm::vec3( 0.45f ), twilightfactor ); + // the legacy renderer has no tonemapping and no srgb framebuffer, so its sky stays as 26.05 made it: + // display-encoded by day (gamma 0.45), with the brightness knee and the plain gradient, and no horizon band. + // the averages taken from these colours give it the ambient light and the fog of 26.05 too + bool const legacy { Global.LegacyRenderer }; + auto const legacygammacorrection = glm::mix( glm::vec3( 0.45f ), glm::vec3( 1.0f ), twilightfactor ); // get zenith luminance auto const chi = static_cast(( 4.0f / 9.0f - m_turbidity / 120.0f ) * ( M_PI - 2.0f * m_thetasun )); @@ -253,7 +279,7 @@ void CSkyDome::RebuildColors() { float const Z = (1.0f - x - y) / y * Y; colorconverter = glm::vec3( X, Y, Z ); - color = colors::XYZtoRGB( colorconverter ); + color = legacy ? xyz_to_adobe_rgb( colorconverter ) : colors::XYZtoRGB( colorconverter ); colorconverter = colors::RGBtoHSV(color); if ( m_linearexpcontrol ) { @@ -264,7 +290,12 @@ void CSkyDome::RebuildColors() { colorconverter.z = 1.0f - std::exp( -m_expfactor * colorconverter.z ); } - colorconverter.z = std::pow( std::max( colorconverter.z, 0.0f ), gammacorrection.x ); + if( false == legacy ) { + colorconverter.z = std::pow( std::max( colorconverter.z, 0.0f ), gammacorrection.x ); + } + else if( colorconverter.z > 0.85f ) { + colorconverter.z = 0.85f + ( colorconverter.z - 0.85f ) * 0.35f; + } colorconverter.y = std::clamp( colorconverter.y * Global.m_skysaturationcorrection, 0.0f, 1.0f ); // desaturate sky colour, based on overcast level @@ -281,7 +312,7 @@ void CSkyDome::RebuildColors() { // this height-based factor is reduced the farther the sun is up in the sky float const shiftfactor = std::clamp( std::lerp(heightbasedphase, sunbasedphase, sunbasedphase), 0.0f, 1.0f ); // h = 210 makes for 'typical' sky tone - glm::vec3 const skytonecolor = colors::HSVtoRGB( glm::vec3( 210.0f, 0.5f, colorconverter.z ) ); + glm::vec3 const skytonecolor = colors::HSVtoRGB( glm::vec3( 210.0f, legacy ? colorconverter.y : 0.5f, colorconverter.z ) ); color = colors::HSVtoRGB( colorconverter ); color = glm::mix( color, skytonecolor, shiftfactor * Global.m_skyhuecorrection ); @@ -296,14 +327,21 @@ void CSkyDome::RebuildColors() { color.x = 0.20f * color.z; color.y = 0.65f * color.z; } - // simple gradient, darkening towards the top - color *= std::clamp( 1.0f - vertex.y * 0.75f, 0.0f, 1.f ); + if( legacy ) { + // simple gradient, darkening towards the top, then the gamma correction + color *= std::clamp( 1.0f - vertex.y, 0.f, 1.f ); + color = glm::pow( glm::max( color, glm::vec3( 0.f ) ), legacygammacorrection ); + } + else { + // simple gradient, darkening towards the top + color *= std::clamp( 1.0f - vertex.y * 0.75f, 0.0f, 1.f ); - float const horizonboost = 1.5f + m_overcast; - float const horizonbandwidth = 0.2f; // boost tapers to 0 by ~11.5 degrees elevation - float const horizonband = std::clamp( 1.0f - vertex.y / horizonbandwidth, 0.0f, 1.0f ); + float const horizonboost = 1.5f + m_overcast; + float const horizonbandwidth = 0.2f; // boost tapers to 0 by ~11.5 degrees elevation + float const horizonband = std::clamp( 1.0f - vertex.y / horizonbandwidth, 0.0f, 1.0f ); - color *= std::lerp( 1.0, horizonboost, horizonband ); + color *= std::lerp( 1.0, horizonboost, horizonband ); + } //color *= ( 0.25f - vertex.y ); m_colours[ i ] = color; diff --git a/gl/glsl_common.cpp b/gl/glsl_common.cpp index e621fdc6b..9c3cfcb1f 100644 --- a/gl/glsl_common.cpp +++ b/gl/glsl_common.cpp @@ -1,6 +1,23 @@ #include "stdafx.h" #include "glsl_common.h" +#include +#include + +namespace +{ +// a float the way glsl reads it, whatever the locale of the program +std::string glsl_float(float const Value) +{ + std::ostringstream text; + text.imbue(std::locale::classic()); + text.setf(std::ios::fixed); + text.precision(3); + text << Value; + return text.str(); +} +} // namespace + std::string gl::glsl_common; void gl::glsl_common_setup() @@ -12,6 +29,7 @@ void gl::glsl_common_setup() "#define POSTFX_ENABLED " + std::to_string((int)!Global.gfx_skippipeline) + "\n" + "#define EXTRAEFFECTS_ENABLED " + std::to_string((int)Global.gfx_extraeffects) + "\n" + "#define ALPHA_TO_COVERAGE_ENABLED " + std::to_string((int)(Global.iMultisampling > 0)) + "\n" + + "#define HEADLIGHT_BEAM_WIDTH " + glsl_float(Global.gfx_headlights_beamwidth) + "\n" + "#define MAX_LIGHTS " + std::to_string(MAX_LIGHTS) + "U\n" + "#define MAX_CASCADES " + std::to_string(MAX_CASCADES) + "U\n" + "#define MAX_PARAMS " + std::to_string(MAX_PARAMS) + "U\n" + diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp index 3a3008a44..5215a7b9f 100644 --- a/rendering/opengl33renderer.cpp +++ b/rendering/opengl33renderer.cpp @@ -988,6 +988,31 @@ void opengl33_renderer::Render_pass(viewport_config &vp, rendermode const Mode) auto const *vehicle = Global.pCamera.m_owner; glm::mat4 mv = OpenGLMatrices.data(GL_MODELVIEW); future = glm::translate(mv, -glm::vec3(vehicle->get_future_movement())) * glm::inverse(mv); + m_freecameraposition.reset(); + } + else if (vp.main) + { + // the free camera (freefly, debug camera) blurs the world with its own movement, as a vehicle does with its: + // without it the ground racing under a low camera strobes in rings at the distances its texture repeats. + // the movement of the frame before stands for the one to come; a jump (a camera preset) is no movement + auto const position{Global.pCamera.Pos}; + if (m_freecameraposition) + { + auto movement{glm::vec3(position - *m_freecameraposition)}; + auto const length{glm::length(movement)}; + if (length < 50.f) + { + // the blur takes the scene where the camera will be: a fast camera (shift, ctrl) moves past the ground + // at the bottom of the screen within a frame, it ends up behind it there and its motion turns over + // into a bright band. half a metre a frame still blurs metres with the shutter of the motion blur + auto const maxmovement{0.5f}; + if (length > maxmovement) + movement *= maxmovement / length; + glm::mat4 mv = OpenGLMatrices.data(GL_MODELVIEW); + future = glm::translate(mv, -movement) * glm::inverse(mv); + } + } + m_freecameraposition = position; } Update_Lights( simulation::Lights ); diff --git a/rendering/opengl33renderer.h b/rendering/opengl33renderer.h index 4322cc2db..3e97683ae 100644 --- a/rendering/opengl33renderer.h +++ b/rendering/opengl33renderer.h @@ -469,6 +469,8 @@ class opengl33_renderer : public gfx_renderer { GLuint64 m_gllasttime = 0; double m_precipitationrotation; + // where the camera with no vehicle of its own was at the frame before, for the motion blur of its movement + std::optional m_freecameraposition; glm::mat4 perspective_projection_raw(float fovy, float aspect, float znear, float zfar); glm::mat4 perspective_projection(const viewport_proj_config &c, float n, float f, glm::mat4 &frustum); diff --git a/shaders/light_common.glsl b/shaders/light_common.glsl index 6261a090d..ddc7c39d3 100644 --- a/shaders/light_common.glsl +++ b/shaders/light_common.glsl @@ -33,7 +33,7 @@ in vec4 UserData; // lit and shaded faces of the same surface). // --------------------------------------------------------------------- const float AMBIENT_SCALE = 0.65; -const float SUN_DIFFUSE_SCALE = 1.5; +const float SUN_DIFFUSE_SCALE = 2.5; // 26.05; at 1.5 the moon left the night black around the headlights const float SUN_NDOTL_SHARPNESS = 1.25; float length2(vec3 v) @@ -242,7 +242,13 @@ vec2 calc_headlights(light_s light, vec3 fragnormal) float distance = length(light.pos - f_pos.xyz); float atten = 1.0f / (1.0f + light.linear * distance + light.quadratic * (distance * distance)); atten *= mix(1.0, 0.0, clamp((coords.z - 0.998) * 500.0, 0.0, 1.0)); - vec3 lights = textureProj(headlightmap, headlightpos).rgb * light.headlight_weights.rgb; + // gfx.headlights.beamwidth spreads the beam sideways around its middle (0.5 of the projected x), so the + // ground beside the track gets the light of the ballast; the brightness along the track stays as it was + vec4 beampos = headlightpos; +#ifdef HEADLIGHT_BEAM_WIDTH + beampos.x = 0.5 * beampos.w + (beampos.x - 0.5 * beampos.w) / HEADLIGHT_BEAM_WIDTH; +#endif + vec3 lights = textureProj(headlightmap, beampos).rgb * light.headlight_weights.rgb; float lightintensity = max(max(lights.r, lights.g), lights.b); return part * atten * lightintensity; } @@ -279,7 +285,9 @@ vec3 EnvBRDFApprox(vec3 F0, float roughness, float NoV) // param[1].x its intensity (HSV value unless a material overrides it). vec3 material_diffuse() { - vec3 diffusecolor = pow(max(param[0].rgb, vec3(0.0)), vec3(2.2)); + // the colour as it is, as 26.05 scaled the light by it; linearised (^2.2) it took a quarter off the default + // 0.8 of every scenery shape and more off darker submodels, and the night went black + vec3 diffusecolor = max(param[0].rgb, vec3(0.0)); float value = max(param[0].r, max(param[0].g, param[0].b)); return (value > 0.0 ? diffusecolor * (param[1].x / value) : vec3(0.0)); } @@ -288,6 +296,8 @@ vec3 material_diffuse() // do magic here vec3 apply_lights(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float reflectivity, float specularity, float shadowtone) { + // the sun highlight is tinted by the texture alone, as 26.05 drew it, not by the diffuse colour too + vec3 highlight_tint = texturecolor; // Diffuse colour is applied once, to the albedo; the light terms below are not scaled by it again texturecolor *= material_diffuse(); float weathered = (param[3].w > 0.0 ? clamp(param[3].w * UserData.x, 0.0, 1.0) : 0.0); @@ -313,6 +323,10 @@ vec3 apply_lights(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float refl vec3 view_dir = normalize(-f_pos.xyz); float NdotV = max(dot(fragnormal, view_dir), 0.0); vec3 F0 = mix(vec3(0.04), texturecolor, metalic); + // A metal gives up its diffuse term only as far as its reflection mask lets the environment take its place. + // Assets made before the metal/rough combine mark metal in the specgloss but keep a low mask, and without + // this their metal parts went almost black; a metal with the full mask is drawn as before. + float metal_diffuse_loss = metalic * clamp(reflectivity, 0.0, 1.0); vec3 fresnel = F0 + (1.0 - F0) * pow(1.0 - NdotV, 5.0); const float MAX_REFLECTION_LOD = 8.0; @@ -333,9 +347,9 @@ vec3 apply_lights(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float refl texturecolor = mix(texturecolor, texturecolorfullv, envyuv.r * reflectivity * env_spec_w); if (lights_count == 0U) - // Metals carry no diffuse term; env reflection is gated by the env BRDF + // Metals carry no diffuse term where they reflect; env reflection is gated by the env BRDF // (F0-tinted, roughness-attenuated) so matte surfaces barely reflect. - return fragcolor * texturecolor * (1.0 - metalic) + return fragcolor * texturecolor * (1.0 - metal_diffuse_loss) + emissioncolor * texturecolor + envcolor * env_spec * reflectivity; @@ -375,16 +389,19 @@ vec3 apply_lights(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float refl vec3 env_reflection = envcolor * env_spec * reflectivity * (1.0 - shadow1 * 0.5); // --- Physically-based metal/rough combine (Substance 3D Painter parity) --- - // Dielectrics: keep the full diffuse albedo; the direct sun highlight stays - // light-coloured because dielectric F0 is achromatic (~0.04) and - // must NOT be tinted by the base colour. - // Metals: drop the diffuse term entirely and tint the direct highlight - // with the albedo (metal F0 == base colour). + // Dielectrics: keep the full diffuse albedo; the direct sun highlight is tinted + // by the albedo, as 26.05 drew it. The specular strength of the + // assets (param_specular, the specgloss R) was tuned with that + // multiply; an untinted highlight on dark glossy plastic of an old + // asset turned into white glints along edges and speckles on cab + // desks. + // Metals: drop the diffuse term where the reflection mask is full (see + // metal_diffuse_loss) and tint the direct highlight with the + // albedo (metal F0 == base colour). // The highlight *strength* (specularamount) is deliberately left untouched so - // existing material tuning is preserved — only the colour/energy split that - // was previously inverted gets corrected. - vec3 diffuse_albedo = texturecolor * (1.0 - metalic); - vec3 spec_tint = mix(vec3(1.0), texturecolor, metalic); + // existing material tuning is preserved. + vec3 diffuse_albedo = texturecolor * (1.0 - metal_diffuse_loss); + vec3 spec_tint = highlight_tint; vec3 result = fragcolor * diffuse_albedo // sun + ambient + headlight diffuse + specularcolor * spec_tint // direct sun highlight diff --git a/shaders/mat_colored.frag b/shaders/mat_colored.frag index 46de50f09..59ee3e8f8 100644 --- a/shaders/mat_colored.frag +++ b/shaders/mat_colored.frag @@ -24,8 +24,10 @@ layout(location = 1) out vec4 out_motion; void main() { - // no texture: the diffuse colour alone makes the albedo, apply_lights() applies it to the white base - vec4 tex_color = vec4(1.0, 1.0, 1.0, param[0].a); + // no texture: the diffuse colour, linearised, stands in for the texture, and apply_lights() scales it by the + // colour once more, as 26.05 did (c^2.2 * c); on a white base a dark grey of an untextured car came out + // tens of times lighter than in 26.05: tyres, bumpers and glass grey instead of near black + vec4 tex_color = vec4(pow(max(param[0].rgb, vec3(0.0)), vec3(2.2)), param[0].a); // if (tex_color.a < opacity) // discard; @@ -33,7 +35,7 @@ void main() vec3 fragcolor = ambient; vec3 fragnormal = normalize(f_normal); float reflectivity = param[1].z; - float specularity = dot(pow(param[0].rgb, vec3(2.2)), vec3(0.5)); + float specularity = dot(tex_color.rgb, vec3(0.5)); glossiness = abs(param[1].w); fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); diff --git a/shaders/mat_sunlessnormalmap_specgloss.frag b/shaders/mat_sunlessnormalmap_specgloss.frag index 4e2abe1d9..eb1f9b916 100644 --- a/shaders/mat_sunlessnormalmap_specgloss.frag +++ b/shaders/mat_sunlessnormalmap_specgloss.frag @@ -37,6 +37,7 @@ uniform sampler2D specgloss; vec3 apply_lights_sunless(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float reflectivity, float specularity, float shadowtone) { // diffuse colour applied once, to the albedo (see material_diffuse() in light_common.glsl) + vec3 highlight_tint = texturecolor; texturecolor *= material_diffuse(); // Cab interior: dim ambient less than the exterior path - ambient // is the dominant indoor illumination, but it was still too bright. @@ -47,6 +48,9 @@ vec3 apply_lights_sunless(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, fl vec3 view_dir = normalize(-f_pos.xyz); float NdotV = max(dot(fragnormal, view_dir), 0.0); vec3 F0 = mix(vec3(0.04), texturecolor, metalic); + // A metal gives up its diffuse term only as far as its reflection mask lets the environment take its place + // (the same as apply_lights in light_common.glsl). + float metal_diffuse_loss = metalic * clamp(reflectivity, 0.0, 1.0); vec3 fresnel = F0 + (1.0 - F0) * pow(1.0 - NdotV, 5.0); const float MAX_REFLECTION_LOD = 8.0; @@ -64,7 +68,7 @@ vec3 apply_lights_sunless(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, fl texturecolor = mix(texturecolor, texturecolorfullv, envyuv.r * reflectivity * env_spec_w); if (lights_count == 0U) - return fragcolor * texturecolor * (1.0 - metalic) + return fragcolor * texturecolor * (1.0 - metal_diffuse_loss) + emissioncolor * texturecolor + envcolor * env_spec * reflectivity; @@ -95,11 +99,11 @@ vec3 apply_lights_sunless(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, fl // Env reflection gated by env BRDF (roughness-attenuated, F0-tinted). vec3 env_reflection = envcolor * env_spec * reflectivity; - // Physically-based metal/rough combine (matches apply_lights / Substance): - // dielectric -> light-coloured highlight + full diffuse; metal -> albedo-tinted - // highlight, no diffuse term. Highlight strength left unchanged. - vec3 diffuse_albedo = texturecolor * (1.0 - metalic); - vec3 spec_tint = mix(vec3(1.0), texturecolor, metalic); + // Metal/rough combine, the same as apply_lights: the direct highlight is tinted by + // the albedo (as 26.05 drew it), a metal drops its diffuse term only where its + // reflection mask is full. Highlight strength left unchanged. + vec3 diffuse_albedo = texturecolor * (1.0 - metal_diffuse_loss); + vec3 spec_tint = highlight_tint; vec3 result = fragcolor * diffuse_albedo + specularcolor * spec_tint diff --git a/shaders/postfx_motionblur.frag b/shaders/postfx_motionblur.frag index 146179ac9..d2b23fd03 100644 --- a/shaders/postfx_motionblur.frag +++ b/shaders/postfx_motionblur.frag @@ -32,6 +32,10 @@ void main() vec2 offset = velocity * (float(i) / float(nSamples - 1) - 0.5); vec2 coord = f_coords + offset; + // a sample off the picture would read its edge row again and again: a fast movement towards the bottom + // of the screen (the ground racing under a low free camera) smeared it into a bright band there + if (any(lessThan(coord, 0.5 * texelSize)) || any(greaterThan(coord, vec2(1.0) - 0.5 * texelSize))) + continue; float depth = texture(depth_tex, coord).x; if (abs(depth - ori_depth) < depth_diff) diff --git a/shaders/tonemapping.glsl b/shaders/tonemapping.glsl index 863fe0fe1..701f9d5fd 100644 --- a/shaders/tonemapping.glsl +++ b/shaders/tonemapping.glsl @@ -139,14 +139,15 @@ vec3 ApplyAgX(vec3 linearColorRec709) vec4 tonemap(vec4 x) { - // Use AgX by default. Reinhard and ACES above are kept for reference. + // ACES, as 26.05 drew it. AgX and Reinhard above are kept for reference: AgX with its look crushed the dark + // end, so the night and everything in shadow went black (a night scene lost half its brightness). // Last-line-of-defense sanitize so NaN/Inf/negative HDR values do not // escape into log2()/pow() and produce black flashes or invalid output. vec3 hdr = x.rgb; hdr = mix(hdr, vec3(0.0), vec3(any(isnan(hdr)) || any(isinf(hdr)))); hdr = max(hdr, vec3(0.0)); - return FBOUT(vec4(ApplyAgX(hdr), x.a)); - //return FBOUT(vec4(ACESFilm(hdr), x.a)); + return FBOUT(vec4(ACESFilm(hdr), x.a)); + //return FBOUT(vec4(ApplyAgX(hdr), x.a)); //return FBOUT(vec4(reinhard(x.rgb), x.a)); } diff --git a/simulation/simulationenvironment.cpp b/simulation/simulationenvironment.cpp index 4e8c0e5f7..57c1074a7 100644 --- a/simulation/simulationenvironment.cpp +++ b/simulation/simulationenvironment.cpp @@ -190,7 +190,9 @@ world_environment::update() { // update the fog. setting it to match the average colour of the sky dome is cheap // but quite effective way to make the distant items blend with background better - Global.FogColor = m_skydome.GetAverageHorizonColor() * keylightcolor * + // the legacy renderer keeps the fog of 26.05, lit by the key light at its diffuse level + glm::vec3 const foglightcolor { Global.LegacyRenderer ? keylightcolor * diffuselevel : keylightcolor }; + Global.FogColor = m_skydome.GetAverageHorizonColor() * foglightcolor * std::clamp((float)Global.fLuminance, 0.f, 1.f); diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp index 169e0883c..72b4b7e79 100644 --- a/simulation/simulationtest.cpp +++ b/simulation/simulationtest.cpp @@ -62,6 +62,10 @@ void apply_test_mode_settings() Global.local_start_vehicle = "ghostview"; Global.GfxRenderer = "null"; Global.NvRenderer = false; + // the flags of the gfxrenderer line read from the settings go with it: the legacy one picks the colours of the sky, + // and with them the light level the lamps and the AI go by, so a test run would depend on the renderer of the ini + Global.LegacyRenderer = false; + Global.BasicRenderer = false; Global.bSoundEnabled = false; Global.python_enabled = false; Global.bInactivePause = false; diff --git a/staticFiles/python/local/abstractscreenrenderer.py b/staticFiles/python/local/abstractscreenrenderer.py index 3ebf20813..59341c045 100644 --- a/staticFiles/python/local/abstractscreenrenderer.py +++ b/staticFiles/python/local/abstractscreenrenderer.py @@ -1,6 +1,73 @@ from PIL import Image, ImageDraw, ImageFont from math import ceil, floor, cos, sin, radians +import builtins import os +import sys +import time + +# Linux tells the case of the letters in a file name apart, Windows doesn't, and the data is made on Windows: a screen asks for +# "WS_on.png" where the disk has "ws_on.png", or names a folder in another case. The simulator opens such files of its own through +# FileOnDisk(); the files a screen opens itself (images, fonts, text) are found here the same way. The name given when it's on the +# disk, otherwise the one differing from it only in case, of the file or of its folders. On Windows nothing changes. +_case_sensitive = not sys.platform.startswith('win') +_cased_listings = {} # folder -> (when listed, {name in lower case: name on the disk}) + +def _cased_name(folder, name): + """the name in the folder differing from the one given only in case, as on the disk; None when there's none""" + listed = _cased_listings.get(folder) + # a name missing gets the folder listed again, at most once a second, as FileCased() does + if listed is None or (name.lower() not in listed[1] and time.monotonic() - listed[0] >= 1.0): + names = {} + try: + for entry in os.listdir(folder or '.'): + names.setdefault(entry.lower(), entry) + except OSError: + pass + listed = (time.monotonic(), names) + _cased_listings[folder] = listed + return listed[1].get(name.lower()) + +def file_on_disk(path): + """the file to open: as it's named on the disk, the path given when there's none (and on Windows, which finds it itself)""" + if not _case_sensitive or not isinstance(path, str) or os.path.exists(path): + return path + text = path.replace('\\', '/') + parts = [part for part in text.split('/') if part] + cased = '/' if text.startswith('/') else '' + for index, part in enumerate(parts): + last = index == len(parts) - 1 + found = part + if part not in ('.', '..') and not os.path.exists(cased + part): + found = _cased_name(cased, part) + if found is None: + if not last: + return path + # a file not there yet goes into its folder as named on the disk: one written for the first time. The folder + # gets listed anew next time, the file being there by then + _cased_listings.pop(cased, None) + return cased + part + cased += found if last else found + '/' + return cased + +def _open_files_on_disk(): + # Image.open() opens the file through builtins.open(); the fonts are opened by FreeType, from the name. What the wrappers + # call is held here, not looked up in __main__, which the screens share and could name the same + on_disk = file_on_disk + open_given = builtins.open + truetype_given = ImageFont.truetype + + def open_on_disk(file, *args, **kwargs): + return open_given(on_disk(file), *args, **kwargs) + + def truetype_on_disk(font=None, *args, **kwargs): + return truetype_given(on_disk(font), *args, **kwargs) + + open_on_disk.file_on_disk = True + builtins.open = open_on_disk + ImageFont.truetype = truetype_on_disk + +if _case_sensitive and not getattr(builtins.open, 'file_on_disk', False): + _open_files_on_disk() # Pillow 10 removed ImageFont.getsize(), ImageDraw.textsize() and Image.ANTIALIAS, which the screen scripts use; for # Python 3.14 only a newer Pillow is available, so they are put back, on top of getbbox() / textbbox() and LANCZOS @@ -30,7 +97,7 @@ class abstractscreenrenderer(): def openimage(self, name): exts = [ ".png", ".tga", ".dds" ] for e in exts: - path = name + e + path = file_on_disk(name + e) if os.path.isfile(path): if e == ".dds": return Image.open(path).transpose(Image.FLIP_TOP_BOTTOM) diff --git a/tests/unit/test_brake_charge.cpp b/tests/unit/test_brake_charge.cpp new file mode 100644 index 000000000..238d0bef0 --- /dev/null +++ b/tests/unit/test_brake_charge.cpp @@ -0,0 +1,169 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/brakecharge.h" + +// a standing train starts only with its brake pipe and auxiliary reservoirs charged (TController, the consist check) + +using brake_charge::charged; +using brake_charge::state; + +TEST_CASE("brake charge: a train charged to within the margin may start") { + state s; + CHECK(charged(s, 5.0, 5.0, 0.0)); + s = {}; + CHECK(charged(s, 5.0 - brake_charge::margin, 5.0, 0.0)); + s = {}; + // the last wagon of a long train, for good below the working pressure from what leaks along the pipe + CHECK(charged(s, 4.62, 5.0, 0.0)); +} + +TEST_CASE("brake charge: a train prepared from cold waits while its pipe fills") { + state s; + // the pipe of the last wagon empty, then filling by 0.1 bar every 5 s + auto level{0.0}; + auto time{0.0}; + while (level < 5.0 - brake_charge::margin - 0.05) { + CHECK_FALSE(charged(s, level, 5.0, time)); + CHECK_FALSE(s.stalled); + level += 0.1; + time += 5.0; + } + CHECK(charged(s, 5.0 - brake_charge::margin, 5.0, time)); + CHECK(s.going); +} + +TEST_CASE("brake charge: a charge that stops rising lets the train go after the stall time") { + state s; + // a hose not connected: the last wagon stays at 3.2 bar + CHECK_FALSE(charged(s, 3.2, 5.0, 100.0)); + CHECK_FALSE(charged(s, 3.21, 5.0, 130.0)); // less than the gain that counts + CHECK_FALSE(charged(s, 3.21, 5.0, 100.0 + brake_charge::stall_time - 0.1)); + CHECK(charged(s, 3.21, 5.0, 100.0 + brake_charge::stall_time)); + CHECK(s.stalled); + // and stays let go + CHECK(charged(s, 3.2, 5.0, 300.0)); +} + +TEST_CASE("brake charge: a train let go stays let go while its charge rises again as it starts") { + // the train went on a stalled charge; starting, the brakes release and the pipe refills behind them + state s; + REQUIRE_FALSE(charged(s, 4.3, 5.0, 0.0)); + REQUIRE(charged(s, 4.3, 5.0, brake_charge::stall_time)); + CHECK(charged(s, 4.35, 5.0, brake_charge::stall_time + 1.0)); + CHECK(charged(s, 4.4, 5.0, brake_charge::stall_time + 2.0)); + SUBCASE("until the train is to stand again: the next start is checked anew") { + s.going = false; + CHECK_FALSE(charged(s, 4.42, 5.0, brake_charge::stall_time + 3.0)); + CHECK(charged(s, 4.6, 5.0, brake_charge::stall_time + 4.0)); + } +} + +TEST_CASE("brake charge: a train with nothing to charge with yet isn't let go for a stall") { + // prepared from cold: the pipe empty, the engine not started, no air in the main reservoir + state s; + // a look every 5 s for ten times the stall time + auto const looks{static_cast(10.0 * brake_charge::stall_time / 5.0)}; + for (auto i{0}; i < looks; ++i) { + CHECK_FALSE(charged(s, 0.0, 5.0, 5.0 * i, false)); + } + CHECK_FALSE(s.stalled); + CHECK_FALSE(s.going); + // the engine runs, the pipe fills + auto const start{10.0 * brake_charge::stall_time}; + CHECK_FALSE(charged(s, 0.0, 5.0, start, true)); + // the stall time counts from when there was air to charge with + CHECK_FALSE(charged(s, 0.0, 5.0, start + brake_charge::stall_time - 10.0, true)); + CHECK_FALSE(charged(s, 2.0, 5.0, start + brake_charge::stall_time + 10.0, true)); + CHECK(charged(s, 4.6, 5.0, start + brake_charge::stall_time + 60.0, true)); +} + +TEST_CASE("brake charge: a slow but steady charge isn't taken for a stall") { + state s; + auto time{0.0}; + auto level{2.0}; + // 0.03 bar every 50 s: above the gain within the stall time + for (auto i{0}; i < 20; ++i) { + CHECK_FALSE(charged(s, level, 5.0, time)); + level += 0.03; + time += 50.0; + } + CHECK_FALSE(s.stalled); +} + +TEST_CASE("brake charge: a lower working pressure (the reductor turned down) lowers the charge asked for") { + state s; + CHECK(charged(s, 4.35, 4.8, 0.0)); + s = {}; + CHECK_FALSE(charged(s, 4.25, 4.8, 0.0)); +} + +TEST_CASE("brake charge: the locomotive brake holds the train only with the margin over the grade force") { + using brake_charge::locomotive_brake_holds; + // the 752 with about 720 t: 17 kN on -2.4 per mille, 30 kN on -4.3, against about 100 kN of its brake + CHECK(locomotive_brake_holds(100000.0, 17000.0)); + CHECK(locomotive_brake_holds(100000.0, -30000.0)); + CHECK(locomotive_brake_holds(110001.0, 100000.0)); + CHECK_FALSE(locomotive_brake_holds(100000.0, 100000.0)); + CHECK_FALSE(locomotive_brake_holds(0.0, 1000.0)); + CHECK(locomotive_brake_holds(0.0, 0.0)); +} + +TEST_CASE("brake charge: the locomotive brake holds with no more than the wheels pass on to the rails") { + using brake_charge::locomotive_brake_force; + // an ST43 of 116 t: 1031 kN at the brake blocks, 0.25 of its weight on the rails + CHECK(locomotive_brake_force(1031000.0, 116000.0 * 9.81) == doctest::Approx(284490.0)); + // a weak brake stays what it is + CHECK(locomotive_brake_force(50000.0, 116000.0 * 9.81) == doctest::Approx(50000.0)); + CHECK(locomotive_brake_force(0.0, 116000.0 * 9.81) == doctest::Approx(0.0)); + CHECK(locomotive_brake_force(-1.0, 116000.0 * 9.81) == doctest::Approx(0.0)); +} + +TEST_CASE("brake charge: standing not charged, the release of the locomotive brake waits") { + using brake_charge::release_waits; + // the train brake already off: what is left on is the locomotive brake, which holds the train while it charges + CHECK(release_waits(false, true, false)); +} + +TEST_CASE("brake charge: the release doesn't wait once the train is charged, or once it moves") { + using brake_charge::release_waits; + CHECK_FALSE(release_waits(true, true, false)); + // in motion a release is braking control, not a start + CHECK_FALSE(release_waits(false, false, false)); + CHECK_FALSE(release_waits(true, false, false)); +} + +TEST_CASE("brake charge: the train brake may come off while the train charges") { + using brake_charge::release_waits; + // released, the train brake fills the pipe, which is what charges the train + CHECK_FALSE(release_waits(false, true, true)); +} + +TEST_CASE("brake charge: with the train brake applied the train charges to the head of the pipe, not to an empty one") { + using brake_charge::reference; + // released: the working pressure + CHECK(reference(4.7, 5.0, false) == doctest::Approx(5.0)); + // the first service position: what the head of the pipe has + CHECK(reference(4.65, 5.0, true) == doctest::Approx(4.65)); + // a pipe emptied, or just being filled: no lower than a full service application leaves, with the margin a train + // is charged within. an SM42 with 32 wagons at 0.02 bar counted as charged the moment its brake was applied + CHECK(reference(0.02, 5.0, true) == doctest::Approx(4.0)); + state s; + CHECK_FALSE(brake_charge::charged(s, 0.02, reference(0.02, 5.0, true), 0.0)); + // an overcharged pipe doesn't raise it + CHECK(reference(5.4, 5.0, true) == doctest::Approx(5.0)); +} + +TEST_CASE("brake charge: the light application that holds a charging train stays on when the order to go comes") { + using brake_charge::holds_application; + CHECK(holds_application(true, false, true, 1.0)); + CHECK(holds_application(true, false, true, 0.75)); + // charged, or moving: the start releases it + CHECK_FALSE(holds_application(true, true, true, 1.0)); + CHECK_FALSE(holds_application(true, false, false, 1.0)); + // a train the locomotive brake holds has no such application + CHECK_FALSE(holds_application(false, false, true, 1.0)); + // a stronger application comes off down to the first position; a released handle has nothing to hold + CHECK_FALSE(holds_application(true, false, true, 2.0)); + CHECK_FALSE(holds_application(true, false, true, 0.0)); +} diff --git a/tests/unit/test_brake_releaser.cpp b/tests/unit/test_brake_releaser.cpp index 0e32552b3..ce2c9fb20 100644 --- a/tests/unit/test_brake_releaser.cpp +++ b/tests/unit/test_brake_releaser.cpp @@ -112,3 +112,20 @@ TEST_CASE("brake releaser: an overcharged brake pipe turns the releaser off, in uncoupling.pipe_pressure = 5.3; CHECK_FALSE(brake_releaser::decide(uncoupling).actuate); } + +TEST_CASE("brake releaser: a train charging its brakes standing gets an empty pipe filled up before the order to go") { + // a train placed cold, its pipe below the lock of the driver's brake valve, waits for its brakes to charge + // before the first start (#444): the pipe is unlocked as it stands, not only once the driver wants to go + auto state{standing_braked(-0.2)}; + state.pipe_pressure = 1.5; + state.charging_standing = true; + auto const wanted{brake_releaser::decide(state)}; + CHECK(wanted.actuate); + CHECK(wanted.fill_pipe); + + // once the pipe is above the lock the locomotive stays braked: venting it is a rule for the start only + state.pipe_pressure = 3.5; + auto const charging{brake_releaser::decide(state)}; + CHECK_FALSE(charging.actuate); + CHECK_FALSE(charging.fill_pipe); +} diff --git a/tests/unit/test_uphill_start.cpp b/tests/unit/test_uphill_start.cpp new file mode 100644 index 000000000..d450af68b --- /dev/null +++ b/tests/unit/test_uphill_start.cpp @@ -0,0 +1,103 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/uphillstart.h" + +// starting uphill, the train brake is applied further, a step at a time, until the brake of the unpowered vehicles +// holds the train without the locomotive brake (eu07/maszyna#396). the numbers are those of an ST43 with 37 empty +// wagons on 12.5 per mille: 1040 t, 128.6 kN of grade force, the wagons on G with about 22 s to apply + +using uphill_start::brake_top_up; +using uphill_start::top_up; +using uphill_start::top_up_action; + +namespace { + +double const grade{128600.0}; // [N] +double const application{22.0}; // [s] + +// the train standing with the brake handle at Position, held there long enough for the cylinders to fill, while +// each step adds Gain of brake force (as a multiple of the grade force) to the Start it had. runs the top-up until it +// lets the locomotive brake off, and returns the handle position it stopped at and the number of steps +struct outcome { + double position; + int steps; +}; +outcome run_top_up(double Start, double Gain, double Position = 1.25) { + top_up state; + auto force{Start * grade}; + auto steps{0}; + for (auto guard{0}; guard < 100; ++guard) { + auto const action{brake_top_up(state, force, grade, Position, application, application)}; + if (action == top_up_action::none) { + break; + } + REQUIRE(action == top_up_action::step); + Position += 0.25; + force += Gain * grade; + ++steps; + } + return {Position, steps}; +} + +} // namespace + +TEST_CASE("uphill start: a brake that holds the train isn't applied further") { + top_up state; + CHECK(brake_top_up(state, 1.1 * grade, grade, 1.25, application, application) == top_up_action::none); + CHECK(state.last_force < 0.0); +} + +TEST_CASE("uphill start: each step waits the full application time of the brake") { + top_up state; + CHECK(brake_top_up(state, 0.9 * grade, grade, 1.25, 0.5 * application, application) == top_up_action::wait); + CHECK(brake_top_up(state, 0.9 * grade, grade, 1.25, application, application) == top_up_action::step); + // the handle has just moved + CHECK(brake_top_up(state, 0.95 * grade, grade, 1.5, 0.0, application) == top_up_action::wait); + CHECK(brake_top_up(state, 0.95 * grade, grade, 1.5, application - 0.1, application) == top_up_action::wait); +} + +TEST_CASE("uphill start: a light application is topped up until the brake holds the train") { + // before Nowy Zagorz on linia_107_objazdy: 0.64 bar in the wagons, 128 kN against 129 kN + auto const result{run_top_up(0.995, 0.15)}; + CHECK(result.steps == 1); + CHECK(result.position == doctest::Approx(1.5)); +} + +TEST_CASE("uphill start: a brake that doesn't get stronger ends the top-up after one more step") { + // all the wagon brakes cut out: no step adds anything + auto const result{run_top_up(0.0, 0.0)}; + CHECK(result.steps == 1); + CHECK(result.position < uphill_start::top_up_position); +} + +TEST_CASE("uphill start: a brake that gets stronger by too little ends the top-up") { + // a step adds 1% of the grade force, below the 2% that counts + auto const result{run_top_up(0.3, 0.01)}; + CHECK(result.steps == 1); + SUBCASE("and one that gets stronger by enough goes on") { + auto const going{run_top_up(0.3, 0.05)}; + CHECK(going.steps > 1); + } +} + +TEST_CASE("uphill start: the top-up goes no further than full service") { + // every step adds enough to go on, but never enough to hold the train + auto const result{run_top_up(0.0, 0.03)}; + CHECK(result.position == doctest::Approx(uphill_start::top_up_position)); + CHECK(result.steps == 11); + top_up state; + CHECK(brake_top_up(state, 0.0, grade, uphill_start::top_up_position, application, application) == top_up_action::none); +} + +TEST_CASE("uphill start: once ended, the top-up stays ended for the start") { + top_up state; + REQUIRE(brake_top_up(state, 0.2 * grade, grade, 1.25, application, application) == top_up_action::step); + REQUIRE(brake_top_up(state, 0.2 * grade, grade, 1.5, application, application) == top_up_action::none); + CHECK(state.done); + // the brake gets stronger later all the same: the start has gone on without the top-up + CHECK(brake_top_up(state, 0.5 * grade, grade, 1.5, application, application) == top_up_action::none); + // a new start begins with a new top-up + state = {}; + CHECK(brake_top_up(state, 0.5 * grade, grade, 1.5, application, application) == top_up_action::step); +} diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 3ac6b8f99..9a313dc61 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -1848,6 +1848,12 @@ global_settings::ConfigParse_gfx( cParser &Parser, std::string_view const Token Parser >> gfx_shadow_rank_cutoff; gfx_shadow_rank_cutoff = std::clamp(gfx_shadow_rank_cutoff, 1, 3); } + else if (Token == "gfx.headlights.beamwidth") + { + Parser.getTokens(1); + Parser >> gfx_headlights_beamwidth; + gfx_headlights_beamwidth = std::clamp(gfx_headlights_beamwidth, 1.f, 4.f); + } else { tokenparsed = false; @@ -2137,6 +2143,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "gfx.shadergamma", gfx_shadergamma ); export_as_text( Output, "gfx.shadow.angle.min", gfx_shadow_angle_min ); export_as_text( Output, "gfx.shadow.rank.cutoff", gfx_shadow_rank_cutoff ); + export_as_text( Output, "gfx.headlights.beamwidth", gfx_headlights_beamwidth ); export_as_text( Output, "python.enabled", python_enabled ); export_as_text( Output, "python.threadedupload", python_threadedupload ); export_as_text( Output, "python.uploadmain", python_uploadmain ); diff --git a/utilities/Globals.h b/utilities/Globals.h index a5c0bad67..07c04cb14 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -398,6 +398,9 @@ struct global_settings { float gfx_distance_factor_max { 3.f }; float gfx_shadow_angle_min { -0.2f }; int gfx_shadow_rank_cutoff { 3 }; + // how many times wider sideways the headlight beam is spread than its texture: at 1.7 the ground beside the track gets + // most of the light of the ballast; 1 draws the narrow beam of 26.05 + float gfx_headlights_beamwidth { 1.7f }; float ui_fontsize = 13.0f; float ui_scale = 1.0f; diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index a8477a061..84abd1b97 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -3344,9 +3344,13 @@ bool TController::PrepareEngine() } } // set up train brake - if( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_RP ) ) { - if ( !mvOccupied->Handle->Time - || mvOccupied->Handle->GetCP() < mvOccupied->HighPipePress - 0.05 ); + if( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) { + // standing: the locomotive brake first, then the pipe is filled + secure_standing_train(); + } + else if( ( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_RP ) ) + && ( ( false == mvOccupied->Handle->Time ) + || ( mvOccupied->Handle->GetCP() < mvOccupied->HighPipePress - 0.05 ) ) ) { cue_action( driver_hint::trainbrakerelease ); } // sync spring brake state across consist @@ -3799,7 +3803,7 @@ bool TController::DecBrake() { // a position short of the first one brakes no weaker than that deltaAcc = -AccDesired * BrakeAccFactor() - ( fBrake_a0[ 0 ] + 4 * std::max( 0.0, BrakeCtrlPosition - pos_diff ) * fBrake_a1[ 0 ] ); } - if( bUphillStart ) { + if( bUphillStart && ( false == bUphillRelease ) ) { // starting uphill the train brake holds the train until the power does break; } @@ -3808,6 +3812,13 @@ bool TController::DecBrake() { // any release now raises the pipe, and a long train releases more than the handle is moved back, too late // to apply again before the train stands: keep the brake as it is, and the locomotive brake with it break; + } + if( brake_charge::holds_application( + bBrakeChargeHold, IsConsistCharged, mvOccupied->Vel < EU07_AI_NOMOVEMENT, BrakeCtrlPosition ) ) { + // the order to go came while the train still charges: released now, the wagons let go as their + // reservoirs fill and the train stands on a locomotive brake that doesn't hold it. the locomotive + // brake stays on with it + break; } if (deltaAcc < 0 && /*GBH mvOccupied->BrakeCtrlPosR*/ BrakeCtrlPosition > 0) { OK = /*mvOccupied->*/ BrakeLevelAdd(-0.25); @@ -3817,10 +3828,16 @@ bool TController::DecBrake() { if (BrakeCtrlPosition < 0.74) /*mvOccupied->*/ BrakeLevelSet(gbh_RP); } - if( !OK ) { + // standing, the locomotive brake holds the train until its brakes are charged: off before, a train + // released on a gradient rolls with no air to brake with. nor through DecBrakeEIM(), which takes it off + // as well (the locomotive brake of a vehicle without the integrated handle) + auto const holdlocomotive { + ( false == IsConsistCharged ) + && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) }; + if( ( !OK ) && ( false == holdlocomotive ) ) { OK = mvOccupied->DecLocalBrakeLevel(2); } - if( !OK ) { + if( ( !OK ) && ( false == holdlocomotive ) ) { OK = DecBrakeEIM(); } /* @@ -6614,24 +6631,41 @@ TController::determine_consist_state() { ConsistShade = 0.0; auto *p { pVehicles[ end::front ] }; // pojazd na czole składu double dy; // składowa styczna grawitacji, w przedziale <0,1> + // starting uphill the power is applied against the train brake on purpose, until the power holds the train and + // then while the brake releases + auto const heldforstart { bUphillStart }; + auto released { true }; // the brakes are off, the hold of an uphill start not counted + auto mostapplied { 0.0 }; // the most applied brake, the hold of an uphill start not counted + auto momentum { 0.0 }; + auto chargelevel { std::numeric_limits::max() }; // the lowest pipe or auxiliary reservoir pressure of a working brake while (p) { // sprawdzenie odhamowania wszystkich połączonych pojazdów auto *vehicle { p->MoverParameters }; auto const bp { std::max( 0.0, vehicle->BrakePress - ( vehicle->SpeedCtrlUnit.Parking ? vehicle->MaxBrakePress[ 0 ] * vehicle->StopBrakeDecc : 0.0 ) ) }; - // starting uphill the power is applied against the train brake on purpose, until the power holds the train - auto const heldforstart { bUphillStart }; - if (Ready) { + momentum += vehicle->TotalMass * vehicle->V * ( p->DirectionGet() == iDirection ? 1 : -1 ); + mostapplied = std::max( bp, mostapplied ); + if( ( vehicle->BrakeSystem != TBrakeSystem::Individual ) + && ( vehicle->MaxBrakePress[ 3 ] > 0.0 ) + && ( false == TestFlag( vehicle->Hamulec->GetBrakeStatus(), b_dmg ) ) ) { // a brake cut out doesn't count + chargelevel = std::min( { chargelevel, vehicle->PipePress, vehicle->Hamulec->GetBRP() } ); + } + auto const wasready { Ready }; + if( released || Ready ) { // bo jak coś nie odhamowane, to dalej nie ma co sprawdzać - if( auto const isbraking { TestFlagAny( vehicle->Hamulec->GetBrakeStatus(), b_hld | b_on ) }; - vehicle->Vel < 1.0 ? + auto const isbraking { TestFlagAny( vehicle->Hamulec->GetBrakeStatus(), b_hld | b_on ) }; + if( vehicle->Vel < 1.0 ? isbraking || bp > 0.4 : // ensure the brakes are sufficiently released when starting to move // once in motion a brake down to 0.4 bar counts as released (UIC), even if its distributor // is still in the lap position while the brake pipe recharges ( isbraking && bp > 0.4 ) || vehicle->Fb > 10000.0 ) { // 10 kN - // ready all the same only at a standstill with the power going on against the brake on purpose; - // in motion a braking force left anywhere in the train (a hand brake) stops it as before - Ready = heldforstart && ( vehicle->Vel < 1.0 ); + released = false; + // ready all the same with the power going on against the brake on purpose: at a standstill, and once + // the power holds the train, while the brake releases; otherwise in motion a braking force left + // anywhere in the train (a hand brake) stops it as before + Ready = Ready && heldforstart && ( bUphillRelease || ( vehicle->Vel < 1.0 ) ); } + } + if( wasready ) { // Ra: odluźnianie przeładowanych lokomotyw, ciągniętych na zimno - prowizorka... if( bp >= 0.4 && (AIControllFlag || Global.AITrainman && mvOccupied->Vel < EU07_AI_NOMOVEMENT && !is_emu() && !is_dmu()) && BrakeCtrlPosition == gbh_RP // jest pozycja jazdy && false == TestFlag(vehicle->Hamulec->GetBrakeStatus(), b_dmg) // brake isn't broken @@ -6648,7 +6682,8 @@ TController::determine_consist_state() { vehicle->BrakeReleaser(0); } } - fReady = std::max( heldforstart ? 0.0 : bp, fReady ); // szukanie najbardziej zahamowanego + // the brake held for the start counts again once it is being released + fReady = std::max( ( heldforstart && ( false == bUphillRelease ) ) ? 0.0 : bp, fReady ); // szukanie najbardziej zahamowanego if( ( dy = p->VectorFront().y ) != 0.0 ) { // istotne tylko dla pojazdów na pochyleniu // ciężar razy składowa styczna grawitacji @@ -6744,6 +6779,73 @@ TController::determine_consist_state() { && fReady < 0.8 ) { // delikatniejszy warunek, obejmuje wszystkie wagony Ready = true; //żeby uznać za odhamowany } + // the same test without the hold of an uphill start + IsConsistReleased = released || ( fAccGravity < -0.05 && mostapplied < 0.8 ); + // the frame of the vehicle the AI drives from, as for fAccGravity and AbsAccS + fConsistVelocity = 3.6 * momentum / std::max( 1.0, fMass ) * ( iDirection >= 0 ? 1 : -1 ); + // standing, the train starts only with its brakes charged: released alone, a train prepared from cold has no air to + // brake with while its auxiliary reservoirs fill. with the train brake applied (held for an uphill start, a light + // application while charging) they charge to what the head of the pipe has. + // only the start the charge is in question for: the first after the train was prepared standing, or one with the + // pipe near empty (after an emergency application, brake_charge::empty_level). after an ordinary stop the + // reservoirs refill as the brake releases, and waiting for the last tenths of a bar there only delays the train and + // those behind it. + // and only the pneumatic brake: multiple units with the electro-pneumatic one start as before + if( mvOccupied->Vel > 1.0 ) { + // the start is made. a shunting engine coupling wagons moves at a walking pace: a higher speed would leave its + // every start the first, waiting for each cut of wagons placed cold to charge + bBrakeChargeStart = false; + bBrakeChargeHold = false; + bHasRun = true; + } + auto const chargeable { + ( BrakeSystem == TBrakeSystem::Pneumatic ) + && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) + && ( chargelevel < std::numeric_limits::max() ) }; + if( chargeable && ( chargelevel < brake_charge::empty_level ) ) { + bBrakeChargeStart = true; + } + if( chargeable && bBrakeChargeStart ) { + if( ( VelDesired <= 0.0 ) || ( AccDesired <= EU07_AI_NOACCELERATION ) ) { + // to stand: the next start is checked anew + BrakeCharge.going = false; + } + auto const trainbrakeapplied { + AIControllFlag ? + BrakeCtrlPosition > 0.0 : + // a human driver's handle, which BrakeCtrlPosition doesn't follow + mvOccupied->fBrakeCtrlPos > mvOccupied->Handle->GetPos( bh_RP ) + 0.2 }; + auto const reference { + brake_charge::reference( mvOccupied->PipePress, std::min( mvOccupied->Handle->GetRP(), 5.0 ), trainbrakeapplied ) }; + // air to charge with: the engine prepared, the main reservoir above what the pipe charges to, and the driver's + // brake valve feeding the pipe at the head of the train. a train still being prepared from cold can't charge, + // nor one whose pipe is locked (unlocked by control_releaser()): it waits without that counting as a stall, held + // by its brakes as it can't release them either + auto const supplied { + iEngineActive + && ( std::max( mvControlling->Compressor, mvOccupied->Compressor ) > reference ) + && ( mvOccupied->PipePress >= reference - brake_charge::margin ) }; + auto const wasstalled { BrakeCharge.stalled }; + IsConsistCharged = brake_charge::charged( BrakeCharge, chargelevel, reference, ElapsedTime, supplied ); + if( BrakeCharge.stalled && ( false == wasstalled ) ) { + WriteLog( + "AI: " + mvOccupied->Name + " stopped charging its brakes at " + to_string( chargelevel, 2 ) + + " bar of " + to_string( reference, 2 ) + ", starting all the same" ); + } + if( false == IsConsistCharged ) { + // a human driver is told to wait as the ai does, the locomotive brake applied + cue_action( driver_hint::waitbrakecharge ); + } + } + else { + IsConsistCharged = true; + BrakeCharge = {}; + } + if( AIControllFlag + && ( false == IsConsistCharged ) + && ( false == heldforstart ) ) { + Ready = false; + } auto const departblocked { AIControllFlag && mvOccupied->Vel < EU07_AI_NOMOVEMENT @@ -8830,6 +8932,12 @@ void TController::control_tractive_force() { if( AccDesired > EU07_AI_NOACCELERATION // don't add power if not asked for actual speed-up && (AbsAccS < AccDesired /*- std::min( 0.05, 0.01 * iDriverFailCount )*/ || mvOccupied->SpeedCtrlUnit.IsActive && velocity < mvOccupied->SpeedCtrlUnit.FullPowerVelocity) && false == TestFlag(iDrivigFlags, movePress) && + // starting uphill against the releasing brake, the power that holds the train is enough: the brake coming off + // speeds the train up, more power only drags the brake and slips the wheels. nor is a notch past that taken + // back: the power got there in one notch from below, and the notch below doesn't hold the train + ( false == bUphillRelease || fUphillTractiveForce < uphill_start::holding_force * fUphillHoldingForce ) && + // nor while the train brake is still being applied further to hold the train + false == bUphillBrakeTopUp && velocity < (VelDesired == 1.0 ? // work around for trains getting stuck on tracks with speed limit = 1 VelDesired : VelDesired - fVelMinus) && @@ -8886,15 +8994,20 @@ void TController::control_uphill_start() { && ( false == is_emu() ) && ( false == is_dmu() ) // a multiple unit has no locomotive to hold a train behind it && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) }; false == uphill ) { - bUphillStart = false; + end_uphill_start(); return; } if( false == bUphillStart ) { if( ( std::abs( velocity ) < EU07_AI_NOMOVEMENT ) + // the whole train at a stand, not only its head stopped for a moment while the train rolls back + && ( fConsistVelocity > -0.5 ) && ( AccDesired > EU07_AI_NOACCELERATION ) && ( VelDesired > 0.0 ) - && ( BrakeCtrlPosition > 0.0 ) ) { // only with the train brake still applied to hold the train + && ( BrakeCtrlPosition > 0.0 ) // only with the train brake still applied to hold the train + && ( IsConsistCharged ) ) { // and charged to what the pipe has, or the brake that holds the train has no air bUphillStart = true; + bUphillRelease = false; + UphillTopUp = {}; fUphillStartTime = ElapsedTime; } else { @@ -8903,31 +9016,135 @@ void TController::control_uphill_start() { } if( AccDesired <= EU07_AI_NOACCELERATION ) { // no longer to start: the standing rules take over - bUphillStart = false; + end_uphill_start(); return; } - if( velocity < -0.5 ) { - // rolling back all the same: the rules for a train slipping back take over and apply the brakes - bUphillStart = false; + if( fConsistVelocity < -0.5 ) { + // the train rolls back all the same: the rules for a train slipping back take over and apply the brakes. + // the train as a whole, not its head: with the locomotive brake off, the locomotive and the first vehicles + // run back into the slack of a long train still held by its brake + end_uphill_start(); return; } - if( ( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) - && ( mvOccupied->LocalBrakePosA > 0.0 ) ) { - cue_action( driver_hint::independentbrakerelease ); - } - auto tractiveforce { 0.0 }; + fUphillTractiveForce = 0.0; for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { - // Ft is signed in the vehicle's own frame - tractiveforce += std::max( 0.0, vehicle->MoverParameters->Ft * ( vehicle->DirectionGet() == iDirection ? 1 : -1 ) ); + // Ft is signed in the vehicle's own frame, and turned into the direction of travel as AbsAccS is + fUphillTractiveForce += std::max( 0.0, vehicle->MoverParameters->Ft * ( vehicle->DirectionGet() == iDirection ? 1 : -1 ) * ( iDirection >= 0 ? 1 : -1 ) ); } - auto const holdingforce { fMass * -fAccGravity }; - if( ( velocity > 1.0 ) - || ( tractiveforce > 1.1 * holdingforce ) - // a locomotive that can't hold the train on its own power gets the brake off in the end all the same - || ( ElapsedTime - fUphillStartTime > 45.0 ) ) { - // the power holds the train: the train brake can be released - bUphillStart = false; + fUphillHoldingForce = fMass * -fAccGravity; + bUphillBrakeTopUp = false; + if( false == bUphillRelease ) { + bUphillBrakeTopUp = uphill_brake_top_up(); + if( bUphillBrakeTopUp ) { + return; + } + if( ( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) + && ( mvOccupied->LocalBrakePosA > 0.0 ) ) { + cue_action( driver_hint::independentbrakerelease ); + } + if( ( velocity > 1.0 ) + || ( fUphillTractiveForce > uphill_start::holding_force * fUphillHoldingForce ) + // a locomotive that can't hold the train on its own power gets the brake off in the end all the same + || ( ElapsedTime - fUphillStartTime > 45.0 ) ) { + // the power holds the train: the train brake can be released + bUphillRelease = true; + fUphillReleaseTime = ElapsedTime; + } + return; } + // the train brake is being released with the power on. the start ends once the brakes are off: ended before, + // the brake still on takes the power off, the train rolls back and has to be braked to a stand again + if( IsConsistReleased + // a brake that doesn't come off (a hand brake) ends it all the same + || ( ElapsedTime - fUphillReleaseTime > EU07_AI_UPHILLRELEASETIME ) ) { + end_uphill_start(); + } +} + +// the locomotive brake comes off only once the brake of the rest of the train holds the train on its own: a train +// stopped on a light application stands on the locomotive brake too, and rolls back as soon as it is off. until then +// the train brake is applied further, a step at a time; true while it is +bool TController::uphill_brake_top_up() { + + auto trainbrakeforce { 0.0 }; + auto haswagons { false }; + for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { + if( vehicle->MoverParameters->Power < 0.01 ) { + trainbrakeforce += vehicle->MoverParameters->Fb; + haswagons = true; + } + } + if( false == haswagons ) { + return false; + } + auto const action { uphill_start::brake_top_up( + UphillTopUp, trainbrakeforce, fUphillHoldingForce, BrakeCtrlPosition, fBrakeHeldTime, + mvOccupied->BrakeDelay[ mvOccupied->BrakeDelayFlag > bdelay_G ? 1 : 3 ] ) }; + if( action == uphill_start::top_up_action::none ) { + return false; + } + // the time for the power to hold the train starts once the brake does + fUphillStartTime = ElapsedTime; + if( action == uphill_start::top_up_action::step ) { + BrakeLevelAdd( BrakingLevelIncrease ); + } + return true; +} + +void TController::end_uphill_start() { + + bUphillStart = false; + bUphillRelease = false; + bUphillBrakeTopUp = false; +} + +// standing, a train is prepared as a driver does it: the locomotive brake first, then the brake pipe is filled. the pipe +// filled at once releases the distributors while the auxiliary reservoirs are still empty: the train has no brake left, +// and on a gradient rolls away as it releases. where the locomotive brake alone doesn't hold the train, the train brake +// is applied lightly, so the reservoirs charge with the train held. the locomotive brake comes off only once the train +// is charged and to start (DecBrake()) +void TController::secure_standing_train() { + + if( BrakeSystem != TBrakeSystem::Pneumatic ) { + // the electro-pneumatic brake of a multiple unit is released as before: nothing there takes the locomotive + // brake off again when the unit starts + cue_action( driver_hint::trainbrakerelease ); + return; + } + // the first start of a train that hasn't run yet waits for the brakes to charge. one that has run, prepared again + // (a change of direction, an engine started anew), has its reservoirs charged from the run and starts as before + if( false == bHasRun ) { + bBrakeChargeStart = true; + } + if( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) { + cue_action( driver_hint::independentbrakeapply ); + } + if( false == brake_charge::locomotive_brake_holds( locomotive_brake_force(), fMass * fAccGravity ) ) { + // the first service position: the pipe and the reservoirs charge to a little below the working pressure, the + // distributors keep a light application. a stronger application already there is left as it is, but not + // the emergency one or an empty pipe's, which don't charge + if( AIControllFlag + && ( ( BrakeCtrlPosition < 1.0 ) || ( BrakeCtrlPosition > uphill_start::top_up_position ) ) ) { + BrakeLevelSet( 1.0 ); + } + bBrakeChargeHold = true; + return; + } + bBrakeChargeHold = false; + cue_action( driver_hint::trainbrakerelease ); +} + +// the brake force of the locomotive brake at full application [N]. of the occupied vehicle alone: its handle acts on +// no other, not on a second section or a locomotive in multiple control either, let alone one hauled dead +double TController::locomotive_brake_force() const { + + if( ( mvOccupied->LocalBrake == TLocalBrake::ManualBrake ) + || ( mvOccupied->MaxBrakePress[ 0 ] <= 0.0 ) ) { + return 0.0; + } + return brake_charge::locomotive_brake_force( + mvOccupied->BrakeForceP( mvOccupied->MaxBrakePress[ 0 ], 0.0 ), + mvOccupied->TotalMassxg ); } void TController::increase_tractive_force() { @@ -9001,10 +9218,17 @@ void TController::control_braking_force() { if( TestFlag( iDrivigFlags, movePress ) ) { return; } auto const velocity { DirectionalVel() }; + // a train slipping back uphill is braked, also when it is to go on: released now it only rolls back further. + // its head, or the train as a whole: the locomotive may stop for a moment while the rest of the train runs into it + auto const slippingbackuphill { + ( fAccGravity < -0.05 ) + && ( std::min( velocity, fConsistVelocity ) < -0.1 ) + && ( false == bUphillStart ) }; // jeśli przyspieszamy, to nie hamujemy if( AccDesired > 0.0 && OrderCurrentGet() != Disconnect // przy odłączaniu nie zwalniamy tu hamulca - && false == TestFlag(iDrivigFlags, movePress) ) { + && false == TestFlag(iDrivigFlags, movePress) + && false == slippingbackuphill ) { cue_action(driver_hint::brakingforcesetzero); } @@ -9059,7 +9283,7 @@ void TController::control_braking_force() { else { // a stara wersja w miarę dobrze działa na składy wagonowe if( (accdesiredresultant < fAccGravity - 0.1 && AbsAccS > accdesiredresultant + brake_increase_margin() // regular braking - || fAccGravity < -0.05 && velocity < -0.1 && false == bUphillStart) && // also brake if uphill and slipping back + || slippingbackuphill) && // also brake if uphill and slipping back (fBrakeTime < 0.0 // the size of the brake demand decides whether to skip the reaction time, so the brake-only part // (on a descent a heavy train needs its brake built up at once, the gravity does not help it slow) @@ -9085,7 +9309,14 @@ void TController::control_braking_force() { } if ( (accdesiredresultant < fAccGravity - 0.05 || AccDesired >= EU07_AI_NOACCELERATION) // no braking asked for, yet the train is slowing down more than that - && accdesiredresultant - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 && OrderCurrentGet() != Disconnect && VelDesired > 0.0 ) { + && accdesiredresultant - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 && OrderCurrentGet() != Disconnect && VelDesired > 0.0 + // a human driver standing with the train not charged yet keeps the locomotive brake on, told so by the + // waitbrakecharge hint; the ai is held back in DecBrake() + && ( AIControllFlag + || ( false == brake_charge::release_waits( + IsConsistCharged, + mvOccupied->Vel < EU07_AI_NOMOVEMENT, + mvOccupied->fBrakeCtrlPos > mvOccupied->Handle->GetPos( bh_RP ) + 0.2 ) ) ) ) { // the human driver's handle // jak hamuje, to nie tykaj kranu za często // yB: luzuje hamulec dopiero przy różnicy opóźnień rzędu 0.2 // przy odłączaniu nie zwalniamy tu hamulca @@ -9169,6 +9400,14 @@ void TController::control_releaser() { // stage 3 of uncoupling (UpdateDisconnect), from the direction change until the coupler lets go state.compressing_buffers = state.pressing && ( OrderCurrentGet() & Disconnect ) != 0 && iVehicleCount >= 0 && iDirection == iDirectionOrder; + // a train prepared standing charges its brakes before its first start. a pipe left below the lock of the driver's + // brake valve (a train placed cold, as after an emergency application) is unlocked as the train stands, not only + // once it is to go: else it charges only after the order to go, and starts on what the reservoirs got by then. + // a handle which has to be moved to unlock is left where it holds the train with the train brake + state.charging_standing = + bBrakeChargeStart + && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) + && ( ( mvOccupied->HandleUnlock == -3 ) || ( BrakeCtrlPosition <= 0.0 ) ); auto const wanted { brake_releaser::decide( state ) }; auto const actuate { wanted.actuate }; auto isbrakehandleinrightposition { true }; @@ -9198,7 +9437,9 @@ void TController::control_releaser() { void TController::control_main_pipe() { // unlocking main pipe - if( AccDesired > -0.03 + if( ( AccDesired > -0.03 + // standing to charge before the first start, as in control_releaser() + || ( bBrakeChargeStart && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) ) ) && true == mvOccupied->LockPipe ) { UniversalBrakeButtons |= TUniversalBrake::ub_UnlockPipe; } @@ -9230,9 +9471,12 @@ void TController::control_main_pipe() { update_brake_charging(); - if( mvOccupied->Compressor < 5.0 - || ( BrakeCtrlPosition < gbh_RP - && ( mvOccupied->EqvtPipePress > (fReady < 0.25 ? 5.1 : 5.2) || is_brake_charging_done() ) ) ) { + if( ( mvOccupied->Compressor < 5.0 + || ( BrakeCtrlPosition < gbh_RP + && ( mvOccupied->EqvtPipePress > (fReady < 0.25 ? 5.1 : 5.2) || is_brake_charging_done() ) ) ) + // the light application a charging train stands on stays, as in DecBrake() + && ( false == brake_charge::holds_application( + bBrakeChargeHold, IsConsistCharged, mvOccupied->Vel < EU07_AI_NOMOVEMENT, BrakeCtrlPosition ) ) ) { cue_action( driver_hint::trainbrakerelease ); } } diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 866c913b6..0eae2caf1 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -19,6 +19,8 @@ http://mozilla.org/MPL/2.0/. #include "world/mtable.h" #include "utilities/translation.h" #include "application/driverhints.h" +#include "vehicle/uphillstart.h" +#include "vehicle/brakecharge.h" #include "vehicle/blackbox.h" #include "vehicle/aipower.h" @@ -28,6 +30,7 @@ auto const EU07_AI_BRAKINGTESTACCELERATION = -0.06; auto const EU07_AI_NOMOVEMENT = 0.05; // standstill velocity threshold auto const EU07_AI_MOVEMENT = 1.0; // deliberate movement velocity threshold auto const EU07_AI_UPHILLGRAVITY = -0.025; // [m/s2] about 2.5 per mille up: the gradient that rolls a standing train back +auto const EU07_AI_UPHILLRELEASETIME = 60.0; // [s] the longest an uphill start keeps the power on while the train brake releases auto const EU07_AI_SPEEDLIMITEXTENDSBEYONDSCANRANGE = 10000.0; auto const EU07_AI_SANDEDSTARTVELOCITY = 15.0; // [km/h] a start that slipped keeps the sand on up to this speed @@ -340,6 +343,10 @@ private: bool uphill_stop_hold() const; bool uphill_brake_committed( double const Velocity ) const; void control_uphill_start(); + void end_uphill_start(); + bool uphill_brake_top_up(); + void secure_standing_train(); + double locomotive_brake_force() const; std::pair train_proximity_margins( bool const Passengerstop ) const; void update_timers( double const dt ); @@ -447,6 +454,21 @@ private: bool bSandedStart = false; // the wheels slipped while starting: sand while under power until the train is under way double fSandedStartDecreaseTime = -1.0; // when the power was last taken down a step for a slip while starting double fUphillStartTime = 0.0; // when the uphill start began + bool bUphillRelease = false; // starting uphill, the power holds the train and the train brake is being released + bool bUphillBrakeTopUp = false; // starting uphill, the train brake is applied further before the locomotive brake comes off + uphill_start::top_up UphillTopUp; // starting uphill, what has been done to apply the train brake further + double fUphillReleaseTime = 0.0; // when the release began + double fUphillTractiveForce = 0.0; // the tractive force of the consist while starting uphill [N] + double fUphillHoldingForce = 0.0; // the grade force on the consist while starting uphill [N] + bool IsConsistReleased = true; // the brakes of the consist are off, the hold of an uphill start not counted + bool IsConsistCharged = true; // standing, the brake pipe and the auxiliary reservoirs are charged to start (or stopped charging) + brake_charge::state BrakeCharge; // standing, how the charge of the brakes rose + // the next start waits for the brakes to charge: the first after the train was prepared standing, or one with the + // pipe near empty. cleared once the train runs + bool bBrakeChargeStart = false; + bool bHasRun = false; // the train has moved (above 1 km/h) since it was placed + bool bBrakeChargeHold = false; // charging, the train stands on a light application of the train brake as well + double fConsistVelocity = 0.0; // the mass-weighted speed of the consist, positive in the direction of travel [km/h] double fAccDesiredGravity = 0.0; // część AccDesired odjęta na spadku jako kompensacja pochylenia; AbsAccS zawiera ją już sam double VelforDriver = -1.0; // prędkość, używana przy zmianie kierunku (ograniczenie przy nieznajmości szlaku?) double VelSignal = 0.0; // ograniczenie prędkości z kompilacji znaków i sygnałów // normalnie na początku ma stać, no chyba że jedzie diff --git a/vehicle/brakecharge.cpp b/vehicle/brakecharge.cpp new file mode 100644 index 000000000..18668987d --- /dev/null +++ b/vehicle/brakecharge.cpp @@ -0,0 +1,65 @@ +/* +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/brakecharge.h" + +namespace brake_charge { + +bool charged(state &State, double const Level, double const Reference, double const Time, bool const Supplied) { + + if (State.going) { + return true; + } + if (Level >= Reference - margin) { + State = {}; + State.going = true; + return true; + } + if ((State.best < 0.0) || (Level > State.best + stall_gain) || (false == Supplied)) { + // still charging, or nothing to charge with yet: the time for a stall counts from when there is + State.best = Level; + State.best_time = Time; + State.stalled = false; + return false; + } + State.stalled = (Time - State.best_time >= stall_time); + State.going = State.stalled; + return State.stalled; +} + +double locomotive_brake_force(double const Blockforce, double const Weight) { + + return std::max(0.0, std::min(Blockforce, Weight * adhesion)); +} + +bool locomotive_brake_holds(double const Locomotivebrakeforce, double const Gradeforce) { + + return Locomotivebrakeforce >= holding_force * std::abs(Gradeforce); +} + +double reference(double const Headpipe, double const Working, bool const Trainbrakeapplied) { + + if (false == Trainbrakeapplied) { + return Working; + } + return std::clamp(Headpipe, Working - service_drop + margin, Working); +} + +bool holds_application(bool const Hold, bool const Charged, bool const Standing, double const Position) { + + return Hold && (false == Charged) && Standing && (Position > 0.0) && (Position <= 1.0); +} + +bool release_waits(bool const Charged, bool const Standing, bool const Trainbrakeapplied) { + + return (false == Charged) && Standing && (false == Trainbrakeapplied); +} + +} // namespace brake_charge diff --git a/vehicle/brakecharge.h b/vehicle/brakecharge.h new file mode 100644 index 000000000..f283dade9 --- /dev/null +++ b/vehicle/brakecharge.h @@ -0,0 +1,76 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +// a standing train starts only with its brakes charged, as a driver checks before setting off: the brake pipe and the +// auxiliary reservoir of every vehicle with a working brake close to the working pressure. released alone isn't enough: +// a train prepared from cold is released at once, its pipe still filling, and has no air to brake with +// (TController::PrepareEngine(), TController::determine_consist_state()) +namespace brake_charge { + +// [bar] below the working pressure the pipe and the reservoir count as charged: 4.5 of 5.0. the last wagon of a long +// train stays at about 4.6-4.7 for good, from what leaks along the pipe +auto const margin{0.5}; +// below this the pipe counts as near empty (after an emergency application): the next start waits for the charge +// whatever came before. well below what a service application leaves: the AI stops at a station with the handle past +// the full service position, the pipe at 3.0-3.5 bar, and wagons coupled from cold come with about 3 bar. waiting there +// only delays the train, and the scenery sets the routes of the others later (calkowo_v2_osoba_jar_poranek, l053_poranek) +auto const empty_level{2.5}; // [bar] +// a charge that rises by less than this in stall_time has stopped (a leak, a hose not connected, a pipe cock shut): the +// train goes all the same, rather than stand for good +auto const stall_gain{0.02}; // [bar] +auto const stall_time{60.0}; // [s] +// standing, the locomotive brake alone has to give this multiple of the grade force to hold the train while it charges +auto const holding_force{1.1}; +// the share of a locomotive's weight its brake can hold the train with at most: what the wheels pass on to the rails, +// taken low (a wet rail). the force of the brake blocks alone is several times that +auto const adhesion{0.25}; +// [bar] how far below the working pressure the pipe is at a full service application: with the train brake applied the +// train charges to what the head of the pipe has, but a pipe below this (emptied, or just being filled) is no charge +auto const service_drop{1.5}; + +struct state { + double best{-1.0}; // the highest charge seen while it still rose [bar], -1 before the first look + double best_time{0.0}; // when it was seen [s] + bool stalled{false}; // the charge stopped rising short of charged + // the train was let go: it stays so until the driver clears this, when the train is to stand again. otherwise a + // charge rising again as the train starts (the pipe refilling behind the release) would stop it at a crawl + bool going{false}; +}; + +// Level: the lowest pressure of the brake pipes and auxiliary reservoirs among the vehicles with a working brake [bar]; +// Reference: the pressure they charge to [bar]; Time: now [s]; Supplied: there is air to charge with (the engine +// prepared, the main reservoir above the reference): without it the charge can't rise, and that isn't a stall. +// true once the train may start, and from then on +bool charged(state &State, double Level, double Reference, double Time, bool Supplied = true); + +// what the locomotive brake of a vehicle holds with at full application [N]: the force of its brake blocks (Blockforce), +// but no more than its wheels pass on to the rails, the adhesion share of its Weight [N] +double locomotive_brake_force(double Blockforce, double Weight); + +// whether the locomotive brake, Locomotivebrakeforce at full application [N], holds the standing train against its +// Gradeforce [N] on its own; when it doesn't, the train brake is applied lightly while the train charges +bool locomotive_brake_holds(double Locomotivebrakeforce, double Gradeforce); + +// the pressure the train is to be charged to [bar]: the working pressure with the train brake released; with it applied +// what the head of the pipe has (Headpipe), as the reservoirs get no more, though no less than a full service +// application leaves, or a pipe emptied by an emergency application would count as charged at once +double reference(double Headpipe, double Working, bool Trainbrakeapplied); + +// whether a light application of the train brake (Position, up to the first service position) stays on: the train +// stands on it while it charges (Hold), the locomotive brake not holding it alone +bool holds_application(bool Hold, bool Charged, bool Standing, double Position); + +// whether a release of the brakes waits for the charge: standing, a train not charged yet keeps its locomotive brake +// on. the train brake (Trainbrakeapplied) may come off all the same: released, it fills the pipe, which is what charges +// the train. the hint a human driver gets to release the brakes waits with it (driver_hint::waitbrakecharge instead) +bool release_waits(bool Charged, bool Standing, bool Trainbrakeapplied); + +} // namespace brake_charge diff --git a/vehicle/brakereleaser.cpp b/vehicle/brakereleaser.cpp index 0a51c9a62..e9c189bb2 100644 --- a/vehicle/brakereleaser.cpp +++ b/vehicle/brakereleaser.cpp @@ -43,6 +43,11 @@ decision decide(conditions const &State) { result.fill_pipe = State.pipe_pressure < 3.0; result.actuate = wanted_to_start(State); } + else if (State.charging_standing) { + // a train placed cold charges its brakes standing: only the pipe is filled up, the other rules are for a start + result.fill_pipe = State.pipe_pressure < 3.0; + result.actuate = result.fill_pipe; + } // uncoupling, stage 3: the locomotive has to push the slack of the coupler out whatever its speed table says. // the consist stays held by its own brakes, applied in stage 2, and the push asks for 2 km/h at most. a signal // at stop that the consist stands across after the direction change caps the speed at 0 and so AccDesired diff --git a/vehicle/brakereleaser.h b/vehicle/brakereleaser.h index 62bc2e7c1..e4ba14ad6 100644 --- a/vehicle/brakereleaser.h +++ b/vehicle/brakereleaser.h @@ -24,6 +24,9 @@ struct conditions { bool uphill_start{false}; // starting uphill with the train brake held on purpose bool pressing{false}; // (un)coupling: the driver presses the buffers (movePress) bool compressing_buffers{false}; // uncoupling, stage 3: pushing towards the cut to slacken the coupler + // standing, the train charges its brakes before its first start (bBrakeChargeStart), with the brake handle where + // the pipe can be unlocked: a pipe below the lock is unlocked as the train stands, not only once it is to go + bool charging_standing{false}; }; struct decision { diff --git a/vehicle/uphillstart.cpp b/vehicle/uphillstart.cpp new file mode 100644 index 000000000..dd1895b11 --- /dev/null +++ b/vehicle/uphillstart.cpp @@ -0,0 +1,36 @@ +/* +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/uphillstart.h" + +namespace uphill_start { + +top_up_action brake_top_up( + top_up &State, double const Brakeforce, double const Holdingforce, double const Brakeposition, double const Heldtime, + double const Applicationtime) { + + if (State.done || (Brakeforce >= holding_force * Holdingforce) || (Brakeposition >= top_up_position)) { + return top_up_action::none; + } + // each step is given the full application time of the train brake, for the cylinders along the train to fill + if (Heldtime < Applicationtime) { + return top_up_action::wait; + } + if ((State.last_force >= 0.0) && (Brakeforce - State.last_force < top_up_gain * Holdingforce)) { + // the last step added next to nothing: the brake of this train can't hold it (brakes cut out, a load setting + // too low), and the start goes on without + State.done = true; + return top_up_action::none; + } + State.last_force = Brakeforce; + return top_up_action::step; +} + +} // namespace uphill_start diff --git a/vehicle/uphillstart.h b/vehicle/uphillstart.h new file mode 100644 index 000000000..108662cbe --- /dev/null +++ b/vehicle/uphillstart.h @@ -0,0 +1,41 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +// starting uphill (TController::control_uphill_start()), the AI's driver lets the locomotive brake off only once +// the brake of the rest of the train holds the train on its own: a train stopped on a light application stands on +// the locomotive brake too, and rolls back as soon as it is off. until then the train brake is applied further, a +// step at a time +namespace uphill_start { + +auto const holding_force{1.1}; // a force that holds a train uphill, as a multiple of the grade force +auto const top_up_position{4.0}; // full service: the furthest the train brake is applied to hold the train +// a step that adds less brake force than this, as a multiple of the grade force, is the last one +auto const top_up_gain{0.02}; + +// what has been done to apply the train brake further, in one start +struct top_up { + double last_force{-1.0}; // the brake force when the last step was given, -1 before the first [N] + bool done{false}; // a step added next to nothing: no more of them in this start +}; + +enum class top_up_action { + none, // the brake holds the train, or can't be made to: the start goes on + wait, // the cylinders are still filling after the last step + step // apply the train brake one step further +}; + +// Brakeforce: the brake force of the unpowered vehicles [N]; Holdingforce: the grade force on the train [N]; +// Brakeposition: the train brake handle, as BrakeCtrlPosition; Heldtime: how long the handle has been where it +// is [s]; Applicationtime: the time the train brake takes to apply, for the cylinders along the train to fill [s] +top_up_action brake_top_up( + top_up &State, double Brakeforce, double Holdingforce, double Brakeposition, double Heldtime, double Applicationtime); + +} // namespace uphill_start