diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c9ce73bdc..8a1349535 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -103,6 +103,7 @@ jobs: --exclude='*.o' \ --exclude='*.a' \ --exclude='*.so' \ + --exclude='*.so.*' \ -C "$GITHUB_WORKSPACE" . - name: Upload analysis input diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index d37817d5c..6eef3c7ed 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -76,6 +76,27 @@ jobs: run: | call setup.bat + # the unit tests run at the end of the build and load lua51.dll (the Lua screens), but ref/luajit has only its import + # library. LuaJIT of the same 2.0 line is built here and put on PATH for them; it doesn't go into the uploaded build + - name: Build lua51.dll for the unit tests + shell: cmd + run: | + for /f "usebackq delims=" %%i in (`"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`) do set "VSDIR=%%i" + call "%VSDIR%\VC\Auxiliary\Build\vcvars64.bat" || exit /b 1 + git init -q "%RUNNER_TEMP%\LuaJIT" || exit /b 1 + cd /d "%RUNNER_TEMP%\LuaJIT" + rem the v2.0 branch of LuaJIT, pinned + git fetch -q --depth 1 https://github.com/LuaJIT/LuaJIT.git b83bcba6ea300d4eb16e8257ddf80bcdef1f938b || exit /b 1 + git checkout -q FETCH_HEAD || exit /b 1 + cd src + rem msvcbuild.bat runs the tools it builds (minilua, buildvm) from the current folder + set NoDefaultCurrentDirectoryInExePath= + call .\msvcbuild.bat || exit /b 1 + if not exist lua51.dll exit /b 1 + mkdir "%RUNNER_TEMP%\lua51" + copy /y lua51.dll "%RUNNER_TEMP%\lua51\" || exit /b 1 + echo %RUNNER_TEMP%\lua51>> "%GITHUB_PATH%" + - name: Configure shell: pwsh run: | @@ -248,7 +269,31 @@ jobs: cmake \ --build build \ --parallel "$(nproc)" - + + # the build copies the shared libraries next to the game (CMake_modules/bundle_runtime_libs.cmake) and the + # game looks for them there first ($ORIGIN): each one it loads from outside build/bin has to be one of the system + - name: Check the bundled libraries + run: | + GAME="$(find build/bin -maxdepth 1 -type f -name 'eu07*' -perm -u+x | head -n 1)" + test -n "$GAME" + echo "Game: $GAME" + readelf -d "$GAME" | grep -E 'R(UN)?PATH' + readelf -d "$GAME" | grep -q 'Library rpath: \[\$ORIGIN\]' + cat build/bin/bundled_libs.txt + ldd "$GAME" + if ldd "$GAME" | grep -q 'not found'; then + echo "::error::the game needs a library that is neither bundled nor in the system" + exit 1 + fi + while read -r name; do + [ -n "$name" ] || continue + loaded="$(ldd "$GAME" | awk -v n="$name" '$1 == n { print $3 }')" + if [ -z "$loaded" ] || [ "$(realpath "$loaded")" != "$(realpath "build/bin/$name")" ]; then + echo "::error::$name is bundled, but the game loads it from '$loaded'" + exit 1 + fi + done < build/bin/bundled_libs.txt + - name: Prepare Linux Python environment run: | PYTHON_ROOT="$(python -c 'import sys; print(sys.base_prefix)')" diff --git a/.gitmodules b/.gitmodules index df7f5ddaa..55d108a70 100644 --- a/.gitmodules +++ b/.gitmodules @@ -32,3 +32,7 @@ [submodule "betterRenderer/thirdparty/bvh"] path = betterRenderer/thirdparty/bvh url = https://github.com/madmann91/bvh.git +[submodule "ref/wamr"] + path = ref/wamr + url = https://github.com/bytecodealliance/wasm-micro-runtime + shallow = true diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000..3b52f36ee --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,172 @@ +# MaSzyna: notes for coding agents + +These are the instructions for every coding agent that works in this repository: Claude Code, OpenAI Codex, Gemini CLI and any +other tool that reads `AGENTS.md`. `CLAUDE.md` and `GEMINI.md` only point to this file, so a rule is added or changed here, never +there. + +## The code builds and works with GCC, not only MSVC + +The Linux CI (`.github/workflows/build.yml`) builds with GCC 13 on ubuntu-24.04, through the Sonar build-wrapper, and `sonar.yml` +analyses that build once it has passed. A change that compiles with MSVC only fails there, and a failed GCC build also leaves Sonar +without an analysis of the PR. So every change has to compile with GCC, and behave the same with it, as well as with MSVC. The CI +builds with `-DWITH_BETTER_RENDERER=OFF` and Sonar excludes `betterRenderer/`, so that part is neither built on CI nor analysed. + +Where no GCC is at hand, read the new code for what MSVC lets through and GCC doesn't: + +- `constexpr` initialised from a floating or class-type constant declared only `const`: make the source `constexpr` too. +- Standard headers MSVC pulls in through others: include them yourself. For example, `` for `std::views`, ``, + ``, ``, ``, `` and ``. +- `typename` and `this->` where a template needs them. +- A temporary bound to a non-const reference. +- Explicit specialisations inside a class. +- A name a class uses and then declares again in its own body (GCC: "changes meaning"). +- A nested type with default member initialisers used as a default argument inside the class that encloses it. +- A declaration changed in a header (`const`, parameters) without its definition, or a new member function defined but not declared. +- `std::ifstream` / `std::ofstream` opened with a `std::wstring`. +- MSVC-only functions: `_stricmp`, `sprintf_s`, `fopen_s`, `localtime_s` and the like. +- Designated initialisers out of declaration order. +- `emplace_back(a, b, c)` with parenthesised aggregate initialisation is fine on GCC 13, but not for `std::array`. There is no brace + elision in parentheses, so build a named local instead. + +The same behaviour needs portable code. Don't rely on the order arguments are evaluated in, on the signedness of `char`, on the size of +`wchar_t`, or on `long` being 32 bits. + +## SonarCloud: the PR passes the quality gate + +SonarCloud (`sonar.yml`, `sonar-project.properties`) analyses each PR. A PR has to pass Sonar's quality gate. The gate rates the new +code: reliability, security and maintainability have to be A, duplication is at most 3% and the security hotspots are reviewed. +Any bug or vulnerability on the new code lowers its rating below A, so each one gets fixed (or gets a NOSONAR when it is a false +positive). Code smells count only together, through the maintainability rating, so a single one rarely fails the gate, but many in a +large PR can. A hotspot is reviewed by marking it in SonarCloud as safe or fixed, which is the user's step there, not a reason to +rewrite the code. A remark that doesn't fail the gate doesn't have to be fixed. Leave large restructurings that only answer such a +remark (splitting a class or a file, rewriting a working algorithm) out of the PR. The analysis runs on the GCC build, so a PR that +fails to build with GCC gets no analysis at all, and so it doesn't pass the gate. + +Fixing a remark must not change what the code does: + +- Keep the order of side effects, the conditions and the floating-point results as they were. +- Text in `STR(...)`, `STR_C(...)` and `_(...)` is looked up in the translations (`lang/*.po`), so it stays byte for byte the same. + The same goes for what is written to the log. +- `// NOSONAR: ` is only for a real false positive, or where a fix would change behaviour. Use it rarely, always with the + reason. + +To keep the gate passing, write new code so that it doesn't raise the rules that keep coming up: + +- **S134** (nesting deeper than 3 `if` / `for` / `while` / `switch` / `try`) and **S3776** (cognitive complexity over 25): + - use early `continue` / `return`; + - move loop bodies and branches into named helpers, preferably free functions in the anonymous namespace; + - group the state of a long algorithm in a small struct with methods. + + Every `else if`, every `&&` / `||` sequence and every nested lambda adds to the complexity. +- **S1188**: a lambda over 20 lines becomes a named function. +- **S107**: a function with more than 7 parameters takes a struct. +- **S3608**: lambdas capture explicitly (`[this, &points]`, not `[&]` or `[=]`). The only exception is `[&]` on a lambda passed + straight to a standard algorithm; `[=]` is flagged even there, and so is `[&]` passed to one of our own functions. +- **S6197** / **S5566**: use the `std::ranges::` algorithm that takes the container rather than a begin/end pair or a hand-written + loop. +- **S6165**: use `std::erase_if` rather than erase-remove. +- **S6004**: a variable used only by the condition is declared in the `if (init; condition)`. +- **S3358**: no nested `?:`; use an `if` or a small function. +- **S1121**: no assignment inside an expression, chained ones included (`a = b = c`). +- **S1117**: no declaration shadowing a local, a member or an enumerator. +- **S6003**: `v.emplace_back(a, b, c)` rather than `v.push_back({a, b, c})`. For a `std::array` element, push a named local instead + (see the GCC notes above). +- **S6012**: let class template argument deduction work: `std::vector values{1.0, 2.0}`. +- **S5945**: `std::array` / `std::vector` / `std::string`, not C arrays. +- **S1659**: one declaration per statement. +- **S6009**: `std::string_view` rather than `std::string const &` for a string parameter that is only read. +- **S6185** / **S6494**: `std::format` rather than concatenation or `snprintf`. +- **S924**: at most one `break` per loop. +- **S886**: a `for` whose counter changes in its body becomes a `while`. +- **S5997**: `std::scoped_lock` rather than `std::lock_guard`. +- **S6168**: `std::jthread` rather than `std::thread`. A `std::jthread` joins in its destructor where a `std::thread` would + terminate, so in existing code switch only where the thread is always joined or detached before it is destroyed. +- **S6177**: `using enum` where a function names many enumerators. +- **S5350** / **S995**: `const` on references and pointers that aren't written through. +- **S5817**: `const` on member functions that change nothing. +- **S2193**: no `float` loop counters. +- **S5421**: no non-const globals. +- **S6179**: `std::lerp` rather than a hand-written interpolation, in new code. In existing code only where it gives the very same + result. +- **S6164**: `std::numbers::pi` rather than a literal, in new code. In existing code only where it gives the very same result. + +The project is C++20 (`CMAKE_CXX_STANDARD 20`), so no C++23 library addition is available on any compiler. That rules out +`std::ranges::to`, `views::zip`, `views::enumerate`, `ranges::contains`, `std::print` and `std::expected`. + +## Renderers: the move to OpenGL 4.6 and Vulkan + +The renderers on `master` are to be replaced. `feat/gl46-migration` (PR #216, a draft with milestone 27.04, to be merged after the +26.11 release) replaces the OpenGL 3.3 renderer with an OpenGL 4.6 core one and adds a Vulkan 1.4 renderer beside it. It also +removes the legacy OpenGL 2.1, the OpenGL ES / ANGLE and the NVRHI (`betterRenderer/`) paths. + +- `betterRenderer/` will be removed. Don't put work into it. +- On that branch, of the `rendering/opengl*` files only `openglcamera.*` and `openglmatrixstack.*` stay. The whole + `rendering/opengl33*` family and the rest of the legacy `rendering/opengl*` go, and the new renderers are in + `rendering/opengl46/`, `rendering/vulkan14/` and `rendering/common/`. The shared `rendering/renderer.*`, `geometrybank.*`, + `particles.*` and the like stay. The shaders move from `shaders/` to `shaders/ogl46/` and `shaders/vk14/`. +- So a change on `master` to the code that goes away, or to the shaders, may be pointless. Keep it to fixes and to what a feature + on `master` needs in order to be drawn at all. For such a change, say in the PR where `feat/gl46-migration` has the counterpart, + or that the branch already carries the change. + +## Building, testing and running + +- The unit tests (`tests/unit`) run at the end of the build, which prints `Unit tests: N/N passed` and fails on any failed case. + `-DWITH_TESTS=OFF` builds the game without them. +- A new feature goes on its own branch from `master`, not on whatever branch is checked out. Say which branch the work lands on + before the first edit. A fresh worktree has empty submodules, so it doesn't build until they are filled. +- The editor runs a script when `EU07_EDITOR_SELFTEST=` is set: one command per line, `#` for comments. The commands are in + `application/editormodeselftest*.cpp` (`camera`, `wait`, `select`, `lay`, `screenshot`, `save`, `quit` and many more). + - Run it on a copy of the scenery, never on the original, and delete the copy afterwards. + - Give every run a timeout and keep an eye on its memory. A loop gone wrong can fill the RAM of the whole machine. + - `screenshot` only queues the grab and waits 3 frames; the image is written later on another thread. A click right after it + has been seen to lose the selection, so leave a `wait` of about 15 frames after a `screenshot` before clicking. +- At run time the editor's texts load from `lang/editor_.po` in the game folder (`utilities/translation.cpp`), not from + the build. New strings of a branch show in English until that file has them. Without the `fonts` folder Polish letters show as `?`. +- When a build runs on a copy of the game data made of links to the real folders, turn off whatever writes into the data + (`convertmodels 0` in `eu07.ini`), or the run changes the real game folder through the links. +- A test of code that moves, migrates or deletes files in the user's profile (`%APPDATA%`, `%LOCALAPPDATA%`, caches) gets its own + test folder. Never point it at the real profile. +- A GPU hang (Windows TDR) can freeze the whole machine, not just the game. Don't test a hang hypothesis by running it. Guard the + code against what causes it (degenerate geometry, NaN in the camera or in transforms) and read the `LiveKernelEvent` / watchdog + dumps instead. +- PowerShell variable names are case-insensitive: `$Track` and `$track` are the same variable. + +## Game data and backward compatibility + +The code and the game data live apart. The assets (sceneries, vehicles with their `.fiz` and `.mmd`, models, textures, sounds, +timetables, most of `lang` and the shipped `eu07.ini`) are in a separate SVN repository, `https://svn.eu07.pl/pctga`. It needs an +account; there is no anonymous checkout. Of `lang/`, only `editor_pl.po` is in this repository. Players install and +launch the game through Steam, GOG and the like, and run new builds on the data they already have. + +The official starter is StarterNG (`https://github.com/MaSzyna-EU07/StarterNG`), a separate repository; the older +`MaSzyna-EU07/Starter` is not the one in use. `launcher/` in this repository is the simulator's built-in scenario and vehicle +picker (`launcher_mode`), not StarterNG. + +- Every existing file must still be read the way it was. Don't rename or drop a keyword, change the meaning or the unit of a value, + or make an optional entry required. This holds for every format the game reads: for example `.scn` and its includes, `.fiz`, + `.mmd`, `.e3d` / `.t3d`, `.mat`, the `.txt` timetables and track profiles, `eu07.ini` and the Python screens. +- A bug fix may change what an existing file leads to, such as how a vehicle from its `.fiz` behaves, as long as the PR says so. +- Something new in a format is optional, and without it the code does exactly what it did before. A file that loaded correctly + before doesn't get new warnings or errors in the log. A real fault that is newly detected may be logged. +- A code change must not need a change in the SVN to work. Where it uses new or changed assets, it falls back to the old behaviour + without them, and the PR says what is to be added to the SVN and in what order the two go in. +- A change that uses new or changed assets (and falls back without them, see above) says so plainly in its commit message: which + files, and what is to change in them. It is never left implied. Before such a commit, either make the asset change right away in + the user's SVN working copy, or get the user's agreement to leave it for later. Ask the user where their SVN working copy is; the + installed game folder is not one. Pushing to git and committing to the SVN both need the user's consent. +- A scenery saved by the editor without using a new feature holds nothing the current release can't read. The entries of a new + feature (such as a new kind of node) appear only where that feature was used, and the PR says that the release doesn't read + them. +- Saving patches the scenery files by byte spans: unchanged definitions stay byte for byte, and an edited node is written anew by + its `export_as_text`. A change to saving must not widen what gets rewritten, nor make `export_as_text` drop more of an edited + node (comments, unknown tokens) than it did before. +- A new feature that changes what the simulator does or shows with existing sceneries and vehicles can be turned off in + `eu07.ini`, and turned off, the simulator behaves as it did before the feature. Editor tools and new optional entries of a + format are covered by the points above. The key is parsed in `utilities/Globals.cpp` (`global_settings::ConfigParse*`) and + written by `global_settings::export_as_text`, which puts the settings in the log at start. `eu07.ini` is read from the user's + profile (`user_config_path`), and from the game folder only when the profile has none; test the switch in the file that is + actually read. +- A feature doesn't make existing sceneries and vehicles look suddenly different after an update. A change to how things look is + something the player turns on, or comes in gradually. +- When a format really has to change, read both the old and the new form, and say in the PR what changes for the data and for + the people who make it. diff --git a/CLAUDE.md b/CLAUDE.md index 283058cbe..bbbaa3835 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,168 +1,5 @@ # MaSzyna: notes for Claude Code -## The code builds and works with GCC, not only MSVC +The instructions for every coding agent in this repository are in `AGENTS.md`. Add or change rules there, not here. -The Linux CI (`.github/workflows/build.yml`) builds with GCC 13 on ubuntu-24.04, through the Sonar build-wrapper, and `sonar.yml` -analyses that build once it has passed. A change that compiles with MSVC only fails there, and a failed GCC build also leaves Sonar -without an analysis of the PR. So every change has to compile with GCC, and behave the same with it, as well as with MSVC. The CI -builds with `-DWITH_BETTER_RENDERER=OFF` and Sonar excludes `betterRenderer/`, so that part is neither built on CI nor analysed. - -Where no GCC is at hand, read the new code for what MSVC lets through and GCC doesn't: - -- `constexpr` initialised from a floating or class-type constant declared only `const`: make the source `constexpr` too. -- Standard headers MSVC pulls in through others: include them yourself. For example, `` for `std::views`, ``, - ``, ``, ``, `` and ``. -- `typename` and `this->` where a template needs them. -- A temporary bound to a non-const reference. -- Explicit specialisations inside a class. -- A name a class uses and then declares again in its own body (GCC: "changes meaning"). -- A nested type with default member initialisers used as a default argument inside the class that encloses it. -- A declaration changed in a header (`const`, parameters) without its definition, or a new member function defined but not declared. -- `std::ifstream` / `std::ofstream` opened with a `std::wstring`. -- MSVC-only functions: `_stricmp`, `sprintf_s`, `fopen_s`, `localtime_s` and the like. -- Designated initialisers out of declaration order. -- `emplace_back(a, b, c)` with parenthesised aggregate initialisation is fine on GCC 13, but not for `std::array`. There is no brace - elision in parentheses, so build a named local instead. - -The same behaviour needs portable code. Don't rely on the order arguments are evaluated in, on the signedness of `char`, on the size of -`wchar_t`, or on `long` being 32 bits. - -## SonarCloud: the PR passes the quality gate - -SonarCloud (`sonar.yml`, `sonar-project.properties`) analyses each PR. A PR has to pass Sonar's quality gate. The gate rates the new -code: reliability, security and maintainability have to be A, duplication is at most 3% and the security hotspots are reviewed. -Any bug or vulnerability on the new code lowers its rating below A, so each one gets fixed (or gets a NOSONAR when it is a false -positive). Code smells count only together, through the maintainability rating, so a single one rarely fails the gate, but many in a -large PR can. A hotspot is reviewed by marking it in SonarCloud as safe or fixed, which is the user's step there, not a reason to -rewrite the code. A remark that doesn't fail the gate doesn't have to be fixed. Leave large restructurings that only answer such a -remark (splitting a class or a file, rewriting a working algorithm) out of the PR. The analysis runs on the GCC build, so a PR that -fails to build with GCC gets no analysis at all, and so it doesn't pass the gate. - -Fixing a remark must not change what the code does: - -- Keep the order of side effects, the conditions and the floating-point results as they were. -- Text in `STR(...)`, `STR_C(...)` and `_(...)` is looked up in the translations (`lang/*.po`), so it stays byte for byte the same. - The same goes for what is written to the log. -- `// NOSONAR: ` is only for a real false positive, or where a fix would change behaviour. Use it rarely, always with the - reason. - -To keep the gate passing, write new code so that it doesn't raise the rules that keep coming up: - -- **S134** (nesting deeper than 3 `if` / `for` / `while` / `switch` / `try`) and **S3776** (cognitive complexity over 25): - - use early `continue` / `return`; - - move loop bodies and branches into named helpers, preferably free functions in the anonymous namespace; - - group the state of a long algorithm in a small struct with methods. - - Every `else if`, every `&&` / `||` sequence and every nested lambda adds to the complexity. -- **S1188**: a lambda over 20 lines becomes a named function. -- **S107**: a function with more than 7 parameters takes a struct. -- **S3608**: lambdas capture explicitly (`[this, &points]`, not `[&]` or `[=]`). The only exception is `[&]` on a lambda passed - straight to a standard algorithm; `[=]` is flagged even there, and so is `[&]` passed to one of our own functions. -- **S6197** / **S5566**: use the `std::ranges::` algorithm that takes the container rather than a begin/end pair or a hand-written - loop. -- **S6165**: use `std::erase_if` rather than erase-remove. -- **S6004**: a variable used only by the condition is declared in the `if (init; condition)`. -- **S3358**: no nested `?:`; use an `if` or a small function. -- **S1121**: no assignment inside an expression, chained ones included (`a = b = c`). -- **S1117**: no declaration shadowing a local, a member or an enumerator. -- **S6003**: `v.emplace_back(a, b, c)` rather than `v.push_back({a, b, c})`. For a `std::array` element, push a named local instead - (see the GCC notes above). -- **S6012**: let class template argument deduction work: `std::vector values{1.0, 2.0}`. -- **S5945**: `std::array` / `std::vector` / `std::string`, not C arrays. -- **S1659**: one declaration per statement. -- **S6009**: `std::string_view` rather than `std::string const &` for a string parameter that is only read. -- **S6185** / **S6494**: `std::format` rather than concatenation or `snprintf`. -- **S924**: at most one `break` per loop. -- **S886**: a `for` whose counter changes in its body becomes a `while`. -- **S5997**: `std::scoped_lock` rather than `std::lock_guard`. -- **S6168**: `std::jthread` rather than `std::thread`. A `std::jthread` joins in its destructor where a `std::thread` would - terminate, so in existing code switch only where the thread is always joined or detached before it is destroyed. -- **S6177**: `using enum` where a function names many enumerators. -- **S5350** / **S995**: `const` on references and pointers that aren't written through. -- **S5817**: `const` on member functions that change nothing. -- **S2193**: no `float` loop counters. -- **S5421**: no non-const globals. -- **S6179**: `std::lerp` rather than a hand-written interpolation, in new code. In existing code only where it gives the very same - result. -- **S6164**: `std::numbers::pi` rather than a literal, in new code. In existing code only where it gives the very same result. - -The project is C++20 (`CMAKE_CXX_STANDARD 20`), so no C++23 library addition is available on any compiler. That rules out -`std::ranges::to`, `views::zip`, `views::enumerate`, `ranges::contains`, `std::print` and `std::expected`. - -## Renderers: the move to OpenGL 4.6 and Vulkan - -The renderers on `master` are to be replaced. `feat/gl46-migration` (PR #216, a draft with milestone 27.04, to be merged after the -26.11 release) replaces the OpenGL 3.3 renderer with an OpenGL 4.6 core one and adds a Vulkan 1.4 renderer beside it. It also -removes the legacy OpenGL 2.1, the OpenGL ES / ANGLE and the NVRHI (`betterRenderer/`) paths. - -- `betterRenderer/` will be removed. Don't put work into it. -- On that branch, of the `rendering/opengl*` files only `openglcamera.*` and `openglmatrixstack.*` stay. The whole - `rendering/opengl33*` family and the rest of the legacy `rendering/opengl*` go, and the new renderers are in - `rendering/opengl46/`, `rendering/vulkan14/` and `rendering/common/`. The shared `rendering/renderer.*`, `geometrybank.*`, - `particles.*` and the like stay. The shaders move from `shaders/` to `shaders/ogl46/` and `shaders/vk14/`. -- So a change on `master` to the code that goes away, or to the shaders, may be pointless. Keep it to fixes and to what a feature - on `master` needs in order to be drawn at all. For such a change, say in the PR where `feat/gl46-migration` has the counterpart, - or that the branch already carries the change. - -## Building, testing and running - -- The unit tests (`tests/unit`) run at the end of the build, which prints `Unit tests: N/N passed` and fails on any failed case. - `-DWITH_TESTS=OFF` builds the game without them. -- A new feature goes on its own branch from `master`, not on whatever branch is checked out. Say which branch the work lands on - before the first edit. A fresh worktree has empty submodules, so it doesn't build until they are filled. -- The editor runs a script when `EU07_EDITOR_SELFTEST=` is set: one command per line, `#` for comments. The commands are in - `application/editormodeselftest*.cpp` (`camera`, `wait`, `select`, `lay`, `screenshot`, `save`, `quit` and many more). - - Run it on a copy of the scenery, never on the original, and delete the copy afterwards. - - Give every run a timeout and keep an eye on its memory. A loop gone wrong can fill the RAM of the whole machine. - - `screenshot` only queues the grab and waits 3 frames; the image is written later on another thread. A click right after it - has been seen to lose the selection, so leave a `wait` of about 15 frames after a `screenshot` before clicking. -- At run time the editor's texts load from `lang/editor_.po` in the game folder (`utilities/translation.cpp`), not from - the build. New strings of a branch show in English until that file has them. Without the `fonts` folder Polish letters show as `?`. -- When a build runs on a copy of the game data made of links to the real folders, turn off whatever writes into the data - (`convertmodels 0` in `eu07.ini`), or the run changes the real game folder through the links. -- A test of code that moves, migrates or deletes files in the user's profile (`%APPDATA%`, `%LOCALAPPDATA%`, caches) gets its own - test folder. Never point it at the real profile. -- A GPU hang (Windows TDR) can freeze the whole machine, not just the game. Don't test a hang hypothesis by running it. Guard the - code against what causes it (degenerate geometry, NaN in the camera or in transforms) and read the `LiveKernelEvent` / watchdog - dumps instead. -- PowerShell variable names are case-insensitive: `$Track` and `$track` are the same variable. - -## Game data and backward compatibility - -The code and the game data live apart. The assets (sceneries, vehicles with their `.fiz` and `.mmd`, models, textures, sounds, -timetables, most of `lang` and the shipped `eu07.ini`) are in a separate SVN repository, `https://svn.eu07.pl/pctga`. It needs an -account; there is no anonymous checkout. Of `lang/`, only `editor_pl.po` is in this repository. Players install and -launch the game through Steam, GOG and the like, and run new builds on the data they already have. - -The official starter is StarterNG (`https://github.com/MaSzyna-EU07/StarterNG`), a separate repository; the older -`MaSzyna-EU07/Starter` is not the one in use. `launcher/` in this repository is the simulator's built-in scenario and vehicle -picker (`launcher_mode`), not StarterNG. - -- Every existing file must still be read the way it was. Don't rename or drop a keyword, change the meaning or the unit of a value, - or make an optional entry required. This holds for every format the game reads: for example `.scn` and its includes, `.fiz`, - `.mmd`, `.e3d` / `.t3d`, `.mat`, the `.txt` timetables and track profiles, `eu07.ini` and the Python screens. -- A bug fix may change what an existing file leads to, such as how a vehicle from its `.fiz` behaves, as long as the PR says so. -- Something new in a format is optional, and without it the code does exactly what it did before. A file that loaded correctly - before doesn't get new warnings or errors in the log. A real fault that is newly detected may be logged. -- A code change must not need a change in the SVN to work. Where it uses new or changed assets, it falls back to the old behaviour - without them, and the PR says what is to be added to the SVN and in what order the two go in. -- A change that uses new or changed assets (and falls back without them, see above) says so plainly in its commit message: which - files, and what is to change in them. It is never left implied. Before such a commit, either make the asset change right away in - the user's SVN working copy, or get the user's agreement to leave it for later. Ask the user where their SVN working copy is; the - installed game folder is not one. Pushing to git and committing to the SVN both need the user's consent. -- A scenery saved by the editor without using a new feature holds nothing the current release can't read. The entries of a new - feature (such as a new kind of node) appear only where that feature was used, and the PR says that the release doesn't read - them. -- Saving patches the scenery files by byte spans: unchanged definitions stay byte for byte, and an edited node is written anew by - its `export_as_text`. A change to saving must not widen what gets rewritten, nor make `export_as_text` drop more of an edited - node (comments, unknown tokens) than it did before. -- A new feature that changes what the simulator does or shows with existing sceneries and vehicles can be turned off in - `eu07.ini`, and turned off, the simulator behaves as it did before the feature. Editor tools and new optional entries of a - format are covered by the points above. The key is parsed in `utilities/Globals.cpp` (`global_settings::ConfigParse*`) and - written by `global_settings::export_as_text`, which puts the settings in the log at start. `eu07.ini` is read from the user's - profile (`user_config_path`), and from the game folder only when the profile has none; test the switch in the file that is - actually read. -- A feature doesn't make existing sceneries and vehicles look suddenly different after an update. A change to how things look is - something the player turns on, or comes in gradually. -- When a format really has to change, read both the old and the new form, and say in the PR what changes for the data and for - the people who make it. +@AGENTS.md diff --git a/CMakeLists.txt b/CMakeLists.txt index 4bfe2f369..422ad9de9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -72,6 +72,7 @@ option(WITH_OPENGL_LEGACY "Compile with OpenGL legacy renderer" ON) option(WITH_PYTHON "Python 3.14 embedded scripting" ON) option(WITH_UART "Compile with libserialport" ON) option(WITH_LUA "Compile with lua scripting support" ON) +option(WITH_WASM "WebAssembly script screens (wasmscreen:, wasmdestinationsign:), run by the WAMR interpreter in ref/wamr" ON) option(WITH_OPENVR "Compile with OpenVR" OFF) option(WITH_ZMQ "Compile with cppzmq" OFF) option(WITH_CRASHPAD "Compile with crashpad" OFF) @@ -152,6 +153,7 @@ set(SOURCES "scene/scene.cpp" "scene/scenenode.cpp" "simulation/simulation.cpp" +"simulation/blackboxrecorder.cpp" "model/vertex.cpp" "audio/audio.cpp" "audio/audiorenderer.cpp" @@ -321,6 +323,16 @@ if (WITH_LUA) set(SOURCES ${SOURCES} "scripting/lua.cpp") endif() +# the script screens (scripting/scriptscreens.cpp), with the Lua and the WebAssembly runtime when they're built +set(SOURCES ${SOURCES} "scripting/scriptscreens.cpp") +if (WITH_LUA) + set(SOURCES ${SOURCES} "scripting/luaprogram.cpp") +endif() +if (WITH_WASM) + set(DEFINITIONS ${DEFINITIONS} "WITH_WASM") + set(SOURCES ${SOURCES} "scripting/wasmprogram.cpp") +endif() + if (WITHDUMPGEN) set(DEFINITIONS ${DEFINITIONS} "WITHDUMPGEN") endif() @@ -333,6 +345,7 @@ if (WITH_OPENGL_MODERN) "rendering/opengl33precipitation.cpp" "rendering/opengl33particles.cpp" "rendering/opengl33terrain.cpp" + "rendering/opengl33screenpost.cpp" "rendering/opengl33renderer.cpp") set(DEFINITIONS ${DEFINITIONS} "WITH_OPENGL_MODERN") endif() @@ -459,11 +472,16 @@ set(CORE_SOURCES "McZapkie/friction.cpp" "McZapkie/hamulce.cpp" "McZapkie/Mover.cpp" +"McZapkie/couplerphysics.cpp" "McZapkie/Oerlikon_ESt.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" "scripting/ladderlogic.cpp" +"scripting/scriptscreenrules.cpp" +"scripting/scriptscreenkernels.cpp" +"scripting/scriptscreendrawing.cpp" "simulation/simulationtestrules.cpp" +"vehicle/blackbox.cpp" "vehicle/enginestart.cpp" "vehicle/handover.cpp" "vehicle/horn.cpp" @@ -668,15 +686,71 @@ if (WIN32) ) endif () -if(WIN32 AND WITH_PYTHON) - add_custom_command( - TARGET ${PROJECT_NAME} POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different "${EU07_PY_DLL}" "$" - COMMAND ${CMAKE_COMMAND} -E copy_if_different "${EU07_PY_ZLIB}" "$" - COMMAND ${CMAKE_COMMAND} -E copy_directory "${EU07_PY_LIBDIR}" "$/python64/Lib" - COMMAND ${CMAKE_COMMAND} -E copy_directory "${EU07_PY_DLLSDIR}" "$/python64/DLLs" - ) +# Linux: the game loads its shared libraries from its own folder first ($ORIGIN), and the build copies them there, +# so the folder runs on a system that doesn't have them, or has other versions. the RPATH is a DT_RPATH rather +# than a DT_RUNPATH, because only that one is also used for the libraries the copied ones load (libsndfile's codecs) +if (UNIX AND NOT APPLE) + option(BUNDLE_RUNTIME_LIBS "Linux: copy the shared libraries the game needs next to it and load them from there" ON) endif() +if (UNIX AND NOT APPLE AND BUNDLE_RUNTIME_LIBS) + set_target_properties(${PROJECT_NAME} PROPERTIES + BUILD_WITH_INSTALL_RPATH TRUE + INSTALL_RPATH "$ORIGIN") + target_link_options(${PROJECT_NAME} PRIVATE "LINKER:--disable-new-dtags") + + # the RPATH no longer leads to libraries outside the system folders (Python from setup-python, an OpenAL Soft + # in /usr/local), so their folders are given to the script as well + set(EU07_BUNDLE_SEARCH_DIRS "") + foreach(library IN LISTS Python3_LIBRARIES OPENAL_LIBRARY LUAJIT_LIBRARIES libserialport_LIBRARY) + if (IS_ABSOLUTE "${library}") + get_filename_component(library_dir "${library}" DIRECTORY) + list(APPEND EU07_BUNDLE_SEARCH_DIRS "${library_dir}") + endif() + endforeach() + list(APPEND EU07_BUNDLE_SEARCH_DIRS ${Python3_LIBRARY_DIRS}) + list(REMOVE_DUPLICATES EU07_BUNDLE_SEARCH_DIRS) + string(REPLACE ";" "|" EU07_BUNDLE_SEARCH_DIRS "${EU07_BUNDLE_SEARCH_DIRS}") + + add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD + COMMAND ${CMAKE_COMMAND} + -DGAME=$ + -DSEARCH_DIRS=${EU07_BUNDLE_SEARCH_DIRS} + -DCMAKE_OBJDUMP=${CMAKE_OBJDUMP} + -P "${CMAKE_CURRENT_SOURCE_DIR}/CMake_modules/bundle_runtime_libs.cmake" + COMMENT "Copying the shared libraries next to the game" + VERBATIM) +endif() + +if(WIN32 AND WITH_PYTHON) + # the Python runtime next to the game, copied when it isn't there yet or the Python install changed, rather + # than after every link of the game: the library alone is thousands of files. the folder is the game's + # RUNTIME_OUTPUT_DIRECTORY, spelled out: $ here would make this target depend on the game + get_property(EU07_MULTI_CONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) + if (EU07_MULTI_CONFIG) + set(EU07_PY_TARGET_DIR "${CMAKE_BINARY_DIR}/bin/$") + else() + set(EU07_PY_TARGET_DIR "${CMAKE_BINARY_DIR}/bin") + endif() + set(EU07_PY_STAMP "${EU07_PY_TARGET_DIR}/python64/python_runtime.stamp") + add_custom_command( + OUTPUT "${EU07_PY_STAMP}" + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${EU07_PY_DLL}" "${EU07_PY_TARGET_DIR}" + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${EU07_PY_ZLIB}" "${EU07_PY_TARGET_DIR}" + COMMAND ${CMAKE_COMMAND} -E copy_directory_if_different "${EU07_PY_LIBDIR}" "${EU07_PY_TARGET_DIR}/python64/Lib" + COMMAND ${CMAKE_COMMAND} -E copy_directory_if_different "${EU07_PY_DLLSDIR}" "${EU07_PY_TARGET_DIR}/python64/DLLs" + COMMAND ${CMAKE_COMMAND} -E touch "${EU07_PY_STAMP}" + DEPENDS "${EU07_PY_DLL}" "${EU07_PY_ZLIB}" + COMMENT "Copying the Python runtime next to the game" + VERBATIM) + add_custom_target(eu07_python_runtime DEPENDS "${EU07_PY_STAMP}") + set_target_properties(eu07_python_runtime PROPERTIES FOLDER "libraries") + add_dependencies(${PROJECT_NAME} eu07_python_runtime) +endif() + +if (WITH_WASM) + add_subdirectory("CMake_modules/wamr" "${CMAKE_CURRENT_BINARY_DIR}/wamr") + target_link_libraries(${PROJECT_NAME} eu07_wamr) +endif () if (WITH_BETTER_RENDERER) add_subdirectory("betterRenderer") diff --git a/CMake_modules/bundle_runtime_libs.cmake b/CMake_modules/bundle_runtime_libs.cmake new file mode 100644 index 000000000..a0f71543e --- /dev/null +++ b/CMake_modules/bundle_runtime_libs.cmake @@ -0,0 +1,75 @@ +# copies the shared libraries the game needs next to it, where its RPATH ($ORIGIN) finds them first. Linux only: +# cmake -DGAME= -DSEARCH_DIRS= [-DCMAKE_OBJDUMP=] -P bundle_runtime_libs.cmake +# +# 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 + +get_filename_component(game_folder "${GAME}" DIRECTORY) +set(manifest "${game_folder}/bundled_libs.txt") + +# the libraries copied by the previous build go first: the game's RPATH would find them in its folder, and then +# a library updated in the system would never be copied again +if(EXISTS "${manifest}") + file(STRINGS "${manifest}" previous) + foreach(name IN LISTS previous) + if(NOT name STREQUAL "") + file(REMOVE "${game_folder}/${name}") + endif() + endforeach() + file(REMOVE "${manifest}") +endif() + +string(REPLACE "|" ";" search_dirs "${SEARCH_DIRS}") +if(DEFINED ENV{LD_LIBRARY_PATH}) + string(REPLACE ":" ";" ld_library_path "$ENV{LD_LIBRARY_PATH}") + list(APPEND search_dirs ${ld_library_path}) +endif() +list(REMOVE_ITEM search_dirs "") +list(REMOVE_DUPLICATES search_dirs) + +set(system_libraries + "^ld-linux" + "^linux-vdso" + "^lib(c|m|dl|rt|pthread|resolv|util|mvec|anl|nsl|crypt|BrokenLocale|thread_db)\\.so" + "^libstdc\\+\\+\\.so" + "^libgcc_s\\.so" + "^lib(GL|GLX|EGL|OpenGL|GLdispatch|GLESv1_CM|GLESv2|GLU|gbm|drm|vulkan)\\.so" + "^libX[A-Za-z0-9_-]*\\.so" + "^libxcb" + "^libxkbcommon" + "^libwayland-" + "^libdecor" + "^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") + +file(GET_RUNTIME_DEPENDENCIES + EXECUTABLES "${GAME}" + RESOLVED_DEPENDENCIES_VAR resolved + UNRESOLVED_DEPENDENCIES_VAR unresolved + DIRECTORIES ${search_dirs} + PRE_EXCLUDE_REGEXES ${system_libraries}) + +if(unresolved) + list(JOIN unresolved ", " unresolved_text) + message(WARNING "Bundled libraries: not found, so not copied next to the game: ${unresolved_text}") +endif() + +# each library is copied under the name the game asks for (libpng16.so.16), as a file rather than the chain of +# symlinks it is in the system: the build artifacts don't keep symlinks +set(names "") +foreach(library IN LISTS resolved) + get_filename_component(name "${library}" NAME) + file(REAL_PATH "${library}" source) + file(COPY_FILE "${source}" "${game_folder}/${name}") + list(APPEND names "${name}") +endforeach() + +list(SORT names) +list(JOIN names "\n" manifest_text) +file(WRITE "${manifest}" "${manifest_text}\n") +list(LENGTH names count) +list(JOIN names " " names_text) +message("Bundled libraries (${count}): ${names_text}") diff --git a/CMake_modules/wamr/CMakeLists.txt b/CMake_modules/wamr/CMakeLists.txt new file mode 100644 index 000000000..d12d48cd4 --- /dev/null +++ b/CMake_modules/wamr/CMakeLists.txt @@ -0,0 +1,67 @@ +# The WebAssembly Micro Runtime (ref/wamr) for the WebAssembly script screens (scripting/wasmprogram.cpp). +# +# Built here, in a directory of its own, because the WAMR build scripts set their configuration with +# add_definitions() and include_directories(): kept in this directory, none of it reaches the game's sources. +# Only the interpreter is built (see WAMR_BUILD_FAST_INTERP), with instruction metering so that a screen stuck in a loop +# can't hang the worker thread, and without the signal-based bounds checks, which would compete with the +# game's own crash handling. + +if (WIN32) + set(WAMR_BUILD_PLATFORM "windows") +elseif (APPLE) + set(WAMR_BUILD_PLATFORM "darwin") +else () + set(WAMR_BUILD_PLATFORM "linux") +endif () + +set(WAMR_ROOT_DIR "${CMAKE_SOURCE_DIR}/ref/wamr") + +set(WAMR_BUILD_INTERP 1) +# the fast interpreter counts the instructions only where it dispatches with computed gotos (GCC, Clang): built with +# MSVC it would let a screen stuck in a loop hang the worker. the classic interpreter counts them everywhere +if (MSVC) + set(WAMR_BUILD_FAST_INTERP 0) +else () + set(WAMR_BUILD_FAST_INTERP 1) +endif () +set(WAMR_BUILD_AOT 0) +set(WAMR_BUILD_JIT 0) +set(WAMR_BUILD_FAST_JIT 0) +set(WAMR_BUILD_LIBC_BUILTIN 0) +set(WAMR_BUILD_LIBC_WASI 0) +set(WAMR_BUILD_MULTI_MODULE 0) +set(WAMR_BUILD_LIB_PTHREAD 0) +set(WAMR_BUILD_LIB_WASI_THREADS 0) +set(WAMR_BUILD_THREAD_MGR 0) +set(WAMR_BUILD_SIMD 0) +set(WAMR_BUILD_BULK_MEMORY 1) +set(WAMR_BUILD_REF_TYPES 1) +set(WAMR_BUILD_MINI_LOADER 0) +set(WAMR_BUILD_INSTRUCTION_METERING 1) +# NOTE: the calls into the natives use WAMR's assembler invokeNative (MASM with MSVC). its C version +# (WAMR_BUILD_INVOKE_NATIVE_GENERAL) crashes on Windows x64 as soon as a module runs +set(WAMR_DISABLE_HW_BOUND_CHECK 1) +set(WAMR_DISABLE_STACK_HW_BOUND_CHECK 1) + +find_package(Threads REQUIRED) +include("${WAMR_ROOT_DIR}/build-scripts/runtime_lib.cmake") + +add_library(eu07_wamr STATIC ${WAMR_RUNTIME_LIB_SOURCE}) +target_include_directories(eu07_wamr INTERFACE "${WAMR_ROOT_DIR}/core/iwasm/include") +# with MSVC the WAMR headers declare the API dllimport unless told otherwise; the library is linked statically +target_compile_definitions(eu07_wamr INTERFACE "WASM_RUNTIME_API_EXTERN=") +target_link_libraries(eu07_wamr PRIVATE Threads::Threads) +if (WIN32) + target_link_libraries(eu07_wamr PRIVATE ws2_32 ntdll) +else () + target_link_libraries(eu07_wamr PRIVATE m ${CMAKE_DL_LIBS}) +endif () +if (MSVC) + # third-party code: its warnings are not ours to fix + target_compile_options(eu07_wamr PRIVATE /W0) +else () + target_compile_options(eu07_wamr PRIVATE -w) +endif () +set_target_properties(eu07_wamr PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib" + FOLDER "libraries") diff --git a/GEMINI.md b/GEMINI.md new file mode 100644 index 000000000..bf28f3062 --- /dev/null +++ b/GEMINI.md @@ -0,0 +1,5 @@ +# MaSzyna: notes for Gemini CLI + +The instructions for every coding agent in this repository are in `AGENTS.md`. Add or change rules there, not here. + +@./AGENTS.md diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index aa64b1cf0..27271b817 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -14,6 +14,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include "hamulce.h" +#include "couplerphysics.h" #include "scripting/ladderlogic.h" #include "vehicle/odometerreading.h" @@ -1256,6 +1257,7 @@ struct TCoupling double Dist = 0.0; /*strzalka ugiecia zderzaków*/ bool CheckCollision = false; /*czy sprawdzac sile czy pedy*/ float stretch_duration{0.f}; // seconds, elapsed time with excessive force applied to the coupler + bool broken{false}; // the coupler broke (damage_coupler()), until it's repaired (repair_coupler()) // optional adapter piece double adapter_length{0.0}; // meters, value added on the given end to standard vehicle (half)length double adapter_height{0.0}; // meters, distance from rail level @@ -1265,6 +1267,11 @@ struct TCoupling power_coupling power_110v; power_coupling power_24v; + // 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 + coupler_physics::end_parameters physics; + coupler_physics::pair_state physics_state; + int sounds{0}; // sounds emitted by the coupling devices bool Render = false; /*ABu: czy rysowac jak zaczepiony sprzeg*/ std::string control_type; // abstraction of control coupling interface and communication standard @@ -2008,6 +2015,9 @@ class TMoverParameters glm::vec3 Front{}; std::string Name; /*nazwa wlasna*/ TCoupling Couplers[2]; // urzadzenia zderzno-sprzegowe, polaczenia miedzy wagonami + // the physical coupler model covers the vehicle: it's in the player's train or in one the player's train closes in on + // (vehicle_table::update_coupler_physics()); with couplerphysics all in eu07.ini every vehicle is covered + bool CouplerPhysics{false}; std::array Neighbours; // potential collision sources bool Power110vIsAvailable = false; // cached availability of 110v power bool Power24vIsAvailable = false; // cached availability of 110v power @@ -2267,6 +2277,7 @@ class TMoverParameters int SpeedCtrlAutoTurnOffFlag = 0; /*czy tempomat sam się wyłącza*/ bool EIMCtrlAdditionalZeros = false; /*czy ma dodatkowe zero jazdy i zero hamowania */ bool EIMCtrlEmergency = false; /*czy ma dodatkowe zero jazdy i zero hamowania */ + bool EIMCtrlMainEmergency = false; /*czy zadajnik typu 2 (Elf) ma pozycje hamowania naglego ponizej swojej pozycji 0*/ double eimv_pr = 0; /*realizowany procent dostepnej sily rozruchu/hamowania*/ double eimv[21]; static std::vector const eimv_labels; @@ -2384,6 +2395,10 @@ class TMoverParameters int DettachStatus(int ConnectNo); bool Dettach(int ConnectNo); void damage_coupler(int const End); + // repairs the broken coupler of the end, and the one of the vehicle it was coupled with, so they can be coupled + // again; the vehicles clear their coupler damage once neither of their couplers is broken. returns: whether there + // was a broken coupler to repair + bool repair_coupler(int const End); void Derail(DerailReason Reason); bool DirectionForward(); bool DirectionBackward(void); /*! kierunek ruchu*/ @@ -2441,6 +2456,15 @@ class TMoverParameters int MainCtrlNoPowerPos() const; // highest setting of master controller which won't cause engine to generate extra power int MainCtrlActualPowerPos() const; // current actual setting of master controller, relative to the highest setting not generating extra power int MainCtrlPowerPos() const; // current setting of master controller, relative to the highest setting not generating extra power + // positions the master controller of the EIMCtrlType 2 (Elf) has below its own position 0, the emergency brake (0 or 1) + int EIMCtrlEmergencyPositions() const; + // whether the master controller is in its emergency brake position (EIMCtrlType 2 with EIMCtrlMainEmergency) + bool IsMainCtrlEmergencyPos() const; + // the master controller position sent to the coupled vehicles ("MainCtrl"), the same with and without + // EIMCtrlMainEmergency: the Elf's positions without the emergency brake one, which goes as the full braking + int MainCtrlPosForCoupled() const; + // the master controller position of this vehicle for one received from a coupled vehicle ("MainCtrl") + int MainCtrlPosFromCoupled(int Position) const; /*! pomocniczy nastawnik:*/ bool IncScndCtrl(int CtrlSpeed); bool DecScndCtrl(int CtrlSpeed); @@ -2521,6 +2545,17 @@ class TMoverParameters double BrakeForceP(double press, double velocity) const; double BrakeForce(const TTrackParam &Track); double CouplerForce(int const End, 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; + // the force of the coupling at the end by the physical model (couplerphysics in eu07.ini), see couplerphysics.h + double coupler_force_physical(int const End, double const dt); + // with the physical model: whether the vehicles at the end hit the stop of their springs at the last update and + // still close in on it, so that they collide; a hit hard enough breaks the coupling or crushes the buffers + bool coupler_stop_hit(int const End, TMoverParameters &Other, int const OtherEnd); + // couples the automatic couplers of the end and of the other vehicle pressed against each other, unless the hit + // is too fast for them to catch + void automatic_coupling(int const End, TMoverParameters &Other, int const OtherEnd); void CollisionDetect(int const End, double const dt); // closing speed of a collision [km/h] above which the vehicles involved may derail, adjusted for their mass ratio static constexpr double SafeCollisionVelocity{15.0}; diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index b105ba428..0099e8e62 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -643,6 +643,9 @@ bool TMoverParameters::Attach(int ConnectNo, int ConnectToNr, TMoverParameters * // stykaja sie zderzaki i kompatybilne typy sprzegow, chyba że łączenie na starcie if (thiscoupler.CouplingFlag == coupling::faux) { + // a new coupling: the play of the coupling as set up anew, without the stretch of the one before + thiscoupler.physics_state.couple(); + othercoupler.physics_state.couple(); // jeśli wcześniej nie było połączone, ustalenie z której strony rysować sprzęg thiscoupler.Render = true; // tego rysować othercoupler.Render = false; // a tego nie @@ -1334,6 +1337,15 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) auto const otherend{Neighbours[End].vehicle_end}; auto const &othercoupler{othervehicle->Couplers[otherend]}; + auto const physical{coupler_physics_at(End)}; + if (physical && false == coupler_stop_hit(End, *othervehicle, otherend)) + { + return; + } + // the share of the energy of the relative motion the hit takes: in the physical model the springs gone solid give + // for good, rather than spring back as the legacy model has it + auto const loss{physical ? coupler_physics::solid_hit_loss(thiscoupler.physics, othercoupler.physics) : (thiscoupler.beta + othercoupler.beta) / 2.0}; + // the velocities along this vehicle's axis: the other vehicle's one is turned around when the vehicles face each // other (touch with the same ends), as in CouplerForce() auto const otherdirection{DirPatch(End, otherend)}; @@ -1347,12 +1359,12 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) { case 0: { - CCF = ComputeCollision(velocity, othervehiclevelocity, TotalMass, othervehicle->TotalMass, (thiscoupler.beta + othercoupler.beta) / 2.0, VirtualCoupling) / dt; + CCF = ComputeCollision(velocity, othervehiclevelocity, TotalMass, othervehicle->TotalMass, loss, VirtualCoupling) / dt; break; // yB: ej ej ej, a po } case 1: { - CCF = ComputeCollision(othervehiclevelocity, velocity, othervehicle->TotalMass, TotalMass, (thiscoupler.beta + othercoupler.beta) / 2.0, VirtualCoupling) / dt; + CCF = ComputeCollision(othervehiclevelocity, velocity, othervehicle->TotalMass, TotalMass, loss, VirtualCoupling) / dt; break; } default: @@ -1363,7 +1375,8 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) if (Global.crash_damage) { - if (-thiscoupler.Dist >= thiscoupler.DmaxB && FuzzyLogic(std::abs(CCF), 5.0 * (thiscoupler.FmaxC + 1.0), p_coupldmg)) + // 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)) { // small chance to smash the coupler if it's hit with excessive force damage_coupler(End); @@ -1392,18 +1405,21 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) } } - // adjust velocity and acceleration of affected vehicles + // adjust velocity and acceleration of affected vehicles. the physical model changes the velocities alone: the + // 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)) { auto const accelerationchange{(velocity - V) / dt}; - AccS += accelerationchange; + AccS += accelerationchange * accelerationspike; V = velocity; } if (false == TestFlag(othervehicle->DamageFlag, dtrain_out)) { auto const othervehiclenewvelocity{othervehiclevelocity * otherdirection}; // back along the other vehicle's axis auto const othervehicleaccelerationchange{(othervehiclenewvelocity - othervehicle->V) / dt}; - othervehicle->AccS += othervehicleaccelerationchange; + othervehicle->AccS += othervehicleaccelerationchange * accelerationspike; othervehicle->V = othervehiclenewvelocity; } } @@ -1421,39 +1437,72 @@ void TMoverParameters::damage_coupler(int const End) if (SetFlag(DamageFlag, dtrain_coupling)) EventFlag = true; - if ((thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose) + auto const hosetorn{(thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose}; + if (hosetorn) { // hamowanie nagle - zerwanie przewodow hamulcowych AlarmChainFlag = true; } thiscoupler.CouplingFlag = 0; + thiscoupler.broken = true; if (thiscoupler.Connected != nullptr) { - switch (End) + // break connection with other vehicle, if there's any: on the end it's coupled with, which is the front one too + // for vehicles facing each other + auto &othercoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr]}; + othercoupler.CouplingFlag = coupling::faux; + // the coupling broke between the two, either end can be repaired + othercoupler.broken = true; + if (hosetorn && coupler_physics_at(End)) { - // break connection with other vehicle, if there's any - case 0: - { - thiscoupler.Connected->Couplers[end::rear].CouplingFlag = coupling::faux; - break; - } - case 1: - { - thiscoupler.Connected->Couplers[end::front].CouplingFlag = coupling::faux; - break; - } - default: - { - break; - } + // the brake pipe of the other part of the train vents through the torn hose as well + thiscoupler.Connected->AlarmChainFlag = true; } } WriteLog("Bad driving: " + Name + " broke a coupler"); } +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 +void repair(TMoverParameters &Vehicle, TCoupling &Coupler) +{ + Coupler.broken = false; + Coupler.stretch_duration = 0.f; + Coupler.physics_state.couple(); + if (Vehicle.Couplers[end::front].broken || Vehicle.Couplers[end::rear].broken) + { + return; + } + ClearFlag(Vehicle.DamageFlag, dtrain_coupling); + // either vehicle of the pair may have been braking through the torn hose + Vehicle.AlarmChainFlag = false; +} + +} // namespace + +bool TMoverParameters::repair_coupler(int const End) +{ + auto &thiscoupler{Couplers[End]}; + if (false == thiscoupler.broken) + { + return false; + } + repair(*this, thiscoupler); + // the other half of the coupling, which may be the vehicle flagged with the damage + if (auto *other{thiscoupler.Connected}; other != nullptr && other->Couplers[thiscoupler.ConnectedNr].broken) + { + repair(*other, other->Couplers[thiscoupler.ConnectedNr]); + } + WriteLog(std::format("Coupler of {} repaired, at its {} end", Name, End == end::front ? "front" : "rear")); + return true; +} + void TMoverParameters::Derail(DerailReason const Reason) { if (SetFlag(DamageFlag, dtrain_out)) @@ -2626,7 +2675,7 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) if (true == OK) { ScndCtrlResistiveLockCheck(); // e.g. from the last series position on to the resistive parallel ones - SendCtrlToNext("MainCtrl", MainCtrlPos, CabActive); //??? + SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); //??? SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); } @@ -2752,7 +2801,7 @@ bool TMoverParameters::DecMainCtrl(int CtrlSpeed) if (OK) { ScndCtrlResistiveLockCheck(); // the shunt drops when the master controller leaves a resistance-free position - /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPos, CabActive); // hmmmm...???!!! + /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); // hmmmm...???!!! /*OK:=*/SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); } } @@ -2800,7 +2849,7 @@ int TMoverParameters::MainCtrlNoPowerPos() const } case 2: { - return 3; + return 3 + EIMCtrlEmergencyPositions(); } case 3: { @@ -2825,6 +2874,27 @@ int TMoverParameters::MainCtrlPowerPos() const return MainCtrlPos - MainCtrlNoPowerPos(); } +int TMoverParameters::EIMCtrlEmergencyPositions() const +{ + return (EIMCtrlType == 2 && EIMCtrlMainEmergency) ? 1 : 0; +} + +bool TMoverParameters::IsMainCtrlEmergencyPos() const +{ + return MainCtrlPos < EIMCtrlEmergencyPositions(); +} + +int TMoverParameters::MainCtrlPosForCoupled() const +{ + // the emergency brake itself reaches the train through the brake pipe, vented by the vehicle driven from + return std::max(0, MainCtrlPos - EIMCtrlEmergencyPositions()); +} + +int TMoverParameters::MainCtrlPosFromCoupled(int const Position) const +{ + return Position + EIMCtrlEmergencyPositions(); +} + // ************************************************************************************************* // Q: 20160710 // zwiększenie bocznika @@ -2866,7 +2936,7 @@ bool TMoverParameters::IncScndCtrl(int CtrlSpeed) OK = false; if (OK) { - /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPos, CabActive); //??? + /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); //??? /*OK:=*/SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); } } @@ -2928,7 +2998,7 @@ bool TMoverParameters::DecScndCtrl(int CtrlSpeed) OK = false; if (OK) { - /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPos, CabActive); //??? + /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); //??? /*OK:=*/SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); } } @@ -4690,8 +4760,9 @@ 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) - if (RadioStopFlag || AlarmChainFlag || (EIMCtrlEmergency && LocalBrakePosA >= 1.0) || SecuritySystem.is_braking() || + // 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)) { @@ -5450,6 +5521,10 @@ double TMoverParameters::Adhesive(double staticfriction) const // ************************************************************************************************* double TMoverParameters::CouplerForce(int const End, double dt) { + if (coupler_physics_at(End)) + { + return coupler_force_physical(End, dt); + } auto &thiscoupler{Couplers[End]}; auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; @@ -5563,27 +5638,9 @@ double TMoverParameters::CouplerForce(int const End, double dt) // zderzenie thiscoupler.CheckCollision = true; } - if (-newdistance >= std::min(collisiondistance, dEpsilon) && thiscoupler.type() == TCouplerType::Automatic && thiscoupler.type() == othercoupler.type() && thiscoupler.CouplingFlag == coupling::faux && - thiscoupler.AutomaticCouplingAllowed && - othercoupler.AutomaticCouplingAllowed) + if (-newdistance >= std::min(collisiondistance, dEpsilon)) { - // sprzeganie wagonow z samoczynnymi sprzegami - auto couplingtype{thiscoupler.AutomaticCouplingFlag & othercoupler.AutomaticCouplingFlag}; - // potentially exclude incompatible control coupling - if (thiscoupler.control_type != othercoupler.control_type) - { - couplingtype &= ~coupling::control; - } - couplingtype = CompatibleCoupling(End, *othervehicle, otherend, couplingtype); - - // too fast for the couplers to catch, the vehicles collide instead (and may derail, see CollisionDetect()) - auto const safe{AutomaticCouplingSafe(End, *othervehicle, otherend)}; - auto const caught{safe && Attach(End, otherend, othervehicle, couplingtype)}; - // HACK: we're reusing sound enum to mark whether vehicle was connected to another - AIFlag |= (caught ? sound::attachcoupler : 0); - // coupled, or locked until the vehicles part, so they don't couple as soon as the collision slows them down - thiscoupler.AutomaticCouplingAllowed = safe && false == caught; - othercoupler.AutomaticCouplingAllowed = safe && false == caught; + automatic_coupling(End, *othervehicle, otherend); } } } @@ -5598,6 +5655,172 @@ double TMoverParameters::CouplerForce(int const End, double dt) return CF; } +bool TMoverParameters::coupler_physics_at(int const End) const +{ + if (false == Global.coupler_physics) + { + return false; + } + if (Global.coupler_physics_all || CouplerPhysics) + { + return true; + } + // either vehicle of the pair covered takes the pair in, so both of them compute it the same way + auto const *other{Neighbours[End].vehicle}; + return other != nullptr && other->MoverParameters->CouplerPhysics; +} + +void TMoverParameters::automatic_coupling(int const End, TMoverParameters &Other, int const OtherEnd) +{ + auto &thiscoupler{Couplers[End]}; + auto &othercoupler{Other.Couplers[OtherEnd]}; + + if (thiscoupler.type() != TCouplerType::Automatic || thiscoupler.type() != othercoupler.type() || thiscoupler.CouplingFlag != coupling::faux || false == thiscoupler.AutomaticCouplingAllowed || + false == othercoupler.AutomaticCouplingAllowed) + { + return; + } + // sprzeganie wagonow z samoczynnymi sprzegami + auto couplingtype{thiscoupler.AutomaticCouplingFlag & othercoupler.AutomaticCouplingFlag}; + // potentially exclude incompatible control coupling + if (thiscoupler.control_type != othercoupler.control_type) + { + couplingtype &= ~coupling::control; + } + couplingtype = CompatibleCoupling(End, Other, OtherEnd, couplingtype); + + // too fast for the couplers to catch, the vehicles collide instead (and may derail, see CollisionDetect()) + auto const safe{AutomaticCouplingSafe(End, Other, OtherEnd)}; + auto const caught{safe && Attach(End, OtherEnd, &Other, couplingtype)}; + // HACK: we're reusing sound enum to mark whether vehicle was connected to another + AIFlag |= (caught ? sound::attachcoupler : 0); + // coupled, or locked until the vehicles part, so they don't couple as soon as the collision slows them down + thiscoupler.AutomaticCouplingAllowed = safe && false == caught; + othercoupler.AutomaticCouplingAllowed = safe && false == caught; +} + +namespace +{ + +// the gap between the ends of a coupled pair, taking up the play of the coupling, opens up enough to jerk the train +constexpr double coupler_stretch_threshold{0.001}; + +// the sounds of the buffers hitting each other, and of the coupling taking up its play +struct coupler_sound_input +{ + double gap{0.0}; // between the ends [m] + double previous_gap{0.0}; + double gap_rate{0.0}; // [m/s] + double draw_gear{0.0}; // deflection [m] + double previous_draw_gear{0.0}; + bool coupled{false}; + bool adapter{false}; + bool moving{false}; +}; + +int coupler_sounds(coupler_sound_input const &Input) +{ + if (Input.gap < 0.0 && Input.gap < Input.previous_gap && Input.gap_rate < -0.1 && false == Input.adapter) + { + // 090503: dzwieki pracy zderzakow + return std::abs(Input.gap_rate) > 5.0 ? sound::bufferclash | sound::loud : sound::bufferclash; + } + if (Input.coupled && Input.moving && Input.draw_gear > coupler_stretch_threshold && Input.previous_draw_gear <= coupler_stretch_threshold && std::abs(Input.gap_rate) > 0.005) + { + // 090503: dzwieki pracy sprzegu + return std::abs(Input.gap_rate) > 0.035 ? sound::couplerstretch | sound::loud : sound::couplerstretch; + } + return sound::none; +} + +} // namespace + +double TMoverParameters::coupler_force_physical(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 &state{thiscoupler.physics_state}; + + // the gap as it is now: the distance found at the start of the frame, and the movement of both vehicles since + auto const othervehiclemove{othervehicle->dMoveLen * DirPatch(End, otherend)}; + auto const gap{Neighbours[End].distance + (End == end::front ? othervehiclemove - dMoveLen : dMoveLen - othervehiclemove)}; + // the gap opens up when the front end falls behind the vehicle ahead of it, or the rear end runs ahead of the one behind + auto const gaprate{CouplerVelocityDifference(End, *othervehicle, otherend) * DirF(End)}; + auto const coupled{thiscoupler.CouplingFlag != coupling::faux}; + auto const adapter{thiscoupler.has_adapter() || othercoupler.has_adapter()}; + + if (false == coupled && Neighbours[End].distance > 0.05) + { // arbitrary distance + // potentially reset auto coupling lock + thiscoupler.AutomaticCouplingAllowed = true; + } + + 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})}; + + SetFlag(thiscoupler.sounds, coupler_sounds({gap, previousgap, gaprate, state.draw_gear.deflection, previousdrawgear, coupled, adapter, Vel > 1.0})); + + thiscoupler.CheckCollision = state.stop != 0; + // for the buffers drawn pressed in, see TDynamicObject: twice the deflection of the buffers of this end + thiscoupler.Dist = result.compression > 0.0 ? -2.0 * result.buffers_deflection : std::max(gap, 0.0); + // the link pulled past its yield force, which the AI drivers ease off on + thiscoupler.stretch_duration = result.overloaded ? thiscoupler.stretch_duration + static_cast(dt) : 0.f; + + if (result.broken) + { + damage_coupler(End); + } + if (false == coupled && gap < 0.0) + { + auto const collisiondistance{adapter ? std::min(thiscoupler.DmaxB, othercoupler.DmaxB) : thiscoupler.DmaxB + othercoupler.DmaxB}; + if (-gap >= std::min(collisiondistance, dEpsilon)) + { + automatic_coupling(End, *othervehicle, otherend); + } + } + + // tension pulls this vehicle towards the other one + auto const force{result.force * -DirF(End)}; + if (thiscoupler.CouplingFlag != coupling::faux) + { + // uzgadnianie prawa Newtona, as in CouplerForce() + othercoupler.CForce = -force * DirPatch(End, otherend); + } + return force; +} + +bool TMoverParameters::coupler_stop_hit(int const End, TMoverParameters &Other, int const OtherEnd) +{ + auto &thiscoupler{Couplers[End]}; + auto &othercoupler{Other.Couplers[OtherEnd]}; + auto &state{thiscoupler.physics_state}; + + // the draw gear went solid with the gap opening up, the buffers with it closing + auto const gaprate{CouplerVelocityDifference(End, Other, OtherEnd) * DirF(End)}; + auto const closing{state.stop > 0 ? gaprate : -gaprate}; + if (state.stop == 0 || closing <= 0.0) + { + // parting from the stop already, after the hit on the other vehicle's end + return false; + } + if (false == Global.crash_damage) + { + return true; + } + 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) + { + damage_coupler(End); + } + // a broken coupling lets the vehicles part + return false == hit.broken; +} + // ************************************************************************************************* // Q: 20160714 // oblicza sile trakcyjna lokomotywy (dla elektrowozu tez calkowity prad) @@ -7532,10 +7755,16 @@ void TMoverParameters::CheckEIMIC(double dt) eimic = 0; break; case 2: - if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) + 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; - switch (MainCtrlPos) + // the positions below are those of the controller without the emergency brake position + switch (MainCtrlPos - EIMCtrlEmergencyPositions()) { case 0: case 1: @@ -10946,6 +11175,82 @@ void TMoverParameters::LoadFIZ_Doors(std::string const &line) extract_value(DoorsPermitLightBlinking, "DoorsPermitLightBlinking", line, ""); } +namespace +{ + +// the value of an optional key of the line, or the default without it +double optional_value(std::string const &Line, std::string const &Key, double const Default) +{ + auto value{Default}; + extract_value(value, Key, Line, ""); + return value; +} + +// the value of an optional key of the line given in kilo-units, in units; or the default (in units) without it +double optional_kilo_value(std::string const &Line, std::string const &Key, double const Default) +{ + auto value{0.0}; + return extract_value(value, Key, Line, "") && value > 0.0 ? value * 1000.0 : Default; +} + +// the play of a coupling as made, for each kind: a screw coupling is tightened so that the buffers touch, the knuckles of +// an automatic coupler have about a centimetre between them, a chain hangs loose +double default_slack(TCouplerType const Type) +{ + switch (Type) + { + case TCouplerType::Automatic: + return 0.005; + case TCouplerType::Chain: + return 0.05; + default: + return 0.0; + } +} + +// the parameters of the physical model of the coupling (couplerphysics in eu07.ini, see couplerphysics.h), taken from +// those of the legacy model, and the optional keys of the .fiz for what the legacy model doesn't have: +// Slack [m] the play of the coupling of this end, negative for a screw coupling tightened to press the buffers in +// ProgB, ProgC [-] progression of the buffers and of the draw gear, 0 linear, up to 0.9 +// UnloadB, UnloadC [-] force of the unloading curve of the buffers and of the draw gear to that of the loading one +// FyieldC [kN] the force past which the link stretches for good; DbreakC [m] the elongation at which it breaks +// kL [kN/m] stiffness of the steel parts past the travel of the springs; FcrushB [kN] the buffers give under it +// RestitutionSolid [-] coefficient of restitution of a hit on the springs gone solid +coupler_physics::end_parameters coupler_physics_parameters(TCoupling const &Coupler, std::string const &Line) +{ + coupler_physics::end_parameters parameters; + parameters.buffers = {Coupler.SpringKB, Coupler.DmaxB, std::clamp(optional_value(Line, "ProgB", 0.5), 0.0, 0.9)}; + parameters.draw_gear = {Coupler.SpringKC, Coupler.DmaxC, std::clamp(optional_value(Line, "ProgC", 0.3), 0.0, 0.9)}; + // only a screw coupling can be tightened to press the buffers in, and not past their travel + auto const tightest{Coupler.CouplerType == TCouplerType::Screw ? -Coupler.DmaxB : 0.0}; + parameters.slack = std::max(optional_value(Line, "Slack", default_slack(Coupler.CouplerType)), tightest); + // the legacy model sprang back at beta of the force it was loaded with + auto const unloading{Coupler.beta > 0.0 && Coupler.beta < 1.0 ? Coupler.beta : 0.5}; + parameters.buffers_unloading = std::clamp(optional_value(Line, "UnloadB", unloading), 0.05, 1.0); + parameters.draw_gear_unloading = std::clamp(optional_value(Line, "UnloadC", unloading), 0.05, 1.0); + // as much as the legacy model had + parameters.damping = CouplerTune * (Coupler.FmaxC + Coupler.FmaxB) * std::max(Coupler.beta, 0.0); + + // FmaxC is the rated breaking force of the coupling + auto const ultimate{std::max(Coupler.FmaxC, 1.0)}; + auto const yield{std::min(optional_kilo_value(Line, "FyieldC", 0.8 * ultimate), ultimate)}; + auto const elongation{std::max(optional_value(Line, "DbreakC", 0.02), 0.001)}; + parameters.link = {yield, ultimate, std::max((ultimate - yield) / elongation, 1.0), Coupler.CouplerType != TCouplerType::Articulated}; + // the steel parts give a few millimetres under the rated force + parameters.link_stiffness = optional_kilo_value(Line, "kL", ultimate / 0.003); + parameters.crush_force = optional_kilo_value(Line, "FcrushB", 2.5 * std::max(Coupler.FmaxB, Coupler.FmaxC)); + parameters.solid_restitution = std::clamp(optional_value(Line, "RestitutionSolid", parameters.solid_restitution), 0.05, 0.95); + return parameters; +} + +void scale_strength(coupler_physics::link_strength &Link, double const Factor) +{ + Link.yield *= Factor; + Link.ultimate *= Factor; +} + +} // namespace + void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Index) { @@ -11024,11 +11329,21 @@ void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Inde thiscoupler->DmaxB = std::max(0.05, thiscoupler->FmaxC / thiscoupler->SpringKB); } + thiscoupler->physics = coupler_physics_parameters(*thiscoupler, line); + if (Index == 0) { // 0 indicates single entry for both couplers Couplers[1] = Couplers[0]; } + // each coupling as made is a little stronger than its rated force, a different one at each end + for (int end = end::front; end <= end::rear; ++end) + { + if (Index == 0 || end == (Index == 2 ? end::rear : end::front)) + { + scale_strength(Couplers[end].physics.link, coupler_physics::strength_scatter(Name, end)); + } + } } void TMoverParameters::LoadFIZ_TurboPos(std::string const &Input) @@ -11205,6 +11520,16 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) extract_value(LocHandleTimeTraxx, "LocalBrakeTraxx", line, ""); extract_value(EIMCtrlAdditionalZeros, "EIMCtrlAddZeros", line, ""); extract_value(EIMCtrlEmergency, "EIMCtrlEmergency", line, ""); + // Elf (EIMCtrlType 2): an emergency brake position below the controller's position 0, which shifts the other positions up by one + extract_value(EIMCtrlMainEmergency, "EIMCtrlMainEmergency", line, ""); + if (auto const elfpositions{4 + EIMCtrlEmergencyPositions()}; EIMCtrlEmergencyPositions() > 0 && MainCtrlPosNo < elfpositions) + { + // the old positions in the file: without the fix-up the controller would have no power position, and the + // reverser would stop working at neutral (DirChangeMaxPos read before, in the old positions) + MainCtrlMaxDirChangePos += EIMCtrlEmergencyPositions(); + ErrorLog(std::format("Bad fiz: EIMCtrlMainEmergency needs MCPN={} in {}, DirChangeMaxPos taken as {}", elfpositions, TypeName, MainCtrlMaxDirChangePos)); + MainCtrlPosNo = elfpositions; + } extract_value(ScndS, "ScndS", line, ""); // brak pozycji rownoleglej przy niskiej nastawie PSR extract_value(ScndCtrlResistiveLock, "ScndCtrlResistiveLock", line, ""); // bocznikowanie tylko na pozycjach bezoporowych @@ -12550,9 +12875,10 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do if (Command == "MainCtrl") { - if (MainCtrlPosNo >= floor(CValue1)) + // sent as MainCtrlPosForCoupled(), passed on unchanged + if (auto const position{MainCtrlPosFromCoupled(static_cast(floor(CValue1)))}; MainCtrlPosNo >= position) { - MainCtrlPos = static_cast(floor(CValue1)); + MainCtrlPos = position; if (DelayCtrlFlag) { if (LastRelayTime >= InitialCtrlDelay && MainCtrlPos == 1) diff --git a/McZapkie/couplerphysics.cpp b/McZapkie/couplerphysics.cpp new file mode 100644 index 000000000..f6a226b55 --- /dev/null +++ b/McZapkie/couplerphysics.cpp @@ -0,0 +1,291 @@ +/* +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 "couplerphysics.h" + +#include +#include +#include +#include + +namespace coupler_physics { + +namespace { + +// the transition between the loading and the unloading curve of a device, to the secant stiffness of the pair: the +// friction holds the device stiffer than its springs until the force changes enough to slip it +constexpr double transition_factor{3.0}; +// the force, the deflection and the energy of a curve are computed within this many iterations of the inverse +constexpr int inverse_iterations{50}; +constexpr int series_iterations{60}; + +// a device which doesn't give at all, standing in for the buffers of an end with an adapter +constexpr spring_curve rigid{1.0, 0.0, 0.0}; + +double series_stiffness(double First, double Second) { + return First * Second / (First + Second); +} + +// the buffers of the pair: those of both ends in series, or with an adapter on either end, the device with the shorter +// travel alone, the one of the automatic coupler which takes the push +struct pressed_devices { + spring_curve first; + spring_curve second; + double unloading{0.5}; + double damping{0.0}; +}; + +bool shorter(spring_curve const &First, spring_curve const &Second) { + return std::tie(First.travel, First.stiffness, First.progression) <= std::tie(Second.travel, Second.stiffness, Second.progression); +} + +pressed_devices buffers_of(end_parameters const &First, end_parameters const &Second, bool const Adapter) { + auto const unloading{0.5 * (First.buffers_unloading + Second.buffers_unloading)}; + auto const damping{0.5 * (First.damping + Second.damping)}; + if (false == Adapter) { + return {First.buffers, Second.buffers, unloading, damping}; + } + auto const &coupler{shorter(First.buffers, Second.buffers) ? First.buffers : Second.buffers}; + return {coupler, rigid, unloading, damping}; +} + +pressed_devices draw_gears_of(end_parameters const &First, end_parameters const &Second) { + return {First.draw_gear, Second.draw_gear, 0.5 * (First.draw_gear_unloading + Second.draw_gear_unloading), 0.5 * (First.damping + Second.damping)}; +} + +struct pressed_force { + double force{0.0}; // with the friction and the damping [N] + double curve_force{0.0}; // of the loading curve [N] + double first_deflection{0.0}; // of the first device [m] + bool solid{false}; // both devices at the end of their travel +}; + +// the force of the devices pressed (or pulled) by the deflection growing at the rate +pressed_force press(pressed_devices const &Devices, hysteresis &State, double const Deflection, double const Rate) { + if (Deflection <= 0.0) { + State.reset(); + return {}; + } + auto const split{series(Devices.first, Devices.second, Deflection)}; + auto const travel{Devices.first.travel + Devices.second.travel}; + auto const top{std::max(Devices.first.end_force(), Devices.second.end_force())}; + auto const transition{transition_factor * top / std::max(travel, 1e-3)}; + auto const friction{State.update(Deflection, split.force, Devices.unloading * split.force, transition)}; + // a buffer pushes, a draw gear pulls, neither the other way round however fast they spring back + return {std::max(0.0, friction + Devices.damping * Rate), split.force, split.first, Deflection >= travel}; +} + +bool weaker(link_strength const &First, link_strength const &Second) { + return std::tie(First.ultimate, First.yield, First.hardening) <= std::tie(Second.ultimate, Second.yield, Second.hardening); +} + +} // namespace + +double spring_curve::force(double const Deflection) const { + if (travel <= 0.0 || Deflection <= 0.0) { + return 0.0; + } + auto const u{std::min(Deflection / travel, 1.0)}; + return end_force() * ((1.0 - progression) * u + progression * u * u * u); +} + +double spring_curve::deflection(double const Force) const { + if (travel <= 0.0 || Force <= 0.0) { + return 0.0; + } + auto const f{Force / end_force()}; + if (f >= 1.0) { + return travel; + } + if (progression <= 0.0) { + return f * travel; + } + // the curve is rising and convex, so Newton's method from the end of the travel closes in from above + auto u{1.0}; + auto step{1.0}; + for (int iteration = 0; iteration < inverse_iterations && std::abs(step) > 1e-15; ++iteration) { + auto const value{progression * u * u * u + (1.0 - progression) * u - f}; + auto const slope{3.0 * progression * u * u + (1.0 - progression)}; + step = value / slope; + u -= step; + } + return std::clamp(u, 0.0, 1.0) * travel; +} + +double spring_curve::energy(double const Deflection) const { + if (travel <= 0.0 || Deflection <= 0.0) { + return 0.0; + } + auto const u{std::min(Deflection / travel, 1.0)}; + return end_force() * travel * ((1.0 - progression) * u * u / 2.0 + progression * u * u * u * u / 4.0); +} + +series_split series(spring_curve const &First, spring_curve const &Second, double const Deflection) { + if (Deflection <= 0.0) { + return {}; + } + if (Second.travel <= 0.0) { + return {First.force(Deflection), std::min(Deflection, First.travel), 0.0}; + } + if (First.travel <= 0.0) { + return {Second.force(Deflection), 0.0, std::min(Deflection, Second.travel)}; + } + if (std::tie(First.stiffness, First.travel, First.progression) == std::tie(Second.stiffness, Second.travel, Second.progression)) { + auto const half{std::min(Deflection / 2.0, First.travel)}; + return {First.force(half), half, half}; + } + auto const top{std::max(First.end_force(), Second.end_force())}; + if (Deflection >= First.travel + Second.travel) { + return {top, First.travel, Second.travel}; + } + // the force at which the deflections of both add up to the given one. the sum doesn't depend on the order of + // the devices, so neither does the result + auto low{0.0}; + auto high{top}; + for (int iteration = 0; iteration < series_iterations; ++iteration) { + auto const middle{0.5 * (low + high)}; + if (First.deflection(middle) + Second.deflection(middle) < Deflection) { + low = middle; + } + else { + high = middle; + } + } + auto const force{0.5 * (low + high)}; + return {force, First.deflection(force), Second.deflection(force)}; +} + +double hysteresis::update(double const Deflection, double const Loading, double const Unloading, double const Transition) { + force = std::clamp(force + Transition * (Deflection - deflection), std::min(Unloading, Loading), Loading); + deflection = Deflection; + return force; +} + +void hysteresis::reset() { + force = 0.0; + deflection = 0.0; +} + +double plastic_elongation(link_strength const &Link, double const Force, double const Elongation) { + if (false == Link.breakable || Force <= Link.yield) { + return Elongation; + } + return std::max(Elongation, (Force - Link.yield) / Link.hardening); +} + +double impact_force(double const Velocity, double const Stiffness, double const Mass1, double const Mass2) { + if (Velocity <= 0.0 || Mass1 <= 0.0 || Mass2 <= 0.0) { + return 0.0; + } + auto const mass{Mass1 * Mass2 / (Mass1 + Mass2)}; + return Velocity * std::sqrt(Stiffness * mass); +} + +double strength_scatter(std::string_view const Name, int const End) { + // FNV-1a, which std::hash isn't on every compiler + std::uint64_t hash{14695981039346656037ULL}; + auto const mix = [&hash](unsigned char const Byte) { + hash ^= Byte; + hash *= 1099511628211ULL; + }; + for (auto const character : Name) { + mix(static_cast(character)); + } + mix(static_cast(End)); + // the 53 high bits, as a fraction + auto const fraction{static_cast(hash >> 11) / 9007199254740992.0}; + return 1.0 + 0.2 * fraction; +} + +link_strength weaker_link(end_parameters const &First, end_parameters const &Second) { + auto link{weaker(First.link, Second.link) ? First.link : Second.link}; + // an articulated joint holds whatever the end of the other section is set up to + link.breakable = First.link.breakable && Second.link.breakable; + return link; +} + +double solid_hit_loss(end_parameters const &First, end_parameters const &Second) { + // the collision needs some bounce left (ComputeCollision() asserts it) + auto const restitution{std::clamp(0.5 * (First.solid_restitution + Second.solid_restitution), 0.05, 0.95)}; + return 1.0 - restitution * restitution; +} + +void pair_state::couple() { + draw_gear.reset(); + elongation = 0.0; +} + +pair_result update_pair(end_parameters const &First, end_parameters const &Second, pair_state &State, pair_input const &Input) { + pair_result result; + State.stop = 0; + State.stop_force = 0.0; + + pressed_force pulled; + if (Input.coupled) { + auto const play{First.slack + Second.slack + State.elongation}; + pulled = press(draw_gears_of(First, Second), State.draw_gear, Input.gap - play, Input.gap_rate); + } + else { + State.draw_gear.reset(); + } + auto const pushed{press(buffers_of(First, Second, Input.adapter), State.buffers, -Input.gap, -Input.gap_rate)}; + + result.tension = pulled.force; + result.compression = pushed.force; + result.buffers_deflection = Input.adapter ? 0.0 : pushed.first_deflection; + if (pulled.solid) { + State.stop = 1; + State.stop_force = pulled.curve_force; + } + else if (pushed.solid) { + State.stop = -1; + State.stop_force = pushed.curve_force; + } + + if (Input.coupled) { + auto const link{weaker_link(First, Second)}; + result.overloaded = result.tension > link.yield; + if (Input.damage && link.breakable && result.tension >= link.ultimate) { + result.broken = true; + result.tension = 0.0; + State.draw_gear.reset(); + State.stop = std::min(State.stop, 0); + } + else if (Input.damage) { + State.elongation = plastic_elongation(link, result.tension, State.elongation); + } + } + + result.force = result.tension - result.compression; + State.gap = Input.gap; + return result; +} + +impact_result impact(end_parameters const &First, end_parameters const &Second, pair_state &State, double const Velocity, double const Mass1, double const Mass2) { + impact_result result; + if (State.stop == 0 || Velocity <= 0.0) { + return result; + } + auto const stiffness{series_stiffness(First.link_stiffness, Second.link_stiffness)}; + result.force = State.stop_force + impact_force(Velocity, stiffness, Mass1, Mass2); + if (State.stop > 0) { + auto const link{weaker_link(First, Second)}; + result.broken = link.breakable && result.force >= link.ultimate; + if (false == result.broken) { + State.elongation = plastic_elongation(link, result.force, State.elongation); + } + } + else { + result.crushed = result.force >= std::min(First.crush_force, Second.crush_force); + } + return result; +} + +} // namespace coupler_physics diff --git a/McZapkie/couplerphysics.h b/McZapkie/couplerphysics.h new file mode 100644 index 000000000..47789aba2 --- /dev/null +++ b/McZapkie/couplerphysics.h @@ -0,0 +1,140 @@ +#pragma once + +#include +#include + +// the physical model of the coupling of two vehicles, used with couplerphysics set in eu07.ini (the legacy model of +// TMoverParameters::CouplerForce() otherwise). each vehicle end brings its buffers and its draw gear: progressive +// springs with friction hysteresis, pressed in series against those of the other end. the coupling has play (slack) +// in tension, or pulls the buffers in when its screw is tightened, and its steel link stretches for good past its +// yield force and breaks at its ultimate one, under a steady pull or the jerk of a run-out of the slack +namespace coupler_physics { + +// force-deflection characteristic of the spring device of one vehicle end, its buffers or its draw gear: +// F(d) = F_end * ((1 - p) * u + p * u^3), u = d / travel, F_end = stiffness * travel +// p (the progression) 0 gives a linear spring; towards 1 it's soft at first and stiffens towards the end of the +// travel, as ring springs and elastomer pads do +struct spring_curve { + double stiffness{1.0}; // secant stiffness, up to the end of the travel [N/m] + double travel{0.1}; // [m] + double progression{0.0}; // 0 to 0.9 + + double end_force() const { return stiffness * travel; } + // force at the deflection [N], the deflection held within the travel + double force(double Deflection) const; + // deflection at the force [m]: the end of the travel at the end force and past it + double deflection(double Force) const; + // energy the device takes in along the curve up to the deflection [J] + double energy(double Deflection) const; +}; + +// the devices of both ends pressed against each other: they carry the same force, their deflections add up. past +// the end of the travel of one, the other one takes the rest. the result doesn't depend on the order of the two +struct series_split { + double force{0.0}; // [N] + double first{0.0}; // deflection of the first device [m] + double second{0.0}; // of the second one [m] +}; +series_split series(spring_curve const &First, spring_curve const &Second, double Deflection); + +// friction (Coulomb) hysteresis of a spring device: the force follows the loading curve while the deflection grows, +// drops to the unloading curve when it shrinks, and in between moves along a stiff transition line, as the friction +// of ring springs or of the wedges of a draw gear holds the device until the force changes enough +struct hysteresis { + double force{0.0}; // carried at the last update [N] + double deflection{0.0}; // at the last update [m] + + // the force at the new deflection, given the force of the loading and of the unloading curve there, and the + // stiffness of the transition between them [N/m] + double update(double Deflection, double Loading, double Unloading, double Transition); + void reset(); +}; + +// steel link of the coupling (the screw coupling and the hook, the knuckle of an automatic coupler): elastic up to +// the yield force, stretched for good past it (the hardening gives the force for each metre of it), broken at the +// ultimate force +struct link_strength { + double yield{std::numeric_limits::max()}; // [N] + double ultimate{std::numeric_limits::max()}; // [N] + double hardening{1.0}; // [N/m] + bool breakable{false}; // an articulated joint, or an end without a coupler set up, holds whatever +}; + +// the permanent elongation [m] the link has after carrying the force, given the one it had +double plastic_elongation(link_strength const &Link, double Force, double Elongation); +// peak force [N] of an elastic hit of two masses [kg] at the closing velocity [m/s] on a stop of the stiffness [N/m]: +// the kinetic energy of their relative motion all goes into the stop +double impact_force(double Velocity, double Stiffness, double Mass1, double Mass2); +// spread of the strength of the couplings as made: 1.0 to 1.2 of the rated force, fixed for the vehicle end, and the +// same on every compiler +double strength_scatter(std::string_view Name, int End); + +// what the model takes of one vehicle end +struct end_parameters { + spring_curve buffers; + spring_curve draw_gear; + double slack{0.0}; // play of the coupling in tension [m], negative for the buffers pressed in by a tightened screw coupling + double buffers_unloading{0.5}; // force of the unloading curve to that of the loading one + double draw_gear_unloading{0.5}; + double damping{0.0}; // viscous damping of the devices, while pressed [N s/m] + double link_stiffness{1.0}; // of the steel parts of the end, past the travel of the springs [N/m] + double crush_force{std::numeric_limits::max()}; // a hit on the buffers past their travel with this force crushes them [N] + // coefficient of restitution of a hit on the springs gone solid: the steel of the housings and the underframe gives + // for good rather than springing back, so the vehicles share their momentum rather than pass it on + double solid_restitution{0.2}; + link_strength link; +}; + +// the share of the energy of the relative motion a hit on the solid springs of the two ends takes, as the legacy +// collision (ComputeCollision()) takes it: 1 - e^2 +double solid_hit_loss(end_parameters const &First, end_parameters const &Second); + +// the weaker of the links of the two ends, which gives first; the same whichever end asks +link_strength weaker_link(end_parameters const &First, end_parameters const &Second); + +// state of the coupling of two vehicle ends, which both vehicles keep alike: each updates its own copy with the same +// gap, so the copies stay the same +struct pair_state { + hysteresis draw_gear; + hysteresis buffers; + double elongation{0.0}; // permanent, of the link [m]; it adds to the slack until the vehicles are coupled again + double gap{0.0}; // at the last update [m] + int stop{0}; // at the last update: 1 the draw gear went solid, -1 the buffers did, 0 neither + double stop_force{0.0}; // the springs carried at the stop [N] + + // a new coupling of the ends: the link adjusted (a screw coupling tightened anew), the draw gear released + void couple(); +}; + +struct pair_input { + double gap{0.0}; // between the ends [m], negative with the buffers pressed in + double gap_rate{0.0}; // [m/s] + 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) +}; + +struct pair_result { + double force{0.0}; // between the ends, tension positive [N] + double tension{0.0}; // carried by the link [N] + double compression{0.0}; // carried by the buffers [N] + double buffers_deflection{0.0}; // of the buffers of the first end [m] + bool overloaded{false}; // the link was pulled past its yield force + bool broken{false}; // the link broke, it carries nothing now +}; + +// the force between the first end and the second one at the gap, updating the state of the pair +pair_result update_pair(end_parameters const &First, end_parameters const &Second, pair_state &State, pair_input const &Input); + +// what a hit on the stop does to the ends +struct impact_result { + double force{0.0}; // peak force of the hit [N] + bool broken{false}; // the link broke under it + bool crushed{false}; // the buffers or the coupler of an end were crushed by it +}; + +// the hit on the stop the pair went solid against at the last update (State.stop), at the closing velocity [m/s], of +// the vehicles of the masses [kg]: stretches or breaks the link of a coupled pair, may crush the buffers +impact_result impact(end_parameters const &First, end_parameters const &Second, pair_state &State, double Velocity, double Mass1, double Mass2); + +} // namespace coupler_physics diff --git a/application/application.cpp b/application/application.cpp index d5e5cd44f..157644e8c 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/utilities.h" #include "simulation/simulation.h" #include "simulation/simulationsounds.h" +#include "simulation/blackboxrecorder.h" #include "vehicle/Train.h" #include "utilities/dictionary.h" #include "scene/sceneeditor.h" @@ -425,6 +426,16 @@ int eu07_application::init(int Argc, char *Argv[]) { m_taskqueue.init(); } + crashreport_add_info("luascreens_enabled", Global.luascreens_enabled ? "yes" : "no"); + crashreport_add_info("wasm_enabled", Global.wasm_enabled ? "yes" : "no"); + if (Global.luascreens_enabled || Global.wasm_enabled) + { + m_screenqueue.init(); + if (Global.screens_gpupost) + { + m_screenqueue.set_post_processor(GfxRenderer->Screen_post_processor()); + } + } if ((result = init_modes()) != 0) { ErrorLog("Failed to initialize game modes"); @@ -635,6 +646,7 @@ int eu07_application::run() EditorTerrain.update(Global.pCamera.Pos); m_taskqueue.update(); + m_screenqueue.update(); opengl_texture::reset_unit_cache(); if (!GfxRenderer->Render()) @@ -715,11 +727,15 @@ void eu07_application::exit() auto const step = [closing](char const *What) { WriteLog(std::format("Closing: {} at {} ms", What, std::chrono::duration_cast(std::chrono::steady_clock::now() - closing).count())); }; + step("the black box"); + simulation::Blackbox.close(); step("the modes"); for (auto &mode : m_modes) mode.reset(); step("the renderer"); + // the screens' post-processing goes with the renderer + m_screenqueue.set_post_processor(nullptr); GfxRenderer->Shutdown(); m_network.reset(); @@ -734,6 +750,7 @@ void eu07_application::exit() // the python workers detach their GL context on the way out, so they have to be done before the windows they use are destroyed m_taskqueue.exit(); + m_screenqueue.exit(); step("the windows"); for (auto *window : m_windows) { diff --git a/application/application.h b/application/application.h index 11415603b..850b66e1e 100644 --- a/application/application.h +++ b/application/application.h @@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/. #include "application/applicationmode.h" #include "scripting/PyInt.h" +#include "scripting/scriptscreens.h" #include "network/manager.h" #include "utilities/headtrack.h" #ifdef WITH_UART @@ -49,6 +50,10 @@ public: // frees the python gil and swaps out the main thread void release_python_lock(); + // the screens drawn by scripts (Lua, WebAssembly) + script_screen_queue & + screens() { + return m_screenqueue; } void exit(); void @@ -122,6 +127,7 @@ private: modeptr_array m_modes { nullptr }; // collection of available application behaviour modes mode_stack m_modestack; // current behaviour mode python_taskqueue m_taskqueue; + script_screen_queue m_screenqueue; std::vector m_windows; int m_glfwversion; diff --git a/application/drivermode.cpp b/application/drivermode.cpp index deb906a4a..cde7e80d7 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationtime.h" #include "simulation/simulationenvironment.h" #include "simulation/simulationtest.h" +#include "simulation/blackboxrecorder.h" #include "scene/scene.h" #include "rendering/lightarray.h" #include "rendering/particles.h" @@ -160,6 +161,30 @@ bool driver_mode::init() } // mode-specific update of simulation data. returns: false on error, true otherwise +namespace { + +// the camera as the black box tells it: where it is and where it looks, as the heading of a vehicle +blackbox::camera_state blackbox_camera(TCamera const &Camera, std::uint8_t const Mode, int const View) { + blackbox::camera_state state; + state.mode = Mode; + state.view = static_cast(View); + state.position = Camera.Pos; + state.pitch = Camera.Angle.x; + if (Camera.m_owner != nullptr && false == DebugCameraFlag) { + // it looks at a point, then turns by its yaw from there + auto const where{Camera.LookAt - Camera.Pos}; + state.heading = static_cast(std::atan2(where.x, where.z)) + Camera.Angle.y; + } + else { + // the yaw alone: 0 looks towards -z + state.heading = static_cast(std::atan2(-std::sin(Camera.Angle.y), -std::cos(Camera.Angle.y))); + } + state.heading = std::remainder(state.heading, 2.0f * glm::pi()); + return state; +} + +} // namespace + bool driver_mode::update() { @@ -306,6 +331,17 @@ bool driver_mode::update() simulation::Events.update(); simulation::Region->update_events(); simulation::Lights.update(); + { + // where the user looks from, for the black box + auto const &camera{DebugCameraFlag ? DebugCamera : Camera}; + auto const mode{DebugCameraFlag ? blackbox::camera_modes::debug : + false == FreeFlyModeFlag ? blackbox::camera_modes::cab : + m_externalview ? blackbox::camera_modes::external : + blackbox::camera_modes::free}; + simulation::Blackbox.camera(blackbox_camera(camera, mode, mode == blackbox::camera_modes::external ? m_externalviewmode : 0), + DebugCameraFlag ? nullptr : camera.m_owner); + } + simulation::Blackbox.update(deltatime); if (Global.test.enabled && simulation::is_ready) { diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 029b8d7f1..ba8e7556d 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -38,6 +38,26 @@ http://mozilla.org/MPL/2.0/. #include "utilities/uart.h" #endif +#include + +namespace { + +// how close to a broken coupler the camera has to be for the driving aid to offer its repair [m] +constexpr float coupler_repair_radius { 5.f }; + +// the broken coupler nearest to the camera, within reach: the vehicle and its end, or no vehicle +std::pair broken_coupler_nearby( glm::dvec3 const &Camera ) { + auto const *vehicle { std::get( simulation::Region->find_vehicle( Camera, coupler_repair_radius, false, true ) ) }; + if( vehicle == nullptr || vehicle->MoverParameters == nullptr ) { return { nullptr, end::front }; } + auto const front { glm::distance( vehicle->CouplerPosition( end::front ), Camera ) }; + auto const rear { glm::distance( vehicle->CouplerPosition( end::rear ), Camera ) }; + auto const nearest { front <= rear ? end::front : end::rear }; + if( std::min( front, rear ) > coupler_repair_radius || false == vehicle->MoverParameters->Couplers[ nearest ].broken ) { return { nullptr, end::front }; } + return { vehicle, nearest }; +} + +} // namespace + void drivingaid_panel::update() { @@ -45,6 +65,8 @@ drivingaid_panel::update() { text_lines.clear(); + std::tie( m_brokenvehicle, m_brokenend ) = broken_coupler_nearby( Global.pCamera.Pos ); + auto const *train { simulation::Train }; auto const *controlled { ( train ? train->Dynamic() : nullptr ) }; @@ -70,53 +92,7 @@ drivingaid_panel::update() { } // next speed limit auto const speedlimit { static_cast( owner->VelDesired ) }; - auto nextspeedlimit { speedlimit }; - auto nextspeedlimitdistance { std::numeric_limits::max() }; - if( speedlimit != 0 ) { // if we aren't allowed to move then any next speed limit is irrelevant - // nie przekraczać rozkladowej - auto const schedulespeedlimit { ( - (owner->OrderCurrentGet() & (Obey_train | Bank)) != 0 && owner->TrainParams.TTVmax > 0.0 ? static_cast( owner->TrainParams.TTVmax ) : - (owner->OrderCurrentGet() & (Obey_train | Bank)) == 0 ? static_cast( owner->fShuntVelocity ) : - -1 ) }; - // first take note of any speed change which should occur after passing potential current speed limit - if( owner->VelLimitLastDist.second > 0 ) { - nextspeedlimit = min_speed( schedulespeedlimit, static_cast( owner->VelLimitLastDist.first ) ); - nextspeedlimitdistance = owner->VelLimitLastDist.second; - } - // then take into account speed change ahead, compare it with speed after potentially clearing last limit - // lower of these two takes priority; otherwise limit lasts at least until potential last limit is cleared - auto const noactivespeedlimit { owner->VelLimitLastDist.second < 0 }; - if( auto const speedatproximitydistance { min_speed( schedulespeedlimit, static_cast( owner->VelNext ) ) }; speedatproximitydistance == nextspeedlimit ) { - if( noactivespeedlimit ) { - nextspeedlimit = speedatproximitydistance; - nextspeedlimitdistance = owner->ActualProximityDist; - } - } - else if( speedatproximitydistance < nextspeedlimit ) { - // if the speed limit ahead is more strict than our current limit, it's important enough to report - if( speedatproximitydistance < owner->VelDesired ) { - nextspeedlimit = speedatproximitydistance; - nextspeedlimitdistance = owner->ActualProximityDist; - } - // otherwise report it only if it's located after our current (lower) limit ends - else if( owner->ActualProximityDist > nextspeedlimitdistance ) { - nextspeedlimit = speedatproximitydistance; - nextspeedlimitdistance = owner->ActualProximityDist; - } - } - else if( noactivespeedlimit ) { // implicit proximity > last, report only if last limit isn't present - nextspeedlimit = speedatproximitydistance; - nextspeedlimitdistance = owner->ActualProximityDist; - } - // HACK: if our current speed limit extends beyond our scan range don't display potentially misleading information about its length - if( nextspeedlimitdistance >= EU07_AI_SPEEDLIMITEXTENDSBEYONDSCANRANGE ) { - nextspeedlimit = speedlimit; - } - // HACK: hide next speed limit if the 'limit' is a vehicle in front of us - else if( owner->ActualProximityDist == std::abs( owner->TrackObstacle() ) ) { - nextspeedlimit = speedlimit; - } - } + auto const [ nextspeedlimit, nextspeedlimitdistance ] { owner->next_speed_limit() }; std::string nextspeedlimittext; if( nextspeedlimit != speedlimit ) { std::snprintf( @@ -221,6 +197,12 @@ drivingaid_panel::render_contents() { } } + // only the coupler the camera is next to, and the one of the vehicle it was coupled with + if( m_brokenvehicle != nullptr && ImGui::Button( STR_C( "Repair coupler" ) ) ) { + command_relay commandrelay; + commandrelay.post( user_command::repaircoupler, m_brokenend, 0.0, GLFW_PRESS, 0, glm::vec3( 0.0f ), &m_brokenvehicle->name() ); + } + ui_panel::render_contents(); } @@ -544,6 +526,7 @@ void debug_panel::update() m_powergridlines.clear(); m_cameralines.clear(); m_rendererlines.clear(); + m_couplerlines.clear(); #ifdef WITH_UART m_uartlines.clear(); #endif @@ -557,6 +540,7 @@ void debug_panel::update() update_section_powergrid( m_powergridlines ); update_section_camera( m_cameralines ); update_section_renderer( m_rendererlines ); + update_section_coupler( m_couplerlines ); #ifdef WITH_UART update_section_uart(m_uartlines); #endif @@ -590,6 +574,7 @@ debug_panel::render() { command_relay commandrelay; commandrelay.post(user_command::resetconsist, 0.0, 0.0, GLFW_PRESS, 0, glm::vec3(0.0f), &m_input.vehicle->name()); } + render_section_coupler(); render_section( "Vehicle Engine", m_enginelines ); render_section( "Vehicle AI", m_ailines ); render_section( "Vehicle Scan Table", m_scantablelines ); @@ -1508,6 +1493,172 @@ debug_panel::update_section_renderer( std::vector &Output ) const { } +namespace { + +// how far from the camera a coupler shows in the coupler section [m] +constexpr float coupler_pick_radius { 10.f }; + +std::string_view coupler_type_name( TCouplerType const Type ) { + switch( Type ) { + case TCouplerType::Articulated: { return "articulated"; } + case TCouplerType::Bare: { return "bare"; } + case TCouplerType::Chain: { return "chain"; } + case TCouplerType::Screw: { return "screw"; } + case TCouplerType::Automatic: { return "automatic"; } + default: { return "none"; } + } +} + +// the couplerphysics setting of eu07.ini +std::string_view coupler_physics_setting() { + if( Global.coupler_physics_all ) { return "all"; } + return Global.coupler_physics ? "yes" : "no"; +} + +std::string_view coupler_stop_name( int const Stop ) { + if( Stop > 0 ) { return "draw gear solid"; } + if( Stop < 0 ) { return "buffers solid"; } + return "none"; +} + +// a value shown in the Scale of its unit (1000 for kN, 0.001 for mm), dragged within Min and Max of that unit +bool edit_value( char const *Label, double &Value, double const Scale, double const Min, double const Max, char const *Format ) { + auto shown { Value / Scale }; + if( false == ImGui::DragScalar( Label, ImGuiDataType_Double, &shown, static_cast( ( Max - Min ) / 1000.0 ), &Min, &Max, Format ) ) { + return false; + } + Value = std::clamp( shown, Min, Max ) * Scale; + return true; +} + +bool edit_spring( char const *Name, coupler_physics::spring_curve &Curve, double &Unloading ) { + ImGui::PushID( Name ); + ImGui::TextUnformatted( Name ); + auto changed { edit_value( "Stiffness [kN/m]", Curve.stiffness, 1000.0, 100.0, 50000.0, "%.0f" ) }; + changed = edit_value( "Travel [mm]", Curve.travel, 0.001, 5.0, 300.0, "%.0f" ) || changed; + changed = edit_value( "Progression", Curve.progression, 1.0, 0.0, 0.9, "%.2f" ) || changed; + changed = edit_value( "Unloading ratio", Unloading, 1.0, 0.05, 1.0, "%.2f" ) || changed; + ImGui::Text( "End force: %.0f kN", Curve.end_force() / 1000.0 ); + ImGui::PopID(); + return changed; +} + +bool edit_link( coupler_physics::end_parameters &Parameters ) { + auto &link { Parameters.link }; + ImGui::PushID( "link" ); + ImGui::TextUnformatted( "Link" ); + auto changed { ImGui::Checkbox( "Breakable", &link.breakable ) }; + changed = edit_value( "Ultimate force [kN]", link.ultimate, 1000.0, 10.0, 5000.0, "%.0f" ) || changed; + changed = edit_value( "Yield force [kN]", link.yield, 1000.0, 10.0, 5000.0, "%.0f" ) || changed; + link.yield = std::min( link.yield, link.ultimate ); + // the permanent stretch at which the link breaks, which is what the hardening gives + auto stretch { ( link.ultimate - link.yield ) / link.hardening }; + if( edit_value( "Stretch to break [mm]", stretch, 0.001, 1.0, 200.0, "%.1f" ) ) { + link.hardening = std::max( ( link.ultimate - link.yield ) / stretch, 1.0 ); + changed = true; + } + changed = edit_value( "Link stiffness [kN/m]", Parameters.link_stiffness, 1000.0, 1000.0, 2000000.0, "%.0f" ) || changed; + changed = edit_value( "Buffers crush force [kN]", Parameters.crush_force, 1000.0, 100.0, 10000.0, "%.0f" ) || changed; + changed = edit_value( "Restitution of a solid hit", Parameters.solid_restitution, 1.0, 0.05, 0.95, "%.2f" ) || changed; + ImGui::PopID(); + return changed; +} + +bool edit_coupler_parameters( coupler_physics::end_parameters &Parameters ) { + auto changed { edit_value( "Slack [mm]", Parameters.slack, 0.001, -100.0, 300.0, "%.1f" ) }; + changed = edit_value( "Damping [kN s/m]", Parameters.damping, 1000.0, 0.0, 1000.0, "%.1f" ) || changed; + changed = edit_spring( "Buffers", Parameters.buffers, Parameters.buffers_unloading ) || changed; + changed = edit_spring( "Draw gear", Parameters.draw_gear, Parameters.draw_gear_unloading ) || changed; + changed = edit_link( Parameters ) || changed; + return changed; +} + +} // namespace + +void +debug_panel::update_section_coupler( std::vector &Output ) { + + m_coupler = {}; + if( m_input.camera == nullptr ) { return; } + auto const &camera { m_input.camera->Pos }; + auto const *vehicle { std::get( simulation::Region->find_vehicle( camera, coupler_pick_radius, false, true ) ) }; + if( vehicle == nullptr || vehicle->MoverParameters == nullptr ) { + Output.emplace_back( std::format( "No coupler within {:.0f} m of the camera", coupler_pick_radius ), Global.UITextColor ); + return; + } + auto const nearerfront { glm::distance( vehicle->CouplerPosition( end::front ), camera ) <= glm::distance( vehicle->CouplerPosition( end::rear ), camera ) }; + m_coupler = { vehicle, nearerfront ? end::front : end::rear }; + + auto const &mover { *vehicle->MoverParameters }; + auto const &coupler { mover.Couplers[ m_coupler.end ] }; + auto const &neighbour { mover.Neighbours[ m_coupler.end ] }; + auto const &state { coupler.physics_state }; + + Output.emplace_back( + std::format( "{}, {} end, {} coupler{}", vehicle->name(), nearerfront ? "front" : "rear", coupler_type_name( coupler.type() ), coupler.has_adapter() ? " (adapter)" : "" ), + Global.UITextColor ); + Output.emplace_back( + std::format( + "Model: {} (couplerphysics {}, vehicle {}covered), crash damage {}", + mover.coupler_physics_at( m_coupler.end ) ? "physical" : "legacy", + coupler_physics_setting(), + mover.CouplerPhysics ? "" : "not ", + Global.crash_damage ? "on" : "off" ), + Global.UITextColor ); + if( neighbour.vehicle != nullptr ) { + Output.emplace_back( + std::format( "Neighbour: {} ({} end), coupling [{}], gap {:.1f} mm", neighbour.vehicle->name(), neighbour.vehicle_end == end::front ? "front" : "rear", coupler.CouplingFlag, neighbour.distance * 1000.0 ), + Global.UITextColor ); + } + else { + Output.emplace_back( "Neighbour: none", Global.UITextColor ); + } + Output.emplace_back( std::format( "Force: {:.1f} kN", coupler.CForce / 1000.0 ), Global.UITextColor ); + Output.emplace_back( + std::format( "Draw gear: {:.1f} mm, {:.1f} kN Buffers: {:.1f} mm, {:.1f} kN", state.draw_gear.deflection * 1000.0, state.draw_gear.force / 1000.0, state.buffers.deflection * 1000.0, state.buffers.force / 1000.0 ), + Global.UITextColor ); + Output.emplace_back( + std::format( "Stretch: {:.1f} mm, stop: {}, overloaded for {:.1f} s", state.elongation * 1000.0, coupler_stop_name( state.stop ), coupler.stretch_duration ), + Global.UITextColor ); + if( coupler.broken ) { + Output.emplace_back( "Coupler broken (repair it in the driving aid, F1)", glm::vec4( 1.f, 0.25f, 0.25f, 1.f ) ); + } +} + +bool +debug_panel::render_section_coupler() { + + if( false == render_section( "Coupler", m_couplerlines ) ) { return false; } + // the parameters to try out, in the debug mode, on the simulation itself + if( false == DebugModeFlag || m_coupler.vehicle == nullptr || Application.is_client() ) { return true; } + + ImGui::Separator(); + ImGui::Checkbox( "Physical coupler model", &Global.coupler_physics ); + ImGui::Checkbox( "Physical model for every train", &Global.coupler_physics_all ); + ImGui::Checkbox( "Crash damage", &Global.crash_damage ); + ImGui::Checkbox( "Apply to the other end of the pair too", &m_couplerbothends ); + + auto &mover { *m_coupler.vehicle->MoverParameters }; + auto &coupler { mover.Couplers[ m_coupler.end ] }; + auto const &neighbour { mover.Neighbours[ m_coupler.end ] }; + auto *othercoupler { neighbour.vehicle != nullptr ? &neighbour.vehicle->MoverParameters->Couplers[ neighbour.vehicle_end ] : nullptr }; + + if( auto parameters { coupler.physics }; edit_coupler_parameters( parameters ) ) { + coupler.physics = parameters; + if( m_couplerbothends && othercoupler != nullptr ) { + othercoupler->physics = parameters; + } + } + if( ImGui::Button( "Reset the stretch of the coupling" ) ) { + // both vehicles keep the state of the pair alike + coupler.physics_state.elongation = 0.0; + if( othercoupler != nullptr ) { + othercoupler->physics_state.elongation = 0.0; + } + } + return true; +} + bool debug_panel::render_section( std::string const &Header, std::vector const &Lines ) { diff --git a/application/driveruipanels.h b/application/driveruipanels.h index 393d0e9a3..8c21a6240 100644 --- a/application/driveruipanels.h +++ b/application/driveruipanels.h @@ -25,6 +25,9 @@ public: private: // members std::array m_buffer; + // the broken coupler next to the camera, which the panel offers to repair: the vehicle and its end + TDynamicObject const *m_brokenvehicle { nullptr }; + int m_brokenend { 0 }; }; class timetable_panel : public ui_expandable_panel { @@ -89,6 +92,8 @@ private: void update_section_powergrid( std::vector &Output ) const; void update_section_camera( std::vector &Output ) const; void update_section_renderer( std::vector &Output ) const; + // the coupler nearest to the camera, and the state of its coupling + void update_section_coupler( std::vector &Output ); #ifdef WITH_UART void update_section_uart( std::vector &Output ) const; #endif @@ -100,6 +105,8 @@ private: bool render_section( std::vector const &Lines ) const; bool render_section_scenario(); bool render_section_eventqueue(); + // the coupler section, with the parameters of the physical model to try out in the debug mode + bool render_section_coupler(); bool render_section_settings() const; bool render_section_developer() const; // members @@ -116,6 +123,14 @@ private: std::vector m_powergridlines; std::vector m_rendererlines; std::vector m_uartlines; + std::vector m_couplerlines; + // the coupler nearest to the camera + struct coupler_pick { + TDynamicObject const *vehicle { nullptr }; + int end { 0 }; + }; + coupler_pick m_coupler; + bool m_couplerbothends { true }; // changes to the parameters apply to the end of the other vehicle of the pair too double last_time = std::numeric_limits::quiet_NaN(); diff --git a/application/editormode.cpp b/application/editormode.cpp index 1ad3ef6ed..9b9a70692 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -36,6 +36,7 @@ extern char **environ; #include "simulation/simulation.h" #include "simulation/simulationtime.h" #include "simulation/simulationenvironment.h" +#include "simulation/blackboxrecorder.h" #include "utilities/Timer.h" #include "Console.h" #include "rendering/renderer.h" @@ -5060,6 +5061,8 @@ void editor_mode::update_camera(double const Deltatime) void editor_mode::enter() { m_statebackup = {Global.pCamera, FreeFlyModeFlag, Global.ControlPicking}; + // the editor may remove the tracks and the vehicles the recording refers to: it ends here + simulation::Blackbox.close(); if (simulation::Region != nullptr) { diff --git a/blackbox_doc.md b/blackbox_doc.md new file mode 100644 index 000000000..c58cae100 --- /dev/null +++ b/blackbox_doc.md @@ -0,0 +1,580 @@ +# The black box + +A binary recording of a whole session: the map of the scenery (the rail tracks, the signals, the stop +points W4 and the horn points W6), every vehicle over time, the switches and the aspects of the signals as +they change, and the train the user is in, in detail. The detail includes what the AI driver would have +done at the same moment, every command the user gave, when the autopilot took over, the signals passed, +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. + +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. + +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 +was cut short. + +## Layout + +Little-endian throughout. The types: + +| type | bytes | what | +|---------|-------|---------------------------------------------------------------------------| +| `u8` | 1 | unsigned | +| `i8` | 1 | signed | +| `u16` | 2 | unsigned | +| `u32` | 4 | unsigned | +| `f32` | 4 | IEEE 754 single | +| `f64` | 8 | IEEE 754 double | +| `vec3` | 12 | `f32 x, f32 y, f32 z` | +| `dvec3` | 24 | `f64 x, f64 y, f64 z` | +| `text` | 1+ | UTF-8, after its length in bytes in 7 bit groups, low first, the high bit set on all but the last | + +This is what .NET `BinaryReader` reads: `ReadByte`, `ReadSByte`, `ReadUInt16`, `ReadUInt32`, +`ReadSingle`, `ReadDouble` and `ReadString`. + +Positions are in the frame of the scenery: metres, `y` up, the same as in the `.scn` files. + +The file starts with a header of 12 bytes: + +| offset | type | value | +|--------|----------|-------------------------------| +| 0 | 8 bytes | `EU07BBX` and a zero byte | +| 8 | `u16` | version of the format, now 1 | +| 10 | `u16` | reserved, 0 | + +Then come the records, to the end of the file. Each record is: + +| type | what | +|-------|---------------------------------------| +| `u8` | the kind of the record (below) | +| `u32` | length of the content, in bytes | +| | the content | + +A reader skips a record of a kind it doesn't know, and the content past the fields it knows (later +versions may add fields at the end of a record). A record whose length runs past the end of the file is +still being written: stop there and read on from it later. + +`t`, the time of a record, is an `f64` of seconds of simulation since the recording started. It doesn't +run while the simulation is paused. The `clock` records give the time of day it corresponds to. + +Vehicles are given numbers from 1 up, in the `vehicle` records; 0 means no vehicle. Tracks, signals, +stop points and horn points are given numbers from 0 up, in the order of their `track`, `signal`, +`stop point` and `horn point` records. + +## Records + +### 0x01 info + +Once, first. + +| type | field | +|--------|--------------------------------------------------------------------| +| `text` | scenario file, as the simulator was given it (the starter gives `$.scn`) | +| `text` | local time the recording started at, `YYYY-MM-DDTHH:MM:SS` | +| `u16` | simulation year at the start | +| `u16` | simulation day of the year, 1..366 | +| `f64` | simulation second of the day at the start | +| `text` | the vehicle the user was to start in, `ghostview` for none | +| `text` | version of the simulator | +| `f32` | seconds between the `cab` records (0.1) | +| `f32` | seconds between the `vehicles` records (1) | +| `f32` | seconds between the `vehicles` records which list all the vehicles (60) | + +### 0x10 track + +The map: one for each rail track, two for a switch, one for each of its ways. Written at the start. + +| type | field | +|--------|-----------------------------------------------------------| +| `u32` | number of the track | +| `text` | name, may be empty | +| `u8` | kind: 0 a plain track, 1 a way of a switch | +| `u8` | the switch position this way is taken in (0 for a plain track) | +| `u8` | category: 1 rail | +| `u32` | count of the points | +| `vec3` | the points, along the track, as many as counted | + +### 0x11 signal + +The map: one for each signal. Written at the start. + +| type | field | +|---------|----------------------------------------------------| +| `u32` | number of the signal | +| `text` | name (that of its memory cell, without `_sem_mem`) | +| `dvec3` | position | + +### 0x14 stop point + +The map: one for each stop point of a passenger train (W4), a `putvalues` event with the text +`PassengerStopPoint:` (or a memory cell with that text). Written at the start. + +| type | field | +|---------|-------------------------------------------------------------------------------| +| `u32` | number of the stop point | +| `text` | name of the station as the scenery gives it; what follows a `#` tells the stop points of one station apart | +| `dvec3` | position | +| `f32` | where the train is to stop, the first value of the cell: below 0 its head that many metres before the W4, above 0 the middle of the train that many metres before it | +| `f32` | the second value of the cell: above 0 the length of the platform [m], below 0 the stop is for trains shorter than that (W32), 0 not given | +| `f32` | heading of the trains it is for [rad, from +z towards +x], as the track it is read off gives it: the driver reads the events of the second end of a track going from its first end to the second; NaN on no track, or on tracks of both ways | + +### 0x15 horn point + +The map: one for each event telling the trains to sound the horn (W6), a `putvalues` event with the text +`Warning_signal`. Written at the start. + +| type | field | +|---------|-------------------------------------------| +| `u32` | number of the horn point | +| `text` | name of the event | +| `dvec3` | position | +| `f32` | how long the horn is to sound [s] | +| `f32` | the tone, bits: 1 low, 2 high | + +### 0x12 vehicle + +Every vehicle present at the start, and each one which shows up later, before it appears in any other +record. + +| type | field | +|--------|----------------------------------------------------------| +| `u32` | number of the vehicle | +| `text` | name | +| `text` | type | +| `text` | train number of its timetable, if it leads a train with one | +| `f32` | length [m] | +| `f32` | width [m] | +| `u8` | category: 1 rail, 2 road | + +### 0x13 vehicle removed + +| type | field | +|-------|-----------------------| +| `f64` | t | +| `u32` | number of the vehicle | + +### 0x20 cab + +The vehicle the user is in, every 0.1 s, also while the user looks around outside it. 190 bytes. + +| type | field | +|---------|------------------------------------------------------------------------| +| `f64` | t | +| `u32` | number of the vehicle | +| `dvec3` | position | +| `f32` | speed [km/h], positive along the front of the vehicle | +| `f32` | acceleration along the track [m/s²] | +| `f32` | odometer [km] | +| `u8` | driver: 0 none, 1 the user, 2 the AI (the autopilot) | +| `u8` | flags, below | +| `i8` | master controller position | +| `i8` | secondary controller (field shunting) position | +| `i8` | reverser: -1, 0, 1 | +| `f32` | driver's brake valve position | +| `f32` | local brake position, 0..1 | +| `f32` | brake cylinder pressure [bar] | +| `f32` | brake pipe pressure [bar] | +| `f32` | motor current [A] | +| `f32` | AI: the speed it would hold here [km/h] | +| `f32` | AI: the next speed limit it sees [km/h], -1 none | +| `f32` | AI: distance to that limit [m], -1 none | +| `f32` | AI: the acceleration it would go for [m/s²], below 0 it would brake | +| `f32` | AI: braking distance at this speed [m] | +| `f32` | top speed of the timetable [km/h], -1 none | +| `f32` | top speed of the track [km/h], -1 none | +| `u32` | what is switched on, below | +| `f32` | main reservoir pressure [bar] | +| `f32` | voltage given to the motors [V] | +| `f32` | revolutions of the engine or the motors [rpm] | +| `u16` | lights lit at the head of the train, below | +| `u16` | lights lit at its tail | +| `i8` | the cab the user is in: 1 the front one, -1 the rear one, 0 none | +| `u8` | the train protection, below | +| `f32` | acceleration across the track [m/s²], in the curves | +| `u8` | what the driver of the train goes by: 1 a train run, 2 shunting, 0 anything else or no driver | +| `i16` | the light pattern the timetable or the scenery asks for at the head, bits as the lights; -1 the usual one | +| `i16` | the same at the tail | +| `u16` | the lamps the vehicle at the head has at its outer end, bits as the lights | +| `u16` | the same of the vehicle at the tail | +| `u8` | what drives the vehicle whose motors the cab drives, below | +| `u8` | the setting of the brakes: 1 G, 2 P, 4 R, 8 Mg, as bits | +| `u8` | the radio channel | +| `f32` | what the driver's brake valve shows on its gauge [bar]: the equalizing (control) reservoir of most valves, the time reservoir of the FV4a, empty but after an overcharge | +| `f32` | main reservoir pipe along the train [bar] | +| `f32` | oil pressure of the diesel engine [MPa] | +| `f32` | cooling water temperature of the diesel engine [°C] | +| `f32` | its oil temperature [°C] | +| `f32` | its temperature [°C] | +| `f32` | the speed the cruise control is set to [km/h], 0 none | +| `f32` | power of the engine [kW] | +| `i8` | hand brake position, 0 released | +| `u8` | the mode of the brakes: 1 PS, 2 PN, 4 EP, 8 MED, as bits | +| `u8` | the horn's tones sounding: 1 low, 2 high, 4 a third, 0 silent | +| `f32` | the integrated driving and braking handle of a unit, -1 full braking .. 1 full power | +| `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] | + +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 +upper headlight), and the tail the pattern asked for, the usual one Pc 5 (both red markers); shunting +Tb 1, one headlight at each end. A pattern is checked against the lamps the vehicle has, as the driver +checks it: one without the upper headlight shows Pc 1 with the two others, one with auxiliary lamps may +show them instead of the headlights, and one with no lamps at all the rear-end signals; the tail shows +Pc 5 with the red markers or the rear-end signals it has. A recording made before the movement ends at +the acceleration across, one made before the lamps at the light pattern of the tail, and one made before +the engine at the lamps of the tail. The temperatures and the oil pressure mean something for a diesel +engine only. + +What drives the vehicle: 0 nothing of its own (a draisine, a car), 1 electric series motors, 2 electric +induction motors, 3 a diesel engine with a mechanical or a hydraulic transmission, 4 a diesel-electric one, +5 steam. + +The flags: + +| bit | meaning | +|------|-----------------------------------------------------------------| +| 0x01 | the user is in the cab | +| 0x02 | the AI fields hold what the AI would do: the consist is started | +| 0x04 | the alerter or the cab signalling blinks | +| 0x08 | the alerter or the cab signalling beeps | +| 0x10 | the wheels slip | +| 0x20 | radio-stop | +| 0x40 | the alarm chain was pulled | + +What is switched on: the radio, the horn, the doors and the spring brake are those of the +vehicle the user is in; the battery is on if it is in either; the rest, and the pressures, the voltage and the revolutions, of the vehicle +whose motors the cab drives (the motor car of a unit). + +| bit | meaning | +|--------|--------------------------------------| +| 0x0001 | battery | +| 0x0002 | main breaker closed | +| 0x0004 | front pantograph raised | +| 0x0008 | rear pantograph raised | +| 0x0010 | converter | +| 0x0020 | compressor | +| 0x0040 | line contactors: the motors are on | +| 0x0080 | overload relay tripped | +| 0x0100 | sanding | +| 0x0200 | horn | +| 0x0400 | left doors open | +| 0x0800 | right doors open | +| 0x1000 | radio | +| 0x2000 | train heating | +| 0x4000 | spring brake applied | +| 0x8000 | shunting mode | +| 0x0001'0000 | departure signal sounding | +| 0x0002'0000 | left doors permitted to open | +| 0x0004'0000 | right doors permitted to open | +| 0x0008'0000 | the steps come out with the doors | +| 0x0010'0000 | the door lock is switched on: the doors lock above a speed | +| 0x0020'0000 | the doors are locked | +| 0x0040'0000 | the brake releaser works | +| 0x0080'0000 | fuel pump | +| 0x0100'0000 | oil pump | +| 0x0200'0000 | the fans of the traction motors | +| 0x0400'0000 | the diesel engine is too hot | +| 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. + +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 +light, 0x200 left and 0x400 right high beam. Those of the head are at the outer end of the first vehicle +of the train, those of the tail at the outer end of the last one, whichever vehicle the user is in. + +The train protection, of the vehicle whose motors the cab drives; the alerter (CA) and the cab signalling +(SHP) apart: + +| bit | meaning | +|------|-------------------------------------------------------------------------| +| 0x01 | the alerter lamp blinks: the driver is to acknowledge | +| 0x02 | the cab signalling lamp blinks: an SHP magnet was passed | +| 0x04 | the alerter beeps | +| 0x08 | the cab signalling beeps | +| 0x10 | not acknowledged in time: the train protection brakes the train | + +The AI fields are what the AI driver works out from the place and the speed the train has at the time. +It works them out as it goes, also while the user drives, but doesn't act on them then. It is not a +separate run of the AI. They are refreshed every half a second or so, and only once the consist is +started (flag 0x02); before that the speed held, the acceleration and the braking distance are 0, the +next limit, its distance and the top speeds of the timetable and the track -1. + +### 0x21 vehicles + +Every second: the vehicles which moved more than 0.1 m, changed speed or got another driver since they +were last listed. Every 60 s all of them (a keyframe), so a reader can start at any keyframe. + +| type | field | +|-------|-------------------------------------------| +| `f64` | t | +| `u8` | 1 if a keyframe, else 0 | +| `u32` | count of the vehicles | +| | as many times, 25 bytes: | +| `u32` | number of the vehicle | +| `vec3`| position | +| `f32` | heading [rad] of its front, from +z towards +x: the front points to (sin, cos) in (x, z) | +| `f32` | speed [km/h], positive along its front | +| `u8` | driver: 0 none, 1 a user, 2 the AI | + +### 0x22 switch + +The position of a switch: all of them at the start, then as they change (checked every second). + +| type | field | +|-------|---------------------------------------------------------------| +| `f64` | t | +| `u32` | number of the track | +| `u8` | position: the way taken is the `track` record with this branch | + +### 0x23 signal aspect + +What a signal tells: all of them at the start, then as they change (checked every second). The values +are those of its memory cell. + +| type | field | +|--------|----------------------------------------------------------------| +| `f64` | t | +| `u32` | number of the signal | +| `f32` | speed at the signal [km/h]: 0 stop, -1 no limit | +| `f32` | speed at the next signal [km/h] | +| `text` | command of the memory cell, e.g. `SetVelocity`, `ShuntVelocity` | + +### 0x24 timetable + +The timetable of the train the user is in: once the user is in a train which has one, and again whenever +it changes, the user in another train or the train given its next timetable (one recording may hold any +number of them). It is written before the first station record (`0x35`) under it, even when the train +comes to that station at the moment it gets the timetable. The times are minutes of the day (10:05 is 605), +-1 none. + +| type | field | +|--------|---------------------------------------------------------| +| `f64` | t | +| `u32` | number of the vehicle the user was in | +| `text` | train number | +| `text` | category | +| `text` | from | +| `text` | to | +| `f32` | top speed of the train [km/h] | +| `u32` | count of the rows, the stations | +| | as many times: | +| `text` | station | +| `f32` | kilometre | +| `f32` | top speed before the station [km/h], -1 none | +| `f32` | arrival | +| `f32` | departure | +| `u8` | 1 a technical stop, else 0 | + +The rows are numbered from 1, as the `station` records give them. + +### 0x25 camera + +Where the user looks from: at the start, then when it changed, looked at twice a second. From the cab and +in the outside views the camera goes with the train, whose way is written anyway (0x20), so only going to +another mode, view or vehicle counts; the free and the debug camera count as changed as well when they +moved more than 0.5 m or turned more than 0.05 rad. + +| type | field | +|---------|------------------------------------------------------------------------------| +| `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 | +| `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) | +| `f32` | pitch [rad], up from the horizon | + +### 0x30 command + +Every command the user gave: each press and release of a control of the cab, of the keyboard, mouse or a +device. Held controls repeat their command while held; only the press and the release are written, the +`cab` records show the effect. Also the commands to the whole simulation, like the time jumps. + +| type | field | +|--------|-------------------------------------------------------------| +| `f64` | t | +| `u32` | number of the vehicle, 0 for a command to the simulation | +| `u8` | 1 pressed, 0 released | +| `f64` | first parameter | +| `f64` | second parameter | +| `text` | name of the command, as in `eu07_input-keyboard.ini` | + +### 0x31 driver change + +The user or the AI takes over a vehicle: the autopilot switched on (Shift+Q) or off (Q), and entering a +vehicle the AI was driving. + +| type | field | +|-------|--------------------------------| +| `f64` | t | +| `u32` | number of the vehicle | +| `u8` | driver now: 1 the user, 2 the AI | + +### 0x32 signal passed + +A train, any, passed a signal. It is noticed when the AI driver updates its table, up to half a second +later, so the train is somewhat past the signal by then: the position is that of the signal and the +overrun tells how far past it the train had got. + +| type | field | +|---------|---------------------------------------------------------------| +| `f64` | t | +| `u32` | number of the vehicle leading the train | +| `u32` | number of the signal, `0xFFFFFFFF` if it isn't on the map | +| `text` | name of the event telling the aspect | +| `dvec3` | position of the signal | +| `f32` | the aspect when passed: speed at the signal [km/h], 0 stop, -1 no limit | +| `f32` | speed at the next signal [km/h], as the signal shows it when the pass is noticed | +| `f32` | speed of the train [km/h] | +| `f32` | overrun [m] | +| `u8` | flags: 0x01 a shunting signal, 0x02 passed at stop, 0x04 the stop of an automatic block signal; a shunting signal binds only shunting, so passed at stop by a train it has 0x01 alone | + +### 0x33 user vehicle + +The vehicle the user is in changed, the user got out of the cab or back into it, or went to the other cab. + +| type | field | +|-------|---------------------------------------------| +| `f64` | t | +| `u32` | number of the vehicle, 0 for none | +| `u8` | 1 in the cab, 0 outside it | +| `i8` | the cab: 1 the front one, -1 the rear one, 0 none | + +### 0x34 clock + +Every second, and so after a time jump too. + +| type | field | +|-------|--------------------------------| +| `f64` | t | +| `u16` | year | +| `u16` | day of the year, 1..366 | +| `f64` | second of the day | + +### 0x35 station + +A train, any, at a station of its timetable, as its driver (the AI, or the AI watching the user drive) +sees it at the stop point (W4). + +| type | field | +|---------|--------------------------------------------------------------------------| +| `f64` | t | +| `u32` | number of the vehicle leading the train | +| `u8` | what happened, below | +| `u16` | row of the timetable, from 1 | +| `text` | station | +| `dvec3` | position of the stop point | +| `f32` | distance of the head of the train before the stop point [m], below 0 past it | +| `f32` | where the head was to stop: that many metres before the stop point | +| `f32` | length of the train [m] | +| `f32` | the second value of the stop point (see `stop point`): the platform | +| `f32` | arrival of the timetable, in minutes of the day, -1 none | +| `f32` | departure of the timetable | + +What happened: + +| value | meaning | +|-------|-------------------------------------------------------------------------------------------| +| 1 | the train stopped at the stop point of a stop of its timetable | +| 2 | it passed a station where the timetable has no stop | +| 3 | it left the stop point of a stop behind before it was time to go: without stopping, or leaving before the departure; only for a user's train | +| 4 | it was still at the stop point when it was time to go: it may leave | + +How far the distance is from the place the head was to stop at tells how well the train was stopped. + +### 0x36 horn request + +A train, any, was told to sound the horn (it passed a horn point W6). Whether the user did is in the +`cab` records (the horn among what is switched on) and the `command` records. + +| type | field | +|---------|-------------------------------------------------| +| `f64` | t | +| `u32` | number of the vehicle leading the train | +| `f32` | how long the horn is to sound [s] | +| `f32` | the tone, bits: 1 low, 2 high | +| `dvec3` | position of the horn point, or of the train's head if not known | + +### 0x37 coupling + +A coupler of a vehicle, any: at the start those coupled, then each change, looked at every second. A +change is two vehicles coupled, uncoupled, or the hoses and the cables between them connected or not. Both +vehicles of a coupling see it; the one with the lower number tells it. + +| type | field | +|---------|------------------------------------------------------------------------| +| `f64` | t | +| `u32` | number of the vehicle | +| `u8` | its coupler: 0 the front one, 1 the rear one | +| `u32` | number of the vehicle coupled to it now, 0 for none | +| `u8` | the coupler of that vehicle | +| `u8` | what is coupled now, below; 0 nothing | +| `u8` | what was coupled before | +| `u32` | number of the vehicle coupled before, 0 for none | +| `dvec3` | position of the coupler | + +What is coupled: 0x01 the coupler, 0x02 the brake pipe, 0x04 the control (multiple unit), 0x08 the high +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). + +### 0x3F end + +Last, when the simulator closes. + +| type | field | +|-------|-------| +| `f64` | t | + +## What it doesn't hold + +- The kilometrage of the lines: it is known only in an editor session. +- Roads and rivers on the map, only the rail tracks. +- A run of the AI of its own: the AI fields tell what the AI would do from where the user's train is. + +## Reading it + +A minimal reader in C#: + +```csharp +using var reader = new BinaryReader(File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)); +if (new string(reader.ReadChars(7)) != "EU07BBX" || reader.ReadByte() != 0) + throw new InvalidDataException("not a black box"); +ushort version = reader.ReadUInt16(); +reader.ReadUInt16(); + +var stream = reader.BaseStream; +while (stream.Length - stream.Position >= 5) +{ + long start = stream.Position; + byte kind = reader.ReadByte(); + uint length = reader.ReadUInt32(); + if (stream.Length - stream.Position < length) + { + stream.Position = start; // still being written, read on from here later + break; + } + long next = stream.Position + length; + switch (kind) + { + case 0x20: + double t = reader.ReadDouble(); + uint vehicle = reader.ReadUInt32(); + double x = reader.ReadDouble(), y = reader.ReadDouble(), z = reader.ReadDouble(); + float speed = reader.ReadSingle(); + // ... + break; + // ... + } + stream.Position = next; // past what wasn't read, and past fields added later +} +``` diff --git a/input/command.cpp b/input/command.cpp index 7d3fe7d1d..32ba02e94 100644 --- a/input/command.cpp +++ b/input/command.cpp @@ -415,6 +415,7 @@ commanddescription_sequence Commands_descriptions = { {"linebreakertogglec", command_target::vehicle, command_mode::oneoff}, {"linebreakeropenc", command_target::vehicle, command_mode::oneoff}, {"linebreakerclosec", command_target::vehicle, command_mode::oneoff}, + {"repaircoupler", command_target::simulation, command_mode::oneoff}, }; // Maps of command and coresponding strings @@ -809,6 +810,7 @@ std::unordered_map const commandMap = { {"linebreakertogglec", user_command::linebreakertogglec}, {"linebreakeropenc", user_command::linebreakeropenc}, {"linebreakerclosec", user_command::linebreakerclosec}, + {"repaircoupler", user_command::repaircoupler}, {"none", user_command::none}}; } // namespace simulation diff --git a/input/command.h b/input/command.h index aaf361e25..664f6a3ba 100644 --- a/input/command.h +++ b/input/command.h @@ -413,6 +413,7 @@ enum class user_command linebreakertogglec, linebreakeropenc, linebreakerclosec, + repaircoupler, // the broken coupler of the vehicle (payload) at the end (param1) none = -1 }; diff --git a/model/Texture.cpp b/model/Texture.cpp index 4a7b24792..cd275c9e0 100644 --- a/model/Texture.cpp +++ b/model/Texture.cpp @@ -28,6 +28,8 @@ http://mozilla.org/MPL/2.0/. #include "dds-ktx/dds-ktx.h" #include "winheaders.h" +#include + #define EU07_DEFERRED_TEXTURE_UPLOAD #ifndef FOURCC_DX10 @@ -303,6 +305,20 @@ bool bptc_supported() { }(); return supported; } +// format of a compressed texture read back from the gpu, given as the image would have it: the driver tells the srgb variant +// of the format, which the mapping doesn't take. with the components hint of the texture the linear one gives the same gl +// format again on the next upload +GLint readback_format( GLint const Internalformat ) { + switch( Internalformat ) { + case GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC: { return GL_COMPRESSED_RGBA8_ETC2_EAC; } + case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: { return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; } + case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: { return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; } + case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: { return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; } + case GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM: { return GL_COMPRESSED_RGBA_BPTC_UNORM; } + default: { return Internalformat; } + } +} + } // namespace std::array opengl_texture::units = { 0 }; @@ -722,6 +738,10 @@ void opengl_texture::make_request() { auto const components { Split( name, '?' ) }; + if( components.front().ends_with( ".lua" ) || components.front().ends_with( ".wasm" ) ) { + // script destination signs are drawn by the vehicles showing them (script_screen_queue) + return; + } auto dictionary = std::make_shared( components.back() ); @@ -1502,29 +1522,13 @@ opengl_texture::release() { } else { ::glBindTexture(target, id ); - GLint datasize {}; GLint iscompressed {}; ::glGetTexLevelParameteriv(target, 0, GL_TEXTURE_COMPRESSED, &iscompressed ); - if( iscompressed == GL_TRUE ) { - // texture is compressed on the gpu side - // query texture details needed to perform the backup... - ::glGetTexLevelParameteriv(target, 0, GL_TEXTURE_INTERNAL_FORMAT, &data_format ); - ::glGetTexLevelParameteriv(target, 0, GL_TEXTURE_COMPRESSED_IMAGE_SIZE, &datasize ); - data.resize( datasize ); - // ...fetch the data... - ::glGetCompressedTexImage(target, 0, &data[ 0 ] ); + if( ( iscompressed != GL_TRUE ) + || ( false == read_back_compressed() ) ) { + // the texture didn't get compressed during upload, or got a format the upload doesn't take + read_back_uncompressed(); } - else { - // for whatever reason texture didn't get compressed during upload - // fallback on plain rgba storage... - data_format = GL_RGBA; - data_type = GL_UNSIGNED_BYTE; - data.resize( data_width * data_height * 4 ); - // ...fetch the data... - ::glGetTexImage(target, 0, data_format, GL_UNSIGNED_BYTE, &data[ 0 ] ); - } - // ...and update texture object state - data_mapcount = 1; // we keep copy of only top mipmap level data_state = resource_state::good; } } @@ -1536,6 +1540,56 @@ opengl_texture::release() { return; } +// copies all mipmaps of the compressed gl texture into the data, in the layout of a dds file. returns false, leaving the data as +// it was, when the format can't be uploaded again as it is. all levels are kept since the driver may not generate mipmaps +// of a compressed format; without them the texture would be incomplete and drawn black +bool +opengl_texture::read_back_compressed() { + + GLint internalformat {}; + ::glGetTexLevelParameteriv( target, 0, GL_TEXTURE_INTERNAL_FORMAT, &internalformat ); + auto const format { readback_format( internalformat ) }; + if( ( false == precompressed_formats.contains( format ) ) + || ( false == mapping.contains( format ) ) ) { + return false; + } + auto const levelcount { static_cast( std::bit_width( std::max( data_width, data_height ) ) ) }; + std::vector leveldata; + auto mapcount { 0 }; + while( mapcount < levelcount ) { + GLint levelwidth {}; + GLint levelsize {}; + ::glGetTexLevelParameteriv( target, mapcount, GL_TEXTURE_WIDTH, &levelwidth ); + ::glGetTexLevelParameteriv( target, mapcount, GL_TEXTURE_COMPRESSED_IMAGE_SIZE, &levelsize ); + if( ( levelwidth <= 0 ) || ( levelsize <= 0 ) ) { + // the levels past the last one present weren't made + break; + } + auto const offset { leveldata.size() }; + leveldata.resize( offset + static_cast( levelsize ) ); + ::glGetCompressedTexImage( target, mapcount, &leveldata[ offset ] ); + ++mapcount; + } + if( mapcount == 0 ) { + return false; + } + data.swap( leveldata ); + data_format = format; + data_mapcount = static_cast( mapcount ); + return true; +} + +// copies the top level of the gl texture into the data as plain rgba, the mipmaps are generated again on upload +void +opengl_texture::read_back_uncompressed() { + + data_format = GL_RGBA; + data_type = GL_UNSIGNED_BYTE; + data.resize( data_width * data_height * 4 ); + ::glGetTexImage( target, 0, data_format, GL_UNSIGNED_BYTE, &data[ 0 ] ); + data_mapcount = 1; +} + void opengl_texture::alloc_rendertarget( GLint format, GLint components, int width, int height, int l, int s, GLint wrap ) { diff --git a/model/Texture.h b/model/Texture.h index 0a4ae62ec..313d0f6f4 100644 --- a/model/Texture.h +++ b/model/Texture.h @@ -117,6 +117,9 @@ public: // takes over the data read by a worker thread, waiting for it if needed void complete_data(); + // with gfx.resource.move, copies the gl texture back into the data before it's released. requires the texture bound + bool read_back_compressed(); + void read_back_uncompressed(); // members std::shared_ptr request; // data being read by a worker thread diff --git a/ref/wamr b/ref/wamr new file mode 160000 index 000000000..25bd7eb63 --- /dev/null +++ b/ref/wamr @@ -0,0 +1 @@ +Subproject commit 25bd7eb63e828e4bd242cc9b38d260b4b31c6605 diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp index d96c878f4..eec136b70 100644 --- a/rendering/opengl33renderer.cpp +++ b/rendering/opengl33renderer.cpp @@ -416,6 +416,21 @@ bool opengl33_renderer::Init(GLFWwindow *Window) void opengl33_renderer::Shutdown() { vr.reset(); + m_screen_post.reset(); +} + +script_screens::post_processor *opengl33_renderer::Screen_post_processor() +{ + // GLES converts what's written into an sRGB texture, and the passes give the bytes as they are: the cpu does it there + if (Global.gfx_usegles) + { + return nullptr; + } + if (m_screen_post == nullptr) + { + m_screen_post = std::make_unique(); + } + return m_screen_post.get(); } bool opengl33_renderer::AddViewport(const global_settings::extraviewport_config &conf) diff --git a/rendering/opengl33renderer.h b/rendering/opengl33renderer.h index 0e84761e1..288ca0df5 100644 --- a/rendering/opengl33renderer.h +++ b/rendering/opengl33renderer.h @@ -30,6 +30,7 @@ http://mozilla.org/MPL/2.0/. #include "gl/pbo.h" #include "gl/query.h" #include "rendering/opengl33terrain.h" +#include "rendering/opengl33screenpost.h" // bare-bones render controller, in lack of anything better yet class opengl33_renderer : public gfx_renderer { @@ -145,6 +146,7 @@ class opengl33_renderer : public gfx_renderer { info_stats() const override; void MakeScreenshot() override; bool Render_Preview( TAnimModel *Instance, int const Size, int const Margin, bool const Shadows, std::vector &Image ) override; + script_screens::post_processor *Screen_post_processor() override; @@ -515,6 +517,7 @@ class opengl33_renderer : public gfx_renderer { std::unique_ptr m_celestial_shader; std::unique_ptr m_hiddenarea_shader; std::unique_ptr m_copy_shader; + std::unique_ptr m_screen_post; // made on the first request std::unique_ptr m_empty_vao; diff --git a/rendering/opengl33screenpost.cpp b/rendering/opengl33screenpost.cpp new file mode 100644 index 000000000..11bdf5510 --- /dev/null +++ b/rendering/opengl33screenpost.cpp @@ -0,0 +1,250 @@ +/* +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 "rendering/opengl33screenpost.h" + +#include "model/Texture.h" +#include "utilities/Logs.h" + +#include +#include + +namespace +{ + +// the state of the context the passes change, put back after them +class saved_state +{ + public: + saved_state() + { + glGetIntegerv(GL_VIEWPORT, m_viewport.data()); + glGetBooleanv(GL_COLOR_WRITEMASK, m_colormask.data()); + glGetBooleanv(GL_DEPTH_WRITEMASK, &m_depthmask); + for (std::size_t idx = 0; idx < m_capabilities.size(); ++idx) + { + m_enabled[idx] = glIsEnabled(m_capabilities[idx]); + glDisable(m_capabilities[idx]); + } + glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + glDepthMask(GL_FALSE); + } + ~saved_state() + { + for (std::size_t idx = 0; idx < m_capabilities.size(); ++idx) + { + if (m_enabled[idx] == GL_TRUE) + { + glEnable(m_capabilities[idx]); + } + } + glColorMask(m_colormask[0], m_colormask[1], m_colormask[2], m_colormask[3]); + glDepthMask(m_depthmask); + glViewport(m_viewport[0], m_viewport[1], m_viewport[2], m_viewport[3]); + } + saved_state(saved_state const &) = delete; + saved_state &operator=(saved_state const &) = delete; + + private: + // GL_FRAMEBUFFER_SRGB off: the passes write the bytes of the image into the screen's sRGB texture as they are, as + // update_from_memory puts them there + static constexpr std::array m_capabilities{GL_DEPTH_TEST, GL_BLEND, GL_CULL_FACE, GL_SCISSOR_TEST, GL_STENCIL_TEST, GL_FRAMEBUFFER_SRGB}; + std::array m_enabled{}; + std::array m_viewport{}; + std::array m_colormask{}; + GLboolean m_depthmask{GL_TRUE}; +}; + +void unbind_all() +{ + gl::framebuffer::unbind(); + gl::program::unbind(); + gl::vao::unbind(); +} + +// the screen's texture made the size of the result, in the format update_from_memory gives it +void prepare_target(opengl_texture &Target, int const Width, int const Height) +{ + if (Target.id != opengl_texture::invalid_id && Target.data_width == static_cast(Width) && Target.data_height == static_cast(Height) && + Target.data_format == GL_SRGB8_ALPHA8 && Target.data_components == GL_RGBA) + { + return; + } + Target.update_from_memory(Width, Height, nullptr); +} + +} // namespace + +opengl33_screen_post::~opengl33_screen_post() +{ + for (auto const *owned : {&m_source, &m_between[0], &m_between[1]}) + { + if (owned->texture != 0) + { + glDeleteTextures(1, &owned->texture); + } + } +} + +opengl33_screen_post::stage opengl33_screen_post::make_stage(gl::shader const &Vertex, std::string const &Fragment) +{ + gl::shader const fragment{Fragment}; + stage result; + result.program = std::make_unique(std::vector>{Vertex, fragment}); + auto const program{static_cast(*result.program)}; + result.source_size = glGetUniformLocation(program, "source_size"); + result.target_size = glGetUniformLocation(program, "target_size"); + result.flip = glGetUniformLocation(program, "flip"); + result.mode = glGetUniformLocation(program, "mode"); + result.program->bind(); + glUniform1i(glGetUniformLocation(program, "source"), 0); + return result; +} + +bool opengl33_screen_post::setup() +{ + if (m_failed) + { + return false; + } + if (m_led.program != nullptr) + { + return true; + } + try + { + gl::shader const vertex{"quad.vert"}; + m_led = make_stage(vertex, "screen_led.frag"); + m_resize = make_stage(vertex, "screen_resize.frag"); + } + catch (gl::shader_exception const &Error) + { + ErrorLog(std::format("Script screens: the shaders of the post-processing failed: {}", Error.what())); + m_failed = true; + return false; + } + m_vao = std::make_unique(); + m_framebuffer = std::make_unique(); + WriteLog("Script screens: the post-processing of the images runs on the gpu"); + return true; +} + +void opengl33_screen_post::store(surface &Surface, int const Width, int const Height, std::uint8_t const *Pixels) +{ + if (Surface.texture == 0) + { + glGenTextures(1, &Surface.texture); + glBindTexture(GL_TEXTURE_2D, Surface.texture); + // read with texelFetch: no mipmaps, nothing filtered + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + } + else + { + glBindTexture(GL_TEXTURE_2D, Surface.texture); + } + if (Surface.width != Width || Surface.height != Height) + { + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, Width, Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, Pixels); + Surface.width = Width; + Surface.height = Height; + } + else if (Pixels != nullptr) + { + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, Width, Height, GL_RGBA, GL_UNSIGNED_BYTE, Pixels); + } +} + +std::vector opengl33_screen_post::passes_of(std::span const Steps, int Width, int Height) const +{ + std::vector result; + for (auto const &step : Steps) + { + if (step.type == script_screens::post_step::kind::led) + { + Width = Width * 2 + 2; + Height = Height * 2 + 2; + result.emplace_back(&m_led, Width, Height, step.bloom ? 1 : 0); + continue; + } + result.emplace_back(&m_resize, step.width, Height, 0); + result.emplace_back(&m_resize, step.width, step.height, 1); + Width = step.width; + Height = step.height; + } + return result; +} + +bool opengl33_screen_post::draw(pass const &Pass, surface const &Source, GLuint const Target, bool const Last) const +{ + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, Target, 0); + if (auto const status{glCheckFramebufferStatus(GL_FRAMEBUFFER)}; status != GL_FRAMEBUFFER_COMPLETE) + { + ErrorLog(std::format("Script screens: the post-processing can't draw into a texture, framebuffer status {:#x}", status)); + return false; + } + glViewport(0, 0, Pass.width, Pass.height); + Pass.shader->program->bind(); + glUniform2i(Pass.shader->source_size, Source.width, Source.height); + glUniform2i(Pass.shader->target_size, Pass.width, Pass.height); + glUniform1i(Pass.shader->flip, Last ? 1 : 0); + glUniform1i(Pass.shader->mode, Pass.mode); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, Source.texture); + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + return true; +} + +bool opengl33_screen_post::apply(ITexture &Target, std::span const Pixels, int const Width, int const Height, + std::span const Steps) +{ + auto *target{dynamic_cast(&Target)}; + if (target == nullptr || Steps.empty() || Pixels.size() < script_screens::image_size(Width, Height) || false == setup()) + { + return false; + } + auto const passes{passes_of(Steps, Width, Height)}; + prepare_target(*target, passes.back().width, passes.back().height); + + auto succeeded{true}; + { + saved_state const saved; + // what the binding caches of gl:: hold may not be what's bound now: bound anew, and left unbound after the passes + unbind_all(); + m_framebuffer->bind(); + m_vao->bind(); + store(m_source, Width, Height, Pixels.data()); + auto const *source{&m_source}; + for (std::size_t idx = 0; idx < passes.size() && succeeded; ++idx) + { + auto const last{idx + 1 == passes.size()}; + auto &between{m_between[idx % 2]}; + if (false == last) + { + store(between, passes[idx].width, passes[idx].height, nullptr); + } + succeeded = draw(passes[idx], *source, last ? target->id : between.texture, last); + source = ≬ + } + // the screen's texture isn't held by the framebuffer when it's made anew + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); + unbind_all(); + } + if (succeeded) + { + glBindTexture(GL_TEXTURE_2D, target->id); + glGenerateMipmap(GL_TEXTURE_2D); + } + // the textures bound here went past the unit cache + opengl_texture::reset_unit_cache(); + return succeeded; +} diff --git a/rendering/opengl33screenpost.h b/rendering/opengl33screenpost.h new file mode 100644 index 000000000..bb5014e20 --- /dev/null +++ b/rendering/opengl33screenpost.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 "scripting/scriptscreens.h" +#include "gl/framebuffer.h" +#include "gl/shader.h" +#include "gl/vao.h" + +#include +#include +#include +#include +#include +#include + +// the post-processing of the script screens (image:led_post, image:resize) on the gpu, for the OpenGL 3.3 renderer: a +// pass for a led_post and two for a resize (along the rows, then along the columns), the last pass into the screen's +// texture. shaders/screen_led.frag and shaders/screen_resize.frag give the pixels of scripting/scriptscreenkernels.cpp +class opengl33_screen_post final : public script_screens::post_processor +{ + public: + opengl33_screen_post() = default; + ~opengl33_screen_post() override; + + bool apply(ITexture &Target, std::span Pixels, int Width, int Height, std::span Steps) override; + + private: + // a shader of the passes, with the places of its uniforms + struct stage + { + std::unique_ptr program; + GLint source_size{-1}; + GLint target_size{-1}; + GLint flip{-1}; + GLint mode{-1}; + }; + // a texture the passes read + struct surface + { + GLuint texture{0}; + int width{0}; + int height{0}; + }; + struct pass + { + stage const *shader; + int width; + int height; + int mode; // led: 1 with the glow; resize: 0 along the rows, 1 along the columns + }; + + // makes the shaders on the first use. false when they failed, then and from then on + bool setup(); + std::vector passes_of(std::span Steps, int Width, int Height) const; + // draws a pass from the source into the texture; Last: the rows go bottom row first, as the screen's texture takes them + bool draw(pass const &Pass, surface const &Source, GLuint Target, bool Last) const; + + static stage make_stage(gl::shader const &Vertex, std::string const &Fragment); + // sizes the texture, and fills it when there are pixels + static void store(surface &Surface, int Width, int Height, std::uint8_t const *Pixels); + + bool m_failed{false}; + stage m_led; + stage m_resize; + std::unique_ptr m_vao; + std::unique_ptr m_framebuffer; + surface m_source; // the image as drawn + std::array m_between; // what the passes before the last one give, in turn +}; diff --git a/rendering/renderer.h b/rendering/renderer.h index 1a110e689..dec3f752e 100644 --- a/rendering/renderer.h +++ b/rendering/renderer.h @@ -21,6 +21,11 @@ namespace gl class program; } +namespace script_screens +{ +class post_processor; +} + namespace gfx { // material painted over the heightmap terrain, and the size (metres) its textures are repeated at; 0: the size given by the material, or 8 m @@ -130,6 +135,9 @@ public: // seen in perspective from the front, side and above and filling the image less Margin pixels at each edge. // Image receives rgb rows, top row first. returns false if the backend can't make previews or there's nothing to draw virtual auto Render_Preview( TAnimModel *Instance, int const Size, int const Margin, bool const Shadows, std::vector &Image ) -> bool { return false; } + // runs the post-processing of the script screens (image:led_post, image:resize) on the gpu. nullptr when the backend + // can't; the screens then do it on the cpu + virtual auto Screen_post_processor() -> script_screens::post_processor * { return nullptr; } }; class gfx_renderer_factory diff --git a/script_screens_doc.md b/script_screens_doc.md new file mode 100644 index 000000000..52ccc9ced --- /dev/null +++ b/script_screens_doc.md @@ -0,0 +1,210 @@ +# Script screens + +Screens drawn by scripts, alongside the Python screens (`pyscreen:`, `pydestinationsign:`): Lua scripts, run by +LuaJIT, and WebAssembly modules, run by the WAMR interpreter (`ref/wamr`). A script gets the same input a Python +screen gets (the table in `python_var_doc.md`), returns an RGBA image and, in the cab, may send commands. + +A Lua script is text, kept with the vehicles and the `scripts/` folder like the Python screens, and changed with any +editor. A WebAssembly module is compiled from another language (Rust, C, Zig and the like). + +Both run sandboxed: a script reaches only the functions of `eu07` below, and reads files only from its own folder and +below. A Lua script gets no `io`, `os`, `ffi`, `debug` or `require`, and no precompiled code is loaded. + +Unlike a Python screen, which refreshes after a time (`python.updatetime`, `updatetime:`), a script screen refreshes +every so many rendered frames, set in `eu07.ini`. A call into a script may run at most 200 million instructions +(Lua runs without the JIT compiler so that the limit holds). A script that fails, or runs over, is switched off, and +the reason goes to the log. + +## eu07.ini + +| key | default | meaning | +|--------------------------|---------|--------------------------------------------------------------------------------| +| `luascreens.enabled` | 1 | 0: no Lua screens; the vehicles show what they did before | +| `wasm.enabled` | 1 | 0: no WebAssembly screens; the vehicles show what they did before | +| `screens.cabframes` | 4 | a screen in the cab is refreshed every so many frames (1-1000) | +| `screens.externalframes` | 30 | a screen outside the cab (destination sign) is refreshed every so many frames | +| `screens.gpupost` | 1 | 0: `led_post` and `resize` of the Lua screens always run on the cpu, as they did before | + +`wasm.cabframes` and `wasm.externalframes`, the first names of the last two, are read as well. + +A screen may ask for a longer interval of its own (`frames:` below); the longer of the two counts. Screens sharing +an interval are spread over its frames, so they don't all refresh on the same one. A screen in the cab is refreshed +only while the player sits in that cab, a screen outside only while its vehicle is drawn. + +## .mmd + +In the cab section, next to `pyscreen:`: + +``` +luascreen: { ekran.lua target: screen01 frames: 6 parameters: id=1&mode=full } +wasmscreen: { ekran.wasm target: screen02 } +``` + +| key | meaning | +|---------------|---------------------------------------------------------------------------------------------------| +| (first token) | the script, relative to the vehicle folder when it has no path of its own | +| `target:` | the submodel the screen is drawn on (its texture is replaced); `none` for a screen that only sends commands | +| `frames:` | the screen's own refresh interval, used when longer than `screens.cabframes` | +| `parameters:` | extra `key=value` pairs, `&`-separated, added to the input | + +A touch on the screen's submodel comes in the input as the list of points `touches`, as for the Python screens. + +In `internaldata:`, next to `pydestinationsign:`: + +``` +luadestinationsign: { scripts/led_111a20.lua parameters: kod_e=IC&kod_p=TLK&kod_o=R instance: name } +destinationsignbackground: make:scripts/led_111a20.lua?dummy=1 +``` + +`luadestinationsign:` and `wasmdestinationsign:` take the keys of `pydestinationsign:` (`instance:`, `parameters:`, +`background:`) and `frames:`. The input is what a Python sign gets: the timetable (`$timetable`), `_id1` (the +train), `_id2` (the instance) and the parameters, read anew on every refresh, so the sign can follow the journey. The +vehicles of one train showing the same request share one screen and one texture. A static destination texture, when +there is one, still comes first. + +A blank sign (`background:`, or the older `destinationsignbackground:`) named `make: