diff --git a/.gitattributes b/.gitattributes index d2b789541..488a40d4b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4,3 +4,5 @@ text=auto *.h text README text LICENSE text +# the license texts the Windows build ships, checked by their SHA-256: byte for byte as upstream, LF on every checkout +ref/licenses/*.txt -text diff --git a/.github/actions/apt-install/action.yml b/.github/actions/apt-install/action.yml new file mode 100644 index 000000000..0495b07ac --- /dev/null +++ b/.github/actions/apt-install/action.yml @@ -0,0 +1,137 @@ +# Installs Ubuntu packages, with the downloaded .deb files kept in the Actions cache. +# +# The Ubuntu mirror of the hosted runners has been slow: about 150 kB/s, with stalls of 30 s on single files, +# so 130 small packages took over 13 minutes to download. The .deb files of the last install are kept in the +# cache, under a key of the runner image and the package list: +# - the same image and list (the usual case): the cached files are installed as they are, without the mirror +# and without `apt-get update`; should that fail, the next way is taken +# - otherwise: `apt-get update`, then `apt-get install`, which takes the cached files of the same version +# (checked against the index) and downloads the rest; the files of this install are cached for the next run +# +# A cache entry can't be overwritten, so each one is saved under the key with the run appended, and the newest +# entry of a key is restored by its prefix. Cached files that failed to install are then replaced by the next +# save rather than restored again on every run of that image. +# +# Caches of a pull request are seen only by that pull request; the pushes to staging and master (Build binaries) +# fill the ones every pull request starts from. + +name: Install apt packages +description: apt-get install, with the downloaded packages kept in the Actions cache + +inputs: + packages: + description: The packages to install, separated by spaces or new lines + required: true + +runs: + using: composite + steps: + # the key: the runner image (its packages are what the cached files were resolved against) and the list, + # sorted, so neither its order nor its line breaks change it. Without ImageVersion (not a GitHub-hosted + # runner) the image isn't known, so the cached files are never installed as they are + - name: Cache key of the packages + id: key + shell: bash + env: + PACKAGES: ${{ inputs.packages }} + run: | + set -euo pipefail + printf '%s\n' "$PACKAGES" | tr -s '[:space:]' '\n' | sed '/^$/d' | sort -u > "$RUNNER_TEMP/apt-packages.txt" + os="${ImageOS:-$(. /etc/os-release && echo "${ID}${VERSION_ID}")}" + image="${ImageVersion:-unknown}" + prefix="apt-v2-${os}-$(dpkg --print-architecture)-" + list_hash="$(sha256sum < "$RUNNER_TEMP/apt-packages.txt" | cut -c1-16)" + { + echo "key=${prefix}${image}-${list_hash}" + echo "save-key=${prefix}${image}-${list_hash}-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + echo "image-prefix=${prefix}${image}-" + echo "prefix=${prefix}" + echo "known-image=$([ -n "${ImageVersion:-}" ] && echo true || echo false)" + } >> "$GITHUB_OUTPUT" + cat "$RUNNER_TEMP/apt-packages.txt" + + # no entry is saved under the key itself, so this restores the newest entry of the key (by its prefix), else + # a cache of another list (another workflow) or of an older image: the files apt finds there in the version + # it wants aren't downloaded again + - name: Restore the downloaded packages + id: restore + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: /tmp/apt-archives + key: ${{ steps.key.outputs.key }} + restore-keys: | + ${{ steps.key.outputs.image-prefix }} + ${{ steps.key.outputs.prefix }} + + # /tmp rather than the runner's temp folder: apt downloads as the user _apt, who has to reach the folder. + # Recommended packages are left out: the build needs the headers and libraries the packages depend on + - name: Install the packages + id: install + shell: bash + env: + EXACT_HIT: ${{ startsWith(steps.restore.outputs.cache-matched-key, format('{0}-', steps.key.outputs.key)) && steps.key.outputs.known-image == 'true' }} + run: | + set -euo pipefail + archives=/tmp/apt-archives + mkdir -p "$archives/partial" + + # a mirror that stops answering used to hold this step for over an hour: time out each download and + # retry it. The translations of the package descriptions aren't needed + printf '%s\n' \ + 'Acquire::Retries "3";' \ + 'Acquire::http::Timeout "60";' \ + 'Acquire::https::Timeout "60";' \ + 'Acquire::Languages "none";' \ + | sudo tee /etc/apt/apt.conf.d/80-ci-retries > /dev/null + + mapfile -t packages < "$RUNNER_TEMP/apt-packages.txt" + apt=(sudo apt-get -y --no-install-recommends -o "Dir::Cache::Archives=$archives/") + + all_installed() { + local package + for package in "${packages[@]}"; do + [[ "$(dpkg-query -W -f '${db:Status-Abbrev}' "$package" 2> /dev/null)" == ii* ]] || return 1 + done + } + + done=false + fix=() + if [ "$EXACT_HIT" = true ] && compgen -G "$archives/*.deb" > /dev/null; then + echo "::group::Install the $(ls "$archives"/*.deb | wc -l) cached packages" + if "${apt[@]}" install "$archives"/*.deb && all_installed; then + done=true + echo "from-cache=true" >> "$GITHUB_OUTPUT" + else + echo "::warning::The cached packages didn't install; installing from the mirror" + fix=(--fix-broken) + fi + echo "::endgroup::" + fi + + if [ "$done" != true ]; then + sudo apt-get update + "${apt[@]}" "${fix[@]}" install "${packages[@]}" + all_installed + fi + + # only the files of the packages now installed are kept, in the version installed: the cached files then + # are exactly this install, and the next run on this image can install them as they are + sudo rm -rf "$archives/partial" "$archives/lock" + sudo chown -R "$(id -u):$(id -g)" "$archives" + installed="$(dpkg-query -W -f '${db:Status-Abbrev}|${Package}|${Version}|${Architecture}\n' \ + | awk -F'|' '$1 ~ /^ii/ { print $2 "|" $3 "|" $4 }')" + for deb in "$archives"/*.deb; do + [ -e "$deb" ] || continue + id="$(dpkg-deb --show --showformat='${Package}|${Version}|${Architecture}' "$deb")" + grep -qxF -- "$id" <<< "$installed" || rm -f "$deb" + done + echo "Cached packages: $(find "$archives" -maxdepth 1 -name '*.deb' | wc -l), $(du -sh "$archives" | cut -f1)" + + # saved unless the cached files of this image and list installed as they are: after a miss, and after cached + # files that failed to install and were replaced from the mirror + - name: Save the downloaded packages + if: steps.install.outputs.from-cache != 'true' + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: /tmp/apt-archives + key: ${{ steps.key.outputs.save-key }} diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..23c5f7c9d --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,15 @@ +# Keeps the GitHub Actions used by the workflows and by the local actions (.github/actions) up to date. The actions +# are pinned by commit hash, with the version in a comment; Dependabot updates both. One pull request a week for all +# of them, so the workflows stay on the same versions. +version: 2 +updates: + - package-ecosystem: github-actions + directories: + - / + - /.github/actions/* + schedule: + interval: weekly + groups: + github-actions: + patterns: + - "*" diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ff39d872f..44ecf5d92 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -31,7 +31,7 @@ jobs: env: BUILD_WRAPPER_OUT_DIR: bw-output steps: - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 0 submodules: recursive @@ -41,23 +41,20 @@ jobs: with: python-version: '3.14' - # A mirror that stops answering used to hold this step for over an hour. - # Time out each download, retry it, and give up on the whole step early. + # The packages are kept in the Actions cache (.github/actions/apt-install): the mirror of the + # runners has been too slow to download them every time. The timeout is a safety net. + # The X11 packages are the ones GLFW (ref/glfw, 3.4) looks for; xorg-dev brought ~45 more. - name: Install build dependencies timeout-minutes: 15 - run: | - printf '%s\n' \ - 'Acquire::Retries "3";' \ - 'Acquire::http::Timeout "60";' \ - 'Acquire::https::Timeout "60";' \ - | sudo tee /etc/apt/apt.conf.d/80-ci-retries > /dev/null - sudo apt-get update -y - sudo apt-get install -y \ - build-essential \ - libgl1-mesa-dev libglew-dev libglfw3-dev \ - libpng-dev libopenal-dev libluajit-5.1-dev \ - libserialport-dev libsndfile1-dev \ - xorg-dev libxkbcommon-dev libwayland-dev wayland-protocols + uses: ./.github/actions/apt-install + with: + packages: >- + build-essential pkg-config + libgl1-mesa-dev libglew-dev libglfw3-dev + libpng-dev libopenal-dev libluajit-5.1-dev + libserialport-dev libsndfile1-dev + libx11-dev libxcursor-dev libxext-dev libxi-dev libxinerama-dev libxrandr-dev + libxkbcommon-dev libwayland-dev wayland-protocols - name: Build current OpenAL Soft run: | diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index 65d74e36f..b62bb8321 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -180,6 +180,170 @@ jobs: -Recurse ` -Force + # The downloads of the next step, kept between the runs: a release out of reach then doesn't fail the build. The + # key is this file, which pins them; a cache of an older one is taken too, as the next step checks every file by + # its SHA-256 and downloads only those it doesn't have. + - name: Restore the audio library downloads + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ runner.temp }}/audio-dlls-downloads + key: audio-dlls-${{ hashFiles('.github/workflows/build_bin.yml') }} + restore-keys: audio-dlls- + + # The game loads OpenAL32.dll and libsndfile-1.dll from its own folder, and the depot had OpenAL Soft 1.18.1 and + # libsndfile 1.0.28 (2017) there. OpenAL Soft 1.18 lacks ALC_SOFT_reopen_device and ALC_SOFT_system_events, so on + # Windows the sound didn't follow a change of the output device; libsndfile 1.0.28 reads no Opus and no MP3, which + # the Linux build (libsndfile 1.2) does. The official release binaries of both are taken, pinned by SHA-256. They + # need nothing beyond the system DLLs and msvcrt.dll (soft_oal.dll) or KERNEL32.dll (sndfile.dll). soft_oal.dll + # has no AVX code; sndfile.dll (its static opus and mpg123) picks its AVX/AVX2 paths at run time, so the same files + # go with both variants. The exe links them by name: soft_oal.dll is shipped as OpenAL32.dll (as its readme says, + # without the router), sndfile.dll as libsndfile-1.dll. Both are LGPL, so their license texts go with them, in + # licenses/, with those of what the DLLs have built in (below); the libsndfile zip has none, its COPYING is taken + # from the source tree of the same tag. Those texts are kept in ref/licenses (with where each comes from), so the + # build doesn't depend on the servers they come from. + - name: Add the OpenAL Soft and libsndfile DLLs + shell: pwsh + timeout-minutes: 10 + run: | + $ErrorActionPreference = 'Stop' + $ProgressPreference = 'SilentlyContinue' + $output = "build/bin/$env:CONFIG_WIN" + $licenses = Join-Path $output 'licenses' + $work = Join-Path $env:RUNNER_TEMP 'audio-dlls' + $downloads = Join-Path $env:RUNNER_TEMP 'audio-dlls-downloads' + New-Item -ItemType Directory -Force -Path $work, $licenses, $downloads | Out-Null + $pinned = [System.Collections.Generic.List[string]]::new() + + # the file of the URL with the given SHA-256: the one kept by a run before, else downloaded. named by its + # SHA-256 and the last part of its path, without the query + function Get-Pinned([string] $Url, [string] $Sha256) { + $name = "$Sha256-$([uri]::new($Url).Segments[-1])" + $pinned.Add($name) + $file = Join-Path $downloads $name + if ((Test-Path -Path $file) -and (Get-FileHash -Algorithm SHA256 -Path $file).Hash.ToLowerInvariant() -eq $Sha256) { + Write-Host "$Url kept by a run before" + return $file + } + Invoke-WebRequest -Uri $Url -OutFile $file -UserAgent 'ci-download' -MaximumRetryCount 3 -RetryIntervalSec 10 -TimeoutSec 120 + $hash = (Get-FileHash -Algorithm SHA256 -Path $file).Hash.ToLowerInvariant() + if ($hash -ne $Sha256) { + Remove-Item -Path $file -Force + throw "${Url}: SHA-256 $hash, expected $Sha256" + } + return $file + } + + # each package: the zip and, for each file wanted from it, where it goes in the build + $packages = @( + @{ Url = 'https://github.com/kcat/openal-soft/releases/download/1.25.2/openal-soft-1.25.2-bin.zip' + Sha256 = '67a0c4b800bd860c93c04f38caf8cbe4875f9c84700ac430efc451f70e265434' + Files = [ordered]@{ + 'openal-soft-1.25.2-bin/bin/Win64/soft_oal.dll' = 'OpenAL32.dll' + 'openal-soft-1.25.2-bin/COPYING' = 'licenses/openal-soft-COPYING.txt' } }, + @{ Url = 'https://github.com/libsndfile/libsndfile/releases/download/1.2.2/libsndfile-1.2.2-win64.zip' + Sha256 = '2173935c0c1ed13cf627951d34483f9d405ead2eb473190461c42ba220643a3f' + Files = [ordered]@{ + 'libsndfile-1.2.2-win64/bin/sndfile.dll' = 'libsndfile-1.dll' } } + ) + foreach ($package in $packages) { + $zip = Get-Pinned $package.Url $package.Sha256 + $unpacked = Join-Path $work ([IO.Path]::GetFileNameWithoutExtension($zip)) + Expand-Archive -Path $zip -DestinationPath $unpacked -Force + foreach ($entry in $package.Files.GetEnumerator()) { + Copy-Item -Path (Join-Path $unpacked $entry.Key) -Destination (Join-Path $output $entry.Value) -Force + Write-Host "$($entry.Value) <- $($package.Url) $($entry.Key)" + } + } + + # the license texts, each from the source tree of the version built in: of libsndfile, its ALAC and GSM 06.10 + # code, and the libraries its vcpkg build linked into sndfile.dll; of OpenAL Soft's PFFFT, Microsoft GSL and + # its BSD 3-Clause parts, and of the MinGW-w64 runtime and winpthreads, linked into soft_oal.dll (a MinGW GCC + # 15 build: the texts are the same in mingw-w64 12 and 13). + # The versions in sndfile.dll: those it names (libopus 1.4, libFLAC 1.4.2, libVorbis 1.3.7), mpg123 1.31.3 by + # the SHA-512 of its source archive in the build paths it keeps, and libogg 1.3.5 and LAME 3.100 of the vcpkg + # ports of the time (mid 2023). LAME's from Debian's copy of the 3.100 source, the same file as in LAME's own + # repository on SourceForge. The texts are in ref/licenses, whose README names the URL of each; each is + # checked by its SHA-256, so an edit or a line ending changed on the way doesn't go out unnoticed + $texts = [ordered]@{ + 'libsndfile-COPYING.txt' = 'ad01ea5cd2755f6048383c8d54c88459cd6fcb17757c5c8892f8c5ea060f6140' + 'libsndfile-ALAC-LICENSE.txt' = '232efbd83786e157286b0b96c68ebb673541b69b33036287bf1e5ec5067a49d9' + 'libsndfile-GSM610-COPYRIGHT.txt' = '1bbe7119b1bcd1489e0f36cb95b8902f7f0ceec9a2f3a67394bc9f4709a4e0a7' + 'libogg-COPYING.txt' = 'd2ab5758336489da61c12cc5bb757da5339c4ae9001f9bb0562b4370249af814' + 'libvorbis-COPYING.txt' = 'ec1815db59fcd302846df949d7424876cb2e2dc5ed1606c5fb0b36787b1cf43a' + 'flac-COPYING.Xiph.txt' = '6e58d3036f05e2a0d58af854c12a505ddbe75011d71a598a2170987f3b15408d' + 'opus-COPYING.txt' = '8338ce8d922bb4416ce3dd1e5680173332435e3f0755007ac7801ccd674fe682' + 'mpg123-COPYING.txt' = 'c22482728a634a8dfdb4ff72a96d4c1ed64cd8f3e79335c401751ac591609366' + 'lame-COPYING.txt' = 'bfe4a52dc4645385f356a8e83cc54216a293e3b6f1cb4f79f5fc0277abf937fd' + 'openal-soft-pffft-LICENSE.txt' = '64056328b3e7bc104e24ef96accc1a7abead156f0c02d1b87c97e3f3a28030de' + 'openal-soft-gsl-LICENSE.txt' = '4c21dc82a1c7186ea754fd59d504c00947953a3401fe8e24eaa44109ef8e2555' + 'openal-soft-BSD-3Clause.txt' = 'b5a08cf98996dd83aa906a72c163600f6cb17a65ce546a553815a1267abd43ff' + 'openal-soft-winpthreads-COPYING.txt' = '63263614cdd29f2f93cba85e992f041b31f9fc7b4033692f31269489a8a1b177' + 'openal-soft-mingw-w64-runtime.txt' = 'e9b2dc02451ea29092a1f25fa0f3c07207ed421f1807dffb0c4e6dce69dee7bd' + } + foreach ($text in $texts.GetEnumerator()) { + $file = Join-Path 'ref/licenses' $text.Key + $hash = (Get-FileHash -Algorithm SHA256 -Path $file).Hash.ToLowerInvariant() + if ($hash -ne $text.Value) { + throw "${file}: SHA-256 $hash, expected $($text.Value)" + } + Copy-Item -Path $file -Destination (Join-Path $licenses $text.Key) -Force + } + + # OpenAL Soft's bs2b has its license only in its source files: the notice as core/bs2b.cpp of 1.25.2 has it + @' + Copyright (c) 2005 Boris Mikhaylov + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + '@ | Set-Content -Path (Join-Path $licenses 'openal-soft-bs2b-LICENSE.txt') -Encoding utf8 + + # what the DLLs are and have built in, where their source is (the LGPL ones); the DLLs can be replaced by the user + @( + 'OpenAL32.dll: OpenAL Soft 1.25.2, unmodified soft_oal.dll of the official binaries, GNU LGPL 2 or later' + ' (openal-soft-COPYING.txt). Source: https://github.com/kcat/openal-soft/releases/tag/1.25.2' + ' Built in: a modified PFFFT, BSD-style (openal-soft-pffft-LICENSE.txt); Microsoft GSL, MIT' + ' (openal-soft-gsl-LICENSE.txt); the ambisonic rotator, the vocal morpher and the compressor, BSD 3-Clause' + ' (openal-soft-BSD-3Clause.txt); bs2b, MIT (openal-soft-bs2b-LICENSE.txt); {fmt} 11.2.0, MIT, whose' + ' exception for the object form asks for no text. Linked into it by its MinGW-w64 build: the MinGW-w64' + ' runtime (openal-soft-mingw-w64-runtime.txt) and winpthreads, MIT and BSD-style' + ' (openal-soft-winpthreads-COPYING.txt);' + ' libstdc++ and libgcc under the GCC Runtime Library Exception, which asks for no text.' + ' Its default HRTF data set is based on the KEMAR HRTF measurements by Bill Gardner and Keith Martin,' + ' MIT Media Laboratory, 1994: http://sound.media.mit.edu/resources/KEMAR.html' + 'libsndfile-1.dll: libsndfile 1.2.2, unmodified sndfile.dll of the official binaries, GNU LGPL 2.1 or later' + ' (libsndfile-COPYING.txt). Source: https://github.com/libsndfile/libsndfile/releases/tag/1.2.2' + ' Its ALAC code: Apache License 2.0 (libsndfile-ALAC-LICENSE.txt). Its GSM 06.10 code: Jutta Degener and' + ' Carsten Bormann, TU Berlin (libsndfile-GSM610-COPYRIGHT.txt). Its G.721/G.723 code: Sun Microsystems, public' + ' domain.' + ' Linked into it by its build, made with the vcpkg ports of the time and their patches' + ' (https://github.com/microsoft/vcpkg/tree/2023.08.09/ports, the ports named below):' + ' libogg 1.3.5, BSD (libogg-COPYING.txt), port libogg. Source: https://github.com/xiph/ogg/releases/tag/v1.3.5' + ' libvorbis 1.3.7, BSD (libvorbis-COPYING.txt), port libvorbis. Source: https://github.com/xiph/vorbis/releases/tag/v1.3.7' + ' libFLAC 1.4.2, BSD (flac-COPYING.Xiph.txt), port libflac. Source: https://github.com/xiph/flac/releases/tag/1.4.2' + ' libopus 1.4, BSD (opus-COPYING.txt), port opus. Source: https://github.com/xiph/opus/releases/tag/v1.4' + ' mpg123 1.31.3, GNU LGPL 2.1 (mpg123-COPYING.txt), port mpg123. Source: https://www.mpg123.de/download/mpg123-1.31.3.tar.bz2' + ' LAME 3.100, GNU LGPL 2 or later (lame-COPYING.txt), port mp3lame. Source: https://sourceforge.net/projects/lame/files/lame/3.100/' + ) | Set-Content -Path (Join-Path $licenses 'audio-libraries.txt') -Encoding utf8 + + # the files no pin names any more aren't kept for the next run + Get-ChildItem -Path $downloads -File | Where-Object { $pinned -notcontains $_.Name } | Remove-Item -Force + - name: Upload Windows build uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: @@ -236,37 +400,39 @@ jobs: with: python-version: "3.14" - # A mirror that stops answering used to hold this step for over an hour. - # Time out each download, retry it, and give up on the whole step early. + # The packages are kept in the Actions cache (.github/actions/apt-install): the mirror of the runners has been + # too slow to download them every time. The timeout is a safety net. + # libasound2-dev, libpulse-dev and libpipewire-0.3-dev: the headers of OpenAL Soft's audio backends (built below). + # Without them it builds with OSS only, which modern distributions and the Steam Linux Runtime don't have: no sound. + # The X11 packages are the ones GLFW (ref/glfw, 3.4) looks for; xorg-dev brought ~45 more. The game loads the + # X11 and Wayland libraries of the system, none of them is bundled (CMake_modules/bundle_runtime_libs.cmake). - name: Install Linux dependencies timeout-minutes: 15 - run: | - printf '%s\n' \ - 'Acquire::Retries "3";' \ - 'Acquire::http::Timeout "60";' \ - 'Acquire::https::Timeout "60";' \ - | sudo tee /etc/apt/apt.conf.d/80-ci-retries > /dev/null - sudo apt-get update - - # libasound2-dev, libpulse-dev and libpipewire-0.3-dev: the headers of OpenAL Soft's audio backends (built below). - # Without them it builds with OSS only, which modern distributions and the Steam Linux Runtime don't have: no sound. - sudo apt-get install -y \ - build-essential \ - libasound2-dev \ - libpulse-dev \ - libpipewire-0.3-dev \ - libgl1-mesa-dev \ - libglew-dev \ - libglfw3-dev \ - libpng-dev \ - libopenal-dev \ - libluajit-5.1-dev \ - libserialport-dev \ - libsndfile1-dev \ - libcurl4-openssl-dev \ - xorg-dev \ - libxkbcommon-dev \ - libwayland-dev \ + uses: ./.github/actions/apt-install + with: + packages: >- + build-essential + pkg-config + libasound2-dev + libpulse-dev + libpipewire-0.3-dev + libgl1-mesa-dev + libglew-dev + libglfw3-dev + libpng-dev + libopenal-dev + libluajit-5.1-dev + libserialport-dev + libsndfile1-dev + libcurl4-openssl-dev + libx11-dev + libxcursor-dev + libxext-dev + libxi-dev + libxinerama-dev + libxrandr-dev + libxkbcommon-dev + libwayland-dev wayland-protocols # @@ -409,25 +575,25 @@ jobs: steps: # the AVX2 build keeps the old name of the download, so the links already handed out still work - name: Download Windows build (AVX2) - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: maszyna-windows-x64-avx2-${{ env.CONFIG_WIN }} path: dist/maszyna-windows-x64 - name: Download Windows build (no AVX2) - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: maszyna-windows-x64-noavx2-${{ env.CONFIG_WIN }} path: dist/maszyna-windows-x64-noavx2 - name: Download Linux build (AVX2) - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: maszyna-linux-x64-avx2-${{ env.CONFIG_LINUX }} path: dist/maszyna-linux-x64 - name: Download Linux build (no AVX2) - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: maszyna-linux-x64-noavx2-${{ env.CONFIG_LINUX }} path: dist/maszyna-linux-x64-noavx2 diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index d2f00bccd..27fa64bc2 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -47,14 +47,19 @@ jobs: # the same packages as the Build workflow: the game is configured as a whole, # though only the unit tests and the core library they link are built - name: Install build dependencies + timeout-minutes: 15 + uses: ./.github/actions/apt-install + with: + packages: >- + build-essential pkg-config + libgl1-mesa-dev libglew-dev libglfw3-dev + libpng-dev libopenal-dev libluajit-5.1-dev + libserialport-dev libsndfile1-dev + libx11-dev libxcursor-dev libxext-dev libxi-dev libxinerama-dev libxrandr-dev + libxkbcommon-dev libwayland-dev wayland-protocols + + - name: Install gcovr run: | - sudo apt-get update -y - sudo apt-get install -y \ - build-essential \ - libgl1-mesa-dev libglew-dev libglfw3-dev \ - libpng-dev libopenal-dev libluajit-5.1-dev \ - libserialport-dev libsndfile1-dev \ - xorg-dev libxkbcommon-dev libwayland-dev wayland-protocols python3 -m pip install --no-cache-dir --only-binary :all: gcovr==8.3 - name: Build current OpenAL Soft diff --git a/CMakeLists.txt b/CMakeLists.txt index d9ef586f4..1e3ef86d9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -90,6 +90,7 @@ option(WITHDUMPGEN "Enable generating DMP files on crash" ON) option(ENABLE_AVX2 "Enable AVX2 instruction set (requires AVX2-capable CPU, Haswell/2013 or newer)" ON) option(BUNDLE_VC_RUNTIME "Copy the Visual C++ runtime libraries next to the executable (MSVC), so it does not depend on the installed redistributable" ON) option(ADD_VERSION_SUFFIX "Add date and commit hash to the executable name" ON) +option(USE_SYSTEM_JSON "Use an installed nlohmann_json (3.9 or newer) instead of the ref/json submodule" OFF) set(BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) # vcpkg init @@ -121,6 +122,7 @@ set(SOURCES "world/RailCarve.cpp" "world/RailLayer.cpp" "world/TrackUneven.cpp" +"world/TrackBuckle.cpp" "world/Road.cpp" "world/Sweep.cpp" "world/RoadPoint.cpp" @@ -143,6 +145,7 @@ set(SOURCES "vehicle/Button.cpp" "vehicle/Camera.cpp" "vehicle/Driver.cpp" +"vehicle/crewchange.cpp" "application/driverhints.cpp" "vehicle/DynObj.cpp" "EU07.cpp" @@ -164,7 +167,6 @@ set(SOURCES "rendering/nullrenderer.cpp" "rendering/renderer.cpp" "model/ResourceManager.cpp" -"scene/sn_utils.cpp" "world/Segment.cpp" "environment/sky.cpp" "environment/sun.cpp" @@ -206,6 +208,7 @@ set(SOURCES "rendering/screenshot.cpp" "input/driverkeyboardinput.cpp" "application/drivermode.cpp" +"application/consistviews.cpp" "application/driveruilayer.cpp" "application/driveruipanels.cpp" "input/editorkeyboardinput.cpp" @@ -213,6 +216,7 @@ set(SOURCES "editor/editorModelSets.cpp" "editor/editorTrackPresets.cpp" "editor/editorIncludeInfo.cpp" +"editor/editorSwitchDrives.cpp" "editor/editorTerrain.cpp" "editor/editorTrack.cpp" "editor/editorTrackTrace.cpp" @@ -314,6 +318,7 @@ set(SOURCES "utilities/dictionary.cpp" "rendering/particles.cpp" "utilities/headtrack.cpp" +"utilities/hardwareprobe.cpp" "rendering/geometrybank.cpp" "simulation/simulationsounds.cpp" "rendering/openglcamera.cpp" @@ -435,7 +440,8 @@ endif() if (WITH_LUA) set(DEFINITIONS ${DEFINITIONS} "WITH_LUA") - set(SOURCES ${SOURCES} "scripting/lua.cpp") + # the scenery scripts (lua.cpp) and the Lua screens (luaprogram.cpp) share the sandbox of luasandbox.cpp + set(SOURCES ${SOURCES} "scripting/lua.cpp" "scripting/luasandbox.cpp") endif() # the script screens (scripting/scriptscreens.cpp), with the Lua and the WebAssembly runtime when they're built @@ -708,30 +714,58 @@ add_library(eu07_settings INTERFACE) # the parts of the simulation the game shares with the unit tests: the vehicle physics, the vehicle # definition parser, the helpers they use and the rules of the test mode. built once, and tested as the game uses them set(CORE_SOURCES +"audio/startsample.cpp" "McZapkie/friction.cpp" "McZapkie/hamulce.cpp" "McZapkie/Mover.cpp" "McZapkie/couplerphysics.cpp" +"McZapkie/derailment.cpp" +"McZapkie/collision.cpp" +"vehicle/derailmotion.cpp" +"world/TrackCheck.cpp" +"world/SleeperPack.cpp" "McZapkie/Oerlikon_ESt.cpp" +"utilities/logfiles.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" +"utilities/hardwareinfo.cpp" +"scene/sn_utils.cpp" +"scene/regionfile.cpp" +"utilities/inionlysettings.cpp" "utilities/crashsignals.cpp" "scripting/ladderlogic.cpp" "scripting/scriptscreenrules.cpp" "scripting/scriptscreenkernels.cpp" "scripting/scriptscreendrawing.cpp" "simulation/simulationtestrules.cpp" +"vehicle/aipower.cpp" +"vehicle/aiwire.cpp" "vehicle/blackbox.cpp" "utilities/physicslog.cpp" "vehicle/enginestart.cpp" "vehicle/brakesetting.cpp" +"vehicle/fieldshunting.cpp" +"vehicle/gaugewrap.cpp" +"vehicle/drivingaid.cpp" "vehicle/brakingcurve.cpp" +"vehicle/signalpassing.cpp" +"vehicle/brakereleaser.cpp" "vehicle/handover.cpp" +"vehicle/crew.cpp" "vehicle/uphillstart.cpp" +"vehicle/brakecharge.cpp" "vehicle/horn.cpp" +"vehicle/cameraviews.cpp" "vehicle/linebreaker.cpp" "vehicle/smoke.cpp" "vehicle/odometer.cpp" +"world/timetablestart.cpp" +"vehicle/timetableservice.cpp" +"world/timetableflags.cpp" +"world/timetablereader.cpp" +"world/stationnames.cpp" +"world/eventconditions.cpp" +"utilities/wholefile.cpp" ) add_library(eu07_core STATIC ${CORE_SOURCES}) target_link_libraries(eu07_core PUBLIC eu07_settings) @@ -871,10 +905,14 @@ target_link_libraries(eu07_settings INTERFACE Threads::Threads) find_package(GLM REQUIRED) target_include_directories(eu07_settings INTERFACE ${GLM_INCLUDE_DIR}) -# JSON lib -add_subdirectory(ref/json) +# JSON lib: the ref/json submodule by default, or an installed package (e.g. nlohmann-json3-dev, vcpkg nlohmann-json). +# Both give the nlohmann_json::nlohmann_json target; 3.9 is the first release with ordered_json, used by the unit tests. +if (USE_SYSTEM_JSON) + find_package(nlohmann_json 3.9 REQUIRED) +else() + add_subdirectory(ref/json) +endif() target_link_libraries(eu07_settings INTERFACE nlohmann_json::nlohmann_json) -target_include_directories(eu07_settings INTERFACE ${NLOHMANN_JSON_INCLUDE_INSTALL_DIR}) @@ -930,13 +968,16 @@ if (WIN32) endif() # http client of the editor, for the orthophoto, the terrain model and the topo map of geoportal.gov.pl: WinHTTP on Windows, -# libcurl elsewhere when available +# libcurl elsewhere when available. libcurl isn't linked: only its headers are used, and editor/editorHttp.cpp loads the +# system's libcurl at run time (dlopen), so the game starts on a system without it and only the editor's downloads are off +# there. the package doesn't bundle it either (CMake_modules/bundle_runtime_libs.cmake) if (WIN32) target_link_libraries(eu07_settings INTERFACE winhttp) else() find_package(CURL QUIET) if (CURL_FOUND) - target_link_libraries(eu07_settings INTERFACE CURL::libcurl) + target_include_directories(eu07_settings INTERFACE $) + target_link_libraries(eu07_settings INTERFACE ${CMAKE_DL_LIBS}) target_compile_definitions(eu07_settings INTERFACE EU07_WITH_CURL) else() message(STATUS "libcurl not found: the editor's orthophoto and terrain model will only show what's cached, its topo map nothing") diff --git a/CMake_modules/bundle_runtime_libs.cmake b/CMake_modules/bundle_runtime_libs.cmake index a0f71543e..5b95c50e8 100644 --- a/CMake_modules/bundle_runtime_libs.cmake +++ b/CMake_modules/bundle_runtime_libs.cmake @@ -4,6 +4,12 @@ # the libraries of the system itself stay out: the C library and the loader, the GPU driver stack (libGL and its # kin come with the driver), X11 / Wayland, the sound servers, libstdc++ (the GPU drivers bring their own need of a # newer one) and a few more every distribution has. what a library left out depends on isn't bundled either +# +# libcurl and everything it pulls in (TLS, Kerberos, LDAP, HTTP/2, compression, name handling) stay out too: the +# build machine's copy knows the CA bundle path of the build machine's distribution (Debian), so shipped next to +# the game it breaks the certificate checks on Fedora or openSUSE, and the security updates of the TLS stack come +# from the user's system, not from our package. the game isn't linked with libcurl: the editor loads the system's one +# at run time (editor/editorHttp.cpp), and without it only the editor's downloads are off get_filename_component(game_folder "${GAME}" DIRECTORY) set(manifest "${game_folder}/bundled_libs.txt") @@ -43,7 +49,15 @@ set(system_libraries "^lib(asound|pulse|pulse-simple|jack|pipewire-[0-9.]+)\\.so" "^lib(udev|systemd|dbus-1)\\.so" "^libz\\.so" - "^lib(fontconfig|freetype|harfbuzz|expat|uuid)\\.so") + "^lib(fontconfig|freetype|harfbuzz|expat|uuid)\\.so" + "^libcurl" + "^lib(ssl|crypto)\\.so" + "^lib(gssapi_krb5|krb5|k5crypto|krb5support|com_err|keyutils)\\.so" + "^lib(ldap|lber|sasl2)" + "^lib(nghttp2|nghttp3|ngtcp2|rtmp|ssh2?|psl|idn2|unistring)\\.so" + "^libbrotli(dec|enc|common)\\.so" + "^libzstd\\.so" + "^lib(gnutls|hogweed|nettle|gmp|p11-kit|tasn1|ffi)\\.so") file(GET_RUNTIME_DEPENDENCIES EXECUTABLES "${GAME}" diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index d4730f617..cc39d6c18 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -13,9 +13,13 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include "hamulce.h" #include "couplerphysics.h" +#include "derailment.h" +#include "collision.h" #include "scripting/ladderlogic.h" +#include "vehicle/derailmotion.h" #include "vehicle/odometerreading.h" class cParser; @@ -175,6 +179,10 @@ enum DerailReason COLLISION = 5, // powód wykolejenia: zderzenie z innym pojazdem /// Trailing through a switch with a movable nose set the other way. TRAILED_SWITCH = 6, // powód wykolejenia: rozprucie rozjazdu z ruchomym dziobem + /// Climbed onto the vehicle it hit, its end crushed (physics.collisions new). + COLLISION_OVERRIDE = 7, // najechanie + /// Pushed off the track by the force pressing its end (physics.collisions new). + COLLISION_PUSHED_OFF = 8, // wyciśnięcie z toru }; /*wagi prawdopodobienstwa dla funkcji FuzzyLogic*/ @@ -690,6 +698,12 @@ struct TTrackShape double dHtrack = 0.0; // nachylenie /// Track cant / superelevation. double dHrail = 0.0; // przechylka + /// Lateral curvature of the track unevenness under the vehicle [1/m], see world/TrackUneven.h. + double uneven_curvature = 0.0; + /// Cross level unevenness of the track [mm]. + double uneven_cross = 0.0; + /// Curvature a buckle of the track adds under the body [1/m], positive with the curve, see world/TrackBuckle.h. + double buckle_curvature = 0.0; }; /// Per-segment track parameters: gauge, friction, category, load capacity, damage. @@ -707,6 +721,8 @@ struct TTrackParam int DamageFlag = 0; /// Maximum allowed velocity on this segment (used by AI driver). double Velmax; /*dla uzytku maszynisty w ai_driver*/ + /// Name of the track, for the log; nullptr where there is none. + std::string const *Name = nullptr; }; /// Traction-supply parameters at the vehicle's current location. @@ -1278,11 +1294,55 @@ struct TCoupling power_coupling power_high; power_coupling power_110v; power_coupling power_24v; + // the circuit of the power coupling given, nullptr for a coupling which isn't one + power_coupling *power(coupling const Coupling) + { + switch (Coupling) + { + case coupling::highvoltage: + return &power_high; + case coupling::power110v: + return &power_110v; + case coupling::power24v: + return &power_24v; + default: + return nullptr; + } + } + power_coupling const *power(coupling const Coupling) const + { + switch (Coupling) + { + case coupling::highvoltage: + return &power_high; + case coupling::power110v: + return &power_110v; + case coupling::power24v: + return &power_24v; + default: + return nullptr; + } + } // the physical model of the coupling (couplerphysics in eu07.ini), see couplerphysics.h: the parameters of this end, // and the state of the coupling with the vehicle at this end, which that vehicle keeps alike on its own end coupler_physics::end_parameters physics; coupler_physics::pair_state physics_state; + // the collisions past the buffers (physics.collisions new), see collision.h: the optional keys of this end, the depth + // it's crushed to for good [m], and the hit of the pair in the step: whether either vehicle handled it already, its + // peak force [N] and how long that acted [s] + collision::end_definition collision; + double crush{0.0}; + double closing{0.0}; // the velocity the buffers of the pair closed in at, at the start of the step [m/s] + bool hit_handled{false}; + double hit_force{0.0}; + double hit_duration{0.0}; + // physics.collisions monitor: the log told of the crush of this hit of the pair already + bool crush_monitored{false}; + // the energy the contact of the pair brought to its buffers, for the budget of the crush + collision::contact_energy contact; + // the log told of the vehicle at this end being inside this one already + bool inside_reported{false}; int sounds{0}; // sounds emitted by the coupling devices bool Render = false; /*ABu: czy rysowac jak zaczepiony sprzeg*/ @@ -1420,6 +1480,28 @@ class TMoverParameters float pressure{0.f}; // current pressure }; + // the diesel generator set of a dual-mode vehicle: a second source of the traction circuit, next to the + // pantographs (eu07/maszyna#536). none unless the .fiz gives GensetPower + struct genset_device : public basic_device + { + // config (Power: Genset*), revolutions in rev/s, the .fiz gives rpm + double power{0.0}; // GensetPower, electric output at full revolutions [kW]; 0 = no genset + double voltage_nominal{0.0}; // GensetVoltage, regulated DC voltage from the idle revolutions up [V] + double revolutions_idle{0.0}; // GensetIdleRPM + double revolutions_max{0.0}; // GensetMaxRPM + double start_time{8.0}; // GensetStartTime, from the start request to running at idle [s] + double spinup_time{3.0}; // GensetSpinUpTime, time constant of the revolutions [s] + double traction_share{1.0}; // GensetPmaxRatio, part of the power the traction may take + // state + double timer{0.0}; // of the start [s] + bool is_cranking{false}; + // ld outputs + double revolutions{0.0}; // [rev/s] + double voltage{0.0}; // [V] + bool fitted() const { return power > 0.0; } + // the power the genset gives at its present revolutions [kW] + double available_power() const { return revolutions_max > 0.0 ? power * std::clamp(revolutions / revolutions_max, 0.0, 1.0) : 0.0; } + }; // basic approximation of a water pump struct water_pump : public basic_device { @@ -1654,6 +1736,9 @@ class TMoverParameters TDimension Dim; /*wymiary*/ double Cx = 0.0; /*wsp. op. aerodyn.*/ float Floor = 0.96f; // poziom podłogi dla ładunków + // height of the centre of gravity of the empty vehicle above the rail [m] (CoGH in the Dimensions of the .fiz), + // negative when the definition gives none: derailment::default_centre_of_gravity() then + double CentreOfGravity = -1.0; float WheelDiameter = 1.f; /*srednica kol napednych*/ float WheelDiameterL = 0.9f; // Ra: srednica kol tocznych przednich float WheelDiameterT = 0.9f; // Ra: srednica kol tocznych tylnych @@ -1774,6 +1859,10 @@ class TMoverParameters bool MBrake = false; /*Czy jest hamulec reczny*/ double maxTachoSpeed = {0.0}; // maksymalna predkosc na tarczce predkosciomierza analogowego double StopBrakeDecc = 0.0; + // the holding brake (StopBrakeDecc) of a unit with the MED lets go only once power has been demanded for this long (SBDReleaseDelay, s); + // 0 lets it go at the first demand + double StopBrakeReleaseDelay = 0.0; + double StopBrakeReleaseTimer = 0.0; // how long power has been demanded without a break, s bool ReleaseParkingBySpringBrake{false}; bool ReleaseParkingBySpringBrakeWhenDoorIsOpen{false}; bool SpringBrakeCutsOffDrive{true}; @@ -1836,12 +1925,38 @@ class TMoverParameters int FastSerialCircuit = 0; /*0 - po kolei zamyka styczniki az do osiagniecia szeregowej, 1 - natychmiastowe wejscie na szeregowa*/ /*hunter-111012*/ int BackwardsBranchesAllowed = 1; int AutoRelayType = 0; /*0 -brak, 1 - jest, 2 - opcja*/ + // FieldShuntSwitch=Yes: the switch of AutoRelay=Optional of a diesel-electric is its switch of the field shunting, as the SU45's + // and SP45's (fieldshunting.h): off, the field stays full. without it, off hands the shunting to the second controller, as before + bool FieldShuntSwitch = false; bool CoupledCtrl = false; /*czy mainctrl i scndctrl sa sprzezone*/ bool HasCamshaft{false}; int DynamicBrakeType = 0; /*patrz dbrake_**/ int DynamicBrakeAmpmeters = 2; /*liczba amperomierzy przy hamowaniu ED*/ bool SplitEDPneumaticBrake = false; /*czy hamulec ED i pneumatyczny pomocniczy są rozdzielone na osobne nastawniki*/ int DynamicBrakeCtrlPosNo = 10; /*ilosc pozycji nastawnika hamulca ED (DBPN, domyslnie 10)*/ + // the dynamic brake of a diesel-electric vehicle (Engine: EDBrake=...): the traction motors brake into resistors while + // the engine runs, with the force of the definition rather than from a circuit, as the drive of these vehicles is + // computed from the generator's power. no definition, no dynamic brake (MaSzyna-EU07/maszyna#82) + struct diesel_electric_dynamic_brake + { + enum class control + { + none, + controller, // the negative range of the integrated controller (EIMCtrlType > 0), as the TRAXX one of the BR285 + lever // a lever of its own (the SplitEDPneumaticBrake one, DBPN steps), with the master controller at zero + }; + control source{control::none}; + double max_force{0.0}; // [N] at the wheel rims of the whole vehicle, EDBrakeFmax [kN] + double max_power{0.0}; // [W] the resistors take, EDBrakePmax [kW]; 0: no limit + double fade_low{0.0}; // [km/h] EDBrakeV0: no force below + double fade_high{0.0}; // [km/h] EDBrakeV1: the whole force above, rising in between + double rate{0.5}; // [1/s] EDBrakeRate: how fast the effort follows the demand + bool blending{false}; // EDBrakeBlending: the locomotive's train brake lets off while the dynamic brake works (Hamulec->SetED) + // state + double level{0.0}; // the effort, 0..1 + double force{0.0}; // [N] the braking force, against the motion + }; + diesel_electric_dynamic_brake DEDynamicBrake; double DynamicBrakeRes = 5.8; /*rezystancja oporników przy hamowaniu ED*/ double DynamicBrakeRes1 = 5.8; /*rezystancja oporników przy hamowaniu ED - 1 tryb*/ double DynamicBrakeRes2 = 5.8; /*rezystancja oporników przy hamowaniu ED - 2 tryb*/ @@ -2038,6 +2153,13 @@ class TMoverParameters int SoundFlag = 0; /*!o patrz stale sound_ */ int AIFlag{0}; // HACK: events of interest for consist owner double DistCounter = 0.0; /*! licznik kilometrow */ + // the criteria of derailment (physics.derailment new), and the distance travelled since they were checked [m] + derailment::monitor derailment_monitor; + double derailment_distance = 0.0; + // physics.derailment monitor: the name of the track the criteria were last reported on (one report on a track), and + // how many reports there were + std::optional derailment_reported; + int derailment_reports = 0; odometer::reading Odometer; // total distance run, kept between the sessions (eu07/maszyna#72) std::pair EnergyMeter; // energy from grid [kWh] double V = 0.0; // predkosc w [m/s] względem sprzęgów (dodania gdy jedzie w stronę 0) @@ -2074,10 +2196,12 @@ class TMoverParameters double EmergencyValveFlow = 0.0; // air flow through alerter valve during last simulation step /*! przyrosty cisnienia w kroku czasowym*/ double ScndPipePress = 0.0; /*cisnienie w przewodzie zasilajacym*/ + bool ScndPipeCouplersPending{false}; // the main reservoir pipe stepped, its air exchange through the hoses is yet to come (UpdatePipeCouplers()) double BrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych*/ double LocBrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych z pomocniczego*/ double PipeBrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych z przewodu*/ double PipePress = 0.0; /*!o cisnienie w przewodzie glownym*/ + bool PipeCouplersPending{false}; // the brake pipe stepped, its air exchange through the hoses is yet to come (UpdatePipeCouplers()) double EqvtPipePress = 0.0; /*!o cisnienie w przewodzie glownym skladu*/ double Volume = 0.0; /*objetosc spr. powietrza w zbiorniku hamulca*/ double CompressedVolume = 0.0; /*objetosc spr. powietrza w ukl. zasilania*/ @@ -2110,6 +2234,11 @@ class TMoverParameters bool ConverterOverloadRelayOffWhenMainIsOff{false}; fuel_pump FuelPump; oil_pump OilPump; + genset_device Genset; // of a dual-mode vehicle, fitted() only with GensetPower + // the source the traction circuit takes its voltage from (the traction selector of a dual-mode vehicle) + enum class traction_mode { catenary, genset }; + traction_mode TractionMode{traction_mode::catenary}; + bool GensetSelected() const { return TractionMode == traction_mode::genset; } water_pump WaterPump; water_heater WaterHeater; bool WaterCircuitsLink{false}; // optional connection between water circuits @@ -2183,6 +2312,15 @@ class TMoverParameters bool LineBreakerClosesOnlyAtNoPowerPos{false}; bool ControlPressureSwitch{false}; // activates if the main pipe and/or brake cylinder pressure aren't within operational levels bool HasControlPressureSwitch{true}; + // config, .fiz Engine:PressureSwitchBrakeCylinder. whether the pressure switch watches the brake cylinders (it cuts the + // start off above 2 bar there) as well as the brake pipe (below 3.6 bar). off, it's left with the brake pipe alone, + // and the vehicle takes current whatever the pressure in its brake cylinders (EP05) + bool PressureSwitchBrakeCylinder{true}; + // config, .fiz Cntrl.EmergencyBrakeMainOff. the brake pipe pressure [bar] taken for an emergency brake application: + // below it, with the master controller on a power position, the line breaker opens and doesn't close again. where + // the pantographs stay up only through the closed line breaker (PantographsRequireMains) they drop with it (EP05). + // 0: an emergency application leaves the line breaker alone + double EmergencyBrakeMainOffPressure{0.0}; bool ReleaserEnabledOnlyAtNoPowerPos{false}; int MainCtrlPos = 0; /*polozenie glownego nastawnika*/ int ScndCtrlPos = 0; /*polozenie dodatkowego nastawnika*/ @@ -2194,6 +2332,9 @@ class TMoverParameters int CabActive = 0; // numer kabiny, z której jest sterowanie: 1 lub -1; w przeciwnym razie brak sterowania - rozrzad int CabOccupied = 0; // numer kabiny, w ktorej jest obsada (zwykle jedna na skład) // TODO: move to TController bool CabMaster = false; // czy pojazd jest nadrzędny w składzie + // pullee mode ("jazda ciągniona", MaSzyna-EU07/maszyna#64): the vehicle is prepared for being hauled dead in a + // train, see PulleeModeSwitch() + bool PulleeMode{false}; inline bool IsCabMaster() const { return CabActive == CabOccupied && CabMaster; @@ -2424,6 +2565,62 @@ class TMoverParameters // was a broken coupler to repair bool repair_coupler(int const End); void Derail(DerailReason Reason); + // the velocity of the vehicles coupled to this one changes by the Change along the axis of this one [m/s], as the + // legacy derailment changes the velocity of this one (physics.collisions new) + void change_train_velocity(double Change); + // physics.derailment new: the criteria of derailment.h over the step, which travelled the Distance [m]; monitor: what + // they would do, to the log + void check_derailment(TTrackShape const &Shape, TTrackParam const &Track, double Distance); + // the vehicle leaves the rails, as the criteria of derailment.h found + void derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track, std::string const *TrackName = nullptr); + // height of the centre of gravity above the rail with the load [m] + double centre_of_gravity() const; + // the vehicle is back on the rails (resetconsist, SetDamage taking dtrain_out off): not derailed any more, and the + // criteria of derailment start from scratch, so a later derailment goes the way its model has it + void rerail(); + // what resetconsist does to a vehicle: no damage of any kind, the alarm chain released, back on the rails + void repair_damage(); + // how the vehicle left the rails by the criteria of derailment.h: upright, or on its side. none for any other + // derailment, which stops it as the legacy model does (with physics.collisions new by a friction of its weight, the + // forces of the vehicles coupled to it acting on it) + derailment::outcome Derailed{derailment::outcome::none}; + // physics.derailment new: how the vehicle left the rails, for the way it leaves the track (vehicle/derailmotion.h): + // what derailed it, the lateral acceleration of its body out of the curve then [m/s2] (negative into the curve, where a + // buckle bends the line the other way), and the side it was pulled off to by a coupling (1 the left of its front, -1 + // the right; 0 the side the acceleration throws it to, from the track) + derail_motion::cause DerailCause{derail_motion::cause::off_rails}; + double DerailAcceleration{0.0}; + int DerailSide{0}; + // the vehicle off the track, on the ground: begun and stepped by TDynamicObject, which knows the ground; its friction + // and the grade under it go into the forces of this one + derail_motion::body OffTrack; + // physics.derailment new: the vehicle derailed by the physical criteria, the end of the track or a collision has to + // leave the track and its motion on the ground isn't begun yet. never with physics.derailment monitor, old or off + bool leaves_track() const; + // physics.derailment new: a coupling of a vehicle off the track pulls this one off the rails sideways, to the Side + // (1 the left of its front, -1 the right), with the lateral acceleration [m/s2] of the pull on it + void pull_off(int Side, double Acceleration, std::string const &Why); + // physics.collisions new: what the vehicle is for the defaults of its crush and its buffers, the crush curve and the + // height of the buffers of an end, and how long the push of its ends held its wheels over the climbing limit + collision::vehicle_kind collision_kind() const; + collision::crush_curve crush_curve_at(int End) const; + double buffer_height_at(int End) const; + collision::pushed_monitor pushed_off_monitor; + // how the vehicle left the rails in a collision (physics.collisions new): overriding or pushed off, NONE otherwise + DerailReason CollisionDerail{NONE}; + // physics.collisions monitor: how many crushes the log told of, of the hits of this vehicle on the others + int crush_reports{0}; + // physics.collisions new: the hit of the end on the stop of its buffers, harder than the steel takes, crushes the + // weaker end and may let one vehicle climb onto the other one, see collision.h. returns: whether it did, and the + // velocities took the hit; the legacy collision takes the rest. physics.collisions monitor: the log tells what the + // crush of the whole hit would be, once for a hit, nothing changes, and it returns false + bool crush_hit(int End, double dt); + // the force pressing the ends pushes the vehicle off the track (physics.collisions new), the step travelled the + // Distance [m]: the flange climbs while the wheels roll on + void check_pushed_off(double dt, double Distance); + // the vehicle leaves the rails in a collision, the reason told in the log, and slides on as the criteria of + // derailment.h have it + void derail_in_collision(DerailReason Reason, std::string const &Why); bool DirectionForward(); bool DirectionBackward(void); /*! kierunek ruchu*/ bool EIMDirectionChangeAllow(void) const; @@ -2439,6 +2636,10 @@ class TMoverParameters bool CurrentSwitch(bool const State); bool IsMotorOverloadRelayHighThresholdOn() const; void UpdateBatteryVoltage(double dt); + double BatteryDrain(double dt, bool converteractive) const; + double BatteryDrainCharged(double dt, bool converteractive) const; + double BatteryDrainLow(double dt, bool converteractive) const; + double BatteryDrainSwitchedOff(double dt) const; double ComputeMovement(double dt, double dt1, const TTrackShape &Shape, TTrackParam const &Track, TTractionParam const &ElectricTraction, TLocation const &NewLoc, TRotation const &NewRot); // oblicza przesuniecie pojazdu double FastComputeMovement(double dt, const TTrackShape &Shape, TTrackParam &Track, TLocation const &NewLoc, TRotation const &NewRot); // oblicza przesuniecie pojazdu - wersja zoptymalizowana @@ -2479,6 +2680,20 @@ class TMoverParameters bool SetInternalCommand(std::string const &NewCommand, double NewValue1, double NewValue2, int const Couplertype = coupling::control); double GetExternalCommand(std::string &Command) const; bool RunCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype = coupling::control); + // the parts of RunCommand(), by the area of the commands + bool RunControllerCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunRelaysCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunCabCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunBrakeCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunBrakeEquipmentCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunAuxiliariesCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunPumpsCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunBlowersCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunPowerCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunDoorsCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + void DoorPermitCommand(double CValue1, double CValue2); + void DoorRemoteCommand(bool Open, double CValue1, double CValue2); + bool RunLoadCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); bool RunInternalCommand(); void PutCommand(std::string const &NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation); bool CabActivisation(bool const Enforce = false); @@ -2490,6 +2705,11 @@ class TMoverParameters /*! glowny nastawnik:*/ bool IncMainCtrl(int CtrlSpeed); bool DecMainCtrl(int CtrlSpeed); + // the parts of IncMainCtrl() and DecMainCtrl() which depend on the kind of the engine + bool IncMainCtrlByEngine(int CtrlSpeed); + bool IncMainCtrlSeriesMotor(int CtrlSpeed); + bool DecMainCtrlByEngine(int CtrlSpeed); + bool DecMainCtrlSeriesMotor(int CtrlSpeed); bool IsMainCtrlActualNoPowerPos() const; // whether the master controller is actually set to position which won't generate any extra power bool IsMainCtrlNoPowerPos() const; // whether the master controller is set to position which won't generate any extra power bool IsMainCtrlMaxPowerPos() const; @@ -2514,6 +2734,7 @@ class TMoverParameters // ScndCtrlResistiveLock: the shunt controller drops to 0 once the master controller is at zero or on a resistive position, so it // can't stay engaged there, locked in place (eu07/maszyna#402) void ScndCtrlResistiveLockCheck(); + // NOTE: with the cruise control, either end of the secondary controller, as before the split of the two (eu07/maszyna#69) bool IsScndCtrlNoPowerPos() const; bool IsScndCtrlMaxPowerPos() const; @@ -2533,6 +2754,7 @@ class TMoverParameters bool SpringBrakeActivate(bool State); bool SpringBrakeShutOff(bool State); bool SpringBrakeRelease(); + bool PulleeModeSwitch(bool const State); /*! stopnie hamowania - hamulec zasadniczy*/ bool IncBrakeLevelOld(void); @@ -2568,11 +2790,26 @@ class TMoverParameters /*pomocnicze funkcje dla ukladow pneumatycznych*/ void UpdateBrakePressure(double dt); void UpdatePipePressure(double dt); + // the parts of UpdatePipePressure() + void UpdateLocalBrakeValve(double dt); + void UpdateMainValve(double dt); + double MainValveSupply(); + double MainValveHandlePosition() const; + void UpdateEmergencyValve(double dt); + void UpdateDistributorSettings(); + void UpdateEPBrake(); void CompressorCheck(double dt); /*wlacza, wylacza kompresor, laduje zbiornik*/ void UpdatePantVolume(double dt); // Ra + void PantPressureSwitchCheck(); + void PantPressureSwitchTrip(); void UpdateScndPipePressure(double dt); void UpdateSpringBrake(double dt); double GetDVc(double dt); + int PipeCouplersSubsteps(double dt) const; + double GetScndDVc(double dt); + int ScndPipeCouplersSubsteps(double dt) const; + // the air exchange through the brake and main reservoir hoses, after the vehicles stepped + static void UpdatePipeCouplers(std::vector const &Vehicles, double dt); /*funkcje obliczajace sily*/ void ComputeConstans(void); // ABu: wczesniejsze wyznaczenie stalych dla liczenia sil @@ -2580,11 +2817,54 @@ class TMoverParameters void ComputeTotalForce(double dt); double Adhesive(double staticfriction) const; double TractionForce(double dt); + // the parts of TractionForce(), in the order it makes them + double UpdateEngineRevolutions(double dt, double &dtrans, double &dmoment); + double DieselElectricTargetRevolutions(); + void UpdateVentilators(double dt); + void UpdateResistorBlowers(double dt); + double UpdateEnginePower(); + void VoltageRelaysCheck(); + void DumbTractionForce(double PosRatio); + void WheelsDrivenTractionForce(double dt); + void SeriesMotorTractionForce(double dt); + void SeriesMotorDynamicBrake(double dt); + void DieselEngineTractionForce(double dt, double dmoment, double dtrans); + void DieselElectricTractionForce(double tmp); + void DieselElectricShuntForce(double tmpV, double &tmp); + double DieselElectricDigitalForce(double tmpV, double &tempUmax, double &tempImax); + double DieselElectricForce(double tmpV, double LinePower, double Ratio, double HyperbolaPower) const; + void DieselElectricShuntPower(double tmp); + void DieselElectricGenerator(double tmp, double tempUmax, double tempImax); + void ShuntFieldRelaysCheck(double tmpV, double PosRatio, double tmp); + void ShuntFieldRelaysType2(double tmp); + void ShuntFieldRelaysType41(double tmpV); + void ShuntFieldRelaysType45(); + void ShuntFieldRelaysType46(); + void ShuntFieldRelaysType46Up(); + void ShuntFieldRelaysType46Down(); + void InductionMotorTractionForce(double dt); + void InductionMotorSpeedControl(double dt); + void SpeedControlByTime(double dt); + void SpeedControlByPosition(double dt); + void InductionMotorBrakeBlending(double ActiveInverters, double &PosRatio, double &tmp); + void InductionMotorDynamicBrakeFlag(); + double InductionMotorBrakeRatio(double ActiveInverters, double edBCP); + void InductionMotorDrive(double dt); + void InductionMotorForceLimits(); + void UpdateInverterFrequency(); + void InductionMotorOff(); + // the dynamic brake of a diesel-electric vehicle: the effort following the demand, the force it gives at the speed + void update_dieselelectric_dynamic_brake(double dt); + double dieselelectric_dynamic_brake_demand() const; // 0..1, the effort the driver asks for + double dieselelectric_dynamic_brake_limit() const; // [N] the force at full effort at the speed + void apply_dieselelectric_dynamic_brake(double dt); // the force in place of the drive's one, over the step dt + double dieselelectric_motor_current(double Moment) const; // the current of the motors giving the moment double FrictionForce() const; double BrakeForceR(double ratio, double velocity) const; double BrakeForceP(double press, double velocity) const; double BrakeForce(const TTrackParam &Track); double CouplerForce(int const End, double dt); + void CouplerStretchCheck(int End, double CF, double dt); // whether the coupling at the end is computed by the physical model: couplerphysics set in eu07.ini, and this // vehicle or the one at the end covered by it (CouplerPhysics), or every vehicle with couplerphysics all bool coupler_physics_at(int const End) const; @@ -2624,6 +2904,12 @@ class TMoverParameters { return false == ControlPressureSwitch && (HasControlPressureSwitch || BrakePress < 1.0); } + // whether an emergency brake application holds the line breaker open: the brake pipe below the pressure taken for one + // (EmergencyBrakeMainOffPressure) while the master controller is on a power position + bool EmergencyBrakeHoldsMainOff() const + { + return EmergencyBrakeMainOffPressure > 0.0 && PipePress < EmergencyBrakeMainOffPressure && false == IsMainCtrlNoPowerPos(); + } // whether the lamp of the open line contactors is lit. on the electric locomotives it tells the start can be made, so // it goes out with the start cut off; on the diesel-electric ones (the SU45 and SU46 family) it just tells the // contactors are open, whatever opened them: the master controller at 0, or the pressure switch (eu07/maszyna#263) @@ -2707,6 +2993,13 @@ class TMoverParameters bool HeatingSwitch(bool const State, range_t const Notify = range_t::consist); void HeatingSwitch_(bool const State); double EnginePowerSourceVoltage() const; // returns voltage of defined main engine power source + bool TractionModeSwitch(traction_mode const Mode, range_t const Notify = range_t::consist); // traction selector of a dual-mode vehicle + bool GensetSwitch(bool const State, range_t const Notify = range_t::consist); // genset start/stop request + double TractionSourceVoltage() const; // of the vehicle's own source the traction selector picks: the pantographs' or the genset's + double TractionSupplyVoltage() const; // what the traction circuit gets: the own source's, or the train's high voltage line's + double TractionSupplyMinVoltage() const; // below it the line breaker opens (undervoltage) + double GensetTractionPowerLimit() const; // [kW] at the wheels, the largest double unless running on the genset + double CatenaryCurrent() const; // [A] what the vehicle draws through its pantographs, if they touch the wire // whether the main circuit feeds what runs on it (the converter, a compressor, the heating, the motor and resistor // blowers, the traction motors): the line breaker closed, and where it closes ahead of the pantographs and holds // without traction voltage (PantographsRequireMains) also the voltage there, at least the one the undervoltage @@ -2717,6 +3010,11 @@ class TMoverParameters void LowVoltagePowerCheck(double const Deltatime); void MainsCheck(double const Deltatime); void PowerCouplersCheck(double const Deltatime, coupling const Coupling); + // the parts of PowerCouplersCheck() + double LocalPowerVoltage(coupling Coupling); + void PowerCouplersVoltage(coupling Coupling, double abslocalvoltage, bool localpowersource); + void PowerCouplersCurrent(coupling Coupling, bool localpowersource); + double *PowerCircuitCurrent(coupling Coupling); void ConverterCheck(double const Timestep); // przetwornica void HeatingCheck(double const Timestep); void WaterPumpCheck(double const Timestep); @@ -2727,6 +3025,7 @@ class TMoverParameters // whether the circuit a traction motor blower runs off has power: the battery, the converter or the main circuit, by its start type bool MotorBlowerPowerIsAvailable(cooling_fan const &Blower) const; void PantographsCheck(double const Timestep); + void GensetCheck(double const Deltatime); void LightsCheck(double const Timestep); bool FuseOn(range_t const Notify = range_t::consist); // bezpiecznik nadamiary bool FuseFlagCheck(void) const; // sprawdzanie flagi nadmiarowego @@ -2741,6 +3040,11 @@ class TMoverParameters /*funkcje uzalezniajace sile pociagowa od predkosci: v2n, n2r, current, momentum*/ double v2n(void); double Current(double n, double U); + // the parts of Current() + void UpdateSeriesMotorDynamicBrakeFlag(); + double SeriesMotorCurrent(double n, double U, double R, double Mn) const; + double SeriesMotorDrivingCurrent(double n, double U, double Rz, double Mn, int SP) const; + void MotorFailuresCheck(double n); double Momentum(double I) const; double MomentumF(double I, double Iw, int SCP) const; @@ -2750,6 +3054,15 @@ class TMoverParameters bool MinCurrentSwitch(bool State); // przelacznik pradu automatycznego rozruchu bool AutoRelaySwitch(bool State); // przelacznik automatycznego rozruchu bool AutoRelayCheck(); // symulacja automatycznego rozruchu + // the parts of AutoRelayCheck() + bool AutoRelayShuntStep(bool ARFASI2); + bool AutoRelayMainStep(bool ARFASI); + bool AutoRelayMainUp(bool ARFASI); + bool AutoRelayMainNotchUp(); + bool AutoRelayMainDown(); + bool AutoRelayLineContactorsStep(bool motorconnectorsoff); + bool CamshaftRunDown(); + bool CamshaftRunDownEMU(); bool MotorConnectorsCheck(); bool ResistorsFlagCheck(void) const; // sprawdzenie kontrolki oporow rozruchowych NBMX @@ -2758,7 +3071,27 @@ class TMoverParameters bool DropAllPantographs(bool const State, range_t const Notify = range_t::consist); void CheckEIMIC(double dt); // sprawdzenie i zmiana nastawy zintegrowanego nastawnika jazdy/hamowania + // the parts of CheckEIMIC(), by the kind of the controller + void EIMICFromController(double brakeDemand, double offset, double multiplier); + void EIMICFromSteps(double dt); + void EIMICFromFourPositions(double dt); + void EIMICFromUniversalController(double dt, double brakeDemand); + void UniversalControllerTrainBrake(); + void EIMICTraxxLocalBrake(double dt); + void EIMICLimit(); + // whether the holding brake (StopBrakeDecc) lets go at the power demand (eimic, above 0 when power is demanded) of this step of + // Dt seconds: once the demand has stayed above 0 for StopBrakeReleaseDelay. a demand of 0 or less starts the count again + bool UpdateStopBrakeRelease(double Demand, double Dt); void CheckSpeedCtrl(double dt); + void SpeedCtrlRegulator(double dt, double accfactor); + // whether the cruise control has a switch of its own: the secondary controller doubles as its switch unless it + // shunts the field of the traction motors already, or there's none (the 6Dg, the ST45; eu07/maszyna#69) + bool IsSpeedCtrlSeparate() const; + // whether the cruise control is switched on: by its own switch, or by the secondary controller off its zero position + bool IsSpeedCtrlEngaged() const; + // the driver's switch of the cruise control: on, to hold the speed of the moment, or off. its own switch, or the + // secondary controller doubling as one (first position on, back to zero off); returns whether it did anything + bool SpeedCtrlSwitch(bool State); void SpeedCtrlButton(int button); void SpeedCtrlInc(); void SpeedCtrlDec(); @@ -2769,8 +3102,18 @@ class TMoverParameters bool dizel_EngageSwitch(double state); bool dizel_EngageChange(double dt); bool dizel_AutoGearCheck(void); + bool dizel_GearShiftCheck(double VelUp, double VelDown); + bool dizel_GearShiftRequest(double VelUp, double VelDown); + void dizel_ClutchCheck(); + void dizel_ClutchByController(); + void dizel_ClutchByIntegratedController(); double dizel_fillcheck(int mcp, double dt); + double dizel_DigitalFill(double dt); + double dizel_GovernorFill(int mcp, double realfill) const; + double dizel_GovernorRevolutions(int mcp, double &realfill) const; double dizel_Momentum(double dizel_fill, double n, double dt); + void hydro_TCFillCheck(double dt); + void hydro_TCTorque(); double dizel_MomentumRetarder(double n, double dt); // moment hamowania retardera void dizel_HeatSet(float const Value); void dizel_Heat(double const dt); @@ -2793,6 +3136,16 @@ class TMoverParameters // whether the door closure lamp in the cab of this vehicle is lit: with DoorClosureSignal, for the given state of the // consist; without it, for the lock of the vehicle's own doors, as the lamp always worked bool door_closure_lamp_lit(door_closure_t const Consist, bool const BlinkLit) const; + // the parts of update_doors() + // not const: the door they change is one of Doors.instances + void update_door_requests(basic_door &door, bool localopencontrol, bool remoteopencontrol, bool localclosecontrol, bool remoteclosecontrol); + void move_door(basic_door &door, double Deltatime); + bool door_open_request(basic_door const &door, bool localopencontrol, bool remoteopencontrol) const; + bool door_close_request(basic_door const &door, bool localclosecontrol, bool remoteclosecontrol) const; + bool doors_powered() const; + bool door_step_folding(basic_door const &door) const; + float door_open_duration(basic_door const &door, bool localopencontrol, bool remoteopencontrol) const; + void update_door_timers(double Deltatime); /* funkcje dla samochodow*/ bool ChangeOffsetH(double DeltaOffset); @@ -2801,12 +3154,24 @@ class TMoverParameters bool LoadFIZ(std::string const &chkpath); // Q 20160717 bool LoadChkFile(std::string chkpath); bool LoadFIZ_Text(std::string const &Text); // the same, from text in the .fiz format bool CheckLocomotiveParameters(bool ReadyFlag, int Dir); + // the parts of CheckLocomotiveParameters() + void CreateBrakeValve(); + void CreateBrakeHandles(); + void CreateBrakePipes(); + double InitialScndPipePress(double HosePressure) const; + void SetReadyToDepart(); + void SetBraked(); std::string EngineDescription(int what) const; // the cab interior light the light preset at given position (1-based, as LightsPos) sets, if it sets one std::optional LightsPresetCabLight(int Position) const; private: bool LoadFIZ_Parse(cParser &Parser); // reads the definition from either of the above + // the parts of LoadFIZ_Parse(), for a line of the definition + bool LoadFIZ_TableEnd(std::string const &inputline) const; + bool LoadFIZ_Section(std::string const &inputline, std::map> &fizlines); + bool LoadFIZ_TableSection(std::string const &inputline, std::map> &fizlines); + void LoadFIZ_TableRow(std::string const &inputline); void LoadFIZ_Param(std::string const &line); void LoadFIZ_Load(std::string const &line); void LoadFIZ_Dimensions(std::string const &line); @@ -2816,6 +3181,11 @@ class TMoverParameters void LoadFIZ_BuffCoupl(std::string const &line, int const Index); void LoadFIZ_TurboPos(std::string const &line); void LoadFIZ_Cntrl(std::string const &line); + void LoadFIZ_CntrlBrakes(std::string const &line); + void LoadFIZ_CntrlTrainBrake(std::string const &line); + void LoadFIZ_CntrlAntiSlipBrake(std::string_view asb); + void LoadFIZ_CntrlControllers(std::string const &line); + void LoadFIZ_CntrlStarts(std::string const &line); void LoadFIZ_Blending(std::string const &line); void LoadFIZ_DCEMUED(std::string const &line); void LoadFIZ_SpringBrake(std::string const &line); @@ -2823,14 +3193,20 @@ class TMoverParameters void LoadFIZ_Headlights(std::string const &Line); void LoadFIZ_Clima(std::string const &line); void LoadFIZ_Power(std::string const &Line); + void LoadFIZ_Genset(std::string const &Line); void LoadFIZ_SpeedControl(std::string const &Line); void LoadFIZ_Engine(std::string const &Input); + void LoadFIZ_EngineDiesel(std::string const &Input); + void LoadFIZ_EngineDieselElectric(std::string const &Input); + void LoadFIZ_EngineInductionMotor(std::string const &Input); + void LoadFIZ_EngineDieselShared(std::string const &Input); void LoadFIZ_Switches(std::string const &Input); void LoadFIZ_MotorParamTable(std::string const &Input); void LoadFIZ_Circuit(std::string const &Input); void LoadFIZ_AI(std::string const &Input); void LoadFIZ_RList(std::string const &Input); void LoadFIZ_UCList(std::string const &Input); + void LoadFIZ_DieselElectricDynamicBrake(std::string const &Input); void LoadFIZ_DList(std::string const &Input); void LoadFIZ_FFList(std::string const &Input); void LoadFIZ_FFEDList(std::string const &Input); diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index d74aee11f..2cffe93cc 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "utilities/parser.h" #include "simulation/simulation.h" +#include "vehicle/fieldshunting.h" #include #include @@ -70,6 +71,30 @@ int DirPatch(int Coupler1, int Coupler2) return Coupler1 != Coupler2 ? 1 : -1; } +namespace +{ + +// physics.collisions new: a rail vehicle derailed the legacy way keeps the deceleration of the legacy model, g, as the +// friction of its weight, and the forces of the vehicles coupled to it act on it as on any other: the train behind it +// pushes it on, and it holds the train back. alone it stops as the legacy model has it. the legacy model stops it +// whatever pushes it, and the train behind it stopped at once against it, in a hit no train had +bool legacy_derailed_slides(TMoverParameters const &Vehicle) +{ + return Global.collisions == global_settings::collision_model::physical && TestFlag(Vehicle.CategoryFlag, 1) && TestFlag(Vehicle.DamageFlag, dtrain_out) && + Vehicle.Derailed == derailment::outcome::none; +} + +// a derailed vehicle tears its brake hoses: the brake pipe vents and the rest of the train brakes in emergency +void tear_brake_hoses(TMoverParameters &Vehicle) +{ + if (std::any_of(std::begin(Vehicle.Couplers), std::end(Vehicle.Couplers), [](auto const &Coupler) { return (Coupler.CouplingFlag & coupling::brakehose) == coupling::brakehose; })) + { + Vehicle.AlarmChainFlag = true; + } +} + +} // namespace + int DirF(int CouplerN) { switch (CouplerN) @@ -319,44 +344,10 @@ double TMoverParameters::Current(double n, double U) double R; double MotorCurrent; - double Rz; - double Delta; - double Isf; double Mn; // przujmuje int, ale dla poprawnosci obliczeń double Bn; - int SP = 0; - double U1; // napiecie z korekta - MotorCurrent = 0; - // i dzialanie hamulca ED w EP09 - if (DynamicBrakeType == dbrake_automatic && TrainType != dt_EZT) - { - if ((Hamulec->GetEDBCP() < 0.25 && Vadd < 1) || BrakePress > 2.1) - DynamicBrakeFlag = false; - else if (BrakePress > 0.25 && Hamulec->GetEDBCP() > 0.25) - DynamicBrakeFlag = true; - DynamicBrakeFlag = DynamicBrakeFlag && Power110vIsAvailable; - } - if (DynamicBrakeType == dbrake_automatic && TrainType == dt_EZT) - { - DynamicBrakeFlag = Power110vIsAvailable && (TUHEX_Active || Vadd > TUHEX_MinIw) && DynamicBrakeEMUStatus; - } - - // wylacznik cisnieniowy yBARC - to jest chyba niepotrzebne tutaj Q: no to usuwam... - - // BrakeSubsystem = ss_LSt; - // if (BrakeSubsystem == ss_LSt) WriteLog("LSt"); - // if (BrakeSubsystem == ss_LSt) // zrobiona funkcja virtualna - if (DynamicBrakeFlag) - { - Hamulec->SetED(abs(Im / 350)); // hamulec ED na EP09 dziala az do zatrzymania lokomotywy - //- WriteLog("A"); - } - else - { - Hamulec->SetED(0); - //- WriteLog("B"); - } + UpdateSeriesMotorDynamicBrakeFlag(); ResistorsFlag = RList[MainCtrlActualPos].R > 0.01; // and (!DelayCtrlFlag) ResistorsFlag = ResistorsFlag || (DynamicBrakeFlag == true && DynamicBrakeType == dbrake_automatic); @@ -394,65 +385,7 @@ double TMoverParameters::Current(double n, double U) } else { // wlaczone... - SP = ScndCtrlActualPos; - - if (ScndCtrlActualPos < 255) // tak smiesznie bede wylaczal - { - if (ScndInMain && RList[MainCtrlActualPos].ScndAct != 255) - { - SP = RList[MainCtrlActualPos].ScndAct; - } - - Rz = Mn * WindingRes + R; - - if (DynamicBrakeFlag) // hamowanie - { - if (DynamicBrakeType > 1) - { - // if DynamicBrakeType<>dbrake_automatic then - // MotorCurrent:=-fi*n/Rz {hamowanie silnikiem na oporach rozruchowych} - /* begin - U:=0; - Isf:=Isat; - Delta:=SQR(Isf*Rz+Mn*fi*n-U)+4*U*Isf*Rz; - MotorCurrent:=(U-Isf*Rz-Mn*fi*n+SQRT(Delta))/(2*Rz) - end*/ - if (DynamicBrakeType == dbrake_switch && TrainType == dt_ET42) - { // z Megapacka - Rz = WindingRes + R; - MotorCurrent = -motor_param(SP).fi * n / Rz; //{hamowanie silnikiem na oporach rozruchowych} - } - } - else - MotorCurrent = 0; // odciecie pradu od silnika - } - else - { - U1 = U + Mn * n * motor_param(SP).fi0 * motor_param(SP).fi; - // writepaslog("U1 ", FloatToStr(U1)); - // writepaslog("Isat ", FloatToStr(MotorParam[SP].Isat)); - // writepaslog("fi ", FloatToStr(MotorParam[SP].fi)); - Isf = Sign(U1) * motor_param(SP).Isat; - // writepaslog("Isf ", FloatToStr(Isf)); - Delta = square(Isf * Rz + Mn * motor_param(SP).fi * n - U1) + 4.0 * U1 * Isf * Rz; // 105 * 1.67 + Mn * 140.9 * 20.532 - U1 - // DeltaQ = Isf * Rz + Mn * MotorParam[SP].fi * n - U1 + 4 * U1 * Isf * Rz; - // writepaslog("Delta ", FloatToStr(Delta)); - // writepaslog("DeltaQ ", FloatToStr(DeltaQ)); - // writepaslog("U ", FloatToStr(U)); - if (MainCircuitPowered()) - { - if (U > 0) - MotorCurrent = (U1 - Isf * Rz - Mn * motor_param(SP).fi * n + std::sqrt(Delta)) / (2.0 * Rz); - else - MotorCurrent = (U1 - Isf * Rz - Mn * motor_param(SP).fi * n - std::sqrt(Delta)) / (2.0 * Rz); - } - else - MotorCurrent = 0; - } // else DBF - - } // 255 - else - MotorCurrent = 0; + MotorCurrent = SeriesMotorCurrent(n, U, R, Mn); } // writepaslog("MotorCurrent ", FloatToStr(MotorCurrent)); @@ -467,6 +400,125 @@ double TMoverParameters::Current(double n, double U) EnginePower = abs(Itot) * (1 + RList[MainCtrlActualPos].Mn) * abs(U) / 1000.0; + MotorFailuresCheck(n); + + return Im; +} + +// the automatic dynamic brake of the series motors (EP09, the units) on or off, and the distributor told of it +void TMoverParameters::UpdateSeriesMotorDynamicBrakeFlag() +{ + // i dzialanie hamulca ED w EP09 + if (DynamicBrakeType == dbrake_automatic && TrainType != dt_EZT) + { + if ((Hamulec->GetEDBCP() < 0.25 && Vadd < 1) || BrakePress > 2.1) + DynamicBrakeFlag = false; + else if (BrakePress > 0.25 && Hamulec->GetEDBCP() > 0.25) + DynamicBrakeFlag = true; + DynamicBrakeFlag = DynamicBrakeFlag && Power110vIsAvailable; + } + if (DynamicBrakeType == dbrake_automatic && TrainType == dt_EZT) + { + DynamicBrakeFlag = Power110vIsAvailable && (TUHEX_Active || Vadd > TUHEX_MinIw) && DynamicBrakeEMUStatus; + } + + // wylacznik cisnieniowy yBARC - to jest chyba niepotrzebne tutaj Q: no to usuwam... + + // BrakeSubsystem = ss_LSt; + // if (BrakeSubsystem == ss_LSt) WriteLog("LSt"); + // if (BrakeSubsystem == ss_LSt) // zrobiona funkcja virtualna + if (DynamicBrakeFlag) + { + Hamulec->SetED(abs(Im / 350)); // hamulec ED na EP09 dziala az do zatrzymania lokomotywy + //- WriteLog("A"); + } + else + { + Hamulec->SetED(0); + //- WriteLog("B"); + } +} + +// the current of the series motors connected, at the revolutions n and the voltage U, through the resistance R of +// Mn motors in series +double TMoverParameters::SeriesMotorCurrent(double const n, double const U, double const R, double const Mn) const +{ + double MotorCurrent{0.0}; + double Rz; + int SP = ScndCtrlActualPos; + + if (ScndCtrlActualPos < 255) // tak smiesznie bede wylaczal + { + if (ScndInMain && RList[MainCtrlActualPos].ScndAct != 255) + { + SP = RList[MainCtrlActualPos].ScndAct; + } + + Rz = Mn * WindingRes + R; + + if (DynamicBrakeFlag) // hamowanie + { + // if DynamicBrakeType<>dbrake_automatic then + // MotorCurrent:=-fi*n/Rz {hamowanie silnikiem na oporach rozruchowych} + /* begin + U:=0; + Isf:=Isat; + Delta:=SQR(Isf*Rz+Mn*fi*n-U)+4*U*Isf*Rz; + MotorCurrent:=(U-Isf*Rz-Mn*fi*n+SQRT(Delta))/(2*Rz) + end*/ + // only the ET42's switched brake brakes on the starting resistors, otherwise the current is cut off (0) + if (DynamicBrakeType == dbrake_switch && TrainType == dt_ET42) + { // z Megapacka + Rz = WindingRes + R; + MotorCurrent = -motor_param(SP).fi * n / Rz; //{hamowanie silnikiem na oporach rozruchowych} + } + } + else + { + MotorCurrent = SeriesMotorDrivingCurrent(n, U, Rz, Mn, SP); + } // else DBF + + } // 255 + else + MotorCurrent = 0; + return MotorCurrent; +} + +// the current of the series motors driving, at the revolutions n, the voltage U and the resistance Rz of Mn motors in +// series, by the motor parameters of the shunt field SP +double TMoverParameters::SeriesMotorDrivingCurrent(double const n, double const U, double const Rz, double const Mn, int const SP) const +{ + double MotorCurrent; + double Delta; + double Isf; + double U1; // napiecie z korekta + U1 = U + Mn * n * motor_param(SP).fi0 * motor_param(SP).fi; + // writepaslog("U1 ", FloatToStr(U1)); + // writepaslog("Isat ", FloatToStr(MotorParam[SP].Isat)); + // writepaslog("fi ", FloatToStr(MotorParam[SP].fi)); + Isf = Sign(U1) * motor_param(SP).Isat; + // writepaslog("Isf ", FloatToStr(Isf)); + Delta = square(Isf * Rz + Mn * motor_param(SP).fi * n - U1) + 4.0 * U1 * Isf * Rz; // 105 * 1.67 + Mn * 140.9 * 20.532 - U1 + // DeltaQ = Isf * Rz + Mn * MotorParam[SP].fi * n - U1 + 4 * U1 * Isf * Rz; + // writepaslog("Delta ", FloatToStr(Delta)); + // writepaslog("DeltaQ ", FloatToStr(DeltaQ)); + // writepaslog("U ", FloatToStr(U)); + if (MainCircuitPowered()) + { + if (U > 0) + MotorCurrent = (U1 - Isf * Rz - Mn * motor_param(SP).fi * n + std::sqrt(Delta)) / (2.0 * Rz); + else + MotorCurrent = (U1 - Isf * Rz - Mn * motor_param(SP).fi * n - std::sqrt(Delta)) / (2.0 * Rz); + } + else + MotorCurrent = 0; + return MotorCurrent; +} + +// the line breaker opened, and the motors damaged, by too high revolutions or current +void TMoverParameters::MotorFailuresCheck(double const n) +{ + double MotorCurrent; // awarie MotorCurrent = abs(Im); // zmienna pomocnicza @@ -481,8 +533,6 @@ double TMoverParameters::Current(double n, double U) EventFlag = true; /*! dorobic grzanie oporow rozruchowych i silnika*/ } - - return Im; } // ************************************************************************************************* @@ -918,55 +968,7 @@ void TMoverParameters::UpdatePantVolume(double dt) if (!PantCompFlag && PantVolume > 0.1) PantVolume -= dt * 0.0003 * std::max(1.0, PantPress * 0.5); // nieszczelności: 0.0003=0.3l/s - if (PantPress < EnginePowerSource.CollectorParameters.MinPress) - { - // 3.5 wg http://www.transportszynowy.pl/eu06-07pneumat.php - if (true == PantPressSwitchActive) - { - // opuszczenie pantografów przy niskim ciśnieniu - if (TrainType != dt_EZT) - { - // pressure switch safety measure -- open the line breaker, unless there's alternate source of traction voltage - if (GetTrainsetHighVoltage() < EnginePowerSource.CollectorParameters.MinV) - { - // TODO: check whether line breaker should be open EMU-wide - MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); - } - } - else - { - // specialized variant for EMU -- pwr system disables converter and heating, - // and prevents their activation until pressure switch is set again - PantPressLockActive = true; - // TODO: separate 'heating allowed' from actual heating flag, so we can disable it here without messing up heating toggle - ConverterSwitch(false, range_t::unit); - } - // mark the pressure switch as spent - PantPressSwitchActive = false; - } - } - else - { - if (PantPress >= 4.6) - { - // NOTE: we require active low power source to prime the pressure switch - // this is a work-around for potential isssues caused by the switch activating on otherwise idle vehicles, but should check whether it's accurate - if (true == Power24vIsAvailable || true == Power110vIsAvailable) - { - // prime the pressure switch - PantPressSwitchActive = true; - // turn off the subsystems lock - PantPressLockActive = false; - } - - if (PantPress >= 4.8) - { - // Winger - automatyczne wylaczanie malej sprezarki - // TODO: governor lock, disables usage until pressure drop below 3.8 (should really make compressor object we could reuse) - PantCompFlag = false; - } - } - } + PantPressureSwitchCheck(); } else { // a tu coś dla SM42 i SM31, aby pokazywać na manometrze @@ -974,80 +976,79 @@ void TMoverParameters::UpdatePantVolume(double dt) } }; +// the pantographs' pressure switch: low, it opens the line breaker (or locks the converter of a unit) once; +// primed again over 4.6 bar, where the pantographs' compressor stops at 4.8 +void TMoverParameters::PantPressureSwitchCheck() +{ + if (PantPress < EnginePowerSource.CollectorParameters.MinPress) + { + // 3.5 wg http://www.transportszynowy.pl/eu06-07pneumat.php + if (true == PantPressSwitchActive) + { + PantPressureSwitchTrip(); + } + } + else if (PantPress >= 4.6) + { + // NOTE: we require active low power source to prime the pressure switch + // this is a work-around for potential isssues caused by the switch activating on otherwise idle vehicles, but should check whether it's accurate + if (true == Power24vIsAvailable || true == Power110vIsAvailable) + { + // prime the pressure switch + PantPressSwitchActive = true; + // turn off the subsystems lock + PantPressLockActive = false; + } + + if (PantPress >= 4.8) + { + // Winger - automatyczne wylaczanie malej sprezarki + // TODO: governor lock, disables usage until pressure drop below 3.8 (should really make compressor object we could reuse) + PantCompFlag = false; + } + } +} + +// the pantographs' pressure switch tripped by the low pressure: the line breaker opened, unless the voltage comes from +// elsewhere, or the converter of a unit locked; spent until primed again +void TMoverParameters::PantPressureSwitchTrip() +{ + // opuszczenie pantografów przy niskim ciśnieniu + if (TrainType != dt_EZT) + { + // pressure switch safety measure -- open the line breaker, unless there's alternate source of traction voltage + // (the genset of a dual-mode vehicle, when the selector is on it, doesn't need the pantographs) + if (GetTrainsetHighVoltage() < EnginePowerSource.CollectorParameters.MinV && false == GensetSelected()) + { + // TODO: check whether line breaker should be open EMU-wide + MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); + } + } + else + { + // specialized variant for EMU -- pwr system disables converter and heating, + // and prevents their activation until pressure switch is set again + PantPressLockActive = true; + // TODO: separate 'heating allowed' from actual heating flag, so we can disable it here without messing up heating toggle + ConverterSwitch(false, range_t::unit); + } + // mark the pressure switch as spent + PantPressSwitchActive = false; +} + void TMoverParameters::UpdateBatteryVoltage(double dt) { // przeliczenie obciążenia baterii - double sn1 = 0.0; - double sn2 = 0.0; - double sn3 = 0.0; - double sn4 = 0.0; - double sn5 = 0.0; // Ra: zrobić z tego amperomierz NN - if (BatteryVoltage > 0 && EngineType != TEngineType::DieselEngine && EngineType != TEngineType::WheelsDriven && NominalBatteryVoltage > 0) + using enum TEngineType; + if (BatteryVoltage > 0 && EngineType != DieselEngine && EngineType != WheelsDriven && NominalBatteryVoltage > 0) { // HACK: allow to draw power also from adjacent converter, applicable for EMUs // TODO: expand power cables system to include low voltage power transfers // HACK: emulate low voltage generator powered directly by the diesel engine - auto const converteractive{Power110vIsAvailable || (EngineType == TEngineType::DieselElectric && true == Mains) || (EngineType == TEngineType::DieselEngine && true == Mains)}; + auto const converteractive{Power110vIsAvailable || (EngineType == DieselElectric && true == Mains) || (EngineType == DieselEngine && true == Mains)}; - if (NominalBatteryVoltage / BatteryVoltage < 1.22 && Battery) - { // 110V - if (!converteractive) - sn1 = dt * 2.0; // szybki spadek do ok 90V - else - sn1 = 0; - if (converteractive) - sn2 = -(dt * 2.0); // szybki wzrost do 110V - else - sn2 = 0; - if (Mains) - sn3 = dt * 0.05; - else - sn3 = 0; - if (iLights[0] & 63) // 64=blachy, nie ciągną prądu //rozpisać na poszczególne żarówki... - sn4 = dt * 0.003; - else - sn4 = 0; - if (iLights[1] & 63) // 64=blachy, nie ciągną prądu - sn5 = dt * 0.001; - else - sn5 = 0; - } - if (NominalBatteryVoltage / BatteryVoltage >= 1.22 && Battery) - { // 90V - if (PantCompFlag) - sn1 = dt * 0.0046; - else - sn1 = 0; - if (converteractive) - sn2 = -(dt * 50); // szybki wzrost do 110V - else - sn2 = 0; - if (Mains) - sn3 = dt * 0.001; - else - sn3 = 0; - if (iLights[0] & 63) // 64=blachy, nie ciągną prądu - sn4 = dt * 0.0030; - else - sn4 = 0; - if (iLights[1] & 63) // 64=blachy, nie ciągną prądu - sn5 = dt * 0.0010; - else - sn5 = 0; - } - if (!Battery) - { - if (NominalBatteryVoltage / BatteryVoltage < 1.22) - sn1 = dt * 50; - else - sn1 = 0; - sn2 = dt * 0.000001; - sn3 = dt * 0.000001; - sn4 = dt * 0.000001; - sn5 = dt * 0.000001; // bardzo powolny spadek przy wyłączonych bateriach - } - BatteryVoltage -= sn1 + sn2 + sn3 + sn4 + sn5; - if (NominalBatteryVoltage / BatteryVoltage > 1.57 && MainSwitch(false) && EngineType != TEngineType::DieselEngine && EngineType != TEngineType::WheelsDriven) + BatteryVoltage -= BatteryDrain(dt, converteractive); + if (NominalBatteryVoltage / BatteryVoltage > 1.57 && MainSwitch(false) && EngineType != DieselEngine && EngineType != WheelsDriven) EventFlag = true; // wywalanie szybkiego z powodu zbyt niskiego napiecia if (BatteryVoltage > NominalBatteryVoltage) BatteryVoltage = NominalBatteryVoltage; // wstrzymanie ładowania pow. 110V @@ -1061,6 +1062,105 @@ void TMoverParameters::UpdateBatteryVoltage(double dt) } }; +// the drop of the battery's voltage in dt, by what draws from it, or its rise by the converter charging it +double TMoverParameters::BatteryDrain(double dt, bool const converteractive) const +{ + if (NominalBatteryVoltage / BatteryVoltage < 1.22 && Battery) + { // 110V + return BatteryDrainCharged(dt, converteractive); + } + if (NominalBatteryVoltage / BatteryVoltage >= 1.22 && Battery) + { // 90V + return BatteryDrainLow(dt, converteractive); + } + if (!Battery) + { + return BatteryDrainSwitchedOff(dt); + } + return 0.0; +} + +// the drain of a battery at its voltage, the converter charging it +double TMoverParameters::BatteryDrainCharged(double dt, bool const converteractive) const +{ + double sn1; + double sn2; + double sn3; + double sn4; + double sn5; + if (!converteractive) + sn1 = dt * 2.0; // szybki spadek do ok 90V + else + sn1 = 0; + if (converteractive) + sn2 = -(dt * 2.0); // szybki wzrost do 110V + else + sn2 = 0; + if (Mains) + sn3 = dt * 0.05; + else + sn3 = 0; + if (iLights[0] & 63) // 64=blachy, nie ciągną prądu //rozpisać na poszczególne żarówki... + sn4 = dt * 0.003; + else + sn4 = 0; + if (iLights[1] & 63) // 64=blachy, nie ciągną prądu + sn5 = dt * 0.001; + else + sn5 = 0; + return sn1 + sn2 + sn3 + sn4 + sn5; +} + +// the drain of a battery run down to 90 V, the converter charging it +double TMoverParameters::BatteryDrainLow(double dt, bool const converteractive) const +{ + double sn1; + double sn2; + double sn3; + double sn4; + double sn5; + if (PantCompFlag) + sn1 = dt * 0.0046; + else + sn1 = 0; + if (converteractive) + sn2 = -(dt * 50); // szybki wzrost do 110V + else + sn2 = 0; + if (Mains) + sn3 = dt * 0.001; + else + sn3 = 0; + if (iLights[0] & 63) // 64=blachy, nie ciągną prądu + sn4 = dt * 0.0030; + else + sn4 = 0; + if (iLights[1] & 63) // 64=blachy, nie ciągną prądu + sn5 = dt * 0.0010; + else + sn5 = 0; + return sn1 + sn2 + sn3 + sn4 + sn5; +} + +// the drain of a battery switched off, very slow +double TMoverParameters::BatteryDrainSwitchedOff(double dt) const +{ + double sn1; + double sn2; + double sn3; + double sn4; + double sn5; + if (NominalBatteryVoltage / BatteryVoltage < 1.22) + sn1 = dt * 50; + else + sn1 = 0; + sn2 = dt * 0.000001; + sn3 = dt * 0.000001; + sn4 = dt * 0.000001; + sn5 = dt * 0.000001; // bardzo powolny spadek przy wyłączonych bateriach + return sn1 + sn2 + sn3 + sn4 + sn5; +} + /* Ukrotnienie EN57: 1 //układ szeregowy 2 //układ równoległy @@ -1339,6 +1439,19 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) auto const &othercoupler{othervehicle->Couplers[otherend]}; auto const physical{coupler_physics_at(End)}; + // physics.collisions new: past the buffers the ends of rail vehicles crush (collision.h); a hit the steel takes stays + // the legacy one, and so do the collisions of the road vehicles (the traffic of a scenery), with the legacy rule + auto const rails{TestFlag(CategoryFlag, 1) && TestFlag(othervehicle->CategoryFlag, 1)}; + auto const crushing{Global.collisions == global_settings::collision_model::physical && rails}; + if (crushing && (thiscoupler.hit_handled || crush_hit(End, dt))) + { + return; + } + // physics.collisions monitor: the legacy collision follows, the log tells what the crush would be + if (Global.collisions == global_settings::collision_model::monitor && rails) + { + crush_hit(End, dt); + } if (physical && false == coupler_stop_hit(End, *othervehicle, otherend)) { return; @@ -1374,7 +1487,8 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) } } - if (Global.crash_damage) + // the new model crushes the ends and derails the vehicles by the crush, see crush_hit() + if (Global.crash_damage && false == crushing) { // the physical model breaks the coupling and crushes the buffers by the force of the hit (coupler_stop_hit()) if (false == physical && -thiscoupler.Dist >= thiscoupler.DmaxB && FuzzyLogic(std::abs(CCF), 5.0 * (thiscoupler.FmaxC + 1.0), p_coupldmg)) @@ -1410,13 +1524,19 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) // integration of the next step (ComputeMovement()) would carry a quarter of an acceleration spike over into the // velocity once more, and the vehicles would bounce off the stop faster than they hit it auto const accelerationspike{physical ? 0.0 : 1.0}; - if (false == TestFlag(DamageFlag, dtrain_out)) + // derailed the legacy way a vehicle is a wall, off the rails by the new criteria it slides on and takes the hit. with + // the crush, the vehicles coupled to the wall push it on (crush_hit()) + auto const coupled{thiscoupler.CouplingFlag != coupling::faux}; + auto const wall = [crushing, coupled](TMoverParameters const &Vehicle) { + return TestFlag(Vehicle.DamageFlag, dtrain_out) && (false == crushing || (Vehicle.Derailed == derailment::outcome::none && false == coupled)); + }; + if (false == wall(*this)) { auto const accelerationchange{(velocity - V) / dt}; AccS += accelerationchange * accelerationspike; V = velocity; } - if (false == TestFlag(othervehicle->DamageFlag, dtrain_out)) + if (false == wall(*othervehicle)) { auto const othervehiclenewvelocity{othervehiclevelocity * otherdirection}; // back along the other vehicle's axis auto const othervehicleaccelerationchange{(othervehiclenewvelocity - othervehicle->V) / dt}; @@ -1466,16 +1586,414 @@ void TMoverParameters::damage_coupler(int const End) WriteLog("Bad driving: " + Name + " broke a coupler"); } +// ************************************************************************************************* +// physics.collisions new: the collisions past the buffers, see collision.h +// ************************************************************************************************* +collision::vehicle_kind TMoverParameters::collision_kind() const +{ + auto const powered{EngineType != TEngineType::None && EngineType != TEngineType::Dumb}; + auto const unit{(TrainType & (dt_EZT | dt_DMU)) != 0}; + auto const passengers{std::any_of(LoadAttributes.begin(), LoadAttributes.end(), [](auto const &Load) { return ToLower(Load.name).starts_with("passenger"); })}; + // a coach heats its compartments; the crash zone is a matter of each end (crush_of()) + return collision::kind_of(powered, unit || passengers || (false == powered && HeatingPower > 0.0), false); +} + +collision::crush_curve TMoverParameters::crush_curve_at(int const End) const +{ + return collision::crush_of(Couplers[End].collision, collision_kind()); +} + +double TMoverParameters::buffer_height_at(int const End) const +{ + auto const loadshare{MaxLoad > 0.f ? LoadAmount / MaxLoad : 0.0}; + return collision::buffer_height(Couplers[End].collision, collision_kind(), loadshare); +} + +void TMoverParameters::derail_in_collision(DerailReason const Reason, std::string const &Why) +{ + if (false == SetFlag(DamageFlag, dtrain_out)) + { + return; + } + // upright, it slides on the sleepers and keeps passing the forces on + Derailed = derailment::outcome::off_rails; + DerailCause = derail_motion::cause::collision; + DerailAcceleration = 0.0; + DerailSide = 0; + CollisionDerail = Reason; + EventFlag = true; + MainSwitch(false, range_t::local); + if (Vel < 5.0) + { + // HACK: prevent permanent axle spin in static vehicle after a collision + nrot = 0.0; + SlippingWheels = false; + } + // the brake hoses tear: the brake pipe vents and the rest of the train brakes in emergency + tear_brake_hoses(*this); + derailment_monitor.reset(); + pushed_off_monitor.reset(); + ErrorLog(std::format("Bad driving: {} derailed in a collision, {}: {}", Name, Reason == COLLISION_OVERRIDE ? "overriding" : "pushed off the track", Why)); +} + 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 +char const *end_name(int const End) +{ + return End == end::front ? "front" : "rear"; +} + +char const *kind_name(collision::vehicle_kind const Kind) +{ + switch (Kind) + { + case collision::vehicle_kind::locomotive: + return "locomotive"; + case collision::vehicle_kind::coach: + return "coach"; + case collision::vehicle_kind::crash_zone: + return "crash zone"; + case collision::vehicle_kind::wagon: + default: + return "wagon"; + } +} + +// the force pressing the end in, of the coupling or of the buffers touching [N]: forwards at the front pulls +double compression_at(TCoupling const &Coupler, int const End) +{ + return std::max(0.0, (End == end::front ? -1.0 : 1.0) * Coupler.CForce); +} + +// the steel parts of both ends in series [N/m] +double steel_stiffness(TCoupling const &First, TCoupling const &Second) +{ + auto const first{std::max(First.physics.link_stiffness, 1.0)}; + auto const second{std::max(Second.physics.link_stiffness, 1.0)}; + return first * second / (first + second); +} + +// the hit of the pair in the step, for the push off the track: the peak force and how long it acted +void record_hit(TCoupling &Coupler, double const Force, double const Duration) +{ + Coupler.hit_force = std::max(Coupler.hit_force, Force); + Coupler.hit_duration = std::max(Coupler.hit_duration, Duration); +} + +} // namespace + +bool TMoverParameters::crush_hit(int const End, double const dt) +{ + auto &thiscoupler{Couplers[End]}; + auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; + auto const otherend{Neighbours[End].vehicle_end}; + auto &othercoupler{othervehicle->Couplers[otherend]}; + + auto const physical{coupler_physics_at(End)}; + // the buffers pressed all the way, not the draw gear pulled all the way, and the pair still closing in + auto const buffers{physical ? thiscoupler.physics_state.stop < 0 : thiscoupler.Dist < 0.0}; + auto const closing{-CouplerVelocityDifference(End, *othervehicle, otherend) * DirF(End)}; + if (false == Global.crash_damage || false == buffers || closing <= 0.0) + { + // the hit is over, the next one is another one for the monitor + thiscoupler.crush_monitored = false; + othercoupler.crush_monitored = false; + return false; + } + auto const monitor{Global.collisions == global_settings::collision_model::monitor}; + // put down by the scenery inside each other: pressed past the stop of the buffers and the crush of the ends by more + // than a hit takes them in a step. the legacy collision pushes them apart; their springs, the stops at both ends + // and the neighbours found at either end there make up any closing velocity, not a hit + auto const stop{std::max(thiscoupler.DmaxB + othercoupler.DmaxB, thiscoupler.physics.buffers.travel + othercoupler.physics.buffers.travel) + thiscoupler.crush + othercoupler.crush}; + auto const overlap{-static_cast(Neighbours[End].distance)}; + if (overlap > stop + collision::inside_margin + closing * dt) + { + // nor is what their springs took in pressed past the stop and back a hit, for as long as the buffers touch + thiscoupler.contact.inside(); + othercoupler.contact.inside(); + if (false == thiscoupler.inside_reported) + { + thiscoupler.inside_reported = true; + othercoupler.inside_reported = true; + WriteLog(std::format("Bad scenery: {} and {} are inside each other, their buffers pressed {:.2f} m past their stop, no crush", Name, othervehicle->Name, overlap - stop)); + } + return false; + } + // parting at the start of the step: what closes the pair in now is the knock of a hit of either vehicle in the step, + // or of the vehicles inside each other next to it, not a hit of this pair. the legacy collision takes it; a pair + // still closing in at the start of the next step is a hit + if (thiscoupler.closing < 0.0) + { + return false; + } + // a vehicle derailed the legacy way (the end of the track, say) stays where it is, whatever hits it from outside its + // train. the vehicles coupled to it push it on, as the train behind a derailed vehicle does: a wall to them, it + // stopped the whole train at once, and the vehicles behind it crushed by the energy of the train + auto const coupled{thiscoupler.CouplingFlag != coupling::faux}; + auto const wall{false == coupled && TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none}; + auto const otherwall{false == coupled && TestFlag(othervehicle->DamageFlag, dtrain_out) && othervehicle->Derailed == derailment::outcome::none}; + if (wall && otherwall) + { + return false; + } + constexpr double immovable{1e12}; + auto const mass{wall ? immovable : TotalMass}; + auto const othermass{otherwall ? immovable : othervehicle->TotalMass}; + auto const loss{physical ? coupler_physics::solid_hit_loss(thiscoupler.physics, othercoupler.physics) : (thiscoupler.beta + othercoupler.beta) / 2.0}; + + auto const firstcurve{crush_curve_at(End)}; + auto const secondcurve{othervehicle->crush_curve_at(otherend)}; + auto const stiffness{steel_stiffness(thiscoupler, othercoupler)}; + auto const springs{compression_at(thiscoupler, End)}; + collision::hit_input input; + input.velocity = closing; + input.mass1 = mass; + input.mass2 = othermass; + input.restitution = std::sqrt(std::max(0.0, 1.0 - loss)); + input.stiffness = stiffness; + input.springs = springs; + // the monitor takes the whole hit at once, over a second, longer than the crush of any hit lasts + input.dt = monitor ? 1.0 : dt; + input.start_velocity = thiscoupler.closing; + // the crush takes only what the hit brings past what the buffers of EN 15551 of both ends take in. an automatic + // coupler (or its adapter) has no buffers at the side: its draft gear takes in what its springs of the .fiz do + auto const reduced{mass * othermass / (mass + othermass)}; + auto const central{thiscoupler.type() == TCouplerType::Automatic || othercoupler.type() == TCouplerType::Automatic || thiscoupler.has_adapter() || othercoupler.has_adapter()}; + auto const capacity{central ? 0.0 : collision::buffer_capacity(thiscoupler.collision, collision_kind()) + collision::buffer_capacity(othercoupler.collision, othervehicle->collision_kind())}; + auto const hitvelocity{std::max(closing, thiscoupler.closing)}; + input.budget = thiscoupler.contact.budget(reduced, hitvelocity, capacity); + auto const hit{collision::hit({firstcurve, thiscoupler.crush}, {secondcurve, othercoupler.crush}, input)}; + // the override, by the crush of both ends + auto const climbing_of = [&](double const Crush1, double const Crush2) { + collision::override_input climbing; + climbing.crush1 = Crush1; + climbing.crush2 = Crush2; + climbing.mass1 = TotalMass - Mred; + climbing.mass2 = othervehicle->TotalMass - othervehicle->Mred; + climbing.height1 = buffer_height_at(End); + climbing.height2 = othervehicle->buffer_height_at(otherend); + climbing.anticlimbers = collision::anticlimber_of(thiscoupler.collision, collision_kind()) && collision::anticlimber_of(othercoupler.collision, othervehicle->collision_kind()); + climbing.zone1 = firstcurve.densify; + climbing.zone2 = secondcurve.densify; + return climbing; + }; + if (monitor) + { + if (hit.crushing && false == thiscoupler.crush_monitored) + { + thiscoupler.crush_monitored = true; + othercoupler.crush_monitored = true; + ++crush_reports; + auto const crush1{thiscoupler.crush + hit.crush1}; + auto const crush2{othercoupler.crush + hit.crush2}; + auto const climbed{collision::override_of(climbing_of(crush1, crush2))}; + auto const torn{std::max(crush1, crush2) >= collision::draw_gear_crush}; + std::string const outcome{climbed.first && climbed.second ? std::string{"both would leave the rails"} + : climbed.first ? Name + " would ride up onto " + othervehicle->Name + : climbed.second ? othervehicle->Name + " would ride up onto " + Name + : std::string{"both would stay on the rails"}}; + WriteLog(std::format("collision monitor: {} and {} collided at {:.0f} km/h: the {} end of {} ({:.1f} t {}) would crush by {:.2f} m, the {} end of {} ({:.1f} t {}) by {:.2f} m, " + "at {:.0f} kN; draw gear {}; {}", + Name, othervehicle->Name, closing * 3.6, end_name(End), Name, TotalMass / 1000.0, kind_name(collision_kind()), crush1, end_name(otherend), othervehicle->Name, + othervehicle->TotalMass / 1000.0, kind_name(othervehicle->collision_kind()), crush2, hit.force / 1000.0, torn ? "torn off" : "holds", outcome)); + } + return false; + } + if (false == hit.crushing) + { + // the steel takes it, the legacy collision follows; its peak, under the force an end gives at, for the push + // off the track + auto const weaker{std::min(firstcurve.force(thiscoupler.crush), secondcurve.force(othercoupler.crush))}; + auto const peak{std::min(springs + coupler_physics::impact_force(closing, stiffness, mass, othermass), weaker)}; + auto const duration{std::min(dt, (1.0 + input.restitution) * std::sqrt(reduced / stiffness))}; + record_hit(thiscoupler, peak, duration); + record_hit(othercoupler, peak, duration); + return false; + } + // the other vehicle doesn't take it again in this step + thiscoupler.hit_handled = true; + othercoupler.hit_handled = true; + + // the hit at the force the weaker end gives at pushes the vehicles apart: the velocities alone change, along this + // vehicle's axis as in CollisionDetect() + auto const otherdirection{DirPatch(End, otherend)}; + auto const apart{End == end::front ? -1.0 : 1.0}; + if (false == wall) + { + V += apart * hit.impulse / mass; + } + if (false == otherwall) + { + othervehicle->V -= apart * hit.impulse / othermass * otherdirection; + } + record_hit(thiscoupler, hit.force, hit.duration); + record_hit(othercoupler, hit.force, hit.duration); + + // the energy the crush took, for both vehicles' count of the contact + thiscoupler.contact.crushed(hit.work); + othercoupler.contact.crushed(hit.work); + // what the log tells of the pair, for the analysis of a crush + auto const kinetic{0.5 * reduced * hitvelocity * hitvelocity}; + auto const pair = [&]() { + return std::format("{} {:.1f} t {}, {} end crushed {:.2f} m, gives at {:.0f} kN; {} {:.1f} t {}, {} end crushed {:.2f} m, gives at {:.0f} kN; force {:.0f} kN, springs {:.0f} kN, " + "closing at {:.1f} km/h at the start of the step; energy {:.0f} kJ of the motion and {:.0f} kJ in the buffers, past the {:.0f} kJ they take in, " + "{:.0f} kJ crushed in the contact", + Name, TotalMass / 1000.0, kind_name(collision_kind()), end_name(End), thiscoupler.crush, firstcurve.force(thiscoupler.crush) / 1000.0, othervehicle->Name, + othervehicle->TotalMass / 1000.0, kind_name(othervehicle->collision_kind()), end_name(otherend), othercoupler.crush, + secondcurve.force(othercoupler.crush) / 1000.0, hit.force / 1000.0, springs / 1000.0, input.start_velocity * 3.6, kinetic / 1000.0, + thiscoupler.contact.absorbed() / 1000.0, capacity / 1000.0, thiscoupler.contact.crush_work() / 1000.0); + }; + auto const crushed = [&](TMoverParameters const &Vehicle, int const VehicleEnd, double const Before, double const After) { + if (Before < collision::crush_mark && After >= collision::crush_mark) + { + ErrorLog(std::format("Bad driving: {} and {} collided at {:.0f} km/h, the {} end of {} crushed ({})", Name, othervehicle->Name, closing * 3.6, end_name(VehicleEnd), Vehicle.Name, pair())); + } + }; + auto const before{thiscoupler.crush}; + auto const otherbefore{othercoupler.crush}; + thiscoupler.crush += hit.crush1; + othercoupler.crush += hit.crush2; + crushed(*this, End, before, thiscoupler.crush); + crushed(*othervehicle, otherend, otherbefore, othercoupler.crush); + + // the crushed headstock tears off the draw gear, with the brake hose: both parts of the train brake in emergency. + // the coupler of an end not coupled is gone as well, it doesn't couple any more + if (thiscoupler.CouplingFlag != coupling::faux && std::max(thiscoupler.crush, othercoupler.crush) >= collision::draw_gear_crush) + { + auto const hose{(thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose}; + damage_coupler(End); + if (hose) + { + othervehicle->AlarmChainFlag = true; + } + } + else if (thiscoupler.CouplingFlag == coupling::faux) + { + if (thiscoupler.crush >= collision::draw_gear_crush && false == thiscoupler.broken) + { + damage_coupler(End); + } + if (othercoupler.crush >= collision::draw_gear_crush && false == othercoupler.broken) + { + othervehicle->damage_coupler(otherend); + } + } + + // the end crushed deep enough lets one vehicle climb onto the other one + auto const climbing{climbing_of(thiscoupler.crush, othercoupler.crush)}; + auto const climbed{collision::override_of(climbing)}; + auto const why = [&](TMoverParameters const &Climber, TMoverParameters const &Other) { + return std::format("{} rode up onto {} at {:.0f} km/h, the ends crushed by {:.2f} m, buffers at {:.0f} / {:.0f} mm, anticlimbers {} ({})", Climber.Name, Other.Name, closing * 3.6, + thiscoupler.crush + othercoupler.crush, climbing.height1 * 1000.0, climbing.height2 * 1000.0, climbing.anticlimbers ? "yes" : "no", pair()); + }; + if (climbed.first) + { + derail_in_collision(COLLISION_OVERRIDE, why(*this, *othervehicle)); + } + if (climbed.second) + { + othervehicle->derail_in_collision(COLLISION_OVERRIDE, why(*othervehicle, *this)); + } + return true; +} + +void TMoverParameters::check_pushed_off(double const dt, double const Distance) +{ + if (Global.collisions != global_settings::collision_model::physical || false == Global.crash_damage || TestFlag(DamageFlag, dtrain_out) || false == TestFlag(CategoryFlag, 1) || + DebugModeFlag) + { + pushed_off_monitor.reset(); + return; + } + collision::pushed_vehicle vehicle; + vehicle.mass = TotalMass - Mred; + vehicle.axles = NAxles > 0 ? NAxles : 4; + vehicle.length = Dim.L; + vehicle.pivots = BDist; + vehicle.axle_base = ADist > 0.0 ? ADist : BDist; + + auto climbs{false}; + auto distance{0.0}; + auto lifted{false}; + auto duration{0.0}; + auto worst{0.0}; + auto worstforce{0.0}; + auto worstend{static_cast(end::front)}; + for (int end = end::front; end <= end::rear; ++end) + { + auto const *other{Neighbours[end].vehicle}; + if (other == nullptr) + { + continue; + } + auto const &coupler{Couplers[end]}; + collision::pushed_end pushed; + pushed.other_length = other->MoverParameters->Dim.L; + pushed.crush = coupler.crush; + // the steady push of the springs over the step, or the peak of a hit for as long as it lasted: the flange climbs + // over the distance the wheels rolled meanwhile, a wheel lifted off the rail goes in a short time, rolling or not + for (auto const &[force, time] : {std::pair{compression_at(coupler, end), dt}, std::pair{coupler.hit_force, coupler.hit_duration}}) + { + pushed.force = force; + auto const wheel{collision::pushed_forces(vehicle, pushed, RunningShape.R)}; + auto const ratio{wheel.ratio()}; + if (ratio < derailment::climbing_limit) + { + continue; + } + climbs = true; + distance = std::max(distance, Distance * std::clamp(time / std::max(dt, 1e-9), 0.0, 1.0)); + if (wheel.lifted()) + { + lifted = true; + duration = std::max(duration, time); + } + if (ratio > worst) + { + worst = ratio; + worstforce = force; + worstend = end; + } + } + } + if (pushed_off_monitor.update(climbs, distance, lifted, duration)) + { + derail_in_collision(COLLISION_PUSHED_OFF, std::format("{:.0f} kN pressing its {} end in, {}, at {:.0f} km/h, curve radius {:.0f} m: Y/Q {:.2f} ({:.1f} t {}, {} axles, " + "springs {:.0f} / {:.0f} kN, hits {:.0f} / {:.0f} kN, crushed {:.2f} / {:.2f} m)", + worstforce / 1000.0, end_name(worstend), + lifted ? std::format("its wheels lifted off the rail for {:.3f} s", pushed_off_monitor.time()) + : std::format("the flange climbing over {:.2f} m", pushed_off_monitor.distance()), + Vel, std::abs(RunningShape.R), std::min(worst, 99.0), + vehicle.mass / 1000.0, kind_name(collision_kind()), vehicle.axles, compression_at(Couplers[end::front], end::front) / 1000.0, + compression_at(Couplers[end::rear], end::rear) / 1000.0, Couplers[end::front].hit_force / 1000.0, Couplers[end::rear].hit_force / 1000.0, + Couplers[end::front].crush, Couplers[end::rear].crush)); + } +} + +namespace +{ + +// the end as it was built (physics.collisions new): not crushed, and nothing of a contact or a hit kept +void restore_end(TCoupling &Coupler) +{ + Coupler.crush = 0.0; + Coupler.contact.reset(); + Coupler.hit_handled = false; + Coupler.hit_force = 0.0; + Coupler.hit_duration = 0.0; + Coupler.crush_monitored = false; + Coupler.inside_reported = false; +} + +// the coupler as good as new, its end with it (the crush that tore the draw gear off), the vehicle without the coupler +// damage (and the emergency braking of the torn brake hose) once neither of its couplers is broken void repair(TMoverParameters &Vehicle, TCoupling &Coupler) { Coupler.broken = false; Coupler.stretch_duration = 0.f; Coupler.physics_state.couple(); + restore_end(Coupler); if (Vehicle.Couplers[end::front].broken || Vehicle.Couplers[end::rear].broken) { return; @@ -1504,6 +2022,132 @@ bool TMoverParameters::repair_coupler(int const End) return true; } +static_assert(derailment::track_damage::railwear == dtrack_railwear && derailment::track_damage::freerail == dtrack_freerail && derailment::track_damage::thinrail == dtrack_thinrail && + derailment::track_damage::railbend == dtrack_railbend); + +double TMoverParameters::centre_of_gravity() const +{ + auto const kind{EngineType == TEngineType::None ? derailment::vehicle_class::unpowered : derailment::vehicle_class::powered}; + auto const empty{CentreOfGravity > 0.0 ? CentreOfGravity : derailment::default_centre_of_gravity(Dim.H, kind)}; + auto const loadmass{TotalMass - Mass - Mred}; + auto const loadshare{MaxLoad > 0.f ? LoadAmount / MaxLoad : 1.0}; + return derailment::loaded_centre_of_gravity(empty, Mass, loadmass, loadshare, Floor, Dim.H); +} + +void TMoverParameters::check_derailment(TTrackShape const &Shape, TTrackParam const &Track, double const Distance) +{ + if (TestFlag(DamageFlag, dtrain_out) || false == TestFlag(CategoryFlag, 1) || DebugModeFlag) + { + derailment_monitor.reset(); + return; + } + derailment::vehicle_state vehicle; + vehicle.mass = TotalMass - Mred; + vehicle.axles = NAxles > 0 ? NAxles : 4; + vehicle.length = Dim.L; + vehicle.axle_base = ADist > 0.0 ? ADist : BDist; + vehicle.centre_of_gravity = centre_of_gravity(); + for (int end = end::front; end <= end::rear; ++end) + { + auto const *other{Neighbours[end].vehicle}; + if (other == nullptr) + { + continue; + } + // the force of the coupling, or of the buffers touching, along this vehicle: forwards at the front pulls + vehicle.ends[end].compression = (end == end::front ? -1.0 : 1.0) * Couplers[end].CForce; + vehicle.ends[end].other_length = other->MoverParameters->Dim.L; + } + derailment::track_state track; + track.radius = Shape.R; + track.cant = Shape.dHrail; + track.gauge = TrackW; + track.uneven_curvature = Shape.uneven_curvature; + track.uneven_cross = Shape.uneven_cross; + track.buckle_curvature = Shape.buckle_curvature; + track.damage = Track.DamageFlag; + + auto const verdict{derailment_monitor.update(vehicle, track, V, Distance)}; + if (verdict.result == derailment::outcome::none) + { + return; + } + if (Global.derailment == global_settings::derailment_model::physical) + { + derail(verdict, vehicle, track, Track.Name); + return; + } + // physics.derailment monitor: the legacy draw decides, the log tells what the criteria would do, once on a track + if (derailment_reported.has_value() && *derailment_reported == Track.Name) + { + return; + } + derailment_reported = Track.Name; + ++derailment_reports; + WriteLog("derailment monitor: " + Name + " " + derailment::report(verdict, vehicle, track, V, Track.Name != nullptr ? *Track.Name : std::string{})); +} + +void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track, std::string const *TrackName) +{ + if (false == SetFlag(DamageFlag, dtrain_out)) + { + return; + } + Derailed = Verdict.result; + DerailCause = Verdict.result == derailment::outcome::overturned ? derail_motion::cause::overturned : derail_motion::cause::off_rails; + // out of the curve; a buckle bending the line against the curve more than the curve does throws it into the curve + DerailAcceleration = std::abs(Track.radius) > 1e-3 && derailment::line_curvature(Track) < 0.0 ? -Verdict.acceleration : Verdict.acceleration; + DerailSide = 0; + EventFlag = true; + MainSwitch(false, range_t::local); + // the brake hoses tear: the brake pipe vents and the rest of the train brakes in emergency + tear_brake_hoses(*this); + ErrorLog("Bad driving: " + Name + " " + derailment::report(Verdict, Vehicle, Track, V, TrackName != nullptr ? *TrackName : std::string{})); + if (Track.buckle_curvature != 0.0) + { + ErrorLog(std::format("Bad driving: {} derailed on buckled track, the buckle bending the line by 1/{:.0f} m {} the curve", Name, 1.0 / std::abs(Track.buckle_curvature), + Track.buckle_curvature > 0.0 ? "with" : "against")); + } +} + +void TMoverParameters::rerail() +{ + ClearFlag(DamageFlag, dtrain_out); + Derailed = derailment::outcome::none; + // and back on the track; what derailed it before has no say in how it leaves the track the next time + OffTrack.reset(); + DerailCause = derail_motion::cause::off_rails; + DerailAcceleration = 0.0; + DerailSide = 0; + derailment_monitor.reset(); + derailment_distance = 0.0; + derailment_reported.reset(); + // nor derailed in a collision + CollisionDerail = NONE; + pushed_off_monitor.reset(); + // back on the axis of the track, which the derailment shifted the vehicle off aside and down (a road vehicle keeps + // its place on the road) + if (TestFlag(CategoryFlag, 1)) + { + OffsetTrackH = 0.0; + OffsetTrackV = 0.0; + } +} + +void TMoverParameters::repair_damage() +{ + DamageFlag = 0; + EngDmgFlag = 0; + WheelFlat = 0.0; + AlarmChainFlag = false; + // the crushed ends rebuilt + for (auto &coupler : Couplers) + { + restore_end(coupler); + } + rerail(); +} + void TMoverParameters::Derail(DerailReason const Reason) { if (SetFlag(DamageFlag, dtrain_out)) @@ -1511,8 +2155,16 @@ void TMoverParameters::Derail(DerailReason const Reason) EventFlag = true; MainSwitch(false, range_t::local); + auto const velocity{V}; AccS *= 0.65; V *= 0.65; + // physics.collisions new: the vehicles coupled to it lose the speed with it. the cut in a step stands for the + // train coming to a stop with the vehicle; the coupled ones keeping their speed would run into it at a third of + // the speed of the train, and crush their ends and ride up onto it for a hit no train had + if (Global.collisions == global_settings::collision_model::physical && TestFlag(CategoryFlag, 1)) + { + change_train_velocity(V - velocity); + } RunningShape.R = 0; if (Vel < 5.0) { @@ -1520,6 +2172,16 @@ void TMoverParameters::Derail(DerailReason const Reason) nrot = 0.0; SlippingWheels = false; } + // physics.derailment new: off the end of the track the vehicle runs on straight on its wheels, sliding on the + // ground as the vehicles the criteria derail do, and its brake hoses tear + if (Reason == END_OF_TRACK && Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1)) + { + Derailed = derailment::outcome::off_rails; + DerailCause = derail_motion::cause::end_of_track; + DerailAcceleration = 0.0; + DerailSide = 0; + tear_brake_hoses(*this); + } // Print a message in the log. if (Reason == END_OF_TRACK) @@ -1537,6 +2199,52 @@ void TMoverParameters::Derail(DerailReason const Reason) } } +bool TMoverParameters::leaves_track() const +{ + return Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1) && TestFlag(DamageFlag, dtrain_out) && Derailed != derailment::outcome::none && + false == OffTrack.active(); +} + +void TMoverParameters::pull_off(int const Side, double const Acceleration, std::string const &Why) +{ + if (Global.derailment != global_settings::derailment_model::physical || false == SetFlag(DamageFlag, dtrain_out)) + { + return; + } + // upright, its flange climbs the rail the coupling pulls it over + Derailed = derailment::outcome::off_rails; + DerailCause = derail_motion::cause::pulled_off; + DerailAcceleration = Acceleration; + DerailSide = Side; + EventFlag = true; + MainSwitch(false, range_t::local); + tear_brake_hoses(*this); + derailment_monitor.reset(); + ErrorLog(std::format("Bad driving: {} pulled off the track by the vehicle coupled to it, {}", Name, Why)); +} + +void TMoverParameters::change_train_velocity(double const Change) +{ + // the vehicles coupled to this one in a line, each with the direction of its axis to the axis of this one + std::vector> train{{this, 1}}; + for (std::size_t i = 0; i < train.size(); ++i) + { + auto const [vehicle, direction] = train[i]; + for (int end = end::front; end <= end::rear; ++end) + { + auto const &coupler{vehicle->Couplers[end]}; + auto *other{coupler.Connected}; + if (other == nullptr || coupler.CouplingFlag == coupling::faux || std::any_of(train.begin(), train.end(), [other](auto const &Entry) { return Entry.first == other; })) + { + continue; + } + auto const otherdirection{direction * DirPatch(end, coupler.ConnectedNr)}; + other->V += Change * otherdirection; + train.emplace_back(other, otherdirection); + } + } +} + // ************************************************************************************************* // Oblicza przemieszczenie taboru // ************************************************************************************************* @@ -1559,6 +2267,11 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap // abs(ElectricTraction.TractionResistivity * Itot * // 0)*/; // zasadniczo ED oporowe nie zmienia napięcia w sieci } + else if (OffTrack.active()) + { + // off the track the grade is that of the ground under it, along its heading + RunningShape.dHtrack = Shape.dHtrack; + } if (CategoryFlag == 4) OffsetTrackV = TotalMass / (Dim.L * Dim.W * 1000.0); @@ -1579,8 +2292,14 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap AccS = std::lerp(AccSprev, FTotal / TotalMass, 0.5); // std::clamp( dt * 3.0, 0.0, 1.0 ) ); // prawo Newtona ale z wygladzaniem (średnia z poprzednim) - if (TestFlag(DamageFlag, dtrain_out)) + // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce(), and so does one + // derailed the legacy way with physics.collisions new + if (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this)) AccS = -Sign(V) * g * 1; // random(0.0, 0.1) + // stuck in the ballast: the friction holds a derailed vehicle once it stopped, until the forces on it are larger + auto const stuck{(Derailed != derailment::outcome::none || legacy_derailed_slides(*this)) && V == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; + if (stuck) + AccS = 0.0; // przyspieszenie normalne if (abs(Shape.R) > 0.01) @@ -1591,6 +2310,8 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap // velocity change auto const Vprev{V}; V += (3.0 * AccS - AccSprev) * dt / 2.0; // przyrost predkosci + if (stuck) + V = 0.0; if (V * Vprev <= 0 && std::abs(FStand) > std::abs(FTrain)) { // tlumienie predkosci przy hamowaniu @@ -1622,7 +2343,9 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap { if (TestFlag(Track.DamageFlag, dtrack_norail)) Derail(END_OF_TRACK); - if (FuzzyLogic(AccN / g * (1.0 + 0.1 * (Track.DamageFlag & dtrack_freerail)), TrackW / Dim.H, 1)) + // too fast in a curve: the legacy draw in every step (physics.derailment old), or the physical criteria + // once the step's distance is known, below + if ((Global.derailment == global_settings::derailment_model::old || Global.derailment == global_settings::derailment_model::monitor) && FuzzyLogic(AccN / g * (1.0 + 0.1 * (Track.DamageFlag & dtrack_freerail)), TrackW / Dim.H, 1)) Derail(TOO_HIGH_SPEED); // wykolejanie na poszerzeniu toru if (FuzzyLogic(abs(Track.Width - TrackW), TrackW / 10.0, 1)) @@ -1635,10 +2358,17 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap // dL:=(V+AccS*dt/2)*dt; // przyrost dlugosci czyli przesuniecie dL = (3.0 * V - Vprev) * dt / 2.0; // metoda Adamsa-Bashfortha} + if (Global.derailment == global_settings::derailment_model::physical || Global.derailment == global_settings::derailment_model::monitor) + { + // over the distance of this step and of the simpler ones of the frame before it + check_derailment(Shape, Track, derailment_distance + std::abs(dL)); + } + derailment_distance = 0.0; // ale jesli jest kolizja (zas. zach. pedu) to...} for (int b = 0; b < 2; b++) if (Couplers[b].CheckCollision) CollisionDetect(b, dt); // zmienia niejawnie AccS, V !!! + check_pushed_off(dt, std::abs(dL)); } // liczone dL, predkosc i przyspieszenie @@ -1676,14 +2406,19 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh AccS = std::lerp(AccSprev, FTotal / TotalMass, 0.5); // std::clamp( dt * 3.0, 0.0, 1.0 ) ); // prawo Newtona ale z wygladzaniem (średnia z poprzednim) - if (TestFlag(DamageFlag, dtrain_out)) + if (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this)) AccS = -Sign(V) * g * 1; // * random(0.0, 0.1) + auto const stuck{(Derailed != derailment::outcome::none || legacy_derailed_slides(*this)) && V == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; + if (stuck) + AccS = 0.0; // simple mode skips calculation of normal acceleration // velocity change auto const Vprev{V}; V += (3.0 * AccS - AccSprev) * dt / 2.0; // przyrost predkosci + if (stuck) + V = 0.0; if (V * Vprev <= 0 && std::abs(FStand) > std::abs(FTrain)) { // tlumienie predkosci przy hamowaniu @@ -1696,17 +2431,22 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh // simple mode skips calculation of vertical acceleration AccVert = 0.0; - if (true == TestFlag(DamageFlag, dtrain_out) && Vel < 1.0) + // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce(), and so does one + // derailed the legacy way with physics.collisions new + if (true == TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this) && Vel < 1.0) { V = 0.0; AccS = 0.0; } dL = (3.0 * V - Vprev) * dt / 2.0; // metoda Adamsa-Bashfortha + // the criteria of derailment go by the distance, checked in the full step which ends the frame + derailment_distance += std::abs(dL); // ale jesli jest kolizja (zas. zach. pedu) to... for (int b = 0; b < 2; b++) if (Couplers[b].CheckCollision) CollisionDetect(b, dt); // zmienia niejawnie AccS, V !!! + check_pushed_off(dt, std::abs(dL)); } // liczone dL, predkosc i przyspieszenie auto const d{(EngineType == TEngineType::WheelsDriven ? dL * CabActive : // na chwile dla testu @@ -1789,6 +2529,7 @@ void TMoverParameters::compute_movement_(double const Deltatime) LowVoltagePowerCheck(Deltatime); // power sources PantographsCheck(Deltatime); + GensetCheck(Deltatime); // main circuit MainsCheck(Deltatime); // traction motors @@ -1875,6 +2616,11 @@ void TMoverParameters::MainsCheck(double const Deltatime) break; } } + if (GensetSelected()) + { + // the traction selector of a dual-mode vehicle on the genset isolates the pantographs + localvoltage = Genset.voltage; + } // a line breaker closed ahead of the pantographs gets ready on the low voltage circuits auto const maincircuitpowersupply{std::abs(localvoltage) > 0.1 || GetTrainsetHighVoltage() > 0.1 || (PantographsRequireMains && (Power24vIsAvailable || Power110vIsAvailable))}; @@ -1901,6 +2647,12 @@ void TMoverParameters::MainsCheck(double const Deltatime) // no power supply MainsInitTimeCountdown = MainsInitTime; } + + // an emergency brake application made under power opens the line breaker, where the vehicle has such an interlock + if (Mains && EmergencyBrakeHoldsMainOff()) + { + MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); + } } void TMoverParameters::LowVoltagePowerCheck(double const /*Deltatime*/) @@ -1928,10 +2680,41 @@ void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling c return; } + auto const localvoltage{LocalPowerVoltage(Coupling)}; + + auto const abslocalvoltage{std::abs(localvoltage)}; + auto const localpowersource{(abslocalvoltage > 1.0)}; + + // przekazywanie napiec + PowerCouplersVoltage(Coupling, abslocalvoltage, localpowersource); + + // przekazywanie pradow + PowerCouplersCurrent(Coupling, localpowersource); +} + +// the current the vehicle draws from the circuit of the power coupling given +double *TMoverParameters::PowerCircuitCurrent(coupling const Coupling) +{ + switch (Coupling) + { + case coupling::highvoltage: + return &TotalCurrent; + case coupling::power110v: + return &PowerCircuits[1].second; + case coupling::power24v: + return &PowerCircuits[0].second; + default: + return nullptr; + } +} + +// the voltage of the vehicle's own source for the coupling given; notes the low voltage circuits' too +double TMoverParameters::LocalPowerVoltage(coupling const Coupling) +{ auto localvoltage{0.0}; // local power sources - // TODO: make local voltage calculations a separate method, store results in PowerCircuit fields + // the results could be kept in the PowerCircuit fields switch (Coupling) { @@ -1955,7 +2738,8 @@ void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling c case TPowerSource::Main: { // HACK: main circuit can be fed through couplers, so we explicitly check pantograph supply here - localvoltage = MainCircuitPowered() ? PantographVoltage : 0.0; + // (or the genset's, where the traction selector of a dual-mode vehicle is on it) + localvoltage = MainCircuitPowered() ? TractionSourceVoltage() : 0.0; break; } default: @@ -1964,10 +2748,10 @@ void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling c } } } - // high voltage power sources + // high voltage power sources: the pantographs, or the genset of a dual-mode vehicle, by its traction selector if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector) { - localvoltage = std::max(localvoltage, PantographVoltage); + localvoltage = std::max(localvoltage, TractionSourceVoltage()); } break; } @@ -2000,10 +2784,17 @@ void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling c } } - auto const abslocalvoltage{std::abs(localvoltage)}; - auto const localpowersource{(abslocalvoltage > 1.0)}; + return localvoltage; +} - // przekazywanie napiec +// the voltage passed through the vehicle to the coupler at its other end, from the coupled vehicle or its own source +void TMoverParameters::PowerCouplersVoltage(coupling const Coupling, double const abslocalvoltage, bool const localpowersource) +{ + if (Couplers[end::front].power(Coupling) == nullptr) + { + // not a power coupling, there's no voltage to pass + return; + } for (auto side = 0; side < 2; ++side) { @@ -2047,14 +2838,8 @@ void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling c } } - auto const *coupling = Coupling == coupling::highvoltage ? &thiscoupler.power_high : - Coupling == coupling::power110v ? &thiscoupler.power_110v : - Coupling == coupling::power24v ? &thiscoupler.power_24v : - nullptr; - auto *oppositecoupling = Coupling == coupling::highvoltage ? &oppositecoupler.power_high : - Coupling == coupling::power110v ? &oppositecoupler.power_110v : - Coupling == coupling::power24v ? &oppositecoupler.power_24v : - nullptr; + auto const *coupling = thiscoupler.power(Coupling); + auto *oppositecoupling = oppositecoupler.power(Coupling); // start with base voltage oppositecoupling->voltage = abslocalvoltage; @@ -2064,10 +2849,7 @@ void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling c if (thiscoupler.Connected != nullptr) { auto const &connectedcoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr]}; - auto const *connectedcoupling = Coupling == coupling::highvoltage ? &connectedcoupler.power_high : - Coupling == coupling::power110v ? &connectedcoupler.power_110v : - Coupling == coupling::power24v ? &connectedcoupler.power_24v : - nullptr; + auto const *connectedcoupling = connectedcoupler.power(Coupling); auto const connectedvoltage{(connectedcoupling->is_live ? connectedcoupling->voltage : 0.0)}; oppositecoupling->voltage = std::max(oppositecoupling->voltage, connectedvoltage - coupling->current * 0.02); oppositecoupling->is_live = connectedvoltage > 0.1 && oppositecouplingispresent; @@ -2079,43 +2861,24 @@ void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling c oppositecoupling->is_live |= abslocalvoltage > 0.1 && localpowerexportisenabled; } } +} - // przekazywanie pradow - auto couplervoltage{0}; - switch (Coupling) +// the current drawn through the couplers, shared by their voltages, or added to the vehicle's own +void TMoverParameters::PowerCouplersCurrent(coupling const Coupling, bool const localpowersource) +{ + auto const *frontcoupling{Couplers[end::front].power(Coupling)}; + auto const *rearcoupling{Couplers[end::rear].power(Coupling)}; + auto *totalcurrent{PowerCircuitCurrent(Coupling)}; + if (frontcoupling == nullptr || rearcoupling == nullptr || totalcurrent == nullptr) { - case coupling::highvoltage: - { - couplervoltage = static_cast(Couplers[end::front].power_high.voltage + Couplers[end::rear].power_high.voltage); - break; + // not a power coupling, there's no current to share + return; } - case coupling::power110v: - { - couplervoltage = static_cast(Couplers[end::front].power_110v.voltage + Couplers[end::rear].power_110v.voltage); - break; - } - case coupling::power24v: - { - couplervoltage = static_cast(Couplers[end::front].power_24v.voltage + Couplers[end::rear].power_24v.voltage); - break; - } - default: - { - break; - } - } - - auto *totalcurrent = Coupling == coupling::highvoltage ? &TotalCurrent : - Coupling == coupling::power110v ? &PowerCircuits[1].second : - Coupling == coupling::power24v ? &PowerCircuits[0].second : - nullptr; + auto const couplervoltage{static_cast(frontcoupling->voltage + rearcoupling->voltage)}; for (auto &thiscoupler : Couplers) { - auto *coupling = Coupling == coupling::highvoltage ? &thiscoupler.power_high : - Coupling == coupling::power110v ? &thiscoupler.power_110v : - Coupling == coupling::power24v ? &thiscoupler.power_24v : - nullptr; + auto *coupling = thiscoupler.power(Coupling); coupling->current = 0.0; @@ -2125,10 +2888,7 @@ void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling c } auto const &connectedothercoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr == end::front ? end::rear : end::front]}; - auto const *connectedothercoupling = Coupling == coupling::highvoltage ? &connectedothercoupler.power_high : - Coupling == coupling::power110v ? &connectedothercoupler.power_110v : - Coupling == coupling::power24v ? &connectedothercoupler.power_24v : - nullptr; + auto const *connectedothercoupling = connectedothercoupler.power(Coupling); auto const extracurrent = Coupling == coupling::highvoltage ? std::abs(Itot) * IsVehicleEIMBrakingFactor() : 0.0; if (false == localpowersource) @@ -2298,7 +3058,7 @@ void TMoverParameters::HeatingCheck(double const /*Timestep*/) } case TPowerSource::Main: { - voltage = MainCircuitPowered() ? std::max(GetTrainsetHighVoltage(), PantographVoltage) : 0.0; + voltage = MainCircuitPowered() ? TractionSupplyVoltage() : 0.0; break; } default: @@ -2490,6 +3250,63 @@ void TMoverParameters::PantographsCheck(double const /*Timestep*/) } } +// the genset of a dual-mode vehicle: started on request with the battery on, it cranks for start_time, then runs at +// idle and up to full revolutions with the traction demand; stopped, it coasts down. regulated voltage from idle up +void TMoverParameters::GensetCheck(double const Deltatime) +{ + if (false == Genset.fitted()) + { + return; + } + auto &genset{Genset}; + auto const wasactive{genset.is_active}; + auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; + auto const requested{lowvoltagepower && false == genset.is_disabled && (genset.start_type == start_t::automatic ? GensetSelected() : genset.is_enabled)}; + if (false == requested) + { + genset.is_active = false; + genset.is_cranking = false; + genset.timer = 0.0; + } + else if (false == genset.is_active) + { + genset.is_cranking = true; + genset.timer += Deltatime; + if (genset.timer >= genset.start_time) + { + genset.is_cranking = false; + genset.is_active = true; + } + } + // revolutions: the start brings them up to idle in start_time; running they follow the traction demand, stopped + // they coast down to 0, both with the time constant spinup_time + if (genset.is_cranking) + { + genset.revolutions = std::max(genset.revolutions, genset.revolutions_idle * std::min(1.0, genset.timer / std::max(genset.start_time, 0.01))); + } + else if (genset.is_active && false == wasactive) + { + genset.revolutions = std::max(genset.revolutions, genset.revolutions_idle); + } + else + { + auto const demand{GensetSelected() && Mains ? std::clamp(eimv_pr, 0.0, 1.0) : 0.0}; + auto const target{genset.is_active ? genset.revolutions_idle + (genset.revolutions_max - genset.revolutions_idle) * demand : 0.0}; + genset.revolutions += (target - genset.revolutions) * std::min(1.0, Deltatime / genset.spinup_time); + if (genset.revolutions < 0.001) + { + genset.revolutions = 0.0; + } + } + // no excitation while cranking; running or coasting down, regulated from idle up, proportional below it + genset.voltage = genset.is_cranking ? 0.0 : genset.voltage_nominal * std::clamp(genset.revolutions / genset.revolutions_idle, 0.0, 1.0); + + if (genset.is_active != wasactive) + { + WriteLog("Genset of " + Name + (genset.is_active ? ": running" : ": stopped")); + } +} + void TMoverParameters::LightsCheck(double const /*Timestep*/) { @@ -2562,114 +3379,7 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) bool OK = false; if (MainCtrlPos < MainCtrlPosNo) { - switch (EngineType) - { - case TEngineType::None: - case TEngineType::Dumb: - case TEngineType::DieselElectric: - case TEngineType::ElectricInductionMotor: - { - if (CtrlSpeed > 1) - { - OK = IncMainCtrl(1) && IncMainCtrl(CtrlSpeed - 1); // a fail will propagate up the recursion chain. should this be || instead? - break; - } - ++MainCtrlPos; - OK = true; - if (EIMCtrlType == 0 && ( SpeedCtrlAutoTurnOffFlag & 1 ) == 1 && MainCtrlActualPos != MainCtrlPos) - { - DecScndCtrl(2); - SpeedCtrlUnit.IsActive = false; - } - break; - } - - case TEngineType::ElectricSeriesMotor: - { - if (DirActive == 0) - { - return false; - } - - if (CtrlSpeed > 1) - { - // szybkie przejœcie na bezoporow¹ - if (TrainType == dt_ET40) - { - break; // this means ET40 won't react at all to fast acceleration command. should it issue just IncMainCtrl(1) instead? - } - while (RList[MainCtrlPos].R > 0.0 && IncMainCtrl(1)) - { - // all work is done in the loop header - } - OK = false; // shouldn't this be part of the loop above? - // if (TrainType=dt_ET40) then - // while Abs (Im)>IminHi do - // dec(MainCtrlPos); - // OK:=false ; - } - else - { // CtrlSpeed == 1 - ++MainCtrlPos; - OK = true; - if (Imax == ImaxHi && RList[MainCtrlPos].Bn > 1) - { - /* NOTE: disabled, relay configuration was moved to compute_movement_ - if( true == MaxCurrentSwitch( false )) { - // wylaczanie wysokiego rozruchu - SetFlag( SoundFlag, sound::relay ); - } - */ - if (TrainType == dt_ET42) - { - --MainCtrlPos; - OK = false; - } - } - // - // if (TrainType == "et40") - // if (Abs(Im) > IminHi) - // { - // MainCtrlPos--; //Blokada nastawnika po przekroczeniu minimalnego pradu - // OK = false; - // } - //} - } - - if (TrainType == dt_ET42 && true == DynamicBrakeFlag && MainCtrlPos > 20) - { - MainCtrlPos = 20; - OK = false; - } - break; - } - - case TEngineType::DieselEngine: - { - if (CtrlSpeed > 1) - { - while (MainCtrlPos < MainCtrlPosNo && IncMainCtrl(1)) - { - // all work is done in the loop header - } - } - else - { - ++MainCtrlPos; - } - CompressorAllow = MainCtrlPowerPos() > 0; - OK = true; - break; - } - - case TEngineType::WheelsDriven: - { - OK = AddPulseForce(CtrlSpeed); - break; - } - default: - break; - } // switch EngineType of + OK = IncMainCtrlByEngine(CtrlSpeed); } else { // MainCtrlPos>=MainCtrlPosNo @@ -2713,6 +3423,130 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) return OK; } +// a notch up, as the kind of the engine takes it; returns whether the controller moved +bool TMoverParameters::IncMainCtrlByEngine(int const CtrlSpeed) +{ + bool OK = false; + switch (EngineType) + { + case TEngineType::None: + case TEngineType::Dumb: + case TEngineType::DieselElectric: + case TEngineType::ElectricInductionMotor: + { + if (CtrlSpeed > 1) + { + OK = IncMainCtrl(1) && IncMainCtrl(CtrlSpeed - 1); // a fail will propagate up the recursion chain. should this be || instead? + break; + } + ++MainCtrlPos; + OK = true; + if (EIMCtrlType == 0 && ( SpeedCtrlAutoTurnOffFlag & 1 ) == 1 && MainCtrlActualPos != MainCtrlPos) + { + SpeedCtrlSwitch(false); + SpeedCtrlUnit.IsActive = false; + } + break; + } + + case TEngineType::ElectricSeriesMotor: + { + OK = IncMainCtrlSeriesMotor(CtrlSpeed); + break; + } + + case TEngineType::DieselEngine: + { + if (CtrlSpeed > 1) + { + while (MainCtrlPos < MainCtrlPosNo && IncMainCtrl(1)) + { + // all work is done in the loop header + } + } + else + { + ++MainCtrlPos; + } + CompressorAllow = MainCtrlPowerPos() > 0; + OK = true; + break; + } + + case TEngineType::WheelsDriven: + { + OK = AddPulseForce(CtrlSpeed); + break; + } + default: + break; + } // switch EngineType of + return OK; +} + +// a notch up of the series motors' controller: CtrlSpeed over 1 runs it to the first position without resistors; +// returns whether it moved as asked +bool TMoverParameters::IncMainCtrlSeriesMotor(int const CtrlSpeed) +{ + bool OK = false; + if (DirActive == 0) + { + return false; + } + + if (CtrlSpeed > 1) + { + // szybkie przejœcie na bezoporow¹ + if (TrainType == dt_ET40) + { + return false; // this means ET40 won't react at all to fast acceleration command. should it issue just IncMainCtrl(1) instead? + } + while (RList[MainCtrlPos].R > 0.0 && IncMainCtrl(1)) + { + // all work is done in the loop header + } + OK = false; // shouldn't this be part of the loop above? + // if (TrainType=dt_ET40) then + // while Abs (Im)>IminHi do + // dec(MainCtrlPos); + // OK:=false ; + } + else + { // CtrlSpeed == 1 + ++MainCtrlPos; + OK = true; + if (Imax == ImaxHi && RList[MainCtrlPos].Bn > 1) + { + /* NOTE: disabled, relay configuration was moved to compute_movement_ + if( true == MaxCurrentSwitch( false )) { + // wylaczanie wysokiego rozruchu + SetFlag( SoundFlag, sound::relay ); + } + */ + if (TrainType == dt_ET42) + { + --MainCtrlPos; + OK = false; + } + } + // + // if (TrainType == "et40") + // if (Abs(Im) > IminHi) + // { + // MainCtrlPos--; //Blokada nastawnika po przekroczeniu minimalnego pradu + // OK = false; + // } + //} + } + + if (TrainType == dt_ET42 && true == DynamicBrakeFlag && MainCtrlPos > 20) + { + MainCtrlPos = 20; + OK = false; + } + return OK; +} + // ***************************************************************************** // Q: 20160710 // zmniejszenie nastawnika @@ -2743,70 +3577,7 @@ bool TMoverParameters::DecMainCtrl(int CtrlSpeed) OK = true; } else - switch (EngineType) - { - case TEngineType::None: - case TEngineType::Dumb: - case TEngineType::DieselElectric: - case TEngineType::ElectricInductionMotor: - { - if ((CtrlSpeed == 1 && EngineType != TEngineType::DieselElectric) || (CtrlSpeed == 1 && EngineType == TEngineType::DieselElectric)) - { - MainCtrlPos--; - OK = true; - if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1 && MainCtrlActualPos != MainCtrlPos) - { - DecScndCtrl(2); - SpeedCtrlUnit.IsActive = false; - } - } - else if (CtrlSpeed > 1) - OK = DecMainCtrl(1) && DecMainCtrl(CtrlSpeed - 1); // CtrlSpeed-1); - break; - } - - case TEngineType::ElectricSeriesMotor: - { - if (CtrlSpeed == 1) /*and (ScndCtrlPos=0)*/ - { - MainCtrlPos--; - // if (MainCtrlPos=0) and (ScndCtrlPos=0) and - // (TrainType<>dt_ET40)and(TrainType<>dt_EP05) then - // StLinFlag:=false; - // if (MainCtrlPos=0) and (TrainType<>dt_ET40) and - // (TrainType<>dt_EP05) then - // MainCtrlActualPos:=0; //yBARC: co to tutaj robi? ;) - OK = true; - } - else if (CtrlSpeed > 1) /*and (ScndCtrlPos=0)*/ - { - OK = true; - if (RList[MainCtrlPos].R == 0) // Q: tu zrobilem = ;] - DecMainCtrl(1); - while (RList[MainCtrlPos].R > 0 && DecMainCtrl(1)) - ; // takie chamskie, potem poprawie} - } - break; - } - - case TEngineType::DieselEngine: - { - if (CtrlSpeed == 1) - { - MainCtrlPos--; - OK = true; - } - else if (CtrlSpeed > 1) - { - while (MainCtrlPos > 0 || RList[MainCtrlPos].Mn > 0) - DecMainCtrl(1); - OK = true; - } - break; - } - default: - break; - } // switch EngineType + OK = DecMainCtrlByEngine(CtrlSpeed); } } else if (EngineType == TEngineType::WheelsDriven) @@ -2836,6 +3607,85 @@ bool TMoverParameters::DecMainCtrl(int CtrlSpeed) return OK; } +// a notch down, as the kind of the engine takes it; returns whether the controller moved +bool TMoverParameters::DecMainCtrlByEngine(int const CtrlSpeed) +{ + bool OK = false; + switch (EngineType) + { + case TEngineType::None: + case TEngineType::Dumb: + case TEngineType::DieselElectric: + case TEngineType::ElectricInductionMotor: + { + if (CtrlSpeed == 1) + { + MainCtrlPos--; + OK = true; + if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1 && MainCtrlActualPos != MainCtrlPos) + { + SpeedCtrlSwitch(false); + SpeedCtrlUnit.IsActive = false; + } + } + else if (CtrlSpeed > 1) + OK = DecMainCtrl(1) && DecMainCtrl(CtrlSpeed - 1); // CtrlSpeed-1); + break; + } + + case TEngineType::ElectricSeriesMotor: + { + OK = DecMainCtrlSeriesMotor(CtrlSpeed); + break; + } + + case TEngineType::DieselEngine: + { + if (CtrlSpeed == 1) + { + MainCtrlPos--; + OK = true; + } + else if (CtrlSpeed > 1) + { + while (MainCtrlPos > 0 || RList[MainCtrlPos].Mn > 0) + DecMainCtrl(1); + OK = true; + } + break; + } + default: + break; + } // switch EngineType + return OK; +} + +// a notch down of the series motors' controller: CtrlSpeed over 1 runs it down to the first position without resistors +bool TMoverParameters::DecMainCtrlSeriesMotor(int const CtrlSpeed) +{ + bool OK = false; + if (CtrlSpeed == 1) /*and (ScndCtrlPos=0)*/ + { + MainCtrlPos--; + // if (MainCtrlPos=0) and (ScndCtrlPos=0) and + // (TrainType<>dt_ET40)and(TrainType<>dt_EP05) then + // StLinFlag:=false; + // if (MainCtrlPos=0) and (TrainType<>dt_ET40) and + // (TrainType<>dt_EP05) then + // MainCtrlActualPos:=0; //yBARC: co to tutaj robi? ;) + OK = true; + } + else if (CtrlSpeed > 1) /*and (ScndCtrlPos=0)*/ + { + OK = true; + if (RList[MainCtrlPos].R == 0) // Q: tu zrobilem = ;] + DecMainCtrl(1); + while (RList[MainCtrlPos].R > 0 && DecMainCtrl(1)) + ; // takie chamskie, potem poprawie} + } + return OK; +} + bool TMoverParameters::IsMainCtrlActualNoPowerPos() const { // TODO: wrap controller pieces into a class for potential specializations, similar to brake subsystems @@ -2931,7 +3781,8 @@ bool TMoverParameters::IncScndCtrl(int CtrlSpeed) { // TBD, TODO: refactor this validation as part of relay check routine (currently in tractionforce() // TBD, TODO: diesel electric engine utilize scndctrlactualpos like the other types? - if (EngineType == TEngineType::DieselElectric && (IsMainCtrlNoPowerPos() || AutoRelayFlag || ShuntMode || false == Mains)) + if (EngineType == TEngineType::DieselElectric && + (IsMainCtrlNoPowerPos() || fieldshunting::diesel_electric(AutoRelayType, FieldShuntSwitch, AutoRelayFlag) != fieldshunting::control::manual || ShuntMode || false == Mains)) { OK = false; } @@ -3092,6 +3943,11 @@ bool TMoverParameters::CabActivisation(bool const Enforce) bool OK = false; OK = Enforce || CabActive == 0; // numer kabiny, z której jest sterowanie + if (PulleeMode) + { + // nobody drives from a vehicle prepared for hauling + OK = false; + } if (OK) { CabActive = CabOccupied; // sterowanie jest z kabiny z obsadą @@ -3352,6 +4208,11 @@ void TMoverParameters::SecuritySystemCheck(double dt) bool TMoverParameters::BatterySwitch(bool State, range_t const Notify) { using enum range_t; + if (PulleeMode && State) + { + // the battery of a vehicle prepared for hauling stays off + return false; + } auto const initialstate{Battery}; // Ra: ukrotnienie załączania baterii jest jakąś fikcją... @@ -3436,6 +4297,35 @@ bool TMoverParameters::SpringBrakeRelease() return false; } +// ************************************************************************************************* +// pullee mode ("jazda ciągniona", MaSzyna-EU07/maszyna#64): prepares the vehicle for being hauled dead in a +// train, or puts it back in service. while in the mode the vehicle: +// - vents the brake pipe for nothing of its own (inactive cab, vigilance, radio-stop, spring brake), only when +// the train parts (UpdatePipePressure()), +// - gets no force from its spring brake, whatever air its cylinder has (BrakeForce()), +// - has its driver's valve cut out and its local brake released, whatever the handles show; the distributor +// stays on the brake pipe, so it brakes and releases with the train, +// - keeps its battery off and takes no cab (BatterySwitch(), CabActivisation() and their commands). +// entering it also lets go of the hand brake and of the spring brake switch. +// returns whether the mode changed; a vehicle driven from can't enter it +// ************************************************************************************************* +bool TMoverParameters::PulleeModeSwitch(bool const State) +{ + if (PulleeMode == State || (State && CabActive != 0)) + { + return false; + } + PulleeMode = State; + if (PulleeMode) + { + DecManualBrakeLevel(ManualBrakePosNo); + SpringBrake.Activate = false; + SecuritySystem.set_enabled(false); + Battery = false; + } + return true; +} + // ************************************************************************************************* // Q: 20160710 // kierunek do tyłu @@ -3887,6 +4777,11 @@ bool TMoverParameters::MainSwitchCheck() const break; } } + if (GensetSelected()) + { + // on the genset of a dual-mode vehicle the line breaker closes only on a running one, whatever the pantographs give + powerisavailable = Genset.is_active && Genset.voltage >= TractionSupplyMinVoltage(); + } return powerisavailable && (ScndCtrlPos == 0 || EngineType == ElectricInductionMotor) && MainsInitTimeCountdown <= 0.0 && (ConvOvldFlag == false || ConverterOverloadRelayOffWhenMainIsOff) && true == GroundRelay && (true == NoVoltRelay || PantographsRequireMains) && true == OvervoltageRelay && @@ -3894,7 +4789,7 @@ bool TMoverParameters::MainSwitchCheck() const (HasCamshaft ? IsMainCtrlActualNoPowerPos() : LineBreakerClosesOnlyAtNoPowerPos ? IsMainCtrlNoPowerPos() : true) && - false == TestFlag(DamageFlag, dtrain_out) && false == TestFlag(EngDmgFlag, 1); + false == TestFlag(DamageFlag, dtrain_out) && false == TestFlag(EngDmgFlag, 1) && false == EmergencyBrakeHoldsMainOff(); } // ************************************************************************************************* @@ -3986,11 +4881,88 @@ void TMoverParameters::HeatingSwitch_(bool const State) HeatingAllow = State; } +// the traction selector of a dual-mode vehicle: moves only with the line breaker open, and only where a genset is +bool TMoverParameters::TractionModeSwitch(traction_mode const Mode, range_t const Notify) +{ + auto const initialstate{TractionMode}; + // refused with the line breaker closed, and then not passed on either, so the train stays on one source + auto const accepted{false == Mains}; + + if (Genset.fitted() && accepted) + { + TractionMode = Mode; + } + + if (Notify != range_t::local && accepted) + { + SendCtrlToNext("TractionMode", Mode == traction_mode::genset ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return TractionMode != initialstate; +} + +// the start request of the genset of a dual-mode vehicle; one which starts on its own ignores it, but passes it on to +// the cars behind, which may start theirs on request +bool TMoverParameters::GensetSwitch(bool const State, range_t const Notify) +{ + auto const initialstate{Genset.is_enabled}; + + if (Genset.start_type != start_t::automatic) + { + Genset.is_enabled = State; + } + + if (Notify != range_t::local) + { + SendCtrlToNext("GensetSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return Genset.is_enabled != initialstate; +} + +// the voltage of the vehicle's own source the traction selector picks: the catenary through the pantographs, or the +// genset of a dual-mode vehicle +double TMoverParameters::TractionSourceVoltage() const +{ + return GensetSelected() ? Genset.voltage : PantographVoltage; +} + +// the voltage the traction circuit gets: from the vehicle's own source, or through the train's high voltage line +double TMoverParameters::TractionSupplyVoltage() const +{ + return std::max(GetTrainsetHighVoltage(), TractionSourceVoltage()); +} + +// below it the undervoltage trip opens the line breaker +double TMoverParameters::TractionSupplyMinVoltage() const +{ + return GensetSelected() ? 0.5 * Genset.voltage_nominal : EnginePowerSource.CollectorParameters.MinV; +} + +// the power the traction may take [kW, at the wheels]: the genset's share at its present revolutions on the genset, +// no limit otherwise +double TMoverParameters::GensetTractionPowerLimit() const +{ + return GensetSelected() ? Genset.available_power() * Genset.traction_share : std::numeric_limits::max(); +} + +// the current the vehicle draws through its pantographs [A], if they touch the wire: the traction's (none while +// braking on the resistors) and the heating's. on the genset the genset feeds the traction circuit, so only a heating +// fed straight from the pantographs is left +double TMoverParameters::CatenaryCurrent() const +{ + if (GensetSelected()) + { + return HeatingPowerSource.SourceType == TPowerSource::CurrentCollector ? TotalCurrent : 0.0; + } + return (DynamicBrakeFlag && ResistorsFlag ? 0 : std::abs(Itot) * IsVehicleEIMBrakingFactor()) + TotalCurrent; +} + // returns voltage of defined main engine power source double TMoverParameters::EnginePowerSourceVoltage() const { - return EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? std::max(GetTrainsetHighVoltage(), PantographVoltage) : + return EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? TractionSupplyVoltage() : EnginePowerSource.SourceType == TPowerSource::Accumulator ? Power24vVoltage : 0.0; } @@ -4011,7 +4983,7 @@ bool TMoverParameters::MainCircuitPowered() const } // closed ahead of the pantographs the line breaker holds without the voltage, which the undervoltage trip isn't // there to vouch for - return EnginePowerSourceVoltage() >= EnginePowerSource.CollectorParameters.MinV; + return EnginePowerSourceVoltage() >= TractionSupplyMinVoltage(); } // ************************************************************************************************* @@ -4709,108 +5681,11 @@ void TMoverParameters::UpdatePipePressure(double dt) if (BrakeCtrlPosNo > 1) { - if (EngineType != TEngineType::ElectricInductionMotor) - { - double lbpa = LocHandleTimeTraxx ? eim_localbrake : LocalBrakePosA; - if (EIMCtrlType > 0 && UniCtrlIntegratedLocalBrakeCtrl) - { - lbpa = std::max(0.0, -eimic_real); - } - if (SpeedCtrlUnit.Parking) - { - lbpa = std::max(lbpa, StopBrakeDecc); - } - dpLocalValve = LocHandle->GetPF(std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); - } - else - { - // in EIM stock the pneumatic local brake is normally driven only by the MED algorithm - // (LocalBrakePosAEIM). When SplitEDPneumaticBrake is active the dedicated LocalBrake - // lever should apply pneumatic pressure on the locomotive directly, bypassing MED. - // LocHandleTimeTraxx also bypasses MED, but has 3 positions (brake-hold-unbrake). - double lbpa; - if (LocHandleTimeTraxx) - { - lbpa = eim_localbrake; - } - else if (SplitEDPneumaticBrake) // When LocHandleTimeTraxx and SplitEDPneumaticBrake are both active, lbpa is taken from LocHandleTimeTraxx, which is the desired behavior. - { - lbpa = LocalBrakePosA; - } - else - { - lbpa = 0.0; - } - dpLocalValve = LocHandle->GetPF(std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); - } - - LockPipe = PipePress < (LockPipe ? LockPipeOff : LockPipeOn); - bool lock_new = (LockPipe && !UnlockPipe && BrakeCtrlPosR > HandleUnlock) || (EmergencyCutsOffHandle && EmergencyValveFlow > 0); // new simple codition based on .fiz - bool lock_old = BrakeHandle == TBrakeHandle::FV4a // old complex condition based on assumptions - && PipePress < 2.75 && (Hamulec->GetStatus() & b_rls) == 0 && BrakeSubsystem == TBrakeSubSystem::ss_LSt && TrainType != dt_EZT && !UnlockPipe; - - if (lock_old || lock_new) - { - temp = PipePress + 0.00001; - } - else - { - temp = ScndPipePress; - } - Handle->SetReductor(BrakeCtrlPos2); - - if ((BrakeOpModes & bom_PS) == 0 || (CabOccupied != 0 && BrakeOpModeFlag != bom_PS)) - { - - if (BrakeOpModeFlag < bom_EP || Handle->GetPos(bh_EB) - 0.5 < BrakeCtrlPosR || (BrakeHandle != TBrakeHandle::MHZ_EN57 && BrakeHandle != TBrakeHandle::MHZ_K8P)) - { - double pos = BrakeCtrlPosR; - if (SpeedCtrlUnit.IsActive && SpeedCtrlUnit.BrakeIntervention && !SpeedCtrlUnit.Standby && BrakeCtrlPos != Handle->GetPos(bh_EB)) - { - pos = Handle->GetPos(bh_NP); - if (SpeedCtrlUnit.BrakeInterventionBraking) - pos = Handle->GetPos(bh_FB); - if (SpeedCtrlUnit.BrakeInterventionUnbraking) - pos = Handle->GetPos(bh_RP); - } - dpMainValve = Handle->GetPF(pos, PipePress, temp, dt, EqvtPipePress); - } - else - { - dpMainValve = Handle->GetPF(0, PipePress, temp, dt, EqvtPipePress); - } - } - else if (BrakeCtrlPos == Handle->GetPos(bh_EB)) - { - dpMainValve = Handle->GetPF(BrakeCtrlPosR, PipePress, temp, dt, EqvtPipePress); - } - - if (dpMainValve < 0) // && (PipePressureVal > 0.01) //50 - { - if (Compressor > ScndPipePress) - { - CompressedVolume = CompressedVolume + dpMainValve / 1500.0; - Pipe2->Flow(dpMainValve / 3.0); - } - else - Pipe2->Flow(dpMainValve); - } + UpdateLocalBrakeValve(dt); + UpdateMainValve(dt); } - // ulepszony hamulec bezp. - EmergencyValveFlow = 0.0; - - - // EngDmgFlag 32 (load destroyed) used to trigger this too; dropped, it has nothing to do with - // the emergency brake (a broken coupler sets AlarmChainFlag instead). the Elf's emergency brake position - // vents the pipe only from the vehicle driven from, whatever the controllers of the others show - if (RadioStopFlag || AlarmChainFlag || (EIMCtrlEmergency && LocalBrakePosA >= 1.0) || (IsMainCtrlEmergencyPos() && IsCabMaster()) || SecuritySystem.is_braking() || - (SpringBrakeDriveEmergencyVel >= 0 && Vel > SpringBrakeDriveEmergencyVel && SpringBrake.IsActive) || - (0 == CabActive && (InactiveCabFlag & activation::emergencybrake) != 0)) - { - EmergencyValveFlow = PF(0, PipePress, 0.15) * dt; - } - dpMainValve += EmergencyValveFlow; + UpdateEmergencyValve(dt); // 0.2*Spg Pipe->Flow(-dpMainValve); @@ -4825,6 +5700,184 @@ void TMoverParameters::UpdatePipePressure(double dt) // if (Hamulec is typeid(TWest)) return 0; + UpdateDistributorSettings(); + + if ((BrakeHandle == TBrakeHandle::FVel6 || BrakeHandle == TBrakeHandle::FVE408) && CabOccupied != 0) + { + UpdateEPBrake(); + } + else if (BrakeHandle == TBrakeHandle::St113 && CabOccupied != 0 && std::abs(EpForce) > 0.001 && !EPBrakeControlPowered()) + { + // the EP brake switched on with the button drops out with the control's supply + SwitchEPBrake(0); + } + + Pipe->Act(); + PipePress = Pipe->P(); + if ((Hamulec->GetBrakeStatus() & b_dmg) == b_dmg) // jesli hamulec wyłączony + temp = 0.0; // odetnij + else + temp = 1.0; // połącz + Pipe->Flow(temp * Hamulec->GetPF(temp * PipePress, dt, Vel)); + // the air the brake hoses carry to and from the neighbours comes once all vehicles have stepped, UpdatePipeCouplers() + PipeCouplersPending = true; + + if (ASBType == 128) + Hamulec->ASB(int(SlippingWheels && Vel > 1) * (1 + 2 * int(nrot_eps < -0.01))); + + dpPipe = 0; + + // yB: jednokrokowe liczenie tego wszystkiego + Pipe->Act(); + PipePress = Pipe->P(); + + dpMainValve = dpMainValve / (100.0 * dt); // normalizacja po czasie do syczenia; + + if (PipePress < -1.0) + { + PipePress = -1.0; + Pipe->CreatePress(-1.0); + Pipe->Act(); + } + + if (CompressedVolume < 0.0) + CompressedVolume = 0.0; +} + +// the flow of the local brake valve, by the handle, the TRAXX's timed one, the integrated controller or the parking +void TMoverParameters::UpdateLocalBrakeValve(double dt) +{ + // the local brake of a vehicle prepared for hauling (PulleeMode) is held released, whatever asks for it + if (EngineType != TEngineType::ElectricInductionMotor) + { + double lbpa = LocHandleTimeTraxx ? eim_localbrake : LocalBrakePosA; + if (EIMCtrlType > 0 && UniCtrlIntegratedLocalBrakeCtrl) + { + lbpa = std::max(0.0, -eimic_real); + } + if (SpeedCtrlUnit.Parking) + { + lbpa = std::max(lbpa, StopBrakeDecc); + } + dpLocalValve = LocHandle->GetPF(PulleeMode ? 0.0 : std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); + } + else + { + // in EIM stock the pneumatic local brake is normally driven only by the MED algorithm + // (LocalBrakePosAEIM). When SplitEDPneumaticBrake is active the dedicated LocalBrake + // lever should apply pneumatic pressure on the locomotive directly, bypassing MED. + // LocHandleTimeTraxx also bypasses MED, but has 3 positions (brake-hold-unbrake). + double lbpa; + if (LocHandleTimeTraxx) + { + lbpa = eim_localbrake; + } + else if (SplitEDPneumaticBrake) // When LocHandleTimeTraxx and SplitEDPneumaticBrake are both active, lbpa is taken from LocHandleTimeTraxx, which is the desired behavior. + { + lbpa = LocalBrakePosA; + } + else + { + lbpa = 0.0; + } + dpLocalValve = LocHandle->GetPF(PulleeMode ? 0.0 : std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); + } +} + +// the lock of the brake pipe and the flow of the driver's handle, from the main reservoir or into the air +void TMoverParameters::UpdateMainValve(double dt) +{ + auto const temp{MainValveSupply()}; + Handle->SetReductor(BrakeCtrlPos2); + + if (PulleeMode) + { + // the driver's valve of a vehicle prepared for hauling is cut out, whatever its handle shows + dpMainValve = 0; + } + else if ((BrakeOpModes & bom_PS) == 0 || (CabOccupied != 0 && BrakeOpModeFlag != bom_PS)) + { + + if (BrakeOpModeFlag < bom_EP || Handle->GetPos(bh_EB) - 0.5 < BrakeCtrlPosR || (BrakeHandle != TBrakeHandle::MHZ_EN57 && BrakeHandle != TBrakeHandle::MHZ_K8P)) + { + dpMainValve = Handle->GetPF(MainValveHandlePosition(), PipePress, temp, dt, EqvtPipePress); + } + else + { + dpMainValve = Handle->GetPF(0, PipePress, temp, dt, EqvtPipePress); + } + } + else if (BrakeCtrlPos == Handle->GetPos(bh_EB)) + { + dpMainValve = Handle->GetPF(BrakeCtrlPosR, PipePress, temp, dt, EqvtPipePress); + } + + if (dpMainValve < 0) // && (PipePressureVal > 0.01) //50 + { + if (Compressor > ScndPipePress) + { + CompressedVolume = CompressedVolume + dpMainValve / 1500.0; + Pipe2->Flow(dpMainValve / 3.0); + } + else + Pipe2->Flow(dpMainValve); + } +} + +// the pressure the driver's handle is fed from: the main pipe's, or the brake pipe's own with the pipe locked +double TMoverParameters::MainValveSupply() +{ + LockPipe = PipePress < (LockPipe ? LockPipeOff : LockPipeOn); + bool lock_new = (LockPipe && !UnlockPipe && BrakeCtrlPosR > HandleUnlock) || (EmergencyCutsOffHandle && EmergencyValveFlow > 0); // new simple codition based on .fiz + bool lock_old = BrakeHandle == TBrakeHandle::FV4a // old complex condition based on assumptions + && PipePress < 2.75 && (Hamulec->GetStatus() & b_rls) == 0 && BrakeSubsystem == TBrakeSubSystem::ss_LSt && TrainType != dt_EZT && !UnlockPipe; + + if (lock_old || lock_new) + { + return PipePress + 0.00001; + } + return ScndPipePress; +} + +// the position the driver's handle works at: its own, or the one the speed control's brake intervention sets +double TMoverParameters::MainValveHandlePosition() const +{ + double pos = BrakeCtrlPosR; + if (SpeedCtrlUnit.IsActive && SpeedCtrlUnit.BrakeIntervention && !SpeedCtrlUnit.Standby && BrakeCtrlPos != Handle->GetPos(bh_EB)) + { + pos = Handle->GetPos(bh_NP); + if (SpeedCtrlUnit.BrakeInterventionBraking) + pos = Handle->GetPos(bh_FB); + if (SpeedCtrlUnit.BrakeInterventionUnbraking) + pos = Handle->GetPos(bh_RP); + } + return pos; +} + +void TMoverParameters::UpdateEmergencyValve(double dt) +{ + // ulepszony hamulec bezp. + EmergencyValveFlow = 0.0; + + + // EngDmgFlag 32 (load destroyed) used to trigger this too; dropped, it has nothing to do with + // the emergency brake (a broken coupler sets AlarmChainFlag instead). the Elf's emergency brake position + // vents the pipe only from the vehicle driven from, whatever the controllers of the others show. + // a vehicle prepared for hauling (PulleeMode) vents it for nothing of its own, only for the alarm chain, + // which a train parting sets too + auto const ownemergency{RadioStopFlag || (EIMCtrlEmergency && LocalBrakePosA >= 1.0) || (IsMainCtrlEmergencyPos() && IsCabMaster()) || SecuritySystem.is_braking() || + (SpringBrakeDriveEmergencyVel >= 0 && Vel > SpringBrakeDriveEmergencyVel && SpringBrake.IsActive) || + (0 == CabActive && (InactiveCabFlag & activation::emergencybrake) != 0)}; + if (AlarmChainFlag || (ownemergency && false == PulleeMode)) + { + EmergencyValveFlow = PF(0, PipePress, 0.15) * dt; + } + dpMainValve += EmergencyValveFlow; +} + +// what the distributor valve gets of the local brake and the load, by its kind +void TMoverParameters::UpdateDistributorSettings() +{ switch (BrakeValve) { @@ -4930,62 +5983,29 @@ void TMoverParameters::UpdatePipePressure(double dt) break; } } // switch +} - if ((BrakeHandle == TBrakeHandle::FVel6 || BrakeHandle == TBrakeHandle::FVE408) && CabOccupied != 0) - { - if (EPBrakeControlPowered()) // tu powinien byc jeszcze bezpiecznik EP i baterie - - // temp = (Handle as TFVel6).GetCP - EpForce = Handle->GetEP(); - else - EpForce = 0.0; - - DynamicBrakeEMUStatus = EpForce > 0.001 ? Power110vIsAvailable : true; - - double temp1 = EpForce; - if (DCEMUED_EP_max_Vel > 0.001 && Vel > DCEMUED_EP_max_Vel && DynamicBrakeEMUStatus) - temp1 = 0; - if (DCEMUED_EP_min_Im > 0.001 && abs(Im) > DCEMUED_EP_min_Im && DynamicBrakeEMUStatus) - temp1 = 0; - Hamulec->SetEPS(temp1); - TUHEX_StageActual = static_cast(EpForce); - TUHEX_Active = TUHEX_StageActual > 0; - // Ra 2014-11: na tym się wysypuje, ale nie wiem, w jakich warunkach - SendCtrlToNext("Brake", EpForce, CabActive); - } - else if (BrakeHandle == TBrakeHandle::St113 && CabOccupied != 0 && std::abs(EpForce) > 0.001 && !EPBrakeControlPowered()) - { - // the EP brake switched on with the button drops out with the control's supply - SwitchEPBrake(0); - } - - Pipe->Act(); - PipePress = Pipe->P(); - if ((Hamulec->GetBrakeStatus() & b_dmg) == b_dmg) // jesli hamulec wyłączony - temp = 0.0; // odetnij +// the ep brake of the FVel6 and FVE408 handles, passed along the unit +void TMoverParameters::UpdateEPBrake() +{ + if (EPBrakeControlPowered()) // tu powinien byc jeszcze bezpiecznik EP i baterie - + // temp = (Handle as TFVel6).GetCP + EpForce = Handle->GetEP(); else - temp = 1.0; // połącz - Pipe->Flow(temp * Hamulec->GetPF(temp * PipePress, dt, Vel) + GetDVc(dt)); + EpForce = 0.0; - if (ASBType == 128) - Hamulec->ASB(int(SlippingWheels && Vel > 1) * (1 + 2 * int(nrot_eps < -0.01))); + DynamicBrakeEMUStatus = EpForce > 0.001 ? Power110vIsAvailable : true; - dpPipe = 0; - - // yB: jednokrokowe liczenie tego wszystkiego - Pipe->Act(); - PipePress = Pipe->P(); - - dpMainValve = dpMainValve / (100.0 * dt); // normalizacja po czasie do syczenia; - - if (PipePress < -1.0) - { - PipePress = -1.0; - Pipe->CreatePress(-1.0); - Pipe->Act(); - } - - if (CompressedVolume < 0.0) - CompressedVolume = 0.0; + double temp1 = EpForce; + if (DCEMUED_EP_max_Vel > 0.001 && Vel > DCEMUED_EP_max_Vel && DynamicBrakeEMUStatus) + temp1 = 0; + if (DCEMUED_EP_min_Im > 0.001 && abs(Im) > DCEMUED_EP_min_Im && DynamicBrakeEMUStatus) + temp1 = 0; + Hamulec->SetEPS(temp1); + TUHEX_StageActual = static_cast(EpForce); + TUHEX_Active = TUHEX_StageActual > 0; + // Ra 2014-11: na tym się wysypuje, ale nie wiem, w jakich warunkach + SendCtrlToNext("Brake", EpForce, CabActive); } // ************************************************************************************************* @@ -5015,50 +6035,19 @@ void TMoverParameters::UpdateScndPipePressure(double dt) } const double Spz = 0.5067; - TMoverParameters *c; - double dv1; - double dv2; - double dV; UpdateSpringBrake(dt); - dv1 = 0; - dv2 = 0; - - // sprzeg 1 - if (Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic)) - { - c = Couplers[0].Connected; // skrot - dv1 = 0.5 * dt * PF(ScndPipePress, c->ScndPipePress, Spz * 0.75); - c->Pipe2->Flow(-dv1); - if (pipe_wakes(dv1, ScndPipePress, *c->Pipe2)) - c->switch_physics(true, wake_cause::scndpipe); - } - // sprzeg 2 - if (Couplers[1].Connected != nullptr && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) - { - c = Couplers[1].Connected; // skrot - dv2 = 0.5 * dt * PF(ScndPipePress, c->ScndPipePress, Spz * 0.75); - c->Pipe2->Flow(-dv2); - if (pipe_wakes(dv2, ScndPipePress, *c->Pipe2)) - c->switch_physics(true, wake_cause::scndpipe); - } - if (Couplers[1].Connected != nullptr && Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic) && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) - { - dV = 0.00025 * dt * PF(Couplers[0].Connected->ScndPipePress, Couplers[1].Connected->ScndPipePress, Spz * 0.25); - Couplers[0].Connected->Pipe2->Flow(+dV); - Couplers[1].Connected->Pipe2->Flow(-dV); - } - Pipe2->Flow(Hamulec->GetHPFlow(ScndPipePress, dt)); // NOTE: condition disabled to allow the air flow from the main hose to the main tank as well if (/* ( ( Compressor > ScndPipePress ) && ( */ VeselVolume > 0.0 /* ) ) || ( TrainType == dt_EZT ) || ( TrainType == dt_DMU ) */) { - dV = PF(Compressor, ScndPipePress, Spz) * dt; + double const dV = PF(Compressor, ScndPipePress, Spz) * dt; CompressedVolume += dV / 1000.0; Pipe2->Flow(-dV); } - Pipe2->Flow(dv1 + dv2); + // the air the main reservoir hoses carry to and from the neighbours comes once all vehicles have stepped, UpdatePipeCouplers() + ScndPipeCouplersPending = true; Pipe2->Act(); ScndPipePress = Pipe2->P(); @@ -5145,6 +6134,167 @@ double TMoverParameters::GetDVc(double dt) return dv2 + dv1; } +// ************************************************************************************************* +// the air the main reservoir hoses carry between the vehicle's pipe and the neighbours' in dt: the neighbours' +// share is sent to them, the vehicle's own returned +// ************************************************************************************************* +double TMoverParameters::GetScndDVc(double dt) +{ + const double Spz = 0.5067; + TMoverParameters *c; + double dv1 = 0; + double dv2 = 0; + + // sprzeg 1 + if (Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic)) + { + c = Couplers[0].Connected; // skrot + dv1 = 0.5 * dt * PF(ScndPipePress, c->ScndPipePress, Spz * 0.75); + c->Pipe2->Flow(-dv1); + if (pipe_wakes(dv1, ScndPipePress, *c->Pipe2)) + c->switch_physics(true, wake_cause::scndpipe); + } + // sprzeg 2 + if (Couplers[1].Connected != nullptr && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) + { + c = Couplers[1].Connected; // skrot + dv2 = 0.5 * dt * PF(ScndPipePress, c->ScndPipePress, Spz * 0.75); + c->Pipe2->Flow(-dv2); + if (pipe_wakes(dv2, ScndPipePress, *c->Pipe2)) + c->switch_physics(true, wake_cause::scndpipe); + } + if (Couplers[1].Connected != nullptr && Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic) && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) + { + double const dV = 0.00025 * dt * PF(Couplers[0].Connected->ScndPipePress, Couplers[1].Connected->ScndPipePress, Spz * 0.25); + Couplers[0].Connected->Pipe2->Flow(+dV); + Couplers[1].Connected->Pipe2->Flow(-dV); + } + return dv1 + dv2; +} + +namespace +{ + +// a pipe along the train, whose air the hoses between the vehicles carry (TMoverParameters::UpdatePipeCouplers()) +struct train_pipe +{ + std::shared_ptr TMoverParameters::*reservoir; + double TMoverParameters::*pressure; + bool TMoverParameters::*pending; // the vehicle stepped the pipe, the exchange through its hoses is yet to come + int hose; // the coupling flag of the pipe's hose + double (TMoverParameters::*exchange)(double); // the air the hoses carry in a step, the neighbours' share sent to them + double (*area)(TMoverParameters const &); // the cross-section of the hose, as the exchange takes it +}; + +// the brake pipe, GetDVc() +train_pipe const brake_pipe{&TMoverParameters::Pipe, + &TMoverParameters::PipePress, + &TMoverParameters::PipeCouplersPending, + ctrain_pneumatic, + &TMoverParameters::GetDVc, + [](TMoverParameters const &Vehicle) { return Vehicle.Spg / (1.0 + 0.015 / Vehicle.Spg * Vehicle.Dim.L); }}; +// the main reservoir pipe, GetScndDVc() +train_pipe const main_reservoir_pipe{&TMoverParameters::Pipe2, + &TMoverParameters::ScndPipePress, + &TMoverParameters::ScndPipeCouplersPending, + ctrain_scndpneumatic, + &TMoverParameters::GetScndDVc, + [](TMoverParameters const &) { return 0.5067 * 0.75; }}; + +// the number of sub-steps of dt the air exchange through the hoses of the vehicle's pipe needs: in one, the air a +// hose carries stays below what evens out the pipes on its ends +int hose_substeps(TMoverParameters const &Vehicle, train_pipe const &Pipe, double const dt) +{ + auto substeps{1}; + auto const area{Pipe.area(Vehicle)}; + auto const capacity{(Vehicle.*Pipe.reservoir)->GetCap()}; + for (auto const &hose : Vehicle.Couplers) + { + if (hose.Connected == nullptr || false == TestFlag(hose.CouplingFlag, Pipe.hose)) + { + continue; + } + auto const &other{*hose.Connected}; + auto const othercapacity{(other.*Pipe.reservoir)->GetCap()}; + // the flow per bar of the difference, at small differences, where it's the largest + auto const pressure{std::max(Vehicle.*Pipe.pressure, other.*Pipe.pressure)}; + auto const conductance{std::abs(PF(pressure, pressure - 0.01, area)) / 0.01}; + auto const equalising{capacity * othercapacity / (capacity + othercapacity)}; + substeps = std::max(substeps, static_cast(std::ceil(dt * conductance / equalising))); + } + return std::min(substeps, 10); +} + +// the air exchange through the hoses of the pipe, for the vehicles which stepped it since the last call, in the order +// they stepped: in as many sub-steps of dt as the vehicle needing the most of them takes, each going through the +// vehicles one after another, as the step of the vehicles does +void exchange_through_hoses(std::vector const &Vehicles, train_pipe const &Pipe, double const dt) +{ + auto substeps{1}; + for (auto const *vehicle : Vehicles) + { + if (vehicle->*Pipe.pending) + { + substeps = std::max(substeps, hose_substeps(*vehicle, Pipe, dt)); + } + } + auto const substep{dt / substeps}; + for (auto i = 0; i < substeps; ++i) + { + for (auto *vehicle : Vehicles) + { + if (false == vehicle->*Pipe.pending) + { + continue; + } + auto &pipe{*(vehicle->*Pipe.reservoir)}; + pipe.Act(); // what the neighbours have sent in the meantime + vehicle->*Pipe.pressure = pipe.P(); + pipe.Flow((vehicle->*Pipe.exchange)(substep)); + pipe.Act(); + vehicle->*Pipe.pressure = pipe.P(); + } + } + for (auto *vehicle : Vehicles) + { + vehicle->*Pipe.pending = false; + } +} + +} // namespace + +// ************************************************************************************************* +// the number of sub-steps of dt the air exchange through the brake hoses of the vehicle needs. taken in a single +// step of 0.01 s, the hose between two 14 m freight wagons carries twice the air which evens out their pipes, the +// pipes overshoot each other in turns and the distributors see the pressure up to 0.28 bar off what's in the pipe +// (eu07/maszyna#368) +// ************************************************************************************************* +int TMoverParameters::PipeCouplersSubsteps(double const dt) const +{ + return hose_substeps(*this, brake_pipe, dt); +} + +// ************************************************************************************************* +// the number of sub-steps of dt the air exchange through the main reservoir hoses of the vehicle needs. taken in a +// single step of 0.01 s, the hose carries about 1.5 times the air which evens out the pipes on its ends; along with +// the vehicles' own main reservoirs feeding the pipe in the same step, the pipes of the middle vehicles of a +// multiple unit or of locomotives in multiple traction kept jumping 0.8 bar to and fro between the steps +// ************************************************************************************************* +int TMoverParameters::ScndPipeCouplersSubsteps(double const dt) const +{ + return hose_substeps(*this, main_reservoir_pipe, dt); +} + +// ************************************************************************************************* +// the air exchange through the brake and the main reservoir hoses of the vehicles which stepped their pipes +// (UpdatePipePressure(), UpdateScndPipePressure()) since the last call, each pipe in its own sub-steps +// ************************************************************************************************* +void TMoverParameters::UpdatePipeCouplers(std::vector const &Vehicles, double const dt) +{ + exchange_through_hoses(Vehicles, brake_pipe, dt); + exchange_through_hoses(Vehicles, main_reservoir_pipe, dt); +} + // ************************************************************************************************* // Q: 20160713 // Obliczenie stałych potrzebnych do dalszych obliczeń @@ -5275,9 +6425,24 @@ void TMoverParameters::ComputeTotalForce(double dt) FStand = FrictionForce(); // siła oporów ruchu if (true == TestFlag(DamageFlag, dtrain_out)) { - // HACK: crude way to reduce speed after derailment - // TBD, TODO: more accurate approach? - FStand *= 1e20; + if (Derailed != derailment::outcome::none) + { + // off the rails by the physical criteria: the vehicle slides on the sleepers and the ballast, or on its side; + // off the track on the ground, as far as it tipped over (physics.derailment new) + auto const friction{OffTrack.active() ? OffTrack.friction() : derailment::sliding_friction(Derailed)}; + FStand = friction * (TotalMass - Mred) * g; + } + else if (legacy_derailed_slides(*this)) + { + // derailed the legacy way with physics.collisions new: the deceleration of g of the legacy model, as a friction + FStand = TotalMass * g; + } + else + { + // HACK: crude way to reduce speed after derailment + // TBD, TODO: more accurate approach? + FStand *= 1e20; + } } double old_nrot = abs(nrot); nrot = v2n(); // przeliczenie prędkości liniowej na obrotową @@ -5310,7 +6475,7 @@ void TMoverParameters::ComputeTotalForce(double dt) } // bo nie dzialalo else { - EngineVoltage = Power > 1.0 ? std::max(GetTrainsetHighVoltage(), PantographVoltage) : 0.0; + EngineVoltage = Power > 1.0 ? TractionSupplyVoltage() : 0.0; } FTrain = Power > 0 ? TractionForce(dt) : 0; @@ -5376,13 +6541,26 @@ void TMoverParameters::ComputeTotalForce(double dt) // doliczenie sił z innych pojazdów for (int end = end::front; end <= end::rear; ++end) { + // a new step: the hit of the pair not taken by either vehicle yet + Couplers[end].hit_handled = false; + Couplers[end].hit_force = 0.0; + Couplers[end].hit_duration = 0.0; + Couplers[end].closing = 0.0; if (Neighbours[end].vehicle != nullptr) { + // the velocities before the step, the forces of all the vehicles come before their movement + Couplers[end].closing = -CouplerVelocityDifference(end, *Neighbours[end].vehicle->MoverParameters, Neighbours[end].vehicle_end) * DirF(end); Couplers[end].CForce = CouplerForce(end, dt); FTrain += Couplers[end].CForce; + // what the buffers of the pair take in, for the budget of the crush (physics.collisions new and monitor) + auto &coupler{Couplers[end]}; + coupler.contact.update(coupler.Dist < 0.0, coupler.CheckCollision, coupler.closing, compression_at(coupler, end), std::max(0.0, -coupler.Dist), dt); } else + { Couplers[end].CForce = 0; + Couplers[end].contact.reset(); + } } FStand += Fb; @@ -5465,7 +6643,8 @@ double TMoverParameters::BrakeForce(TTrackParam const & /*Track*/) K = MaxBrakeForce * ManualBrakeRatio(); } - if (SpringBrake.IsReady) + // the spring brake of a vehicle prepared for hauling (PulleeMode) is released by hand: no force, whatever its cylinder has + if (SpringBrake.IsReady && false == PulleeMode) K += std::max(0.0, SpringBrake.MinForcePressure - SpringBrake.Cylinder->P()) * SpringBrake.MaxBrakeForce; u = (BrakePress * P2FTrans - BrakeCylSpring) * BrakeCylMult[0] - BrakeSlckAdj; @@ -5588,13 +6767,16 @@ double TMoverParameters::CouplerForce(int const End, double dt) auto &thiscoupler{Couplers[End]}; auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; auto const otherend{Neighbours[End].vehicle_end}; - auto &othercoupler{othervehicle->Couplers[otherend]}; + auto const &othercoupler{othervehicle->Couplers[otherend]}; auto const othervehiclemove{(othervehicle->dMoveLen * DirPatch(End, otherend))}; auto const initialdistance{Neighbours[End].distance}; // odległość od sprzęgu sąsiada auto const distancedelta{(End == end::front ? othervehiclemove - dMoveLen : dMoveLen - othervehiclemove)}; - auto const newdistance{initialdistance + 10.0 * distancedelta}; + // the ends crushed for good (physics.collisions new, see collision.h) let the buffers meet that much closer + auto const crushed{thiscoupler.crush + othercoupler.crush}; + auto const rawdistance{initialdistance + 10.0 * distancedelta}; + auto const newdistance{rawdistance < 0.0 ? std::min(0.0, rawdistance + crushed) : rawdistance}; auto const dV{CouplerVelocityDifference(End, *othervehicle, otherend)}; auto const absdV{std::abs(dV)}; @@ -5661,21 +6843,7 @@ double TMoverParameters::CouplerForce(int const End, double dt) // zderzenie thiscoupler.CheckCollision = true; } - if (std::abs(CF) > thiscoupler.FmaxC) - { - // coupler is stretched with excessive force, may break - thiscoupler.stretch_duration += static_cast(dt); - // give coupler 1 sec of leeway to account for simulation glitches, before checking whether it breaks - // (arbitrary) chance to break grows from 10-100% over 10 sec period - if (Global.crash_damage && thiscoupler.stretch_duration > 1.f && Random() < thiscoupler.stretch_duration * 0.1f * dt) - { - damage_coupler(End); - } - } - else - { - thiscoupler.stretch_duration = 0.f; - } + CouplerStretchCheck(End, CF, dt); } if (newdistance < 0) { @@ -5714,6 +6882,27 @@ double TMoverParameters::CouplerForce(int const End, double dt) return CF; } +// a coupler stretched with more than its strength for over a second breaks, the more likely the longer, with crash damage on +void TMoverParameters::CouplerStretchCheck(int const End, double const CF, double dt) +{ + auto &thiscoupler{Couplers[End]}; + if (std::abs(CF) > thiscoupler.FmaxC) + { + // coupler is stretched with excessive force, may break + thiscoupler.stretch_duration += static_cast(dt); + // give coupler 1 sec of leeway to account for simulation glitches, before checking whether it breaks + // (arbitrary) chance to break grows from 10-100% over 10 sec period + if (Global.crash_damage && thiscoupler.stretch_duration > 1.f && Random() < thiscoupler.stretch_duration * 0.1f * dt) + { + damage_coupler(End); + } + } + else + { + thiscoupler.stretch_duration = 0.f; + } +} + bool TMoverParameters::coupler_physics_at(int const End) const { if (false == Global.coupler_physics) @@ -5739,6 +6928,11 @@ void TMoverParameters::automatic_coupling(int const End, TMoverParameters &Other { return; } + // a coupler torn off by the crush of its end (physics.collisions new) doesn't catch + if (Global.collisions == global_settings::collision_model::physical && (thiscoupler.broken || othercoupler.broken)) + { + return; + } // sprzeganie wagonow z samoczynnymi sprzegami auto couplingtype{thiscoupler.AutomaticCouplingFlag & othercoupler.AutomaticCouplingFlag}; // potentially exclude incompatible control coupling @@ -5818,7 +7012,7 @@ double TMoverParameters::coupler_force_physical(int const End, double const dt) auto const previousgap{state.gap}; auto const previousdrawgear{state.draw_gear.deflection}; - auto const result{coupler_physics::update_pair(thiscoupler.physics, othercoupler.physics, state, {gap, gaprate, coupled, adapter, Global.crash_damage})}; + auto const result{coupler_physics::update_pair(thiscoupler.physics, othercoupler.physics, state, {gap, gaprate, coupled, adapter, Global.crash_damage, thiscoupler.crush + othercoupler.crush})}; SetFlag(thiscoupler.sounds, coupler_sounds({gap, previousgap, gaprate, state.draw_gear.deflection, previousdrawgear, coupled, adapter, Vel > 1.0})); @@ -5872,7 +7066,8 @@ bool TMoverParameters::coupler_stop_hit(int const End, TMoverParameters &Other, auto const hit{coupler_physics::impact(thiscoupler.physics, othercoupler.physics, state, closing, TotalMass, Other.TotalMass)}; // the other vehicle keeps the state of the pair alike othercoupler.physics_state.elongation = state.elongation; - if (hit.broken || hit.crushed) + // with physics.collisions new the crush of the ends past the buffers is crush_hit()'s + if (hit.broken || (hit.crushed && Global.collisions != global_settings::collision_model::physical)) { damage_coupler(End); } @@ -5886,14 +7081,91 @@ bool TMoverParameters::coupler_stop_hit(int const End, TMoverParameters &Other, // ************************************************************************************************* double TMoverParameters::TractionForce(double dt) { - double PosRatio; - double dmoment; - double dtrans; - double tmp; - + using enum TEngineType; Ft = 0; - dtrans = 0; - dmoment = 0; + double dtrans{0.0}; + double dmoment{0.0}; + auto const revolutions{UpdateEngineRevolutions(dt, dtrans, dmoment)}; + + eAngle += enrot * dt; + if (eAngle > M_PI * 2.0) + eAngle = std::fmod(eAngle, M_PI * 2.0); + /* + while (eAngle > M_PI * 2.0) + // eAngle = Pirazy2 - eAngle; <- ABu: a nie czasem tak, jak nizej? + eAngle -= M_PI * 2.0; + */ + // hunter-091012: przeniesione z if DirActive<>0 (zeby po zejsciu z kierunku dalej spadala predkosc wentylatorow) + // wentylatory rozruchowe + // TBD, TODO: move this to update, it doesn't exactly have much to do with traction + UpdateVentilators(dt); + auto const PosRatio{UpdateEnginePower()}; + VoltageRelaysCheck(); + + if (EngineType == DieselElectric && DEDynamicBrake.source != diesel_electric_dynamic_brake::control::none) + { + update_dieselelectric_dynamic_brake(dt); + } + + if (DirActive != 0) + switch (EngineType) + { + case Dumb: + { + DumbTractionForce(PosRatio); + break; + } + case WheelsDriven: + { + WheelsDrivenTractionForce(dt); + break; + } + case ElectricSeriesMotor: + { + SeriesMotorTractionForce(dt); + break; + } + case DieselEngine: + { + DieselEngineTractionForce(dt, dmoment, dtrans); + break; + } + case DieselElectric: // youBy + { + DieselElectricTractionForce(revolutions); + if (DEDynamicBrake.level > 0.0) + { + // braking: no power asked for, so the drive above gave no force + apply_dieselelectric_dynamic_brake(dt); + } + break; + } + case ElectricInductionMotor: + { + InductionMotorTractionForce(dt); + break; + } + case None: + default: + { + break; + } + } // case EngineType + + if (EngineType == DieselElectric) + { + // rough approximation of extra effort to overcome friction etc + EnginePower += EngineRPMRatio() * 0.15 * DElist[MainCtrlPosNo].GenPower; + } + + return Ft; +} + +// the revolutions of the engine; returns those a diesel-electric engine aims at [1/s], 0 for the others. +// for a diesel engine, the ratio of the transmission and the engine's moment +double TMoverParameters::UpdateEngineRevolutions(double dt, double &dtrans, double &dmoment) +{ + double tmp{0.0}; // youBy switch (EngineType) { @@ -5901,19 +7173,7 @@ double TMoverParameters::TractionForce(double dt) { if (true == Mains && true == FuelPump.is_active) { - - if (EIMCtrlType > 0) // sterowanie cyfrowe - tmp = (DElist[0].RPM + (DElist[MainCtrlPosNo].RPM - DElist[0].RPM) * std::max(0.0, eimic_real)) / 60.0; - else - tmp = DElist[ControlPressureSwitch ? MainCtrlNoPowerPos() : MainCtrlPos].RPM / 60.0; - - if (true == HeatingAllow && HeatingPower > 0 && EngineHeatingRPM > 0) - { - // bump engine revolutions up if needed, when heating is on - tmp = std::max(tmp, std::min(EngineMaxRPM(), EngineHeatingRPM) / 60.0); - } - // NOTE: fake dizel_fill calculation for the sake of smoke emitter which uses this parameter to determine smoke opacity - dizel_fill = std::clamp(0.2 + 0.35 * (tmp - enrot) + 0.5 * (std::abs(Im) / DElist[MainCtrlPosNo].Imax), 0.05, 1.0); + tmp = DieselElectricTargetRevolutions(); } else { @@ -5949,17 +7209,32 @@ double TMoverParameters::TractionForce(double dt) } } - eAngle += enrot * dt; - if (eAngle > M_PI * 2.0) - eAngle = std::fmod(eAngle, M_PI * 2.0); - /* - while (eAngle > M_PI * 2.0) - // eAngle = Pirazy2 - eAngle; <- ABu: a nie czasem tak, jak nizej? - eAngle -= M_PI * 2.0; - */ - // hunter-091012: przeniesione z if DirActive<>0 (zeby po zejsciu z kierunku dalej spadala predkosc wentylatorow) - // wentylatory rozruchowe - // TBD, TODO: move this to update, it doesn't exactly have much to do with traction + return tmp; +} + +// the revolutions a diesel-electric's engine aims at [1/s], by the controller and the heating; the fill shown by the smoke +double TMoverParameters::DieselElectricTargetRevolutions() +{ + double tmp; + + if (EIMCtrlType > 0) // sterowanie cyfrowe + tmp = (DElist[0].RPM + (DElist[MainCtrlPosNo].RPM - DElist[0].RPM) * std::max(0.0, eimic_real)) / 60.0; + else + tmp = DElist[ControlPressureSwitch ? MainCtrlNoPowerPos() : MainCtrlPos].RPM / 60.0; + + if (true == HeatingAllow && HeatingPower > 0 && EngineHeatingRPM > 0) + { + // bump engine revolutions up if needed, when heating is on + tmp = std::max(tmp, std::min(EngineMaxRPM(), EngineHeatingRPM) / 60.0); + } + // NOTE: fake dizel_fill calculation for the sake of smoke emitter which uses this parameter to determine smoke opacity + dizel_fill = std::clamp(0.2 + 0.35 * (tmp - enrot) + 0.5 * (std::abs(Im) / DElist[MainCtrlPosNo].Imax), 0.05, 1.0); + return tmp; +} + +// the starting resistors' blowers, and the diesels' radiator fans +void TMoverParameters::UpdateVentilators(double dt) +{ switch (EngineType) { @@ -5967,50 +7242,7 @@ double TMoverParameters::TractionForce(double dt) { if (MainCircuitPowered()) { - switch (RVentType) - { - - case 1: - { // manual - if (true == RVentForceOn || (DirActive != 0 && RList[MainCtrlActualPos].R > RVentCutOff)) - { - RventRot += (RVentnmax - RventRot) * RVentSpeed * dt; - } - else - { - RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); - } - break; - } - - case 2: - { // automatic - auto const motorcurrent{std::min(ImaxHi, std::abs(Im))}; - if (std::abs(Itot) > RVentMinI && RList[MainCtrlActualPos].R > RVentCutOff) - { - - RventRot += (RVentnmax * std::min(1.0, motorcurrent / NPoweredAxles / RVentMinI) * motorcurrent / ImaxLo - RventRot) * RVentSpeed * dt; - } - else if (DynamicBrakeType == dbrake_automatic && true == DynamicBrakeFlag) - { - RventRot += (RVentnmax * motorcurrent / ImaxLo - RventRot) * RVentSpeed * dt; - } - else if (RVentForceOn) - { - RventRot += (RVentnmax - RventRot) * RVentSpeed * dt; - } - else - { - RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); - } - break; - } - - default: - { - break; - } - } // rventtype + UpdateResistorBlowers(dt); } // mains else { @@ -6059,7 +7291,61 @@ double TMoverParameters::TractionForce(double dt) break; } } +} +// the starting resistors' blowers of the series motors with the line breaker closed, worked by hand or by the current +void TMoverParameters::UpdateResistorBlowers(double dt) +{ + switch (RVentType) + { + + case 1: + { // manual + if (true == RVentForceOn || (DirActive != 0 && RList[MainCtrlActualPos].R > RVentCutOff)) + { + RventRot += (RVentnmax - RventRot) * RVentSpeed * dt; + } + else + { + RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); + } + break; + } + + case 2: + { // automatic + auto const motorcurrent{std::min(ImaxHi, std::abs(Im))}; + if (std::abs(Itot) > RVentMinI && RList[MainCtrlActualPos].R > RVentCutOff) + { + + RventRot += (RVentnmax * std::min(1.0, motorcurrent / NPoweredAxles / RVentMinI) * motorcurrent / ImaxLo - RventRot) * RVentSpeed * dt; + } + else if (DynamicBrakeType == dbrake_automatic && true == DynamicBrakeFlag) + { + RventRot += (RVentnmax * motorcurrent / ImaxLo - RventRot) * RVentSpeed * dt; + } + else if (RVentForceOn) + { + RventRot += (RVentnmax - RventRot) * RVentSpeed * dt; + } + else + { + RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); + } + break; + } + + default: + { + break; + } + } // rventtype +} + +// the power of a dumb or diesel engine; returns the ratio of the power a dumb engine is set to +double TMoverParameters::UpdateEnginePower() +{ + double PosRatio{0.0}; switch (EngineType) { case TEngineType::Dumb: @@ -6090,6 +7376,12 @@ double TMoverParameters::TractionForce(double dt) } } + return PosRatio; +} + +// the line breaker opened by a voltage out of the motors' range, and the line contactors of a diesel-electric +void TMoverParameters::VoltageRelaysCheck() +{ switch (EngineType) { @@ -6118,8 +7410,9 @@ double TMoverParameters::TractionForce(double dt) // TODO: check if we can use instead the code for electricseriesmotor // nie wchodzić w funkcję bez potrzeby // (a line breaker closed ahead of the pantographs holds without voltage) - if (Mains && ((std::max(GetTrainsetHighVoltage(), PantographVoltage) < EnginePowerSource.CollectorParameters.MinV && false == PantographsRequireMains) || - std::max(GetTrainsetHighVoltage(), PantographVoltage) > EnginePowerSource.CollectorParameters.MaxV + 200)) + // (the source by the traction selector of a dual-mode vehicle: the pantographs or the genset) + if (Mains && ((TractionSupplyVoltage() < TractionSupplyMinVoltage() && false == PantographsRequireMains) || + TractionSupplyVoltage() > EnginePowerSource.CollectorParameters.MaxV + 200)) { MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide } @@ -6141,826 +7434,1021 @@ double TMoverParameters::TractionForce(double dt) break; } } +} - if (DirActive != 0) - switch (EngineType) - { - case TEngineType::Dumb: - { - if (Mains && CabActive != 0) - { - if (Vel > 0.1) - { - Ft = std::min(1000.0 * Power / std::abs(V), Ftmax) * PosRatio; - } - else - { - Ft = Ftmax * PosRatio; - } - Ft = Ft * DirAbsolute; // DirActive*CabActive; - } - else - { - Ft = 0; - } - break; - } // Dumb - - case TEngineType::WheelsDriven: - { - if (EnginePowerSource.SourceType == TPowerSource::InternalSource && EnginePowerSource.PowerType == TPowerType::BioPower) - Ft = Sign(sin(eAngle)) * PulseForce * Transmision.Ratio; - PulseForceTimer = PulseForceTimer + dt; - if (PulseForceTimer > CtrlDelay) - { - PulseForce = 0; - if (PulseForceCount > 0) - PulseForceCount--; - } - EnginePower = Ft * (1.0 + Vel); - break; - } // WheelsDriven - - case TEngineType::ElectricSeriesMotor: - { - // enrot:=Transmision.Ratio*nrot; - // yB: szereg dwoch sekcji w ET42 - if (TrainType == dt_ET42 && Imax == ImaxHi) - EngineVoltage = EngineVoltage / 2.0; - Mm = Momentum(Current(enrot, EngineVoltage)); // oblicza tez prad p/slinik - - if (TrainType == dt_ET42) - { - if (Imax == ImaxHi) - EngineVoltage = EngineVoltage * 2; - if (DynamicBrakeFlag && abs(Im) > 300) // przeiesione do mover.cpp - FuseOff(); - } - if (DynamicBrakeType == dbrake_automatic && DynamicBrakeFlag) - { - if (TUHEX_Stages > 0) // hamowanie wielostopniowe, nadpisuje wartości domyślne - { - if (Vel > 100) - TUHEX_StageActual = std::min(TUHEX_StageActual, 1); - switch (TUHEX_StageActual) - { - case 1: - TUHEX_Sum = TUHEX_Sum1; - DynamicBrakeRes = DynamicBrakeRes1; - break; - case 2: - TUHEX_Sum = TUHEX_Sum2; - DynamicBrakeRes = DynamicBrakeRes1; - break; - case 3: - TUHEX_Sum = TUHEX_Sum3; - if (Vadd > 0.99 * TUHEX_MaxIw && DynamicBrakeRes == DynamicBrakeRes1) - TUHEX_ResChange = true; - if (TUHEX_ResChange && Vadd < 0.5 * TUHEX_MaxIw) - { - TUHEX_ResChange = false; - DynamicBrakeRes = DynamicBrakeRes2; - } - break; - default: - DynamicBrakeRes = DynamicBrakeRes1; - TUHEX_Sum = 0; - break; - } - } - if (Vadd + abs(Im) > TUHEX_Sum + TUHEX_Diff || Hamulec->GetEDBCP() < 0.25 || TUHEX_ResChange || (TUHEX_StageActual == 0 && TUHEX_Stages > 0)) - { - Vadd -= 500.0 * dt; - if (Vadd < TUHEX_MinIw) - { - Vadd = 0; - DynamicBrakeFlag = false; - } - } - else if (DynamicBrakeFlag && Vadd + abs(Im) < TUHEX_Sum - TUHEX_Diff) - { - Vadd += 70.0 * dt; - Vadd = std::min(std::max(Vadd, TUHEX_MinIw), TUHEX_MaxIw); - } - if (Vadd > 0) - Mm = MomentumF(Im, Vadd, 0); - } - - if (TrainType == dt_ET22 && DelayCtrlFlag) // szarpanie przy zmianie układu w byku - Mm = Mm * RList[MainCtrlActualPos].Bn / (RList[MainCtrlActualPos].Bn + 1); // zrobione w momencie, żeby nie dawac elektryki w przeliczaniu sił - - if (abs(Im) > Imax) - Vhyp += dt; //*(abs(Im) / Imax - 0.9) * 10; // zwieksz czas oddzialywania na PN - else - Vhyp = 0; - if (Vhyp > CtrlDelay / 2) // jesli czas oddzialywania przekroczony - FuseOff(); // wywalanie bezpiecznika z powodu przetezenia silnikow - - if ((DynamicBrakeType == dbrake_automatic || DynamicBrakeType == dbrake_switch) && DynamicBrakeFlag) - Itot = Im * 2; // 2x2 silniki w EP09 - else if (TrainType == dt_EZT && Imin == IminLo && ScndS) // yBARC - boczniki na szeregu poprawnie - Itot = Im; - else - Itot = Im * RList[MainCtrlActualPos].Bn; // prad silnika * ilosc galezi - Mw = Mm * Transmision.Ratio * Transmision.Efficiency; - Fw = Mw * 2.0 / WheelDiameter; - Ft = Fw * NPoweredAxles; // sila trakcyjna - break; - } - - case TEngineType::DieselEngine: - { - Mw = dmoment * dtrans * Transmision.Efficiency; // dmoment i dtrans policzone przy okazji enginerotation - if (hydro_R && hydro_R_Placement == 0) - Mw -= dizel_MomentumRetarder(nrot * Transmision.Ratio, dt) * Transmision.Ratio * Transmision.Efficiency; - Fw = Mw * 2.0 / WheelDiameter / NPoweredAxles; - Ft = Fw * NPoweredAxles; // sila trakcyjna - Ft = Ft * DirAbsolute; // DirActive*CabActive; - break; - } - - case TEngineType::DieselElectric: // youBy - { - // tmpV:=V*CabActive*DirActive; - auto const tmpV{nrot * Pirazy2 * 0.5 * WheelDiameter * DirAbsolute}; //*CabActive*DirActive; - auto tempUmax = 0.0; - auto tempImax = 0.0; - auto tempPmax = 0.0; - // jazda manewrowa - if (EIMCtrlType > 0) // sterowanie cyfrowe - { - auto eimic_positive = std::max(0.0, eimic_real); - auto const rpmratio{EngineRPMRatio()}; - tempImax = DElist[MainCtrlPosNo].Imax * eimic_positive; - tempUmax = DElist[MainCtrlPosNo].Umax * std::min(eimic_positive, rpmratio); - tempPmax = DElist[MainCtrlPosNo].GenPower * std::min(eimic_positive, rpmratio); - tmp = tempPmax; - if (true == StLinFlag) - { - - if (tmpV < Vhyp * tempPmax / DElist[MainCtrlPosNo].GenPower) - { - // czy na czesci prostej, czy na hiperboli - Ft = - (Ftmax - (Ftmax - 1000.0 * DElist[MainCtrlPosNo].GenPower / (Vhyp + Vadd)) * (tmpV / Vhyp) / PowerCorRatio) * eimic_positive; // posratio - bo sila jakos tam sie rozklada - } - else - { - // na hiperboli - // 1.107 - wspolczynnik sredniej nadwyzki Ft w symku nad charakterystyka - Ft = 1000.0 * tempPmax / (tmpV + Vadd) / PowerCorRatio; // tu jest zawarty stosunek mocy - } - } - else - Ft = 0; // jak nastawnik na zero, to sila tez zero - - PosRatio = tempPmax / DElist[MainCtrlPosNo].GenPower; - } - else if (true == ShuntMode) - { - if (true == StLinFlag) - { - EngineVoltage = SST[MainCtrlPos].Umax * AnPos + SST[MainCtrlPos].Umin * (1.0 - AnPos); - // NOTE: very crude way to approximate power generated at current rpm instead of instant top output - // NOTE, TODO: doesn't take into account potentially increased revolutions if heating is on, fix it - tmp = EngineRPMRatio() * (SST[MainCtrlPos].Pmax * AnPos) + SST[MainCtrlPos].Pmin * (1.0 - AnPos); - Ft = tmp * 1000.0 / (abs(tmpV) + 1.6); - } - else - { - EngineVoltage = 0; - Ft = 0; - } - PosRatio = 1; - } - else // jazda ciapongowa - { - auto power = Power; - tempImax = DElist[MainCtrlPos].Imax; - tempUmax = DElist[MainCtrlPos].Umax; - if (true == Heating) - { - power -= HeatingPower; - } - if (power < 0.0) - { - power = 0.0; - } - // NOTE: very crude way to approximate power generated at current rpm instead of instant top output - // NOTE, TODO: doesn't take into account potentially increased revolutions if heating is on, fix it - auto const currentgenpower{(DElist[MainCtrlPos].RPM > 0 ? DElist[MainCtrlPos].GenPower * (60.0 * enrot / DElist[MainCtrlPos].RPM) : 0.0)}; - - tmp = std::min(power, currentgenpower); - - PosRatio = currentgenpower / DElist[MainCtrlPosNo].GenPower; - // stosunek mocy teraz do mocy max - // NOTE: Mains in this context is working diesel engine - if (true == StLinFlag) - { - - if (tmpV < Vhyp * power / DElist[MainCtrlPosNo].GenPower) - { - // czy na czesci prostej, czy na hiperboli - Ft = (Ftmax - (Ftmax - 1000.0 * DElist[MainCtrlPosNo].GenPower / (Vhyp + Vadd)) * (tmpV / Vhyp) / PowerCorRatio) * PosRatio; // posratio - bo sila jakos tam sie rozklada - } - else - { - // na hiperboli - // 1.107 - wspolczynnik sredniej nadwyzki Ft w symku nad charakterystyka - Ft = 1000.0 * tmp / (tmpV + Vadd) / PowerCorRatio; // tu jest zawarty stosunek mocy - } - } - else - Ft = 0; // jak nastawnik na zero, to sila tez zero - - PosRatio = tmp / DElist[MainCtrlPosNo].GenPower; - } - - if (FuseFlag) - Ft = 0; - else - Ft = Ft * DirAbsolute; // DirActive * CabActive; //zwrot sily i jej wartosc - Fw = Ft / NPoweredAxles; // sila na obwodzie kola - Mw = Fw * WheelDiameter / 2.0; // moment na osi kola - Mm = Mw / Transmision.Ratio; // moment silnika trakcyjnego - - // with MotorParam[ScndCtrlPos] do - if (abs(Mm) > motor_param(ScndCtrlPos).fi) - Im = NPoweredAxles * abs(abs(Mm) / motor_param(ScndCtrlPos).mfi + motor_param(ScndCtrlPos).mIsat); - else - Im = NPoweredAxles * sqrt(abs(Mm * motor_param(ScndCtrlPos).Isat)); - - if (ShuntMode) - { - EnginePower = EngineVoltage * Im / 1000.0; - if (EnginePower > tmp) - { - EnginePower = tmp; - EngineVoltage = EnginePower * 1000.0 / Im; - } - if (EnginePower < tmp) - { - Ft *= EnginePower / tmp; - } - } - else - { - if (abs(Im) > tempImax) - { // nie ma nadmiarowego, tylko Imax i zwarcie na pradnicy - Ft = Ft / Im * tempImax; - Im = tempImax; - } - - if (Im > 0) - { - // jak pod obciazeniem - if (true == Flat) - { - // ograniczenie napiecia w pradnicy - plaszczak u gory - EngineVoltage = 1000.0 * tmp / std::abs(Im); - } - else - { - auto tempMCP = EIMCtrlType > 0 ? 1 + 99 * std::max(1.0, eimic_real) : MainCtrlPos; - auto tempMCPN = EIMCtrlType > 0 ? 100 : MainCtrlPosNo; - // charakterystyka pradnicy obcowzbudnej (elipsa) - twierdzenie Pitagorasa - EngineVoltage = std::sqrt(std::abs(square(tempUmax) - square(tempUmax * Im / tempImax))) * (tempMCP - 1) + (1.0 - Im / tempImax) * tempUmax * (tempMCPN - tempMCP); - EngineVoltage /= tempMCPN - 1; - EngineVoltage = safe_clamp(EngineVoltage, Im * 0.05, 1000.0 * tmp / std::abs(Im)); - } - } - - if (EngineVoltage > tempUmax || Im == 0) - { - // gdy wychodzi za duze napiecie albo przy biegu jalowym (jest cos takiego?) - EngineVoltage = tempUmax * (ConverterFlag ? 1 : 0); - } - - EnginePower = EngineVoltage * Im / 1000.0; - /* - // power curve drop - // NOTE: disabled for the time being due to side-effects - if( ( tmpV > 1 ) && ( EnginePower < tmp ) ) { - Ft = std::lerp( - Ft, EnginePower / tmp, - std::clamp( tmpV - 1.0, 0.0, 1.0 ) ); - } - */ - } - - if (Imax > 1 && Im > Imax) - FuseOff(); - if (FuseFlag) - EngineVoltage = 0; - - // przekazniki bocznikowania, kazdy inny dla kazdej pozycji - if (false == StLinFlag || ShuntMode) - { - ScndCtrlPos = 0; - } - else - { - if (AutoRelayFlag) - { - - auto const shuntfieldstate{ScndCtrlPos}; - - switch (RelayType) - { - - case 0: - { - - if (ScndCtrlPos < ScndCtrlPosNo && Im <= MPTRelay[ScndCtrlPos].Iup * PosRatio) - { - ++ScndCtrlPos; - } - if (ScndCtrlPos > 0 && Im >= MPTRelay[ScndCtrlPos].Idown * PosRatio) - { - --ScndCtrlPos; - } - break; - } - case 1: - { - - if (ScndCtrlPos < ScndCtrlPosNo && MPTRelay[ScndCtrlPos].Iup < Vel) - { - ++ScndCtrlPos; - } - if (ScndCtrlPos > 0 && MPTRelay[ScndCtrlPos].Idown > Vel) - { - --ScndCtrlPos; - } - break; - } - case 2: - { - - if (ScndCtrlPos < ScndCtrlPosNo && MPTRelay[ScndCtrlPos].Iup < Vel && EnginePower < tmp * 0.99) - { - ++ScndCtrlPos; - } - if (ScndCtrlPos > 0 && MPTRelay[ScndCtrlPos].Idown < Im) - { - --ScndCtrlPos; - } - break; - } - case 41: - { - if (ScndCtrlPos < ScndCtrlPosNo && MainCtrlPos == MainCtrlPosNo && tmpV * 3.6 > MPTRelay[ScndCtrlPos].Iup) - { - ++ScndCtrlPos; - enrot = enrot * 0.73; - } - if (ScndCtrlPos > 0 && Im > MPTRelay[ScndCtrlPos].Idown) - { - --ScndCtrlPos; - } - break; - } - case 45: - { - if (ScndCtrlPos < ScndCtrlPosNo && MainCtrlPos >= 11) - { - - if (Im < MPTRelay[ScndCtrlPos].Iup) - { - ++ScndCtrlPos; - } - // check for cases where the speed drops below threshold for level 2 or 3 - if (ScndCtrlPos > 1 && Vel < MPTRelay[ScndCtrlPos - 1].Idown) - { - --ScndCtrlPos; - } - } - // malenie - if (ScndCtrlPos > 0 && MainCtrlPos < 11) - { - - if (ScndCtrlPos == 1) - { - if (Im > MPTRelay[ScndCtrlPos - 1].Idown) - { - --ScndCtrlPos; - } - } - else - { - if (Vel < MPTRelay[ScndCtrlPos].Idown) - { - --ScndCtrlPos; - } - } - } - // 3rd level drops with master controller at position lower than 10... - if (MainCtrlPos < 11) - { - ScndCtrlPos = std::min(2, ScndCtrlPos); - } - // ...and below position 7 field shunt drops altogether - if (MainCtrlPos < 8) - { - ScndCtrlPos = 0; - } - /* - // crude woodward approximation; difference between rpm for consecutive positions is ~5% - // so we get full throttle until ~half way between desired and previous position, or zero on rpm reduction - auto const woodward { std::clamp( - ( DElist[ MainCtrlPos ].RPM / ( enrot * 60.0 ) - 1.0 ) * 50.0, - 0.0, 1.0 ) }; - */ - break; - } - case 46: - { - // wzrastanie - if (MainCtrlPos >= 12 && ScndCtrlPos < ScndCtrlPosNo) - { - if (ScndCtrlPos % 2 == 0) - { - if (MPTRelay[ScndCtrlPos].Iup > Im) - { - ++ScndCtrlPos; - } - } - else - { - if (MPTRelay[ScndCtrlPos - 1].Iup > Im && MPTRelay[ScndCtrlPos].Iup < Vel) - { - ++ScndCtrlPos; - } - } - } - // malenie - if (MainCtrlPos < 12 && ScndCtrlPos > 0 && Vel < 50.0) - { - // above 50 km/h already active shunt field can be maintained until lower controller setting - if (ScndCtrlPos % 2 == 0) - { - if (MPTRelay[ScndCtrlPos].Idown < Im) - { - --ScndCtrlPos; - } - } - else - { - if (MPTRelay[ScndCtrlPos + 1].Idown < Im && MPTRelay[ScndCtrlPos].Idown > Vel) - { - --ScndCtrlPos; - } - } - } - if (MainCtrlPos < 11) - { - ScndCtrlPos = std::min(2, ScndCtrlPos); - } - if (MainCtrlPos < 8) - { - ScndCtrlPos = 0; - } - break; - } - default: - { - break; - } - } // switch RelayType - - if (ScndCtrlPos != shuntfieldstate) - { - SetFlag(SoundFlag, sound::relay | sound::shuntfield); - } - } - } - break; - } // DieselElectric - - case TEngineType::ElectricInductionMotor: - { - if (MainCircuitPowered() && !SecuritySystem.is_engine_blocked()) - { - double ActiveInverters = 0.0; - for (auto const &inv : Inverters) - { - if (inv.IsActive) - ActiveInverters += 1.0; - } - InvertersRatio = ActiveInverters / (double)InvertersNo; - if (EIM_Pmax_Table.size() > 1) - { - eimc[eimc_p_Pmax] = TableInterpolation(EIM_Pmax_Table, Vel); - } - // tempomat - if (ScndCtrlPosNo == 4 && SpeedCtrlTypeTime) - { - SpeedCtrlUnit.IsActive = SpeedCtrlValue > 0; - switch (ScndCtrlPos) - { - case 0: - NewSpeed = 0; - SpeedCtrlValue = 0; - SpeedCtrlTimer = 10; - break; - case 1: - if (SpeedCtrlTimer > SpeedCtrlDelay) - { - SpeedCtrlTimer = 0; - NewSpeed -= 10; - if (NewSpeed < 0) - NewSpeed = 0; - } - else - SpeedCtrlTimer += dt; - break; - case 2: - SpeedCtrlTimer = 10; - SpeedCtrlValue = NewSpeed; - break; - case 3: - if (SpeedCtrlTimer > SpeedCtrlDelay) - { - SpeedCtrlTimer = 0; - NewSpeed += 10; - if (NewSpeed > Vmax) - NewSpeed = Vmax; - } - else - SpeedCtrlTimer += dt; - break; - case 4: - NewSpeed = Vmax; - SpeedCtrlValue = Vmax; - SpeedCtrlTimer = 10; - break; - default: - break; - } - } - else if (ScndCtrlPosNo > 1) - { - if (ScndCtrlPos != NewSpeed) - { - - SpeedCtrlTimer = 0; - NewSpeed = ScndCtrlPos; - } - else - { - SpeedCtrlTimer += dt; - if (SpeedCtrlTimer > SpeedCtrlDelay) - { - auto NewSCAP = static_cast((float)ScndCtrlPos / (float)ScndCtrlPosNo * Vmax); - if (NewSCAP != SpeedCtrlValue) - { - SpeedCtrlValue = NewSCAP; - // SendCtrlToNext("SpeedCntrl", SpeedCtrlValue, CabActive); - } - } - } - SpeedCtrlUnit.IsActive = SpeedCtrlValue > 0; - } - double edBCP = Hamulec->GetEDBCP(); - auto const localbrakeactive{CabOccupied != 0 && LocHandle->GetCP() > 0.25}; - // gdy SplitEDPneumaticBrake jest aktywne, hamulec pomocniczy (LocalBrake) NIE wymusza - // zalaczenia hamulca elektrodynamicznego - ED jest sterowany wlasnym nastawnikiem - auto const dynbrakectrlactive{SplitEDPneumaticBrake && DynamicBrakeRatio() > 0.01 && DynamicBrakeAvailable()}; - auto const localbrakeforED{SplitEDPneumaticBrake ? false : localbrakeactive}; - if (false == Doors.instances[side::left].is_closed || false == Doors.instances[side::right].is_closed || - (Doors.permit_needed && (Doors.instances[side::left].open_permit || Doors.instances[side::right].open_permit))) - { - DynamicBrakeFlag = true; - } - else if ((edBCP < 0.25 && false == localbrakeforED && false == dynbrakectrlactive && AnPos < 0.01) || - (edBCP < 0.25 && ShuntModeAllow && false == dynbrakectrlactive && LocalBrakePosA < 0.01)) - DynamicBrakeFlag = false; - else if (BrakePress > 0.25 && edBCP > 0.25 || localbrakeforED || AnPos > 0.02 || dynbrakectrlactive) - DynamicBrakeFlag = true; - edBCP = Hamulec->GetEDBCP() * eimc[eimc_p_abed]; // stala napedu - if (DynamicBrakeFlag) - { - // ustalanie współczynnika blendingu do luzowania hamulca PN - if (eimv[eimv_Fmax] * Sign(V) * DirAbsolute < -1) - { - PosRatio = -Sign(V) * DirAbsolute * eimv[eimv_Fr] / (eimc[eimc_p_Fh] * std::max(edBCP, std::max(0.01, Hamulec->GetEDBCP())) / MaxBrakePress[0]); - PosRatio = std::clamp(PosRatio, 0.0, 1.0); - } - else - { - PosRatio = 0; - } - PosRatio = static_cast(Round(20.0 * PosRatio)) / 20.0; // stopniowanie PN/ED - if (PosRatio < 19.5 / 20.0) - PosRatio *= 0.9; - Hamulec->SetED(std::max(0.0, std::min(PosRatio, 1.0))); // ustalenie stopnia zmniejszenia ciśnienia - // ustalanie siły hamowania ED - if (Hamulec->GetEDBCP() > 0.25 && eimc[eimc_p_abed] < 0.001 || ActiveInverters < InvertersNo) // jeśli PN wyłącza ED - { - PosRatio = 0; - eimv[eimv_Fzad] = 0; - } - else - { - // strefa wylaczenia ED (Vh0..Vh1) - mnoznik 0..1 zaleznie od predkosci - double const vhRamp = std::max(0.0, std::min(1.0, (Vel - eimc[eimc_p_Vh0]) / (eimc[eimc_p_Vh1] - eimc[eimc_p_Vh0]))); - if (SplitEDPneumaticBrake) - { - // w trybie split LocalBrake nie zaleca ED; uzywany jest DynamicBrakeCtrl - // oraz zwykle zapotrzebowanie z hamulca zespolonego (edBCP) - double const edLeverDemand = DynamicBrakeRatio(); - PosRatio = -std::max(std::max(edLeverDemand, std::min(edBCP / MaxBrakePress[0], 1.0)), AnPos) * vhRamp; - eimv[eimv_Fzad] = -std::min(1.0, std::max(edLeverDemand, edBCP / MaxBrakePress[0])); - } - else - { - PosRatio = -std::max(std::min(edBCP * 1.0 / MaxBrakePress[0], 1.0), AnPos) * vhRamp; - eimv[eimv_Fzad] = -std::min(1.0, std::max(LocalBrakeRatio(), edBCP / MaxBrakePress[0])); - } - } - tmp = 5; - } - else - { - PosRatio = std::max(eimic_real, 0.); - eimv[eimv_Fzad] = PosRatio; - if (Flat && eimc[eimc_p_F0] * eimv[eimv_Fful] > 0) - PosRatio = std::min(PosRatio * eimc[eimc_p_F0] / eimv[eimv_Fful], 1.); - /* if (ScndCtrlActualPos > 0) //speed control - if (Vmax < 250) - PosRatio = std::min(PosRatio, std::max(-1, 0.5 * (ScndCtrlActualPos - Vel))); - else - PosRatio = - std::min(PosRatio, std::max(-1, 0.5 * (ScndCtrlActualPos * 2 - Vel))); */ - // PosRatio = 1.0 * (PosRatio * 0 + 1) * PosRatio; // 1 * 1 * PosRatio = PosRatio - Hamulec->SetED(0); - // (Hamulec as TLSt).SetLBP(LocBrakePress); - tmp = 4; // szybkie malenie, powolne wzrastanie - } - // NOTE: the commands to operate the sandbox are likely to conflict with other similar ai decisions - // TODO: gather these in single place so they can be resolved together - if (SlippingWheels) - { - PosRatio = 0; - tmp = 10; - SandboxAuto(true, range_t::unit); - } // przeciwposlizg - else - { - // switch sandbox off - SandboxAuto(false, range_t::unit); - } - if (ActiveInverters == 0.0) - { - PosRatio = 0; - eimv_pr = 0; - } - - eimv_pr += std::max(std::min(PosRatio - eimv_pr, 0.02), -0.02) * 12 * tmp /*2{+4*byte(PosRatio= 0) - Vadd *= 1.0 - 2.0 * dt; - else if (std::abs(EngineVoltage) < EnginePowerSource.CollectorParameters.MaxV) - Vadd *= 1.0 - dt; - else - Vadd = std::max(Vadd * (1.0 - 0.2 * dt), 0.007 * (std::abs(EngineVoltage) - (EnginePowerSource.CollectorParameters.MaxV - 100))); - Itot = eimv[eimv_Ipoj] * (0.01 + std::min(0.99, 0.99 - Vadd)); - - EnginePower = abs(eimv[eimv_Ic] * eimv[eimv_U] * NPoweredAxles) / 1000; - // power inverters - auto const tmpV{std::abs(eimv[eimv_fp])}; - auto const useFFEDList = FFEDListSize > 0 && DynamicBrakeFlag; - auto const list = useFFEDList ? FFEDlist : FFlist; - - if (auto const listSize = useFFEDList ? FFEDListSize : FFListSize; listSize > 0 && std::abs(eimv[eimv_If]) > 1.0 && tmpV > 0.0001) - { - - int i = 0; - while (i < listSize - 1 && list[i + 1].v < tmpV) - { - ++i; - } - InverterFrequency = (tmpV - list[i].v) / std::max(1.0, list[i + 1].v - list[i].v) * (list[i + 1].freq - list[i].freq) + list[i].freq; - } - else - { - InverterFrequency = 0.0; - } - - Mm = eimv[eimv_M] * DirAbsolute; - Mw = Mm * Transmision.Ratio * Transmision.Efficiency; - Fw = Mw * 2.0 / WheelDiameter; - Ft = Fw * NPoweredAxles * InvertersRatio; - eimv[eimv_Fr] = DirAbsolute * Ft / 1000; - } // mains - else - { - for (auto &inv : Inverters) - { - inv.Freal = 0.0; - inv.IsActive = false; - } - Im = 0.0; - Mm = 0.0; - Mw = 0.0; - Fw = 0.0; - Ft = 0.0; - Itot = 0.0; - eimv_pr = 0.0; - EnginePower = 0.0; - { - for (auto &eimvvalue : eimv) - eimvvalue = 0.0; - } - Hamulec->SetED(0.0); - InverterFrequency = 0.0; //(Hamulec as TLSt).SetLBP(LocBrakePress); - } - break; - } // ElectricInductionMotor - - case TEngineType::None: - default: - { - break; - } - } // case EngineType - - if (EngineType == TEngineType::DieselElectric) +void TMoverParameters::DumbTractionForce(double const PosRatio) +{ + if (Mains && CabActive != 0) { - // rough approximation of extra effort to overcome friction etc - EnginePower += EngineRPMRatio() * 0.15 * DElist[MainCtrlPosNo].GenPower; + if (Vel > 0.1) + { + Ft = std::min(1000.0 * Power / std::abs(V), Ftmax) * PosRatio; + } + else + { + Ft = Ftmax * PosRatio; + } + Ft = Ft * DirAbsolute; // DirActive*CabActive; + } + else + { + Ft = 0; + } +} + +void TMoverParameters::WheelsDrivenTractionForce(double dt) +{ + if (EnginePowerSource.SourceType == TPowerSource::InternalSource && EnginePowerSource.PowerType == TPowerType::BioPower) + Ft = Sign(sin(eAngle)) * PulseForce * Transmision.Ratio; + PulseForceTimer = PulseForceTimer + dt; + if (PulseForceTimer > CtrlDelay) + { + PulseForce = 0; + if (PulseForceCount > 0) + PulseForceCount--; + } + EnginePower = Ft * (1.0 + Vel); +} + +void TMoverParameters::SeriesMotorTractionForce(double dt) +{ + // enrot:=Transmision.Ratio*nrot; + // yB: szereg dwoch sekcji w ET42 + if (TrainType == dt_ET42 && Imax == ImaxHi) + EngineVoltage = EngineVoltage / 2.0; + Mm = Momentum(Current(enrot, EngineVoltage)); // oblicza tez prad p/slinik + + if (TrainType == dt_ET42) + { + if (Imax == ImaxHi) + EngineVoltage = EngineVoltage * 2; + if (DynamicBrakeFlag && abs(Im) > 300) // przeiesione do mover.cpp + FuseOff(); + } + if (DynamicBrakeType == dbrake_automatic && DynamicBrakeFlag) + { + SeriesMotorDynamicBrake(dt); } - return Ft; + if (TrainType == dt_ET22 && DelayCtrlFlag) // szarpanie przy zmianie układu w byku + Mm = Mm * RList[MainCtrlActualPos].Bn / (RList[MainCtrlActualPos].Bn + 1); // zrobione w momencie, żeby nie dawac elektryki w przeliczaniu sił + + if (abs(Im) > Imax) + Vhyp += dt; //*(abs(Im) / Imax - 0.9) * 10; // zwieksz czas oddzialywania na PN + else + Vhyp = 0; + if (Vhyp > CtrlDelay / 2) // jesli czas oddzialywania przekroczony + FuseOff(); // wywalanie bezpiecznika z powodu przetezenia silnikow + + if ((DynamicBrakeType == dbrake_automatic || DynamicBrakeType == dbrake_switch) && DynamicBrakeFlag) + Itot = Im * 2; // 2x2 silniki w EP09 + else if (TrainType == dt_EZT && Imin == IminLo && ScndS) // yBARC - boczniki na szeregu poprawnie + Itot = Im; + else + Itot = Im * RList[MainCtrlActualPos].Bn; // prad silnika * ilosc galezi + Mw = Mm * Transmision.Ratio * Transmision.Efficiency; + Fw = Mw * 2.0 / WheelDiameter; + Ft = Fw * NPoweredAxles; // sila trakcyjna +} + +// the automatic dynamic brake of the series motors: the excitation current, by the stages of the ep brake (TUHEX) +void TMoverParameters::SeriesMotorDynamicBrake(double dt) +{ + if (TUHEX_Stages > 0) // hamowanie wielostopniowe, nadpisuje wartości domyślne + { + if (Vel > 100) + TUHEX_StageActual = std::min(TUHEX_StageActual, 1); + switch (TUHEX_StageActual) + { + case 1: + TUHEX_Sum = TUHEX_Sum1; + DynamicBrakeRes = DynamicBrakeRes1; + break; + case 2: + TUHEX_Sum = TUHEX_Sum2; + DynamicBrakeRes = DynamicBrakeRes1; + break; + case 3: + TUHEX_Sum = TUHEX_Sum3; + if (Vadd > 0.99 * TUHEX_MaxIw && DynamicBrakeRes == DynamicBrakeRes1) + TUHEX_ResChange = true; + if (TUHEX_ResChange && Vadd < 0.5 * TUHEX_MaxIw) + { + TUHEX_ResChange = false; + DynamicBrakeRes = DynamicBrakeRes2; + } + break; + default: + DynamicBrakeRes = DynamicBrakeRes1; + TUHEX_Sum = 0; + break; + } + } + if (Vadd + abs(Im) > TUHEX_Sum + TUHEX_Diff || Hamulec->GetEDBCP() < 0.25 || TUHEX_ResChange || (TUHEX_StageActual == 0 && TUHEX_Stages > 0)) + { + Vadd -= 500.0 * dt; + if (Vadd < TUHEX_MinIw) + { + Vadd = 0; + DynamicBrakeFlag = false; + } + } + else if (DynamicBrakeFlag && Vadd + abs(Im) < TUHEX_Sum - TUHEX_Diff) + { + Vadd += 70.0 * dt; + Vadd = std::min(std::max(Vadd, TUHEX_MinIw), TUHEX_MaxIw); + } + if (Vadd > 0) + Mm = MomentumF(Im, Vadd, 0); +} + +void TMoverParameters::DieselEngineTractionForce(double dt, double const dmoment, double const dtrans) +{ + Mw = dmoment * dtrans * Transmision.Efficiency; // dmoment i dtrans policzone przy okazji enginerotation + if (hydro_R && hydro_R_Placement == 0) + Mw -= dizel_MomentumRetarder(nrot * Transmision.Ratio, dt) * Transmision.Ratio * Transmision.Efficiency; + Fw = Mw * 2.0 / WheelDiameter / NPoweredAxles; + Ft = Fw * NPoweredAxles; // sila trakcyjna + Ft = Ft * DirAbsolute; // DirActive*CabActive; +} + +// tmp: the revolutions the engine aims at [1/s], see UpdateEngineRevolutions() +void TMoverParameters::DieselElectricTractionForce(double tmp) +{ + double PosRatio; + // tmpV:=V*CabActive*DirActive; + auto const tmpV{nrot * Pirazy2 * 0.5 * WheelDiameter * DirAbsolute}; //*CabActive*DirActive; + auto tempUmax = 0.0; + auto tempImax = 0.0; + // jazda manewrowa + if (EIMCtrlType > 0) // sterowanie cyfrowe + { + tmp = DieselElectricDigitalForce(tmpV, tempUmax, tempImax); + PosRatio = tmp / DElist[MainCtrlPosNo].GenPower; + } + else if (true == ShuntMode) + { + DieselElectricShuntForce(tmpV, tmp); + PosRatio = 1; + } + else // jazda ciapongowa + { + auto power = Power; + tempImax = DElist[MainCtrlPos].Imax; + tempUmax = DElist[MainCtrlPos].Umax; + if (true == Heating) + { + power -= HeatingPower; + } + power = std::max(power, 0.0); + // NOTE: very crude way to approximate power generated at current rpm instead of instant top output + // NOTE, TODO: doesn't take into account potentially increased revolutions if heating is on, fix it + auto const currentgenpower{(DElist[MainCtrlPos].RPM > 0 ? DElist[MainCtrlPos].GenPower * (60.0 * enrot / DElist[MainCtrlPos].RPM) : 0.0)}; + + tmp = std::min(power, currentgenpower); + + PosRatio = currentgenpower / DElist[MainCtrlPosNo].GenPower; + // stosunek mocy teraz do mocy max + // NOTE: Mains in this context is working diesel engine + if (true == StLinFlag) + Ft = DieselElectricForce(tmpV, power, PosRatio, tmp); + else + Ft = 0; // jak nastawnik na zero, to sila tez zero + + PosRatio = tmp / DElist[MainCtrlPosNo].GenPower; + } + + if (FuseFlag) + Ft = 0; + else + Ft = Ft * DirAbsolute; // DirActive * CabActive; //zwrot sily i jej wartosc + Fw = Ft / NPoweredAxles; // sila na obwodzie kola + Mw = Fw * WheelDiameter / 2.0; // moment na osi kola + Mm = Mw / Transmision.Ratio; // moment silnika trakcyjnego + + Im = dieselelectric_motor_current(Mm); + + if (ShuntMode) + { + DieselElectricShuntPower(tmp); + } + else + { + DieselElectricGenerator(tmp, tempUmax, tempImax); + } + + if (Imax > 1 && Im > Imax) + FuseOff(); + if (FuseFlag) + EngineVoltage = 0; + + // przekazniki bocznikowania, kazdy inny dla kazdej pozycji + if (auto const fieldshuntingcontrol{fieldshunting::diesel_electric(AutoRelayType, FieldShuntSwitch, AutoRelayFlag)}; + false == StLinFlag || ShuntMode || fieldshuntingcontrol == fieldshunting::control::off) + { + ScndCtrlPos = 0; + } + else if (AutoRelayFlag) + { + // the shunting relays set the field shunting (fieldshunting::control::automatic) + ShuntFieldRelaysCheck(tmpV, PosRatio, tmp); + } +} + +// the tractive force of a diesel-electric shunting, by the generator's table SST and the shunting controller AnPos; +// tmp, the power the generator gives +void TMoverParameters::DieselElectricShuntForce(double const tmpV, double &tmp) +{ + if (true == StLinFlag) + { + EngineVoltage = SST[MainCtrlPos].Umax * AnPos + SST[MainCtrlPos].Umin * (1.0 - AnPos); + // NOTE: very crude way to approximate power generated at current rpm instead of instant top output + // NOTE, TODO: doesn't take into account potentially increased revolutions if heating is on, fix it + tmp = EngineRPMRatio() * (SST[MainCtrlPos].Pmax * AnPos) + SST[MainCtrlPos].Pmin * (1.0 - AnPos); + Ft = tmp * 1000.0 / (abs(tmpV) + 1.6); + } + else + { + EngineVoltage = 0; + Ft = 0; + } +} + +// the tractive force of a diesel-electric set by the integrated controller, at the speed tmpV; the generator's +// voltage and current limits too. returns the power the generator gives +double TMoverParameters::DieselElectricDigitalForce(double const tmpV, double &tempUmax, double &tempImax) +{ + auto eimic_positive = std::max(0.0, eimic_real); + auto const rpmratio{EngineRPMRatio()}; + tempImax = DElist[MainCtrlPosNo].Imax * eimic_positive; + tempUmax = DElist[MainCtrlPosNo].Umax * std::min(eimic_positive, rpmratio); + auto const tempPmax = DElist[MainCtrlPosNo].GenPower * std::min(eimic_positive, rpmratio); + if (true == StLinFlag) + Ft = DieselElectricForce(tmpV, tempPmax, eimic_positive, tempPmax); + else + Ft = 0; // jak nastawnik na zero, to sila tez zero + return tempPmax; +} + +// the tractive force of a diesel-electric at the speed tmpV: on the straight part of its characteristic under the speed +// Vhyp gives at the power LinePower, at the share Ratio of it, on the hyperbola of the power HyperbolaPower over it +double TMoverParameters::DieselElectricForce(double const tmpV, double const LinePower, double const Ratio, double const HyperbolaPower) const +{ + if (tmpV < Vhyp * LinePower / DElist[MainCtrlPosNo].GenPower) + { + // czy na czesci prostej, czy na hiperboli + return (Ftmax - (Ftmax - 1000.0 * DElist[MainCtrlPosNo].GenPower / (Vhyp + Vadd)) * (tmpV / Vhyp) / PowerCorRatio) * Ratio; // posratio - bo sila jakos tam sie rozklada + } + // na hiperboli + // 1.107 - wspolczynnik sredniej nadwyzki Ft w symku nad charakterystyka + return 1000.0 * HyperbolaPower / (tmpV + Vadd) / PowerCorRatio; // tu jest zawarty stosunek mocy +} + +// in the shunting mode, the generator's power limited to tmp, the power the engine gives +void TMoverParameters::DieselElectricShuntPower(double const tmp) +{ + EnginePower = EngineVoltage * Im / 1000.0; + if (EnginePower > tmp) + { + EnginePower = tmp; + EngineVoltage = EnginePower * 1000.0 / Im; + } + if (EnginePower < tmp) + { + Ft *= EnginePower / tmp; + } +} + +// the generator's current limited to tempImax and its voltage by its characteristic, under tempUmax and the power tmp +void TMoverParameters::DieselElectricGenerator(double const tmp, double const tempUmax, double const tempImax) +{ + if (abs(Im) > tempImax) + { // nie ma nadmiarowego, tylko Imax i zwarcie na pradnicy + Ft = Ft / Im * tempImax; + Im = tempImax; + } + + if (Im > 0) + { + // jak pod obciazeniem + if (true == Flat) + { + // ograniczenie napiecia w pradnicy - plaszczak u gory + EngineVoltage = 1000.0 * tmp / std::abs(Im); + } + else + { + auto tempMCP = EIMCtrlType > 0 ? 1 + 99 * std::max(1.0, eimic_real) : MainCtrlPos; + auto tempMCPN = EIMCtrlType > 0 ? 100 : MainCtrlPosNo; + // charakterystyka pradnicy obcowzbudnej (elipsa) - twierdzenie Pitagorasa + EngineVoltage = std::sqrt(std::abs(square(tempUmax) - square(tempUmax * Im / tempImax))) * (tempMCP - 1) + (1.0 - Im / tempImax) * tempUmax * (tempMCPN - tempMCP); + EngineVoltage /= tempMCPN - 1; + EngineVoltage = safe_clamp(EngineVoltage, Im * 0.05, 1000.0 * tmp / std::abs(Im)); + } + } + + if (EngineVoltage > tempUmax || Im == 0) + { + // gdy wychodzi za duze napiecie albo przy biegu jalowym (jest cos takiego?) + EngineVoltage = tempUmax * (ConverterFlag ? 1 : 0); + } + + EnginePower = EngineVoltage * Im / 1000.0; + /* + // power curve drop + // NOTE: disabled for the time being due to side-effects + if( ( tmpV > 1 ) && ( EnginePower < tmp ) ) { + Ft = std::lerp( + Ft, EnginePower / tmp, + std::clamp( tmpV - 1.0, 0.0, 1.0 ) ); + } + */ +} + +// the shunt field relays of a diesel-electric, each kind its own conditions on the current, the speed or the +// power (tmp, the power the engine gives) +void TMoverParameters::ShuntFieldRelaysCheck(double const tmpV, double const PosRatio, double const tmp) +{ + auto const shuntfieldstate{ScndCtrlPos}; + + switch (RelayType) + { + + case 0: + { + + if (ScndCtrlPos < ScndCtrlPosNo && Im <= MPTRelay[ScndCtrlPos].Iup * PosRatio) + { + ++ScndCtrlPos; + } + if (ScndCtrlPos > 0 && Im >= MPTRelay[ScndCtrlPos].Idown * PosRatio) + { + --ScndCtrlPos; + } + break; + } + case 1: + { + + if (ScndCtrlPos < ScndCtrlPosNo && MPTRelay[ScndCtrlPos].Iup < Vel) + { + ++ScndCtrlPos; + } + if (ScndCtrlPos > 0 && MPTRelay[ScndCtrlPos].Idown > Vel) + { + --ScndCtrlPos; + } + break; + } + case 2: + { + + ShuntFieldRelaysType2(tmp); + break; + } + case 41: + { + ShuntFieldRelaysType41(tmpV); + break; + } + case 45: + { + ShuntFieldRelaysType45(); + break; + } + case 46: + { + ShuntFieldRelaysType46(); + break; + } + default: + { + break; + } + } // switch RelayType + + if (ScndCtrlPos != shuntfieldstate) + { + SetFlag(SoundFlag, sound::relay | sound::shuntfield); + } +} + +// the relays of type 2: up by the speed while the engine has power to spare (tmp, the power it gives), down by the current +void TMoverParameters::ShuntFieldRelaysType2(double const tmp) +{ + if (ScndCtrlPos < ScndCtrlPosNo && MPTRelay[ScndCtrlPos].Iup < Vel && EnginePower < tmp * 0.99) + { + ++ScndCtrlPos; + } + if (ScndCtrlPos > 0 && MPTRelay[ScndCtrlPos].Idown < Im) + { + --ScndCtrlPos; + } +} + +// the relays of type 41: up by the speed tmpV at full power, the engine slowed down, down by the current +void TMoverParameters::ShuntFieldRelaysType41(double const tmpV) +{ + if (ScndCtrlPos < ScndCtrlPosNo && MainCtrlPos == MainCtrlPosNo && tmpV * 3.6 > MPTRelay[ScndCtrlPos].Iup) + { + ++ScndCtrlPos; + enrot = enrot * 0.73; + } + if (ScndCtrlPos > 0 && Im > MPTRelay[ScndCtrlPos].Idown) + { + --ScndCtrlPos; + } +} + +// the relays of type 45, by the current and the speed: up from the 11th position, at most two under it, none under the 8th +void TMoverParameters::ShuntFieldRelaysType45() +{ + if (ScndCtrlPos < ScndCtrlPosNo && MainCtrlPos >= 11) + { + + if (Im < MPTRelay[ScndCtrlPos].Iup) + { + ++ScndCtrlPos; + } + // check for cases where the speed drops below threshold for level 2 or 3 + if (ScndCtrlPos > 1 && Vel < MPTRelay[ScndCtrlPos - 1].Idown) + { + --ScndCtrlPos; + } + } + // malenie + if (ScndCtrlPos > 0 && MainCtrlPos < 11) + { + + if (ScndCtrlPos == 1) + { + if (Im > MPTRelay[ScndCtrlPos - 1].Idown) + { + --ScndCtrlPos; + } + } + else + { + if (Vel < MPTRelay[ScndCtrlPos].Idown) + { + --ScndCtrlPos; + } + } + } + // 3rd level drops with master controller at position lower than 10... + if (MainCtrlPos < 11) + { + ScndCtrlPos = std::min(2, ScndCtrlPos); + } + // ...and below position 7 field shunt drops altogether + if (MainCtrlPos < 8) + { + ScndCtrlPos = 0; + } + /* + // crude woodward approximation; difference between rpm for consecutive positions is ~5% + // so we get full throttle until ~half way between desired and previous position, or zero on rpm reduction + auto const woodward { std::clamp( + ( DElist[ MainCtrlPos ].RPM / ( enrot * 60.0 ) - 1.0 ) * 50.0, + 0.0, 1.0 ) }; + */ +} + +// the relays of type 46, by the current and the speed: up from the 12th position, down under it below 50 km/h, at most two +// under the 11th, none under the 8th +void TMoverParameters::ShuntFieldRelaysType46() +{ + // wzrastanie + if (MainCtrlPos >= 12 && ScndCtrlPos < ScndCtrlPosNo) + { + ShuntFieldRelaysType46Up(); + } + // malenie + if (MainCtrlPos < 12 && ScndCtrlPos > 0 && Vel < 50.0) + { + ShuntFieldRelaysType46Down(); + } + if (MainCtrlPos < 11) + { + ScndCtrlPos = std::min(2, ScndCtrlPos); + } + if (MainCtrlPos < 8) + { + ScndCtrlPos = 0; + } +} + +// a relay of type 46 down: an even one by the current, an odd one by the current and the speed +void TMoverParameters::ShuntFieldRelaysType46Down() +{ + // above 50 km/h already active shunt field can be maintained until lower controller setting + if (ScndCtrlPos % 2 == 0) + { + if (MPTRelay[ScndCtrlPos].Idown < Im) + { + --ScndCtrlPos; + } + } + else + { + if (MPTRelay[ScndCtrlPos + 1].Idown < Im && MPTRelay[ScndCtrlPos].Idown > Vel) + { + --ScndCtrlPos; + } + } +} + +// a relay of type 46 up: an even one by the current, an odd one by the current and the speed +void TMoverParameters::ShuntFieldRelaysType46Up() +{ + if (ScndCtrlPos % 2 == 0) + { + if (MPTRelay[ScndCtrlPos].Iup > Im) + { + ++ScndCtrlPos; + } + } + else + { + if (MPTRelay[ScndCtrlPos - 1].Iup > Im && MPTRelay[ScndCtrlPos].Iup < Vel) + { + ++ScndCtrlPos; + } + } +} + +void TMoverParameters::InductionMotorTractionForce(double dt) +{ + if (MainCircuitPowered() && !SecuritySystem.is_engine_blocked()) + { + double PosRatio; + double tmp; + double ActiveInverters = 0.0; + for (auto const &inv : Inverters) + { + if (inv.IsActive) + ActiveInverters += 1.0; + } + InvertersRatio = ActiveInverters / (double)InvertersNo; + if (EIM_Pmax_Table.size() > 1) + { + eimc[eimc_p_Pmax] = TableInterpolation(EIM_Pmax_Table, Vel); + } + InductionMotorSpeedControl(dt); + InductionMotorBrakeBlending(ActiveInverters, PosRatio, tmp); + // NOTE: the commands to operate the sandbox are likely to conflict with other similar ai decisions + // TODO: gather these in single place so they can be resolved together + if (SlippingWheels) + { + PosRatio = 0; + tmp = 10; + SandboxAuto(true, range_t::unit); + } // przeciwposlizg + else + { + // switch sandbox off + SandboxAuto(false, range_t::unit); + } + if (ActiveInverters == 0.0) + { + PosRatio = 0; + eimv_pr = 0; + } + + eimv_pr += std::max(std::min(PosRatio - eimv_pr, 0.02), -0.02) * 12 * tmp /*2{+4*byte(PosRatio 1) + { + SpeedControlByPosition(dt); + } +} + +// the speed control set by the position of the second controller, after it's been held for its delay +void TMoverParameters::SpeedControlByPosition(double dt) +{ + if (ScndCtrlPos != NewSpeed) + { + + SpeedCtrlTimer = 0; + NewSpeed = ScndCtrlPos; + } + else + { + SpeedCtrlTimer += dt; + if (SpeedCtrlTimer > SpeedCtrlDelay) + { + auto NewSCAP = static_cast((float)ScndCtrlPos / (float)ScndCtrlPosNo * Vmax); + if (NewSCAP != SpeedCtrlValue) + { + SpeedCtrlValue = NewSCAP; + // SendCtrlToNext("SpeedCntrl", SpeedCtrlValue, CabActive); + } + } + } + SpeedCtrlUnit.IsActive = SpeedCtrlValue > 0; +} + +// the speed control of a four position second controller, by time: the speed set down or up by 10 km/h a step, held, +// or off and at the top +void TMoverParameters::SpeedControlByTime(double dt) +{ + SpeedCtrlUnit.IsActive = SpeedCtrlValue > 0; + switch (ScndCtrlPos) + { + case 0: + NewSpeed = 0; + SpeedCtrlValue = 0; + SpeedCtrlTimer = 10; + break; + case 1: + if (SpeedCtrlTimer > SpeedCtrlDelay) + { + SpeedCtrlTimer = 0; + NewSpeed -= 10; + if (NewSpeed < 0) + NewSpeed = 0; + } + else + SpeedCtrlTimer += dt; + break; + case 2: + SpeedCtrlTimer = 10; + SpeedCtrlValue = NewSpeed; + break; + case 3: + if (SpeedCtrlTimer > SpeedCtrlDelay) + { + SpeedCtrlTimer = 0; + NewSpeed += 10; + if (NewSpeed > Vmax) + NewSpeed = Vmax; + } + else + SpeedCtrlTimer += dt; + break; + case 4: + NewSpeed = Vmax; + SpeedCtrlValue = Vmax; + SpeedCtrlTimer = 10; + break; + default: + break; + } +} + +// whether the induction motors brake, and the share of the electrodynamic and the pneumatic brake; sets the +// force asked of the motors (PosRatio) and how fast the drive follows it (tmp) +void TMoverParameters::InductionMotorBrakeBlending(double const ActiveInverters, double &PosRatio, double &tmp) +{ + InductionMotorDynamicBrakeFlag(); + auto const edBCP{Hamulec->GetEDBCP() * eimc[eimc_p_abed]}; // stala napedu + if (DynamicBrakeFlag) + { + PosRatio = InductionMotorBrakeRatio(ActiveInverters, edBCP); + tmp = 5; + } + else + { + PosRatio = std::max(eimic_real, 0.); + eimv[eimv_Fzad] = PosRatio; + if (Flat && eimc[eimc_p_F0] * eimv[eimv_Fful] > 0) + PosRatio = std::min(PosRatio * eimc[eimc_p_F0] / eimv[eimv_Fful], 1.); + /* if (ScndCtrlActualPos > 0) //speed control + if (Vmax < 250) + PosRatio = std::min(PosRatio, std::max(-1, 0.5 * (ScndCtrlActualPos - Vel))); + else + PosRatio = + std::min(PosRatio, std::max(-1, 0.5 * (ScndCtrlActualPos * 2 - Vel))); */ + // PosRatio = 1.0 * (PosRatio * 0 + 1) * PosRatio; // 1 * 1 * PosRatio = PosRatio + Hamulec->SetED(0); + // (Hamulec as TLSt).SetLBP(LocBrakePress); + tmp = 4; // szybkie malenie, powolne wzrastanie + } +} + +// the electrodynamic brake of the induction motors on: with the doors open or permitted, by the train brake, the local +// brake or its own controller; off without them +void TMoverParameters::InductionMotorDynamicBrakeFlag() +{ + double const edBCP = Hamulec->GetEDBCP(); + auto const localbrakeactive{CabOccupied != 0 && LocHandle->GetCP() > 0.25}; + // gdy SplitEDPneumaticBrake jest aktywne, hamulec pomocniczy (LocalBrake) NIE wymusza + // zalaczenia hamulca elektrodynamicznego - ED jest sterowany wlasnym nastawnikiem + auto const dynbrakectrlactive{SplitEDPneumaticBrake && DynamicBrakeRatio() > 0.01 && DynamicBrakeAvailable()}; + auto const localbrakeforED{SplitEDPneumaticBrake ? false : localbrakeactive}; + if (false == Doors.instances[side::left].is_closed || false == Doors.instances[side::right].is_closed || + (Doors.permit_needed && (Doors.instances[side::left].open_permit || Doors.instances[side::right].open_permit))) + { + DynamicBrakeFlag = true; + } + else if ((edBCP < 0.25 && false == localbrakeforED && false == dynbrakectrlactive && AnPos < 0.01) || + (edBCP < 0.25 && ShuntModeAllow && false == dynbrakectrlactive && LocalBrakePosA < 0.01)) + DynamicBrakeFlag = false; + else if (BrakePress > 0.25 && edBCP > 0.25 || localbrakeforED || AnPos > 0.02 || dynbrakectrlactive) + DynamicBrakeFlag = true; +} + +// the share of the electrodynamic brake (negative), and the distributor told how much of the air to let out; none +// when the air brake cuts the electrodynamic one off, or an inverter is out +double TMoverParameters::InductionMotorBrakeRatio(double const ActiveInverters, double const edBCP) +{ + double PosRatio; + // ustalanie współczynnika blendingu do luzowania hamulca PN + if (eimv[eimv_Fmax] * Sign(V) * DirAbsolute < -1) + { + PosRatio = -Sign(V) * DirAbsolute * eimv[eimv_Fr] / (eimc[eimc_p_Fh] * std::max(edBCP, std::max(0.01, Hamulec->GetEDBCP())) / MaxBrakePress[0]); + PosRatio = std::clamp(PosRatio, 0.0, 1.0); + } + else + { + PosRatio = 0; + } + PosRatio = static_cast(Round(20.0 * PosRatio)) / 20.0; // stopniowanie PN/ED + if (PosRatio < 19.5 / 20.0) + PosRatio *= 0.9; + Hamulec->SetED(std::max(0.0, std::min(PosRatio, 1.0))); // ustalenie stopnia zmniejszenia ciśnienia + // ustalanie siły hamowania ED + if (Hamulec->GetEDBCP() > 0.25 && eimc[eimc_p_abed] < 0.001 || ActiveInverters < InvertersNo) // jeśli PN wyłącza ED + { + PosRatio = 0; + eimv[eimv_Fzad] = 0; + } + else + { + // strefa wylaczenia ED (Vh0..Vh1) - mnoznik 0..1 zaleznie od predkosci + double const vhRamp = std::max(0.0, std::min(1.0, (Vel - eimc[eimc_p_Vh0]) / (eimc[eimc_p_Vh1] - eimc[eimc_p_Vh0]))); + if (SplitEDPneumaticBrake) + { + // w trybie split LocalBrake nie zaleca ED; uzywany jest DynamicBrakeCtrl + // oraz zwykle zapotrzebowanie z hamulca zespolonego (edBCP) + double const edLeverDemand = DynamicBrakeRatio(); + PosRatio = -std::max(std::max(edLeverDemand, std::min(edBCP / MaxBrakePress[0], 1.0)), AnPos) * vhRamp; + eimv[eimv_Fzad] = -std::min(1.0, std::max(edLeverDemand, edBCP / MaxBrakePress[0])); + } + else + { + PosRatio = -std::max(std::min(edBCP * 1.0 / MaxBrakePress[0], 1.0), AnPos) * vhRamp; + eimv[eimv_Fzad] = -std::min(1.0, std::max(LocalBrakeRatio(), edBCP / MaxBrakePress[0])); + } + } + return PosRatio; +} + +// the model of the induction motors and their inverters: voltage, frequency, currents, moment and force +void TMoverParameters::InductionMotorDrive(double dt) +{ + double tmp; + if (DynamicBrakeFlag) + tmp = eimc[eimc_f_Uzh]; + else + tmp = eimc[eimc_f_Uzmax]; + + auto f_cfu{DynamicBrakeFlag ? eimc[eimc_f_cfuH] : eimc[eimc_f_cfu]}; + + eimv[eimv_Uzsmax] = std::min(EngineVoltage - eimc[eimc_f_DU], tmp); + eimv[eimv_fkr] = eimv[eimv_Uzsmax] / f_cfu; + if (eimv_pr < 0) + { + eimv[eimv_Pmax] = eimc[eimc_p_Ph]; + } + else + { + eimv[eimv_Pmax] = std::min(eimc[eimc_p_Pmax], 0.001 * EngineVoltage * (eimc[eimc_p_Imax] - eimc[eimc_f_I0]) * Pirazy2 * eimc[eimc_s_cim] / eimc[eimc_s_p] / eimc[eimc_s_cfu]); + if (GensetSelected()) + { + // on the genset of a dual-mode vehicle the traction takes no more than the genset gives + eimv[eimv_Pmax] = std::min(eimv[eimv_Pmax], GensetTractionPowerLimit()); + } + } + eimv[eimv_FMAXMAX] = 0.001 * + square(std::min(1.0, eimv[eimv_fkr] / std::max(abs(enrot) * eimc[eimc_s_p] + eimc[eimc_s_dfmax] * eimv[eimv_ks], eimc[eimc_s_dfmax])) * f_cfu / eimc[eimc_s_cfu]) * + (eimc[eimc_s_dfmax] * eimc[eimc_s_dfic] * eimc[eimc_s_cim]) * Transmision.Ratio * NPoweredAxles * 2.0 / WheelDiameter; + InductionMotorForceLimits(); + for (auto &inv : Inverters) + { + inv.Request = inv.IsActive ? eimv_pr : 0.0; + inv.Error = inv.Failure_Const || (inv.Failure_Drive && inv.Request != 0); + inv.IsActive = inv.Activate && !inv.Error; + } + eimv[eimv_ks] = eimv[eimv_Fr] / eimv[eimv_FMAXMAX]; + eimv[eimv_df] = eimv[eimv_ks] * eimc[eimc_s_dfmax]; + eimv[eimv_fp] = DirAbsolute * enrot * eimc[eimc_s_p] + eimv[eimv_df]; // do przemyslenia dzialanie pp z tmpV + // eimv[eimv_U]:=std::max(eimv[eimv_Uzsmax],std::min(eimc[eimc_f_cfu]*eimv[eimv_fp],eimv[eimv_Uzsmax])); + // eimv[eimv_pole]:=eimv[eimv_U]/(eimv[eimv_fp]*eimc[eimc_s_cfu]); + if (abs(eimv[eimv_fp]) <= eimv[eimv_fkr]) + eimv[eimv_pole] = f_cfu / eimc[eimc_s_cfu]; + else + eimv[eimv_pole] = eimv[eimv_Uzsmax] / eimc[eimc_s_cfu] / abs(eimv[eimv_fp]); + eimv[eimv_U] = eimv[eimv_pole] * eimv[eimv_fp] * eimc[eimc_s_cfu]; + eimv[eimv_Ic] = (eimv[eimv_fp] - DirAbsolute * enrot * eimc[eimc_s_p]) * eimc[eimc_s_dfic] * eimv[eimv_pole]; + eimv[eimv_If] = eimv[eimv_Ic] * eimc[eimc_s_icif]; + eimv[eimv_M] = eimv[eimv_pole] * eimv[eimv_Ic] * eimc[eimc_s_cim]; + eimv[eimv_Ipoj] = eimv[eimv_Ic] * NPoweredAxles * InvertersRatio * eimv[eimv_U] / (EngineVoltage - eimc[eimc_f_DU]) + eimc[eimc_f_I0]; + eimv[eimv_Pm] = DirActive * eimv[eimv_M] * NPoweredAxles * InvertersRatio * enrot * Pirazy2 / 1000; + eimv[eimv_Pe] = eimv[eimv_Ipoj] * EngineVoltage / 1000; + eimv[eimv_eta] = eimv[eimv_Pm] / eimv[eimv_Pe]; + + Im = eimv[eimv_If]; + if (eimv[eimv_Ipoj] >= 0) + Vadd *= 1.0 - 2.0 * dt; + else if (GensetSelected()) + Vadd = 1.0; // the genset of a dual-mode vehicle takes nothing back: all the braking energy to the resistors + else if (std::abs(EngineVoltage) < EnginePowerSource.CollectorParameters.MaxV) + Vadd *= 1.0 - dt; + else + Vadd = std::max(Vadd * (1.0 - 0.2 * dt), 0.007 * (std::abs(EngineVoltage) - (EnginePowerSource.CollectorParameters.MaxV - 100))); + Itot = eimv[eimv_Ipoj] * (0.01 + std::min(0.99, 0.99 - Vadd)); + + EnginePower = abs(eimv[eimv_Ic] * eimv[eimv_U] * NPoweredAxles) / 1000; + // power inverters + UpdateInverterFrequency(); + + Mm = eimv[eimv_M] * DirAbsolute; + Mw = Mm * Transmision.Ratio * Transmision.Efficiency; + Fw = Mw * 2.0 / WheelDiameter; + Ft = Fw * NPoweredAxles * InvertersRatio; + eimv[eimv_Fr] = DirAbsolute * Ft / 1000; +} + +// the force the motors give at full and at the setting (eimv_pr), braking within the power and the force of the +// electrodynamic brake, driving within the power and the starting force +void TMoverParameters::InductionMotorForceLimits() +{ + if (eimv_pr < 0) + { + eimv[eimv_Fful] = std::min(eimc[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(eimc[eimc_p_Fh], eimv[eimv_FMAXMAX])); + eimv[eimv_Fmax] = -Sign(V) * DirAbsolute*std::min(eimc[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-eimc[eimc_p_Fh] * eimv_pr, eimv[eimv_FMAXMAX])); + double pr = eimv_pr; + if (EIMCLogForce) + pr = -log(1 - 4 * pr) / log(5); + eimv[eimv_Fr] = -Sign(V) * DirAbsolute*std::min(eimc[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-eimc[eimc_p_Fh] * pr, eimv[eimv_FMAXMAX])); + if (InvertersRatio < 1.0) + eimv[eimv_Fful] = 0; + //*std::min(1,(Vel-eimc[eimc_p_Vh0])/(eimc[eimc_p_Vh1]-eimc[eimc_p_Vh0])) + } + else + { + eimv[eimv_Fful] = std::min(std::min(3.6 * eimv[eimv_Pmax] / std::max(Vel, 1.), eimc[eimc_p_F0] - Vel * eimc[eimc_p_a1]), eimv[eimv_FMAXMAX]); + // if(not Flat)then + eimv[eimv_Fmax] = eimv[eimv_Fful] * eimv_pr; + // else + // eimv[eimv_Fmax]:=std::min(eimc[eimc_p_F0]*eimv_pr,eimv[eimv_Fful]); + double pr = eimv_pr; + if (EIMCLogForce) + pr = log(1 + 4 * pr) / log(5); + eimv[eimv_Fr] = eimv[eimv_Fful] * pr; + } +} + +// the frequency of the inverters at the motors' slip frequency, from the list of the drive or of its brake +void TMoverParameters::UpdateInverterFrequency() +{ + auto const tmpV{std::abs(eimv[eimv_fp])}; + auto const useFFEDList = FFEDListSize > 0 && DynamicBrakeFlag; + auto const list = useFFEDList ? FFEDlist : FFlist; + + if (auto const listSize = useFFEDList ? FFEDListSize : FFListSize; listSize > 0 && std::abs(eimv[eimv_If]) > 1.0 && tmpV > 0.0001) + { + + int i = 0; + while (i < listSize - 1 && list[i + 1].v < tmpV) + { + ++i; + } + InverterFrequency = (tmpV - list[i].v) / std::max(1.0, list[i + 1].v - list[i].v) * (list[i + 1].freq - list[i].freq) + list[i].freq; + } + else + { + InverterFrequency = 0.0; + } +} + +// the induction motor drive without power, or blocked by the security system +void TMoverParameters::InductionMotorOff() +{ + for (auto &inv : Inverters) + { + inv.Freal = 0.0; + inv.IsActive = false; + } + Im = 0.0; + Mm = 0.0; + Mw = 0.0; + Fw = 0.0; + Ft = 0.0; + Itot = 0.0; + eimv_pr = 0.0; + EnginePower = 0.0; + { + for (auto &eimvvalue : eimv) + eimvvalue = 0.0; + } + Hamulec->SetED(0.0); + InverterFrequency = 0.0; //(Hamulec as TLSt).SetLBP(LocBrakePress); +} + +// the current of a diesel-electric vehicle's traction motors giving the moment [N m] of one motor +double TMoverParameters::dieselelectric_motor_current(double const Moment) const +{ + // with MotorParam[ScndCtrlPos] do + if (abs(Moment) > motor_param(ScndCtrlPos).fi) + return NPoweredAxles * abs(abs(Moment) / motor_param(ScndCtrlPos).mfi + motor_param(ScndCtrlPos).mIsat); + else + return NPoweredAxles * sqrt(abs(Moment * motor_param(ScndCtrlPos).Isat)); +} + +// the effort of a diesel-electric vehicle's dynamic brake the driver asks for, 0..1 +double TMoverParameters::dieselelectric_dynamic_brake_demand() const +{ + switch (DEDynamicBrake.source) + { + case diesel_electric_dynamic_brake::control::controller: + return std::clamp(-eimic_real, 0.0, 1.0); + case diesel_electric_dynamic_brake::control::lever: + return DynamicBrakeRatio(); + default: + return 0.0; + } +} + +// the force [N] of a diesel-electric vehicle's dynamic brake at full effort at the speed: the most the motors take +// (the current), above the speed where the resistors' power takes over, the power; under EDBrakeV1 it fades, down to +// nothing at EDBrakeV0. a brake of direct current motors, whose force grows with the speed (the voltage they generate +// into the resistors), fades from 0 to the speed of its whole force; an inverter's only at the stop +double TMoverParameters::dieselelectric_dynamic_brake_limit() const +{ + auto const &brake{DEDynamicBrake}; + auto limit{brake.max_force}; + if (brake.max_power > 0.0 && std::abs(V) > 0.0) + { + limit = std::min(limit, brake.max_power / std::abs(V)); + } + if (brake.fade_high > brake.fade_low) + { + limit *= std::clamp((Vel - brake.fade_low) / (brake.fade_high - brake.fade_low), 0.0, 1.0); + } + else if (Vel < brake.fade_low) + { + limit = 0.0; + } + return limit; +} + +// the dynamic brake of a diesel-electric vehicle, before the drive's force: the effort follows the demand, the force +// is the share of the most at the speed. the motors brake while the engine runs (it excites them, or keeps the +// control of the inverters going), with the direction set, the overload relay closed, no power asked for and the +// wheels rolling; otherwise there's no brake at once +void TMoverParameters::update_dieselelectric_dynamic_brake(double const dt) +{ + auto &brake{DEDynamicBrake}; + auto const nopower{brake.source == diesel_electric_dynamic_brake::control::controller ? eimic_real <= 0.0 : IsMainCtrlNoPowerPos()}; + if (Mains && DirActive != 0 && false == FuseFlag && false == SlippingWheels && nopower) + { + brake.level += std::clamp(dieselelectric_dynamic_brake_demand() - brake.level, -brake.rate * dt, brake.rate * dt); + } + else + { + brake.level = 0.0; + } + brake.force = brake.level * dieselelectric_dynamic_brake_limit(); + DynamicBrakeFlag = brake.force > 0.0; + if (brake.blending) + { + // the train brake of the locomotive lets off by the share of the dynamic brake's force (LSt, EStED) + Hamulec->SetED(brake.max_force > 0.0 ? brake.force / brake.max_force : 0.0); + } +} + +// the force of a diesel-electric vehicle's dynamic brake, against the motion, in place of the drive's one: the motors +// work as generators into the resistors, the ammeter shows their current, the main generator gives nothing. near the +// stop no more than what stops the vehicle within the step dt: with no fade (EDBrakeV0 = EDBrakeV1 = 0) the whole force +// would turn round each time the speed crosses zero, and in FTrain it never lets the stop of ComputeMovement() catch it +void TMoverParameters::apply_dieselelectric_dynamic_brake(double const dt) +{ + auto const force{dt > 0.0 ? std::min(DEDynamicBrake.force, TotalMass * std::abs(V) / dt) : DEDynamicBrake.force}; + Ft = V > 0.0 ? -force : V < 0.0 ? force : 0.0; + Fw = Ft / NPoweredAxles; + Mw = Fw * WheelDiameter / 2.0; + Mm = Mw / Transmision.Ratio; + Im = dieselelectric_motor_current(Mm); + EngineVoltage = 0.0; + EnginePower = 0.0; } // ************************************************************************************************* @@ -7267,7 +8755,6 @@ bool TMoverParameters::AutoRelayCheck(void) if (motorconnectorsoff || (HasCamshaft ? IsMainCtrlActualNoPowerPos() : IsMainCtrlNoPowerPos())) { StLinFlag = false; - OK = false; if (false == DynamicBrakeFlag) { Im = 0; @@ -7291,253 +8778,16 @@ bool TMoverParameters::AutoRelayCheck(void) { if (RList[MainCtrlActualPos].R == 0 && (ScndCtrlActualPos > 0 || ScndCtrlPos > 0) && (!CoupledCtrl || RList[MainCtrlActualPos].Relay == MainCtrlPos)) { // zmieniaj scndctrlactualpos - // scnd bez samoczynnego rozruchu - if (ScndCtrlActualPos < ScndCtrlPos) - { - if (LastRelayTime > CtrlDelay && ARFASI2) - { - ++ScndCtrlActualPos; - SetFlag(SoundFlag, sound::shuntfield); - OK = true; - } - } - else if (ScndCtrlActualPos > ScndCtrlPos) - { - if (LastRelayTime > CtrlDownDelay && TrainType != dt_EZT) - { - --ScndCtrlActualPos; - SetFlag(SoundFlag, sound::shuntfield); - OK = true; - } - } - else - OK = false; + OK = AutoRelayShuntStep(ARFASI2); } else { // zmieniaj mainctrlactualpos - // running backwards, the motors don't get joined in more branches than allowed (the series connection - // alone, usually); the camshaft still goes back down from there (eu07/maszyna#393: it stayed where it - // was, the line contactors closed, whatever the driver did with the master controller) - auto const backwardslimit{DirActive < 0 && TrainType != dt_PseudoDiesel && RList[MainCtrlActualPos + 1].Bn > BackwardsBranchesAllowed}; - // main bez samoczynnego rozruchu - if (false == backwardslimit && MainCtrlActualPos < std::size(RList) - 1 // crude guard against running out of current fixed table - && (RList[MainCtrlActualPos].Relay < MainCtrlPos || (RList[MainCtrlActualPos + 1].Relay == MainCtrlPos && MainCtrlActualPos < RlistSize) || - (TrainType == dt_ET22 && DelayCtrlFlag))) - { - - // prevent switch to parallel mode if motor overload relay is set to high threshold mode - if (IsMotorOverloadRelayHighThresholdOn() && RList[MainCtrlActualPos + 1].Bn > 1) - { - return false; - } - - if (RList[MainCtrlPos].R == 0 && MainCtrlPos > 0 && MainCtrlPos != MainCtrlPosNo && FastSerialCircuit == 1) - { - // szybkie wchodzenie na bezoporowa (303E) - // MainCtrlActualPos:=MainCtrlPos; //hunter-111012: - ++MainCtrlActualPos; - if (MainCtrlPos - MainCtrlActualPos == 1) - { - // HACK: ensure we play only single sound of basic relays for entire trasition; return false - // for all but last step despite configuration change, to prevent playback of the basic relay sound - // TBD, TODO: move the basic sound event here and enable it with call parameter - OK = true; - } - if (RList[MainCtrlActualPos].R == 0) - { - SetFlag(SoundFlag, sound::parallel | sound::loud); - OK = true; - } - } - else if (LastRelayTime > CtrlDelay && ARFASI) - { - // WriteLog("LRT = " + FloatToStr(LastRelayTime) + ", " + - // FloatToStr(CtrlDelay)); - if (TrainType == dt_ET22 && MainCtrlPos > 1 && (RList[MainCtrlActualPos].Bn < RList[MainCtrlActualPos + 1].Bn || DelayCtrlFlag)) - { - // et22 z walem grupowym - if (!DelayCtrlFlag) // najpierw przejscie - { - ++MainCtrlActualPos; - DelayCtrlFlag = true; // tryb przejscia - OK = true; - } - else if (LastRelayTime > 4 * CtrlDelay) // przejscie - { - - DelayCtrlFlag = false; - OK = true; - } - /* - else - ; - */ - } - else // nie ET22 z wałem grupowym - { - ++MainCtrlActualPos; - OK = true; - } - //--------- - // hunter-111211: poprawki - if (MainCtrlActualPos > 0) - { - if (RList[MainCtrlActualPos].R == 0 && MainCtrlActualPos != MainCtrlPosNo) - { - // wejscie na bezoporowa - SetFlag(SoundFlag, sound::parallel | sound::loud); - } - else if (RList[MainCtrlActualPos].R > 0 && RList[MainCtrlActualPos - 1].R == 0) - { - // wejscie na drugi uklad - SetFlag(SoundFlag, sound::parallel); - } - } - } - } - else if (RList[MainCtrlActualPos].Relay > MainCtrlPos) - { - if (RList[MainCtrlPos].R == 0 && MainCtrlPos > 0 && !(MainCtrlPos == MainCtrlPosNo) && FastSerialCircuit == 1) - { - // szybkie wchodzenie na bezoporowa (303E) - // MainCtrlActualPos:=MainCtrlPos; //hunter-111012: - --MainCtrlActualPos; - OK = true; - if (RList[MainCtrlActualPos].R == 0) - { - SetFlag(SoundFlag, sound::parallel); - } - } - else if (LastRelayTime > CtrlDownDelay) - { - if (TrainType != dt_EZT) // tutaj powinien być tryb sterowania wałem - { - --MainCtrlActualPos; - OK = true; - } - // hunter-111211: poprawki - if (MainCtrlActualPos > 0 && RList[MainCtrlActualPos].R == 0) - { - // dzwieki schodzenia z bezoporowej} - SetFlag(SoundFlag, sound::parallel); - } - } - } - else if (RList[MainCtrlActualPos].R > 0 && ScndCtrlActualPos > 0) - { - if (LastRelayTime > CtrlDownDelay) - { - --ScndCtrlActualPos; // boczniki nie dzialaja na poz. oporowych - SetFlag(SoundFlag, sound::shuntfield); - OK = true; - } - } - else - OK = false; + OK = AutoRelayMainStep(ARFASI); } } else // not StLinFlag { - OK = false; - // ybARC - zalaczenie stycznikow liniowych - if (false == motorconnectorsoff && MainCtrlActualPos == 0 && (TrainType == dt_EZT || HasCamshaft ? MainCtrlPowerPos() > 0 : MainCtrlPowerPos() == 1)) - { - - DelayCtrlFlag = true; - if (LastRelayTime >= InitialCtrlDelay) - { - StLinFlag = true; - MainCtrlActualPos = 1; - DelayCtrlFlag = false; - SetFlag(SoundFlag, sound::relay | sound::loud); - OK = true; - } - } - else - { - DelayCtrlFlag = false; - } - - if (false == StLinFlag && (MainCtrlActualPos > 0 || ScndCtrlActualPos > 0)) - { - - if (CoupledCtrl) - { - - if (TrainType == dt_EZT) - { - // EN57 wal jednokierunkowy calosciowy - if (MainCtrlActualPos == 1) - { - - MainCtrlActualPos = 0; - OK = true; - } - else - { - - if (LastRelayTime > CtrlDownDelay) - { - - if (MainCtrlActualPos < RlistSize) - { - // dojdz do konca - ++MainCtrlActualPos; - } - else if (ScndCtrlActualPos < ScndCtrlPosNo) - { - // potem boki - ++ScndCtrlActualPos; - SetFlag(SoundFlag, sound::shuntfield); - } - else - { - // i sie przewroc na koniec - MainCtrlActualPos = 0; - ScndCtrlActualPos = 0; - } - OK = true; - } - } - } - else - { - // wal kulakowy dwukierunkowy - if (LastRelayTime > CtrlDownDelay) - { - if (ScndCtrlActualPos > 0) - { - --ScndCtrlActualPos; - SetFlag(SoundFlag, sound::shuntfield); - } - else - { - --MainCtrlActualPos; - } - OK = true; - } - } - } - else if (HasCamshaft) - { - // wal kulakowy dwukierunkowy - if (LastRelayTime > CtrlDownDelay) - { - if (MainCtrlActualPos > 0) - { - --MainCtrlActualPos; - } - ScndCtrlActualPos = 0; - OK = true; - } - } - else - { - MainCtrlActualPos = 0; - ScndCtrlActualPos = 0; - OK = true; - } - } + OK = AutoRelayLineContactorsStep(motorconnectorsoff); } if (OK) LastRelayTime = 0; @@ -7546,11 +8796,310 @@ bool TMoverParameters::AutoRelayCheck(void) } } +// a step of the shunt field on a position without resistors, up or down to the second controller +bool TMoverParameters::AutoRelayShuntStep(bool const ARFASI2) +{ + bool OK = false; + // scnd bez samoczynnego rozruchu + if (ScndCtrlActualPos < ScndCtrlPos) + { + if (LastRelayTime > CtrlDelay && ARFASI2) + { + ++ScndCtrlActualPos; + SetFlag(SoundFlag, sound::shuntfield); + OK = true; + } + } + else if (ScndCtrlActualPos > ScndCtrlPos) + { + if (LastRelayTime > CtrlDownDelay && TrainType != dt_EZT) + { + --ScndCtrlActualPos; + SetFlag(SoundFlag, sound::shuntfield); + OK = true; + } + } + else + OK = false; + return OK; +} + +// a step of the main controller's relays, up or down to its position, or the shunt field off on the resistors +bool TMoverParameters::AutoRelayMainStep(bool const ARFASI) +{ + bool OK = false; + // running backwards, the motors don't get joined in more branches than allowed (the series connection + // alone, usually); the camshaft still goes back down from there (eu07/maszyna#393: it stayed where it + // was, the line contactors closed, whatever the driver did with the master controller) + auto const backwardslimit{DirActive < 0 && TrainType != dt_PseudoDiesel && RList[MainCtrlActualPos + 1].Bn > BackwardsBranchesAllowed}; + // main bez samoczynnego rozruchu + if (false == backwardslimit && MainCtrlActualPos < std::size(RList) - 1 // crude guard against running out of current fixed table + && (RList[MainCtrlActualPos].Relay < MainCtrlPos || (RList[MainCtrlActualPos + 1].Relay == MainCtrlPos && MainCtrlActualPos < RlistSize) || + (TrainType == dt_ET22 && DelayCtrlFlag))) + { + OK = AutoRelayMainUp(ARFASI); + } + else if (RList[MainCtrlActualPos].Relay > MainCtrlPos) + { + OK = AutoRelayMainDown(); + } + else if (RList[MainCtrlActualPos].R > 0 && ScndCtrlActualPos > 0) + { + if (LastRelayTime > CtrlDownDelay) + { + --ScndCtrlActualPos; // boczniki nie dzialaja na poz. oporowych + SetFlag(SoundFlag, sound::shuntfield); + OK = true; + } + } + else + OK = false; + return OK; +} + +// a step of the main relays up to the controller's position, at once to the parallel position without resistors +// on a fast serial circuit (303E); returns whether the relays moved, never into parallel with the overload relay high +bool TMoverParameters::AutoRelayMainUp(bool const ARFASI) +{ + bool OK = false; + // prevent switch to parallel mode if motor overload relay is set to high threshold mode + if (IsMotorOverloadRelayHighThresholdOn() && RList[MainCtrlActualPos + 1].Bn > 1) + { + return false; + } + + if (RList[MainCtrlPos].R == 0 && MainCtrlPos > 0 && MainCtrlPos != MainCtrlPosNo && FastSerialCircuit == 1) + { + // szybkie wchodzenie na bezoporowa (303E) + // MainCtrlActualPos:=MainCtrlPos; //hunter-111012: + ++MainCtrlActualPos; + if (MainCtrlPos - MainCtrlActualPos == 1) + { + // HACK: ensure we play only single sound of basic relays for entire trasition; return false + // for all but last step despite configuration change, to prevent playback of the basic relay sound + // TBD, TODO: move the basic sound event here and enable it with call parameter + OK = true; + } + if (RList[MainCtrlActualPos].R == 0) + { + SetFlag(SoundFlag, sound::parallel | sound::loud); + OK = true; + } + } + else if (LastRelayTime > CtrlDelay && ARFASI) + { + OK = AutoRelayMainNotchUp(); + } + return OK; +} + +// a notch up of the main relays after their delay, through the group switch of the ET22, and the sounds of the +// parallel positions; returns whether they moved +bool TMoverParameters::AutoRelayMainNotchUp() +{ + bool OK = false; + // WriteLog("LRT = " + FloatToStr(LastRelayTime) + ", " + + // FloatToStr(CtrlDelay)); + if (TrainType == dt_ET22 && MainCtrlPos > 1 && (RList[MainCtrlActualPos].Bn < RList[MainCtrlActualPos + 1].Bn || DelayCtrlFlag)) + { + // et22 z walem grupowym + if (!DelayCtrlFlag) // najpierw przejscie + { + ++MainCtrlActualPos; + DelayCtrlFlag = true; // tryb przejscia + OK = true; + } + else if (LastRelayTime > 4 * CtrlDelay) // przejscie + { + + DelayCtrlFlag = false; + OK = true; + } + /* + else + ; + */ + } + else // nie ET22 z wałem grupowym + { + ++MainCtrlActualPos; + OK = true; + } + //--------- + // hunter-111211: poprawki + if (MainCtrlActualPos > 0) + { + if (RList[MainCtrlActualPos].R == 0 && MainCtrlActualPos != MainCtrlPosNo) + { + // wejscie na bezoporowa + SetFlag(SoundFlag, sound::parallel | sound::loud); + } + else if (RList[MainCtrlActualPos].R > 0 && RList[MainCtrlActualPos - 1].R == 0) + { + // wejscie na drugi uklad + SetFlag(SoundFlag, sound::parallel); + } + } + return OK; +} + +// a step of the main relays down to the controller's position; returns whether they moved +bool TMoverParameters::AutoRelayMainDown() +{ + bool OK = false; + if (RList[MainCtrlPos].R == 0 && MainCtrlPos > 0 && !(MainCtrlPos == MainCtrlPosNo) && FastSerialCircuit == 1) + { + // szybkie wchodzenie na bezoporowa (303E) + // MainCtrlActualPos:=MainCtrlPos; //hunter-111012: + --MainCtrlActualPos; + OK = true; + if (RList[MainCtrlActualPos].R == 0) + { + SetFlag(SoundFlag, sound::parallel); + } + } + else if (LastRelayTime > CtrlDownDelay) + { + if (TrainType != dt_EZT) // tutaj powinien być tryb sterowania wałem + { + --MainCtrlActualPos; + OK = true; + } + // hunter-111211: poprawki + if (MainCtrlActualPos > 0 && RList[MainCtrlActualPos].R == 0) + { + // dzwieki schodzenia z bezoporowej} + SetFlag(SoundFlag, sound::parallel); + } + } + return OK; +} + +// the line contactors closed at the first position, or, open, the camshaft run back to zero +bool TMoverParameters::AutoRelayLineContactorsStep(bool const motorconnectorsoff) +{ + bool OK = false; + // ybARC - zalaczenie stycznikow liniowych + if (false == motorconnectorsoff && MainCtrlActualPos == 0 && (TrainType == dt_EZT || HasCamshaft ? MainCtrlPowerPos() > 0 : MainCtrlPowerPos() == 1)) + { + + DelayCtrlFlag = true; + if (LastRelayTime >= InitialCtrlDelay) + { + StLinFlag = true; + MainCtrlActualPos = 1; + DelayCtrlFlag = false; + SetFlag(SoundFlag, sound::relay | sound::loud); + OK = true; + } + } + else + { + DelayCtrlFlag = false; + } + + if (false == StLinFlag && (MainCtrlActualPos > 0 || ScndCtrlActualPos > 0)) + { + OK |= CamshaftRunDown(); + } + return OK; +} + +// the camshaft, the line contactors open, run back to its zero position a step at a time, or at once without one; +// returns whether it moved +bool TMoverParameters::CamshaftRunDown() +{ + bool OK = false; + + if (CoupledCtrl) + { + + if (TrainType == dt_EZT) + { + OK = CamshaftRunDownEMU(); + } + else if (LastRelayTime > CtrlDownDelay) // wal kulakowy dwukierunkowy + { + if (ScndCtrlActualPos > 0) + { + --ScndCtrlActualPos; + SetFlag(SoundFlag, sound::shuntfield); + } + else + { + --MainCtrlActualPos; + } + OK = true; + } + } + else if (HasCamshaft) + { + // wal kulakowy dwukierunkowy + if (LastRelayTime > CtrlDownDelay) + { + if (MainCtrlActualPos > 0) + { + --MainCtrlActualPos; + } + ScndCtrlActualPos = 0; + OK = true; + } + } + else + { + MainCtrlActualPos = 0; + ScndCtrlActualPos = 0; + OK = true; + } + return OK; +} + +// the one way camshaft of the EN57 run on to its end and round to zero; returns whether it moved +bool TMoverParameters::CamshaftRunDownEMU() +{ + bool OK = false; + // EN57 wal jednokierunkowy calosciowy + if (MainCtrlActualPos == 1) + { + + MainCtrlActualPos = 0; + OK = true; + } + else + { + + if (LastRelayTime > CtrlDownDelay) + { + + if (MainCtrlActualPos < RlistSize) + { + // dojdz do konca + ++MainCtrlActualPos; + } + else if (ScndCtrlActualPos < ScndCtrlPosNo) + { + // potem boki + ++ScndCtrlActualPos; + SetFlag(SoundFlag, sound::shuntfield); + } + else + { + // i sie przewroc na koniec + MainCtrlActualPos = 0; + ScndCtrlActualPos = 0; + } + OK = true; + } + } + return OK; +} + bool TMoverParameters::MotorConnectorsCheck() { // hunter-111211: wylacznik cisnieniowy - ControlPressureSwitch = HasControlPressureSwitch && (BrakePress > 2.0 || PipePress < 3.6); + // (on some vehicles it watches the brake pipe alone) + ControlPressureSwitch = HasControlPressureSwitch && ((PressureSwitchBrakeCylinder && BrakePress > 2.0) || PipePress < 3.6); if (true == ControlPressureSwitch) { @@ -7807,160 +9356,205 @@ void TMoverParameters::CheckEIMIC(double dt) switch (EIMCtrlType) { case 0: - eimic = brakeDemand > 0.01 ? -brakeDemand : eimic_analog > 0.01 ? eimic_analog : (double)MainCtrlPos / (double)MainCtrlPosNo; - if (EIMCtrlAdditionalZeros || EIMCtrlEmergency) - { - if (eimic > 0.001) - eimic = std::max(0.002, eimic * (double)MainCtrlPosNo / ((double)MainCtrlPosNo - offset) - offset / ((double)MainCtrlPosNo - offset)); - if (eimic < -0.001 && BrakeHandle != TBrakeHandle::MHZ_EN57) - eimic = std::min(-0.002, eimic * (double)LocalBrakePosNo / ((double)LocalBrakePosNo - multiplier) + offset / ((double)LocalBrakePosNo - multiplier)); - } - if (eimic > 0.001 && SpeedCtrlUnit.IsActive) - eimic = std::max(eimic, SpeedCtrlUnit.MinPower); + EIMICFromController(brakeDemand, offset, multiplier); break; case 1: - switch (MainCtrlPos) + EIMICFromSteps(dt); + break; + case 2: + EIMICFromFourPositions(dt); + break; + case 3: + EIMICFromUniversalController(dt, brakeDemand); + break; + } + if (LocHandleTimeTraxx) + { + EIMICTraxxLocalBrake(dt); + } + + EIMICLimit(); +} + +// the controller (EIMCtrlType 0): the position of the main controller, or the analog one, or the brake asked +void TMoverParameters::EIMICFromController(double const brakeDemand, double const offset, double const multiplier) +{ + eimic = brakeDemand > 0.01 ? -brakeDemand : eimic_analog > 0.01 ? eimic_analog : (double)MainCtrlPos / (double)MainCtrlPosNo; + if (EIMCtrlAdditionalZeros || EIMCtrlEmergency) + { + if (eimic > 0.001) + eimic = std::max(0.002, eimic * (double)MainCtrlPosNo / ((double)MainCtrlPosNo - offset) - offset / ((double)MainCtrlPosNo - offset)); + if (eimic < -0.001 && BrakeHandle != TBrakeHandle::MHZ_EN57) + eimic = std::min(-0.002, eimic * (double)LocalBrakePosNo / ((double)LocalBrakePosNo - multiplier) + offset / ((double)LocalBrakePosNo - multiplier)); + } + if (eimic > 0.001 && SpeedCtrlUnit.IsActive) + eimic = std::max(eimic, SpeedCtrlUnit.MinPower); +} + +// EIMCtrlType 1: the positions B+ to TMax move the value at a steady pace +void TMoverParameters::EIMICFromSteps(double dt) +{ + switch (MainCtrlPos) + { + case 0: // B+ + eimic -= std::clamp(1.0 + eimic, 0.0, dt * 0.14); // odejmuj do -1 + break; + case 1: // B + eimic -= std::clamp(0.0 + eimic, 0.0, dt * 0.14); // odejmuj do 0 + break; + case 2: // B- + case 3: // 0 + case 4: // T- + eimic -= std::clamp(0.0 + eimic, 0.0, dt * 0.14); // odejmuj do 0 + eimic += std::clamp(0.0 - eimic, 0.0, dt * 0.14); // dodawaj do 0 + break; + case 5: // T + eimic += std::clamp(0.0 - eimic, 0.0, dt * 0.14); // dodawaj do 0 + break; + case 6: // T+ + eimic += std::clamp(1.0 - eimic, 0.0, dt * 0.14); // dodawaj do 1 + break; + case 7: // TMax + eimic += std::clamp(1.0 - eimic, 0.0, dt * 0.14); // dodawaj do 1, max + break; + default: + break; + } + if (MainCtrlPos >= 3 && eimic < 0) + eimic = 0; + if (MainCtrlPos <= 3 && eimic > 0) + eimic = 0; +} + +// EIMCtrlType 2: the positions 0 to 4 move the value towards -1, 0 or 1, from the controller's delay on; the +// emergency brake position below them, where the controller has one, brakes in full at once +void TMoverParameters::EIMICFromFourPositions(double dt) +{ + if (IsMainCtrlEmergencyPos()) + { + // hamowanie nagle: pelne hamowanie od razu, przewod glowny oproznia UpdatePipePressure() + eimic = -1.0; + } + else if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) + { + double delta = MainCtrlActualPos == MainCtrlPos ? dt * CtrlDelay : 0.01; + // the positions below are those of the controller without the emergency brake position + switch (MainCtrlPos - EIMCtrlEmergencyPositions()) { - case 0: // B+ - eimic -= std::clamp(1.0 + eimic, 0.0, dt * 0.14); // odejmuj do -1 + case 0: + case 1: + eimic -= safe_clamp(1.0 + eimic, 0.0, delta); // odejmuj do -1 + if (eimic > 0) + eimic = 0; break; - case 1: // B - eimic -= std::clamp(0.0 + eimic, 0.0, dt * 0.14); // odejmuj do 0 + case 2: + eimic -= safe_clamp(0.0 + eimic, 0.0, delta); // odejmuj do 0 break; - case 2: // B- - case 3: // 0 - case 4: // T- - eimic -= std::clamp(0.0 + eimic, 0.0, dt * 0.14); // odejmuj do 0 - eimic += std::clamp(0.0 - eimic, 0.0, dt * 0.14); // dodawaj do 0 + case 3: + eimic += safe_clamp(0.0 - eimic, 0.0, delta); // dodawaj do 0 break; - case 5: // T - eimic += std::clamp(0.0 - eimic, 0.0, dt * 0.14); // dodawaj do 0 - break; - case 6: // T+ - eimic += std::clamp(1.0 - eimic, 0.0, dt * 0.14); // dodawaj do 1 - break; - case 7: // TMax - eimic += std::clamp(1.0 - eimic, 0.0, dt * 0.14); // dodawaj do 1, max + case 4: + eimic += safe_clamp(1.0 - eimic, 0.0, delta); // dodawaj do 1 + if (eimic < 0) + eimic = 0; break; default: break; } - if (MainCtrlPos >= 3 && eimic < 0) - eimic = 0; - if (MainCtrlPos <= 3 && eimic > 0) - eimic = 0; - break; - case 2: - if (IsMainCtrlEmergencyPos()) - { - // hamowanie nagle: pelne hamowanie od razu, przewod glowny oproznia UpdatePipePressure() - eimic = -1.0; - } - else if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) - { - double delta = MainCtrlActualPos == MainCtrlPos ? dt * CtrlDelay : 0.01; - // the positions below are those of the controller without the emergency brake position - switch (MainCtrlPos - EIMCtrlEmergencyPositions()) - { - case 0: - case 1: - eimic -= safe_clamp(1.0 + eimic, 0.0, delta); // odejmuj do -1 - if (eimic > 0) - eimic = 0; - break; - case 2: - eimic -= safe_clamp(0.0 + eimic, 0.0, delta); // odejmuj do 0 - break; - case 3: - eimic += safe_clamp(0.0 - eimic, 0.0, delta); // dodawaj do 0 - break; - case 4: - eimic += safe_clamp(1.0 - eimic, 0.0, delta); // dodawaj do 1 - if (eimic < 0) - eimic = 0; - break; - default: - break; - } - } - if (MainCtrlActualPos == MainCtrlPos) - LastRelayTime += dt; - else - { - LastRelayTime = 0; - MainCtrlActualPos = MainCtrlPos; - } - break; - case 3: - if (UniCtrlIntegratedBrakePNCtrl) - { - if (UniCtrlList[MainCtrlPos].mode != BrakeCtrlPos && MainCtrlActualPos == MainCtrlPos) // there was no move of controller, but brake only - { - if (BrakeCtrlPos < UniCtrlList[MainCtrlPosNo].mode) - BrakeLevelSet(UniCtrlList[MainCtrlPosNo].mode); // bottom clamping - if (BrakeCtrlPos > UniCtrlList[0].mode) - BrakeLevelSet(UniCtrlList[0].mode); // top clamping - if (IsCabMaster()) - { - while (BrakeCtrlPos > UniCtrlList[MainCtrlPos].mode) - DecMainCtrl(1); // find nearest position - while (BrakeCtrlPos < UniCtrlList[MainCtrlPos].mode) - IncMainCtrl(1); // find nearest position - } - } - else // controller was moved - BrakeLevelSet(UniCtrlList[MainCtrlPos].mode); - } - - if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) - { - auto const &position{UniCtrlList[MainCtrlPos]}; - double ramped{eimic}; - ramped -= safe_clamp(-position.SetCtrlVal + ramped, 0.0, - MainCtrlActualPos == MainCtrlPos ? dt * position.SpeedDown : sign(position.SpeedDown) * 0.01); // odejmuj do X - ramped += safe_clamp(position.SetCtrlVal - ramped, 0.0, - MainCtrlActualPos == MainCtrlPos ? dt * position.SpeedUp : sign(position.SpeedUp) * 0.01); // dodawaj do X - ramped = safe_clamp(ramped, position.MinCtrlVal, position.MaxCtrlVal); - eimic = UniCtrlValStep > 0.0 ? stepped_uc_value(eimic, ramped, position, UniCtrlValStep, MainCtrlActualPos != MainCtrlPos, eimic_step_progress) : ramped; - } - if (MainCtrlActualPos == MainCtrlPos) - LastRelayTime += dt; - else - { - LastRelayTime = 0; - MainCtrlActualPos = MainCtrlPos; - } - if (Hamulec->GetEDBCP() > 0.3 && eimic < 0 && !UniCtrlIntegratedLocalBrakeCtrl) // when braking with pneumatic brake - eimic = 0; // shut off retarder - if (UniCtrlIntegratedBrakeCtrl == false && UniCtrlIntegratedLocalBrakeCtrl == false) - { - // w trybie SplitEDPneumaticBrake hamowanie ED przychodzi z osobnego nastawnika, - // LocalBrake operuje wylacznie pneumatycznym hamulcem lokomotywy - eimic = brakeDemand > 0.01 ? -brakeDemand : eimic; - } } - if (LocHandleTimeTraxx) + if (MainCtrlActualPos == MainCtrlPos) + LastRelayTime += dt; + else { - if (LocalBrakeRatio() < 0.4) // pozycja 0, odhamowywanie - { - eim_localbrake -= dt * 0.17; - } + LastRelayTime = 0; + MainCtrlActualPos = MainCtrlPos; + } +} - if (LocalBrakeRatio() > 0.6) // pozycja 2, zahamowywanie - { - eim_localbrake += dt * 0.17; - eim_localbrake = std::max(eim_localbrake, BrakePress / MaxBrakePress[0]); - } - else // pozycja 1, utrzymanie cisnienia - { - if (eim_localbrake < Hamulec->GetEDBCP() / MaxBrakePress[0]) - eim_localbrake = 0; - } - eim_localbrake = std::clamp(eim_localbrake, 0.0, 1.0); - if (eim_localbrake > 0.04 && eimic > 0) - eimic = 0; +// EIMCtrlType 3: the universal controller of UniCtrlList, with the train brake built in or not +void TMoverParameters::EIMICFromUniversalController(double dt, double const brakeDemand) +{ + if (UniCtrlIntegratedBrakePNCtrl) + { + UniversalControllerTrainBrake(); } + if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) + { + auto const &position{UniCtrlList[MainCtrlPos]}; + double ramped{eimic}; + ramped -= safe_clamp(-position.SetCtrlVal + ramped, 0.0, + MainCtrlActualPos == MainCtrlPos ? dt * position.SpeedDown : sign(position.SpeedDown) * 0.01); // odejmuj do X + ramped += safe_clamp(position.SetCtrlVal - ramped, 0.0, + MainCtrlActualPos == MainCtrlPos ? dt * position.SpeedUp : sign(position.SpeedUp) * 0.01); // dodawaj do X + ramped = safe_clamp(ramped, position.MinCtrlVal, position.MaxCtrlVal); + eimic = UniCtrlValStep > 0.0 ? stepped_uc_value(eimic, ramped, position, UniCtrlValStep, MainCtrlActualPos != MainCtrlPos, eimic_step_progress) : ramped; + } + if (MainCtrlActualPos == MainCtrlPos) + LastRelayTime += dt; + else + { + LastRelayTime = 0; + MainCtrlActualPos = MainCtrlPos; + } + if (Hamulec->GetEDBCP() > 0.3 && eimic < 0 && !UniCtrlIntegratedLocalBrakeCtrl) // when braking with pneumatic brake + eimic = 0; // shut off retarder + if (UniCtrlIntegratedBrakeCtrl == false && UniCtrlIntegratedLocalBrakeCtrl == false) + { + // w trybie SplitEDPneumaticBrake hamowanie ED przychodzi z osobnego nastawnika, + // LocalBrake operuje wylacznie pneumatycznym hamulcem lokomotywy + eimic = brakeDemand > 0.01 ? -brakeDemand : eimic; + } +} + +// the train brake built into the universal controller: the handle set to the controller's position, or the +// controller, at a brake handle moved alone, to the nearest position of the handle's +void TMoverParameters::UniversalControllerTrainBrake() +{ + if (UniCtrlList[MainCtrlPos].mode != BrakeCtrlPos && MainCtrlActualPos == MainCtrlPos) // there was no move of controller, but brake only + { + if (BrakeCtrlPos < UniCtrlList[MainCtrlPosNo].mode) + BrakeLevelSet(UniCtrlList[MainCtrlPosNo].mode); // bottom clamping + if (BrakeCtrlPos > UniCtrlList[0].mode) + BrakeLevelSet(UniCtrlList[0].mode); // top clamping + if (IsCabMaster()) + { + while (BrakeCtrlPos > UniCtrlList[MainCtrlPos].mode) + DecMainCtrl(1); // find nearest position + while (BrakeCtrlPos < UniCtrlList[MainCtrlPos].mode) + IncMainCtrl(1); // find nearest position + } + } + else // controller was moved + BrakeLevelSet(UniCtrlList[MainCtrlPos].mode); +} + +// the local brake of the TRAXX locomotives, by time: released, held or applied, which cuts the drive off +void TMoverParameters::EIMICTraxxLocalBrake(double dt) +{ + if (LocalBrakeRatio() < 0.4) // pozycja 0, odhamowywanie + { + eim_localbrake -= dt * 0.17; + } + + if (LocalBrakeRatio() > 0.6) // pozycja 2, zahamowywanie + { + eim_localbrake += dt * 0.17; + eim_localbrake = std::max(eim_localbrake, BrakePress / MaxBrakePress[0]); + } + else // pozycja 1, utrzymanie cisnienia + { + if (eim_localbrake < Hamulec->GetEDBCP() / MaxBrakePress[0]) + eim_localbrake = 0; + } + eim_localbrake = std::clamp(eim_localbrake, 0.0, 1.0); + if (eim_localbrake > 0.04 && eimic > 0) + eimic = 0; +} + +// the value limited by the power, the spring brake, the pipe lock, the direction and the doors' permits +void TMoverParameters::EIMICLimit() +{ auto const eimicpowerenabled{(MainCircuitPowered() || Power == 0.0) && (!SpringBrake.IsActive || !SpringBrakeCutsOffDrive) && !LockPipe && DirAbsolute != 0}; auto const eimicdoorenabled{(SpringBrake.IsActive && ReleaseParkingBySpringBrakeWhenDoorIsOpen)}; double eimic_max = 0.0; @@ -7985,6 +9579,19 @@ void TMoverParameters::CheckEIMIC(double dt) eimic = safe_clamp(eimic, -1.0, eimicpowerenabled ? eimic_max : 0.0); } +bool TMoverParameters::UpdateStopBrakeRelease(double const Demand, double const Dt) +{ + if (Demand <= 0.0) + { + StopBrakeReleaseTimer = 0.0; + return false; + } + // the step the demand rises above 0 is time 0 of it, so without the delay the brake lets go at once, as it always did + auto const released{StopBrakeReleaseTimer >= StopBrakeReleaseDelay}; + StopBrakeReleaseTimer += Dt; + return released; +} + void TMoverParameters::CheckSpeedCtrl(double dt) { if (EIMCtrlType == 0) @@ -8016,40 +9623,7 @@ void TMoverParameters::CheckSpeedCtrl(double dt) { if (!SpeedCtrlUnit.Standby) { - if (SpeedCtrlUnit.ManualStateOverride && eimic > 0.0009) - eimic = 1.0; - double error = std::max(SpeedCtrlValue + SpeedCtrlUnit.Offset, 0.0) - Vel; - double factorP = error > 0 ? SpeedCtrlUnit.FactorPpos : SpeedCtrlUnit.FactorPneg; - double eSCP = std::clamp(factorP * error, -1.2, 1.0); // P module - bool retarder_not_work = EngineType != TEngineType::DieselEngine || Vel < SpeedCtrlUnit.BrakeInterventionVel; - if (eSCP < -1.0) - { - SpeedCtrlUnit.BrakeInterventionBraking = eSCP < -1.1 && retarder_not_work && eimicSpeedCtrl < -0.99 * SpeedCtrlUnit.DesiredPower; - eSCP = -1.0; - } - SpeedCtrlUnit.BrakeInterventionUnbraking = eSCP > 0.0 || Vel == 0.0; - if (abs(eSCP) < 0.999) - { - // TODO: check how to disable integral part when braking in smart way - // double factorI = eimicSpeedCtrlIntegral >= 0 ? SpeedCtrlUnit.FactorIpos : SpeedCtrlUnit.FactorIneg; - double factorI = eimicSpeedCtrlIntegral >= 0 ? SpeedCtrlUnit.FactorIpos : SpeedCtrlUnit.FactorIneg; - eimicSpeedCtrlIntegral = safe_clamp(eimicSpeedCtrlIntegral + factorI * eSCP * dt, -1.0 + eSCP, 1.0 - eSCP); - } - else - { - eimicSpeedCtrlIntegral = 0; - } - auto const DesiredeimicSpeedCtrl{safe_clamp(eimicSpeedCtrlIntegral + eSCP, -SpeedCtrlUnit.DesiredPower, accfactor)}; - eimicSpeedCtrl = safe_clamp(DesiredeimicSpeedCtrl, eimicSpeedCtrl - SpeedCtrlUnit.PowerDownSpeed * dt, eimicSpeedCtrl + SpeedCtrlUnit.PowerUpSpeed * dt); - if (Vel < SpeedCtrlUnit.FullPowerVelocity) - { - eimicSpeedCtrl = std::min(eimicSpeedCtrl, SpeedCtrlUnit.InitialPower); - } - if (Vel < SpeedCtrlUnit.StartVelocity && MainCtrlPos < MainCtrlPosNo) - { - eimicSpeedCtrl = 0; - eimic = 0; - } + SpeedCtrlRegulator(dt, accfactor); } else { @@ -8068,7 +9642,7 @@ void TMoverParameters::CheckSpeedCtrl(double dt) } if ((SpeedCtrlAutoTurnOffFlag & 2) == 2 && Hamulec->GetEDBCP() > 0.25) { - DecScndCtrl(2); + SpeedCtrlSwitch(false); SpeedCtrlUnit.IsActive = false; } } @@ -8081,9 +9655,87 @@ void TMoverParameters::CheckSpeedCtrl(double dt) } } +// the PI regulator of the speed control: the power asked of the drive, or its brake intervention, from the error of +// the speed; accfactor, the most power it may ask +void TMoverParameters::SpeedCtrlRegulator(double dt, double const accfactor) +{ + if (SpeedCtrlUnit.ManualStateOverride && eimic > 0.0009) + eimic = 1.0; + double error = std::max(SpeedCtrlValue + SpeedCtrlUnit.Offset, 0.0) - Vel; + double factorP = error > 0 ? SpeedCtrlUnit.FactorPpos : SpeedCtrlUnit.FactorPneg; + double eSCP = std::clamp(factorP * error, -1.2, 1.0); // P module + bool retarder_not_work = EngineType != TEngineType::DieselEngine || Vel < SpeedCtrlUnit.BrakeInterventionVel; + if (eSCP < -1.0) + { + SpeedCtrlUnit.BrakeInterventionBraking = eSCP < -1.1 && retarder_not_work && eimicSpeedCtrl < -0.99 * SpeedCtrlUnit.DesiredPower; + eSCP = -1.0; + } + SpeedCtrlUnit.BrakeInterventionUnbraking = eSCP > 0.0 || Vel == 0.0; + if (abs(eSCP) < 0.999) + { + // TODO: check how to disable integral part when braking in smart way + // double factorI = eimicSpeedCtrlIntegral >= 0 ? SpeedCtrlUnit.FactorIpos : SpeedCtrlUnit.FactorIneg; + double factorI = eimicSpeedCtrlIntegral >= 0 ? SpeedCtrlUnit.FactorIpos : SpeedCtrlUnit.FactorIneg; + eimicSpeedCtrlIntegral = safe_clamp(eimicSpeedCtrlIntegral + factorI * eSCP * dt, -1.0 + eSCP, 1.0 - eSCP); + } + else + { + eimicSpeedCtrlIntegral = 0; + } + auto const DesiredeimicSpeedCtrl{safe_clamp(eimicSpeedCtrlIntegral + eSCP, -SpeedCtrlUnit.DesiredPower, accfactor)}; + eimicSpeedCtrl = safe_clamp(DesiredeimicSpeedCtrl, eimicSpeedCtrl - SpeedCtrlUnit.PowerDownSpeed * dt, eimicSpeedCtrl + SpeedCtrlUnit.PowerUpSpeed * dt); + if (Vel < SpeedCtrlUnit.FullPowerVelocity) + { + eimicSpeedCtrl = std::min(eimicSpeedCtrl, SpeedCtrlUnit.InitialPower); + } + if (Vel < SpeedCtrlUnit.StartVelocity && MainCtrlPos < MainCtrlPosNo) + { + eimicSpeedCtrl = 0; + eimic = 0; + } +} + +bool TMoverParameters::IsSpeedCtrlSeparate() const +{ + // no secondary controller, or one of these engines', which shunts the field of the traction motors (eu07/maszyna#69) + return SpeedCtrl && (ScndCtrlPosNo == 0 || EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric); +} + +bool TMoverParameters::IsSpeedCtrlEngaged() const +{ + return IsSpeedCtrlSeparate() ? SpeedCtrlUnit.IsActive : ScndCtrlPos > 0; +} + +bool TMoverParameters::SpeedCtrlSwitch(bool const State) +{ + if (false == IsSpeedCtrlSeparate()) + { + return State ? IncScndCtrl(1) : DecScndCtrl(2); + } + // its own switch, the secondary controller left to the field shunting + if (State) + { + if (CabActive == 0 || SpeedCtrlUnit.IsActive) + { + return false; + } + SpeedCtrlValue = static_cast(Round(Vel)); + SpeedCtrlUnit.IsActive = true; + return true; + } + auto const wasactive{SpeedCtrlUnit.IsActive}; + SpeedCtrlValue = 0; + SpeedCtrlUnit.IsActive = false; + if (wasactive && SpeedCtrlUnit.ManualStateOverride) + { + eimic = 0.0; + } + return wasactive; +} + void TMoverParameters::SpeedCtrlButton(int button) { - if (SpeedCtrl && ScndCtrlPos > 0) + if (SpeedCtrl && IsSpeedCtrlEngaged()) { SpeedCtrlValue = SpeedCtrlButtons[button]; } @@ -8091,7 +9743,7 @@ void TMoverParameters::SpeedCtrlButton(int button) void TMoverParameters::SpeedCtrlInc() { - if (SpeedCtrl && ScndCtrlPos > 0) + if (SpeedCtrl && IsSpeedCtrlEngaged()) { double x = floor(SpeedCtrlValue / SpeedCtrlUnit.VelocityStep) + 1.0; SpeedCtrlValue = std::min(x * SpeedCtrlUnit.VelocityStep, SpeedCtrlUnit.MaxVelocity); @@ -8100,7 +9752,7 @@ void TMoverParameters::SpeedCtrlInc() void TMoverParameters::SpeedCtrlDec() { - if (SpeedCtrl && ScndCtrlPos > 0) + if (SpeedCtrl && IsSpeedCtrlEngaged()) { double x = ceil(SpeedCtrlValue / SpeedCtrlUnit.VelocityStep) - 1.0; SpeedCtrlValue = std::max(x * SpeedCtrlUnit.VelocityStep, SpeedCtrlUnit.MinVelocity); @@ -8109,7 +9761,7 @@ void TMoverParameters::SpeedCtrlDec() bool TMoverParameters::SpeedCtrlPowerInc() { - if (!(SpeedCtrl && ScndCtrlPos > 0)) + if (!(SpeedCtrl && IsSpeedCtrlEngaged())) return false; if (SpeedCtrlUnit.DesiredPower == SpeedCtrlUnit.MaxPower) @@ -8121,7 +9773,7 @@ bool TMoverParameters::SpeedCtrlPowerInc() bool TMoverParameters::SpeedCtrlPowerDec() { - if (!(SpeedCtrl && ScndCtrlPos > 0)) + if (!(SpeedCtrl && IsSpeedCtrlEngaged())) return false; if (SpeedCtrlUnit.DesiredPower == SpeedCtrlUnit.MinPower) @@ -8196,108 +9848,142 @@ bool TMoverParameters::dizel_AutoGearCheck(void) if (motor_param(ScndCtrlActualPos).AutoSwitch && Mains) { - if (RList[MainCtrlPos].Mn == 0 && !hydro_TC) - { - if (dizel_engagestate > 0) - dizel_EngageSwitch(0); - if (IsMainCtrlNoPowerPos() && ScndCtrlActualPos > 0) - dizel_automaticgearstatus = -1; - } - else - { - if (motor_param(ScndCtrlActualPos).AutoSwitch && dizel_automaticgearstatus == 0) // sprawdz czy zmienic biegi - { - if (Vel > VelUp) - { - // shift up - if (ScndCtrlActualPos < ScndCtrlPosNo) - { - dizel_automaticgearstatus = 1; - OK = true; - } - } - else if (Vel < VelDown) - { - // shift down - if (ScndCtrlActualPos > 0) - { - dizel_automaticgearstatus = -1; - OK = true; - } - } - } - } - if (dizel_engage < 0.1 && dizel_automaticgearstatus != 0) - { - if (dizel_automaticgearstatus == 1) - ScndCtrlActualPos++; - else - ScndCtrlActualPos--; - dizel_automaticgearstatus = 0; - dizel_EngageSwitch(1.0); - OK = true; - } + OK = dizel_GearShiftCheck(VelUp, VelDown); } if (Mains) { - if (EIMCtrlType > 0) // sterowanie komputerowe - { - if (dizel_automaticgearstatus == 0) - { - if ((hydro_TC && hydro_TC_Fill > 0.01) || eimic_real > 0.005) - dizel_EngageSwitch(1.0); - else if (Vel > hydro_R_EngageVel && hydro_R && hydro_R_Fill > 0.01) - dizel_EngageSwitch(0.5); - else - dizel_EngageSwitch(0.0); - } - else - dizel_EngageSwitch(0.0); - } - else if (dizel_automaticgearstatus == 0) // ustaw cisnienie w silowniku sprzegla} - switch (RList[MainCtrlPos].Mn) - { - case 1: - dizel_EngageSwitch(0.5); - break; - case 2: - dizel_EngageSwitch(1.0); - break; - case 3: - if (Vel > dizel_minVelfullengage) - dizel_EngageSwitch(1.0); - else - dizel_EngageSwitch(0.5); - break; - case 4: - if (Vel > dizel_minVelfullengage) - dizel_EngageSwitch(1.0); - else - dizel_EngageSwitch(0.66); - break; - case 5: - if (Vel > dizel_minVelfullengage) - dizel_EngageSwitch(1.0); - else - dizel_EngageSwitch(0.35 * (1 + RList[MainCtrlPos].R) * RList[MainCtrlPos].R); - break; - default: - if (hydro_TC && hydro_TC_Fill > 0.01) - dizel_EngageSwitch(1.0); - else - dizel_EngageSwitch(0.0); - } - else - dizel_EngageSwitch(0.0); - if (!(motor_param(ScndCtrlActualPos).mIsat > 0)) - dizel_EngageSwitch(0.0); // wylacz sprzeglo na pozycjach neutralnych - if (!AutoRelayFlag) - ScndCtrlActualPos = ScndCtrlPos; + dizel_ClutchCheck(); } return OK; } +// the automatic gearbox: a gear up over VelUp, down under VelDown, changed once the clutch is out; returns whether it acted +bool TMoverParameters::dizel_GearShiftCheck(double const VelUp, double const VelDown) +{ + auto OK{false}; + if (RList[MainCtrlPos].Mn == 0 && !hydro_TC) + { + if (dizel_engagestate > 0) + dizel_EngageSwitch(0); + if (IsMainCtrlNoPowerPos() && ScndCtrlActualPos > 0) + dizel_automaticgearstatus = -1; + } + else + { + OK = dizel_GearShiftRequest(VelUp, VelDown); + } + if (dizel_engage < 0.1 && dizel_automaticgearstatus != 0) + { + if (dizel_automaticgearstatus == 1) + ScndCtrlActualPos++; + else + ScndCtrlActualPos--; + dizel_automaticgearstatus = 0; + dizel_EngageSwitch(1.0); + OK = true; + } + return OK; +} + +// a gear up asked over VelUp, down under VelDown, where the gearbox shifts by itself; returns whether one is +bool TMoverParameters::dizel_GearShiftRequest(double const VelUp, double const VelDown) +{ + auto OK{false}; + if (motor_param(ScndCtrlActualPos).AutoSwitch && dizel_automaticgearstatus == 0) // sprawdz czy zmienic biegi + { + if (Vel > VelUp) + { + // shift up + if (ScndCtrlActualPos < ScndCtrlPosNo) + { + dizel_automaticgearstatus = 1; + OK = true; + } + } + else if (Vel < VelDown) + { + // shift down + if (ScndCtrlActualPos > 0) + { + dizel_automaticgearstatus = -1; + OK = true; + } + } + } + return OK; +} + +// the pressure in the clutch's cylinder, by the controller's position or the integrated controller +void TMoverParameters::dizel_ClutchCheck() +{ + if (EIMCtrlType > 0) // sterowanie komputerowe + { + dizel_ClutchByIntegratedController(); + } + else if (dizel_automaticgearstatus == 0) // ustaw cisnienie w silowniku sprzegla} + dizel_ClutchByController(); + else + dizel_EngageSwitch(0.0); + if (!(motor_param(ScndCtrlActualPos).mIsat > 0)) + dizel_EngageSwitch(0.0); // wylacz sprzeglo na pozycjach neutralnych + if (!AutoRelayFlag) + ScndCtrlActualPos = ScndCtrlPos; +} + +// the clutch by the controller's position: half or fully in, fully over the speed of the full engagement +void TMoverParameters::dizel_ClutchByController() +{ + switch (RList[MainCtrlPos].Mn) + { + case 1: + dizel_EngageSwitch(0.5); + break; + case 2: + dizel_EngageSwitch(1.0); + break; + case 3: + if (Vel > dizel_minVelfullengage) + dizel_EngageSwitch(1.0); + else + dizel_EngageSwitch(0.5); + break; + case 4: + if (Vel > dizel_minVelfullengage) + dizel_EngageSwitch(1.0); + else + dizel_EngageSwitch(0.66); + break; + case 5: + if (Vel > dizel_minVelfullengage) + dizel_EngageSwitch(1.0); + else + dizel_EngageSwitch(0.35 * (1 + RList[MainCtrlPos].R) * RList[MainCtrlPos].R); + break; + default: + if (hydro_TC && hydro_TC_Fill > 0.01) + dizel_EngageSwitch(1.0); + else + dizel_EngageSwitch(0.0); + } +} + +// the clutch of the integrated controller: in with the converter filled or the power asked, half in for the retarder +void TMoverParameters::dizel_ClutchByIntegratedController() +{ + if (dizel_automaticgearstatus == 0) + { + if ((hydro_TC && hydro_TC_Fill > 0.01) || eimic_real > 0.005) + dizel_EngageSwitch(1.0); + else if (Vel > hydro_R_EngageVel && hydro_R && hydro_R_Fill > 0.01) + dizel_EngageSwitch(0.5); + else + dizel_EngageSwitch(0.0); + } + else + dizel_EngageSwitch(0.0); +} + // performs diesel engine startup procedure; potentially clears startup switch; returns: true if the engine can be started, false otherwise bool TMoverParameters::dizel_StartupCheck() { @@ -8418,26 +10104,7 @@ double TMoverParameters::dizel_fillcheck(int mcp, double dt) // napelnienie zalezne od MainCtrlPos if (EIMCtrlType > 0) { - realfill = std::max(0.0, std::min(eimic_real, 1 - motor_param(ScndCtrlActualPos).Isat)); - if (eimic_real > 0.005 && !hydro_TC_Lockup) - { - dizel_nreg_min = std::min(dizel_nreg_min + 2.5 * dt, dizel_nmin_hdrive + eimic_real * dizel_nmin_hdrive_factor); - } - else - { - if (Vel < hydro_R_EngageVel && hydro_R && hydro_R_Fill > 0.01) - dizel_nreg_min = std::min(dizel_nreg_min + 5.0 * dt, dizel_nmin_retarder); - else - dizel_nreg_min = dizel_nmin; - } - if (!dizel_vel2nmax_Table.empty() && !hydro_TC_Lockup) - { - dizel_nreg_max = std::min(std::min(dizel_nreg_max, enrot) + dizel_nreg_acc * dt, TableInterpolation(dizel_vel2nmax_Table, Vel)); - } - else - { - dizel_nreg_max = dizel_nmax; - } + realfill = dizel_DigitalFill(dt); } else { @@ -8447,54 +10114,97 @@ double TMoverParameters::dizel_fillcheck(int mcp, double dt) } if (dizel_nmax_cutoff > 0) { - auto nreg{0.0}; - if (EIMCtrlType > 0) - nreg = eimic_real > 0.005 ? dizel_nreg_max : dizel_nmin; - else - switch (RList[MainCtrlPos].Mn) - { - case 0: - case 1: - nreg = dizel_nmin; - break; - case 2: - if (dizel_automaticgearstatus == 0 && true /*(!hydro_TC) || (dizel_engage>dizel_fill)*/) - nreg = dizel_nreg_max; - else - nreg = dizel_nmin; - break; - case 3: - if (dizel_automaticgearstatus == 0 && Vel > dizel_minVelfullengage) - nreg = dizel_nreg_max; - else - nreg = dizel_nmin; - break; - case 4: - if (dizel_automaticgearstatus == 0 && Vel > dizel_minVelfullengage) - nreg = dizel_nmax; - else - nreg = dizel_nmin * 0.75 + dizel_nreg_max * 0.25; - break; - case 5: - if (Vel > dizel_minVelfullengage) - nreg = dizel_nreg_max; - else - nreg = dizel_nmin + 0.8 * (dizel_nreg_max - dizel_nmin) * RList[mcp].R; - break; - default: - realfill = 0; // sluczaj - break; - } - if (enrot > nreg) // nad predkoscia regulatora zeruj dawke - realfill = 0; - if (enrot < dizel_nreg_min && RList[mcp].R > 0.001) // jesli ponizej biegu jalowego i niezerowa dawka, to dawaj pelna - realfill = 1; + realfill = dizel_GovernorFill(mcp, realfill); } } return std::clamp(realfill, 0.0, 1.0); } +// the fill set by the integrated controller, and the idle and top revolutions the governor keeps to +double TMoverParameters::dizel_DigitalFill(double dt) +{ + double realfill; + realfill = std::max(0.0, std::min(eimic_real, 1 - motor_param(ScndCtrlActualPos).Isat)); + if (eimic_real > 0.005 && !hydro_TC_Lockup) + { + dizel_nreg_min = std::min(dizel_nreg_min + 2.5 * dt, dizel_nmin_hdrive + eimic_real * dizel_nmin_hdrive_factor); + } + else + { + if (Vel < hydro_R_EngageVel && hydro_R && hydro_R_Fill > 0.01) + dizel_nreg_min = std::min(dizel_nreg_min + 5.0 * dt, dizel_nmin_retarder); + else + dizel_nreg_min = dizel_nmin; + } + if (!dizel_vel2nmax_Table.empty() && !hydro_TC_Lockup) + { + dizel_nreg_max = std::min(std::min(dizel_nreg_max, enrot) + dizel_nreg_acc * dt, TableInterpolation(dizel_vel2nmax_Table, Vel)); + } + else + { + dizel_nreg_max = dizel_nmax; + } + return realfill; +} + +// the fill cut off over the revolutions the governor allows at the controller's position, or full under the idle ones +double TMoverParameters::dizel_GovernorFill(int const mcp, double realfill) const +{ + auto nreg{0.0}; + if (EIMCtrlType > 0) + nreg = eimic_real > 0.005 ? dizel_nreg_max : dizel_nmin; + else + nreg = dizel_GovernorRevolutions(mcp, realfill); + if (enrot > nreg) // nad predkoscia regulatora zeruj dawke + realfill = 0; + if (enrot < dizel_nreg_min && RList[mcp].R > 0.001) // jesli ponizej biegu jalowego i niezerowa dawka, to dawaj pelna + realfill = 1; + return realfill; +} + +// the revolutions the governor allows at the controller's position, the gearbox and the speed; the fill cut off at +// a position the governor doesn't know +double TMoverParameters::dizel_GovernorRevolutions(int const mcp, double &realfill) const +{ + auto nreg{0.0}; + switch (RList[MainCtrlPos].Mn) + { + case 0: + case 1: + nreg = dizel_nmin; + break; + case 2: + if (dizel_automaticgearstatus == 0 && true /*(!hydro_TC) || (dizel_engage>dizel_fill)*/) + nreg = dizel_nreg_max; + else + nreg = dizel_nmin; + break; + case 3: + if (dizel_automaticgearstatus == 0 && Vel > dizel_minVelfullengage) + nreg = dizel_nreg_max; + else + nreg = dizel_nmin; + break; + case 4: + if (dizel_automaticgearstatus == 0 && Vel > dizel_minVelfullengage) + nreg = dizel_nmax; + else + nreg = dizel_nmin * 0.75 + dizel_nreg_max * 0.25; + break; + case 5: + if (Vel > dizel_minVelfullengage) + nreg = dizel_nreg_max; + else + nreg = dizel_nmin + 0.8 * (dizel_nreg_max - dizel_nmin) * RList[mcp].R; + break; + default: + realfill = 0; // sluczaj + break; + } + return nreg; +} + // ************************************************************************************************* // Q: 20160715 // Oblicza moment siły wytwarzany przez silnik spalinowy @@ -8547,38 +10257,7 @@ double TMoverParameters::dizel_Momentum(double Fill, double n, double dt) dizel_Torque = Moment; - if (hydro_TC) // jesli przetwornik momentu - { - // napelnianie przetwornika - bool IsPower = EIMCtrlType > 0 ? eimic_real > 0.005 : MainCtrlPowerPos() > 0; - if (IsPower && Mains && enrot > dizel_nmin * 0.9) - hydro_TC_Fill += hydro_TC_FillRateInc * dt; - // oproznianie przetwornika - if ((!IsPower && Vel < dizel_maxVelANS) || !Mains || enrot < dizel_nmin * 0.8) - hydro_TC_Fill -= hydro_TC_FillRateDec * dt; - // obcinanie zakresu - hydro_TC_Fill = std::clamp(hydro_TC_Fill, 0.0, 1.0); - - // blokowanie sprzegla blokującego - if (Vel > hydro_TC_LockupSpeed && Mains && enrot > 0.9 * dizel_nmin && IsPower) - { - hydro_TC_Lockup = true; - hydro_TC_LockupRate += hydro_TC_FillRateInc * dt; - } - // luzowanie sprzegla blokujacego - if (Vel < (IsPower ? hydro_TC_LockupSpeed : hydro_TC_UnlockSpeed) || !Mains || enrot < 0.8 * dizel_nmin) - { - hydro_TC_Lockup = false; - hydro_TC_LockupRate -= hydro_TC_FillRateDec * dt; - } - // obcinanie zakresu - hydro_TC_LockupRate = std::clamp(hydro_TC_LockupRate, 0.0, 1.0); - } - else - { - hydro_TC_Fill = 0.0; - hydro_TC_LockupRate = 0.0; - } + hydro_TCFillCheck(dt); // obliczanie momentow poszczegolnych sprzegiel // sprzeglo glowne (skrzynia biegow) @@ -8586,32 +10265,7 @@ double TMoverParameters::dizel_Momentum(double Fill, double n, double dt) if (hydro_TC) // jesli hydro { - double HydroTorque = 0; - HydroTorque += hydro_TC_nIn * hydro_TC_nIn * hydro_TC_TorqueInIn; - HydroTorque += (hydro_TC_nIn - hydro_TC_nOut) * hydro_TC_TorqueInOut; - HydroTorque += hydro_TC_nOut * hydro_TC_nOut * hydro_TC_TorqueOutOut; - double nOut2In = hydro_TC_nOut / std::max(0.01, hydro_TC_nIn); - if (hydro_TC_Table.size() > 1) - { - hydro_TC_TMRatio = TableInterpolation(hydro_TC_Table, nOut2In); - hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; - hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill * std::min(1.0, hydro_TC_TMRatio); - } - else - { - if (nOut2In < hydro_TC_CouplingPoint) - { - hydro_TC_TMRatio = 1 + (hydro_TC_TMMax - 1) * square(1 - nOut2In / hydro_TC_CouplingPoint); - hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill; - hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; - } - else - { - hydro_TC_TMRatio = (1 - nOut2In) / (1 - hydro_TC_CouplingPoint); - hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; - hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; - } - } + hydro_TCTorque(); TorqueH = hydro_TC_TorqueOut; TorqueL = hydro_TC_LockupTorque * hydro_TC_LockupRate; } @@ -8683,6 +10337,74 @@ double TMoverParameters::dizel_Momentum(double Fill, double n, double dt) return gearMoment; } +// the torque converter filled and emptied, and its lockup clutch engaged and released, by the power and the speed +void TMoverParameters::hydro_TCFillCheck(double dt) +{ + if (hydro_TC) // jesli przetwornik momentu + { + // napelnianie przetwornika + bool IsPower = EIMCtrlType > 0 ? eimic_real > 0.005 : MainCtrlPowerPos() > 0; + if (IsPower && Mains && enrot > dizel_nmin * 0.9) + hydro_TC_Fill += hydro_TC_FillRateInc * dt; + // oproznianie przetwornika + if ((!IsPower && Vel < dizel_maxVelANS) || !Mains || enrot < dizel_nmin * 0.8) + hydro_TC_Fill -= hydro_TC_FillRateDec * dt; + // obcinanie zakresu + hydro_TC_Fill = std::clamp(hydro_TC_Fill, 0.0, 1.0); + + // blokowanie sprzegla blokującego + if (Vel > hydro_TC_LockupSpeed && Mains && enrot > 0.9 * dizel_nmin && IsPower) + { + hydro_TC_Lockup = true; + hydro_TC_LockupRate += hydro_TC_FillRateInc * dt; + } + // luzowanie sprzegla blokujacego + if (Vel < (IsPower ? hydro_TC_LockupSpeed : hydro_TC_UnlockSpeed) || !Mains || enrot < 0.8 * dizel_nmin) + { + hydro_TC_Lockup = false; + hydro_TC_LockupRate -= hydro_TC_FillRateDec * dt; + } + // obcinanie zakresu + hydro_TC_LockupRate = std::clamp(hydro_TC_LockupRate, 0.0, 1.0); + } + else + { + hydro_TC_Fill = 0.0; + hydro_TC_LockupRate = 0.0; + } +} + +// the torque converter's moments on its input and output shafts, by their revolutions and its fill +void TMoverParameters::hydro_TCTorque() +{ + double HydroTorque = 0; + HydroTorque += hydro_TC_nIn * hydro_TC_nIn * hydro_TC_TorqueInIn; + HydroTorque += (hydro_TC_nIn - hydro_TC_nOut) * hydro_TC_TorqueInOut; + HydroTorque += hydro_TC_nOut * hydro_TC_nOut * hydro_TC_TorqueOutOut; + double nOut2In = hydro_TC_nOut / std::max(0.01, hydro_TC_nIn); + if (hydro_TC_Table.size() > 1) + { + hydro_TC_TMRatio = TableInterpolation(hydro_TC_Table, nOut2In); + hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; + hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill * std::min(1.0, hydro_TC_TMRatio); + } + else + { + if (nOut2In < hydro_TC_CouplingPoint) + { + hydro_TC_TMRatio = 1 + (hydro_TC_TMMax - 1) * square(1 - nOut2In / hydro_TC_CouplingPoint); + hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill; + hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; + } + else + { + hydro_TC_TMRatio = (1 - nOut2In) / (1 - hydro_TC_CouplingPoint); + hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; + hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; + } + } +} + double TMoverParameters::dizel_MomentumRetarder(double n, double dt) { double RetarderRequest = Mains ? std::max(0.0, -eimic_real) : 0; @@ -9274,89 +10996,8 @@ void TMoverParameters::update_doors(double const Deltatime) for (auto &door : Doors.instances) { - // revoke permit if... - door.open_permit = true == door.open_permit // ...we already have one... - && (false == Doors.permit_presets.empty() // ...there's no preset switch controlling permit state... - || (false == Doors.is_locked // ...and the door lock is engaged... - && false == door.remote_close)); // ...or the door is about to be closed - - door.is_open = door.position >= Doors.range && (false == Doors.step_enabled || door.step_position >= (Doors.step_range != 0.f ? 1.f : 0.f)); - door.is_closed = door.position <= 0.f && door.step_position <= 0.f; - door.is_door_closed = door.position <= 0.f; - - door.local_open = door.local_open && false == door.is_open && (false == Doors.permit_needed || door.open_permit); - door.remote_open = (door.remote_open || Doors.remote_only) && false == door.is_open && (false == Doors.permit_needed || door.open_permit); - door.local_close = door.local_close && false == door.is_closed && (false == remoteopencontrol || false == door.remote_open); - door.remote_close = door.remote_close && false == door.is_closed && (false == localopencontrol || false == door.local_open); - - auto const autoopenrequest{Doors.open_control == control_t::autonomous && (false == Doors.permit_needed || door.open_permit)}; - auto const openrequest{(localopencontrol && door.local_open) || (remoteopencontrol && door.remote_open) || (autoopenrequest && false == door.is_open)}; - - auto const autocloserequest{(Doors.auto_velocity != -1.f && Vel > Doors.auto_velocity) || (door.auto_timer != -1.f && door.auto_timer <= 0.f) || - (Doors.permit_needed && false == door.open_permit)}; - auto const closerequest{(door.remote_close && remoteclosecontrol) || (door.local_close && localclosecontrol) || (autocloserequest && door.is_open)}; - - auto const ispowered{(Doors.voltage == 0 ? true : Doors.voltage == 24 ? Power24vIsAvailable || Power110vIsAvailable : Doors.voltage == 110 ? Power110vIsAvailable : false)}; - - door.is_opening = false == door.is_open && true == ispowered && false == closerequest && (true == door.is_opening || (true == openrequest && false == Doors.is_locked)); - door.is_closing = false == door.is_closed && true == ispowered && false == openrequest && (door.is_closing || closerequest); - door.step_unfolding = Doors.step_range != 0.f && Doors.step_enabled && false == Doors.is_locked && door.step_position < 1.f && door.is_opening; - door.step_folding = door.step_position > 0.f // is unfolded - && (false == Doors.step_enabled // we lost permission to stay open or our door is calling the shots - || (Doors.permit_needed ? false == door.open_permit : door.is_closing)) && - (door.close_delay > Doors.close_delay || door.position <= 0.f); // door is about to close, or already done - - if (true == door.is_opening) - { - door.auto_timer = localopencontrol && door.local_open ? Doors.auto_duration : remoteopencontrol && door.remote_open && Doors.auto_include_remote ? Doors.auto_duration : -1.f; - } - // doors - if (true == door.is_opening) - { - // open door - if (false == door.step_unfolding // no wait if no doorstep - || Doors.step_type == 2) - { // no wait for rotating doorstep - door.open_delay += static_cast(Deltatime); - if (door.open_delay > Doors.open_delay) - { - door.position = std::min(Doors.range, static_cast(door.position + Doors.open_rate * Deltatime)); - } - } - door.close_delay = 0.f; - } - if (true == door.is_closing) - { - // close door - door.close_delay += static_cast(Deltatime); - if (door.close_delay > Doors.close_delay) - { - door.position = std::max(0.f, static_cast(door.position - Doors.close_rate * Deltatime)); - } - door.open_delay = 0.f; - } - // doorsteps - if (door.step_unfolding) - { - // unfold left doorstep - door.step_position = std::min(1.f, static_cast(door.step_position + Doors.step_rate * Deltatime)); - } - if (door.step_folding) - { - // fold left doorstep - if (TrainType == dt_EZT || TrainType == dt_DMU) - { - // multi-unit vehicles typically fold the doorstep only after closing the door - if (door.position <= 0.f) - { - door.step_position = std::max(0.f, static_cast(door.step_position - Doors.step_rate * Deltatime)); - } - } - else - { - door.step_position = std::max(0.f, static_cast(door.step_position - Doors.step_rate * Deltatime)); - } - } + update_door_requests(door, localopencontrol, remoteopencontrol, localclosecontrol, remoteclosecontrol); + move_door(door, Deltatime); } if (false == Doors.instances[side::right].is_open && false == Doors.instances[side::left].is_open) @@ -9366,25 +11007,7 @@ void TMoverParameters::update_doors(double const Deltatime) if (Doors.auto_duration > 0.f) { - // update door timers if the door close after defined time - for (auto &door : Doors.instances) - { - - if (false == door.is_open) - { - continue; - } - - if (door.auto_timer > 0.f) - { - door.auto_timer -= static_cast(Deltatime); - } - // if there's load exchange in progress, reset the timer(s) for already open doors - if (door.auto_timer != -1.f && (LoadStatus & (2 | 1)) != 0) - { - door.auto_timer = Doors.auto_duration; - } - } + update_door_timers(Deltatime); } /* // the door are closed if their timer goes below 0, or if the vehicle is moving faster than defined threshold @@ -9402,6 +11025,169 @@ void TMoverParameters::update_doors(double const Deltatime) */ } +// the permit, the state and the requests of a door, and whether it and its step open or close +void TMoverParameters::update_door_requests(basic_door &door, bool const localopencontrol, bool const remoteopencontrol, bool const localclosecontrol, bool const remoteclosecontrol) +{ + // revoke permit if... + door.open_permit = true == door.open_permit // ...we already have one... + && (false == Doors.permit_presets.empty() // ...there's no preset switch controlling permit state... + || (false == Doors.is_locked // ...and the door lock is engaged... + && false == door.remote_close)); // ...or the door is about to be closed + + door.is_open = door.position >= Doors.range && (false == Doors.step_enabled || door.step_position >= (Doors.step_range != 0.f ? 1.f : 0.f)); + door.is_closed = door.position <= 0.f && door.step_position <= 0.f; + door.is_door_closed = door.position <= 0.f; + + door.local_open = door.local_open && false == door.is_open && (false == Doors.permit_needed || door.open_permit); + door.remote_open = (door.remote_open || Doors.remote_only) && false == door.is_open && (false == Doors.permit_needed || door.open_permit); + door.local_close = door.local_close && false == door.is_closed && (false == remoteopencontrol || false == door.remote_open); + door.remote_close = door.remote_close && false == door.is_closed && (false == localopencontrol || false == door.local_open); + + auto const openrequest{door_open_request(door, localopencontrol, remoteopencontrol)}; + auto const closerequest{door_close_request(door, localclosecontrol, remoteclosecontrol)}; + auto const ispowered{doors_powered()}; + + door.is_opening = false == door.is_open && true == ispowered && false == closerequest && (true == door.is_opening || (true == openrequest && false == Doors.is_locked)); + door.is_closing = false == door.is_closed && true == ispowered && false == openrequest && (door.is_closing || closerequest); + door.step_unfolding = Doors.step_range != 0.f && Doors.step_enabled && false == Doors.is_locked && door.step_position < 1.f && door.is_opening; + door.step_folding = door_step_folding(door); + + if (true == door.is_opening) + { + door.auto_timer = door_open_duration(door, localopencontrol, remoteopencontrol); + } +} + +// whether the door is asked to open, by the passengers, from afar or by itself +bool TMoverParameters::door_open_request(basic_door const &door, bool const localopencontrol, bool const remoteopencontrol) const +{ + auto const autoopenrequest{Doors.open_control == control_t::autonomous && (false == Doors.permit_needed || door.open_permit)}; + return (localopencontrol && door.local_open) || (remoteopencontrol && door.remote_open) || (autoopenrequest && false == door.is_open); +} + +// whether the door is asked to close, by the passengers, from afar, or by itself: over the speed, after its time or +// with its permit taken back +bool TMoverParameters::door_close_request(basic_door const &door, bool const localclosecontrol, bool const remoteclosecontrol) const +{ + auto const autocloserequest{(Doors.auto_velocity != -1.f && Vel > Doors.auto_velocity) || (door.auto_timer != -1.f && door.auto_timer <= 0.f) || + (Doors.permit_needed && false == door.open_permit)}; + return (door.remote_close && remoteclosecontrol) || (door.local_close && localclosecontrol) || (autocloserequest && door.is_open); +} + +// whether the doors have the voltage they work on +bool TMoverParameters::doors_powered() const +{ + if (Doors.voltage == 0) + { + return true; + } + if (Doors.voltage == 24) + { + return Power24vIsAvailable || Power110vIsAvailable; + } + return Doors.voltage == 110 && Power110vIsAvailable; +} + +// whether the unfolded step folds: without the permission to stay out, or with the door closing, once it's about to +// close or closed +bool TMoverParameters::door_step_folding(basic_door const &door) const +{ + auto const unfolded{door.step_position > 0.f}; + auto const mayfold{false == Doors.step_enabled || (Doors.permit_needed ? false == door.open_permit : door.is_closing)}; + return unfolded && mayfold && (door.close_delay > Doors.close_delay || door.position <= 0.f); +} + +// how long the opening door stays open: the time of the doors, for the passengers' opening and, if it counts, the +// opening from afar; none otherwise +float TMoverParameters::door_open_duration(basic_door const &door, bool const localopencontrol, bool const remoteopencontrol) const +{ + if (localopencontrol && door.local_open) + { + return Doors.auto_duration; + } + if (remoteopencontrol && door.remote_open && Doors.auto_include_remote) + { + return Doors.auto_duration; + } + return -1.f; +} + +// a door and its step moved as they open or close +void TMoverParameters::move_door(basic_door &door, double const Deltatime) +{ + // doors + if (true == door.is_opening) + { + // open door + if (false == door.step_unfolding // no wait if no doorstep + || Doors.step_type == 2) + { // no wait for rotating doorstep + door.open_delay += static_cast(Deltatime); + if (door.open_delay > Doors.open_delay) + { + door.position = std::min(Doors.range, static_cast(door.position + Doors.open_rate * Deltatime)); + } + } + door.close_delay = 0.f; + } + if (true == door.is_closing) + { + // close door + door.close_delay += static_cast(Deltatime); + if (door.close_delay > Doors.close_delay) + { + door.position = std::max(0.f, static_cast(door.position - Doors.close_rate * Deltatime)); + } + door.open_delay = 0.f; + } + // doorsteps + if (door.step_unfolding) + { + // unfold left doorstep + door.step_position = std::min(1.f, static_cast(door.step_position + Doors.step_rate * Deltatime)); + } + if (door.step_folding) + { + // fold left doorstep + if (TrainType == dt_EZT || TrainType == dt_DMU) + { + // multi-unit vehicles typically fold the doorstep only after closing the door + if (door.position <= 0.f) + { + door.step_position = std::max(0.f, static_cast(door.step_position - Doors.step_rate * Deltatime)); + } + } + else + { + door.step_position = std::max(0.f, static_cast(door.step_position - Doors.step_rate * Deltatime)); + } + } +} + +// the timers of the open doors which close after a while, kept running while the load is exchanged +void TMoverParameters::update_door_timers(double const Deltatime) +{ + // update door timers if the door close after defined time + for (auto &door : Doors.instances) + { + + if (false == door.is_open) + { + continue; + } + + if (door.auto_timer > 0.f) + { + door.auto_timer -= static_cast(Deltatime); + } + // if there's load exchange in progress, reset the timer(s) for already open doors + if (door.auto_timer != -1.f && (LoadStatus & (2 | 1)) != 0) + { + door.auto_timer = Doors.auto_duration; + } + } +} + // ************************************************************************************************* // Q: 20160713 // Przesuwa pojazd o podaną wartość w bok względem toru (dla samochodów) @@ -10286,7 +12072,7 @@ bool TMoverParameters::LoadFIZ_Text(std::string const &Text) return LoadFIZ_Parse(fizparser); } -bool TMoverParameters::LoadFIZ_Parse(cParser &fizparser) // NOSONAR the former body of LoadFIZ(), moved as it was; splitting it up is a change of its own +bool TMoverParameters::LoadFIZ_Parse(cParser &fizparser) { LISTLINE = 0; startBPT = false; @@ -10311,7 +12097,7 @@ bool TMoverParameters::LoadFIZ_Parse(cParser &fizparser) // NOSONAR the former b // Zbieranie danych zawartych w pliku FIZ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - std::unordered_map fizlines; + std::map> fizlines; std::string inputline; /* while (std::getline(in, inputline)) @@ -10343,542 +12129,11 @@ bool TMoverParameters::LoadFIZ_Parse(cParser &fizparser) // NOSONAR the former b continue; } - // checking if table parsing should be switched off goes first... - if (issection("END-MPT", inputline)) + if (LoadFIZ_TableEnd(inputline) || LoadFIZ_Section(inputline, fizlines) || LoadFIZ_TableSection(inputline, fizlines)) { - startBPT = false; - startMPT = false; - startMPT0 = false; - continue; - } - if (issection("END-RL", inputline)) - { - startBPT = false; - startRLIST = false; - continue; - } - if (issection("END-UCL", inputline)) - { - startBPT = false; - startUCLIST = false; - continue; - } - if (issection("END-DL", inputline)) - { - startBPT = false; - startDLIST = false; - continue; - } - if (issection("END-DML", inputline)) - { - startBPT = false; - startDIZELMOMENTUMLIST = false; - continue; - } - if (issection("END-V2NL", inputline)) - { - startBPT = false; - startDIZELV2NMAXLIST = false; - continue; - } - if (issection("END-HTCL", inputline)) - { - startBPT = false; - startHYDROTCLIST = false; - continue; - } - if (issection("END-PML", inputline)) - { - startBPT = false; - startPMAXLIST = false; - continue; - } - if (issection("endff", inputline)) - { - startBPT = false; - startFFLIST = false; - startFFEDLIST = false; - continue; - } - if (issection("endwl", inputline)) - { - // skonczylismy czytac liste konfiguracji wycieraczek - startBPT = false; - startWiperList = false; - continue; - } - if (issection("endDimmerList", inputline)) - { - // skonczylismy czytac liste konfiguracji pstryka od przyciemnienia - startBPT = false; - startDimmerList = false; - continue; - } - if (issection("END-WWL", inputline)) - { - startBPT = false; - startWWLIST = false; - continue; - } - if (issection("endL", inputline)) - { - startBPT = false; - startLIGHTSLIST = false; - continue; - } - if (issection("endCL", inputline)) - { - startBPT = false; - startCOMPRESSORLIST = false; - continue; - } - // ...then all recognized sections... - if (issection("Param.", inputline)) - { - startBPT = false; - fizlines.try_emplace("Param", inputline); - LoadFIZ_Param(inputline); - continue; - } - - if (issection("Load:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Load", inputline); - LoadFIZ_Load(inputline); - continue; - } - - if (issection("Dimensions:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Dimensions", inputline); - LoadFIZ_Dimensions(inputline); - continue; - } - - if (issection("Wheels:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Wheels", inputline); - LoadFIZ_Wheels(inputline); - continue; - } - - if (issection("Brake:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Brake", inputline); - LoadFIZ_Brake(inputline); - continue; - } - - if (issection("Doors:", inputline)) - { - - startBPT = false; - fizlines.try_emplace("Doors", inputline); - LoadFIZ_Doors(inputline); - continue; - } - - if (issection("BuffCoupl.", inputline)) - { - - startBPT = false; - fizlines.try_emplace("BuffCoupl", inputline); - LoadFIZ_BuffCoupl(inputline, 0); - continue; - } - - else if (issection("BuffCoupl1.", inputline)) - { - - startBPT = false; - fizlines.try_emplace("BuffCoupl1", inputline); - LoadFIZ_BuffCoupl(inputline, 1); - continue; - } - - else if (issection("BuffCoupl2.", inputline)) - { - - startBPT = false; - fizlines.try_emplace("BuffCoupl2", inputline); - LoadFIZ_BuffCoupl(inputline, 2); - continue; - } - - if (issection("TurboPos:", inputline)) - { - - startBPT = false; - fizlines.try_emplace("TurboPos", inputline); - LoadFIZ_TurboPos(inputline); - continue; - } - - if (issection("Cntrl.", inputline)) - { - - startBPT = true; - LISTLINE = 0; - fizlines.try_emplace("Cntrl", inputline); - LoadFIZ_Cntrl(inputline); - continue; - } - - if (issection("Headlights:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Headlights", inputline); - LoadFIZ_Headlights(inputline); - continue; - } - - if (issection("Blending:", inputline)) - { - - startBPT = false; - LISTLINE = 0; - fizlines.try_emplace("Blending", inputline); - LoadFIZ_Blending(inputline); - continue; - } - - if (issection("DCEMUED:", inputline)) - { - - startBPT = false; - LISTLINE = 0; - fizlines.try_emplace("DCEMUED", inputline); - LoadFIZ_DCEMUED(inputline); - continue; - } - - if (issection("SpringBrake:", inputline)) - { - - startBPT = false; - LISTLINE = 0; - fizlines.try_emplace("SpringBrake", inputline); - LoadFIZ_SpringBrake(inputline); - continue; - } - - if (issection("Light:", inputline)) - { - - startBPT = false; - fizlines.try_emplace("Light", inputline); - LoadFIZ_Light(inputline); - continue; - } - - if (issection("Security:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Security", inputline); - SecuritySystem.load(inputline, Vmax); - extract_value(EmergencyBrakeWarningSignal, "EmergencyBrakeWarningSignal", inputline, ""); - continue; - } - - if (issection("Clima:", inputline)) - { - - startBPT = false; - fizlines.try_emplace("Clima", inputline); - LoadFIZ_Clima(inputline); - continue; - } - - if (issection("Power:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Power", inputline); - LoadFIZ_Power(inputline); - continue; - } - - if (issection("SpeedControl:", inputline)) - { - startBPT = false; - fizlines.try_emplace("SpeedControl", inputline); - LoadFIZ_SpeedControl(inputline); - continue; - } - - if (issection("Engine:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Engine", inputline); - LoadFIZ_Engine(inputline); - continue; - } - - if (issection("Switches:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Switches", inputline); - LoadFIZ_Switches(inputline); - continue; - } - - if (issection("MotorParamTable:", inputline)) - { - startBPT = false; - startMPT = true; - LISTLINE = 0; - fizlines.try_emplace("MotorParamTable", inputline); - LoadFIZ_MotorParamTable(inputline); - continue; - } - - if (issection("MotorParamTable0:", inputline)) - { - startBPT = false; - startMPT0 = true; - LISTLINE = 0; - continue; - } - - if (issection("Circuit:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Circuit", inputline); - LoadFIZ_Circuit(inputline); - continue; - } - - if (issection("AI:", inputline)) - { - startBPT = false; - fizlines.try_emplace("AI", inputline); - LoadFIZ_AI(inputline); - continue; - } - - if (issection("RList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("RList", inputline); - startRLIST = true; - LISTLINE = 0; - LoadFIZ_RList(inputline); - continue; - } - - if (issection("UCList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("UCList", inputline); - startUCLIST = true; - LISTLINE = 0; - LoadFIZ_UCList(inputline); - continue; - } - - if (issection("DList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("DList", inputline); - startDLIST = true; - LISTLINE = 0; - LoadFIZ_DList(inputline); - continue; - } - - if (issection("DMList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("DMList", inputline); - startDIZELMOMENTUMLIST = true; - LISTLINE = 0; - continue; - } - - if (issection("HTCList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("HTCList", inputline); - startHYDROTCLIST = true; - LISTLINE = 0; - continue; - } - - if (issection("PmaxList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("PmaxList", inputline); - startPMAXLIST = true; - LISTLINE = 0; - continue; - } - - if (issection("V2NList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("V2NList", inputline); - startDIZELV2NMAXLIST = true; - LISTLINE = 0; - continue; - } - - if (issection("ffList:", inputline)) - { - startBPT = false; - startFFLIST = true; - LISTLINE = 0; - LoadFIZ_FFList(inputline); - continue; - } - - if (issection("ffBrakeList:", inputline)) - { - startBPT = false; - startFFEDLIST = true; - LISTLINE = 0; - LoadFIZ_FFEDList(inputline); - continue; - } - - if (issection("WWList:", inputline)) - { - startBPT = false; - startWWLIST = true; - LISTLINE = 0; - - continue; - } - - if (issection("WiperList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("WiperList", inputline); - startWiperList = true; - LISTLINE = 0; - LoadFIZ_WiperList(inputline); - - continue; - } - - if (issection("DimmerList:", inputline)) - { - dimPositions.clear(); // uzywamy customowej listy - startBPT = false; - startDimmerList = true; - fizlines.try_emplace("DimmerList", inputline); - LoadFIZ_DimmerList(inputline); - continue; - } - - if (issection("LightsList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("LightsList", inputline); - startLIGHTSLIST = true; - LISTLINE = 0; - LoadFIZ_LightsList(inputline); - continue; - } - - if (issection("CompressorList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("CompressorList", inputline); - startCOMPRESSORLIST = true; - LISTLINE = 0; - LoadFIZ_CompressorList(inputline); - continue; - } - - // ...and finally, table parsers. - // NOTE: once table parsing is enabled it lasts until switched off, when another section is recognized - if (true == startBPT) - { - readBPT(inputline); - continue; - } - if (true == startMPT) - { - readMPT(inputline); - continue; - } - if (true == startMPT0) - { - readMPT0(inputline); - continue; - } - if (true == startRLIST) - { - readRList(inputline); - continue; - } - if (true == startUCLIST) - { - readUCList(inputline); - continue; - } - if (true == startDLIST) - { - readDList(inputline); - continue; - } - if (true == startDIZELMOMENTUMLIST) - { - readDMList(inputline); - continue; - } - if (true == startDIZELV2NMAXLIST) - { - readV2NMAXList(inputline); - continue; - } - if (true == startHYDROTCLIST) - { - readHTCList(inputline); - continue; - } - if (true == startPMAXLIST) - { - readPmaxList(inputline); - continue; - } - if (true == startFFLIST) - { - readFFList(inputline); - continue; - } - if (true == startFFEDLIST) - { - readFFEDList(inputline); - continue; - } - if (true == startWWLIST) - { - readWWList(inputline); - continue; - } - if (true == startWiperList) - { - readWiperList(inputline); - continue; - } - if (true == startDimmerList) - { - readDimmerList(inputline); - } - if (true == startLIGHTSLIST) - { - readLightsList(inputline); - continue; - } - if (true == startCOMPRESSORLIST) - { - readCompressorList(inputline); continue; } + LoadFIZ_TableRow(inputline); } // while line /* in.close(); @@ -10905,6 +12160,564 @@ bool TMoverParameters::LoadFIZ_Parse(cParser &fizparser) // NOSONAR the former b return result; } +// the end of the table being read; returns whether the line is one +bool TMoverParameters::LoadFIZ_TableEnd(std::string const &inputline) const +{ + // checking if table parsing should be switched off goes first... + if (issection("END-MPT", inputline)) + { + startBPT = false; + startMPT = false; + startMPT0 = false; + return true; + } + if (issection("END-RL", inputline)) + { + startBPT = false; + startRLIST = false; + return true; + } + if (issection("END-UCL", inputline)) + { + startBPT = false; + startUCLIST = false; + return true; + } + if (issection("END-DL", inputline)) + { + startBPT = false; + startDLIST = false; + return true; + } + if (issection("END-DML", inputline)) + { + startBPT = false; + startDIZELMOMENTUMLIST = false; + return true; + } + if (issection("END-V2NL", inputline)) + { + startBPT = false; + startDIZELV2NMAXLIST = false; + return true; + } + if (issection("END-HTCL", inputline)) + { + startBPT = false; + startHYDROTCLIST = false; + return true; + } + if (issection("END-PML", inputline)) + { + startBPT = false; + startPMAXLIST = false; + return true; + } + if (issection("endff", inputline)) + { + startBPT = false; + startFFLIST = false; + startFFEDLIST = false; + return true; + } + if (issection("endwl", inputline)) + { + // skonczylismy czytac liste konfiguracji wycieraczek + startBPT = false; + startWiperList = false; + return true; + } + if (issection("endDimmerList", inputline)) + { + // skonczylismy czytac liste konfiguracji pstryka od przyciemnienia + startBPT = false; + startDimmerList = false; + return true; + } + if (issection("END-WWL", inputline)) + { + startBPT = false; + startWWLIST = false; + return true; + } + if (issection("endL", inputline)) + { + startBPT = false; + startLIGHTSLIST = false; + return true; + } + if (issection("endCL", inputline)) + { + startBPT = false; + startCOMPRESSORLIST = false; + return true; + } + return false; +} + +// a section of the definition giving values, kept in fizlines by its name; returns whether the line is one +bool TMoverParameters::LoadFIZ_Section(std::string const &inputline, std::map> &fizlines) +{ + // ...then all recognized sections... + if (issection("Param.", inputline)) + { + startBPT = false; + fizlines.try_emplace("Param", inputline); + LoadFIZ_Param(inputline); + return true; + } + + if (issection("Load:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Load", inputline); + LoadFIZ_Load(inputline); + return true; + } + + if (issection("Dimensions:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Dimensions", inputline); + LoadFIZ_Dimensions(inputline); + return true; + } + + if (issection("Wheels:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Wheels", inputline); + LoadFIZ_Wheels(inputline); + return true; + } + + if (issection("Brake:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Brake", inputline); + LoadFIZ_Brake(inputline); + return true; + } + + if (issection("Doors:", inputline)) + { + + startBPT = false; + fizlines.try_emplace("Doors", inputline); + LoadFIZ_Doors(inputline); + return true; + } + + if (issection("BuffCoupl.", inputline)) + { + + startBPT = false; + fizlines.try_emplace("BuffCoupl", inputline); + LoadFIZ_BuffCoupl(inputline, 0); + return true; + } + + else if (issection("BuffCoupl1.", inputline)) + { + + startBPT = false; + fizlines.try_emplace("BuffCoupl1", inputline); + LoadFIZ_BuffCoupl(inputline, 1); + return true; + } + + else if (issection("BuffCoupl2.", inputline)) + { + + startBPT = false; + fizlines.try_emplace("BuffCoupl2", inputline); + LoadFIZ_BuffCoupl(inputline, 2); + return true; + } + + if (issection("TurboPos:", inputline)) + { + + startBPT = false; + fizlines.try_emplace("TurboPos", inputline); + LoadFIZ_TurboPos(inputline); + return true; + } + + if (issection("Cntrl.", inputline)) + { + + startBPT = true; + LISTLINE = 0; + fizlines.try_emplace("Cntrl", inputline); + LoadFIZ_Cntrl(inputline); + return true; + } + + if (issection("Headlights:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Headlights", inputline); + LoadFIZ_Headlights(inputline); + return true; + } + + if (issection("Blending:", inputline)) + { + + startBPT = false; + LISTLINE = 0; + fizlines.try_emplace("Blending", inputline); + LoadFIZ_Blending(inputline); + return true; + } + + if (issection("DCEMUED:", inputline)) + { + + startBPT = false; + LISTLINE = 0; + fizlines.try_emplace("DCEMUED", inputline); + LoadFIZ_DCEMUED(inputline); + return true; + } + + if (issection("SpringBrake:", inputline)) + { + + startBPT = false; + LISTLINE = 0; + fizlines.try_emplace("SpringBrake", inputline); + LoadFIZ_SpringBrake(inputline); + return true; + } + + if (issection("Light:", inputline)) + { + + startBPT = false; + fizlines.try_emplace("Light", inputline); + LoadFIZ_Light(inputline); + return true; + } + + if (issection("Security:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Security", inputline); + SecuritySystem.load(inputline, Vmax); + extract_value(EmergencyBrakeWarningSignal, "EmergencyBrakeWarningSignal", inputline, ""); + return true; + } + + if (issection("Clima:", inputline)) + { + + startBPT = false; + fizlines.try_emplace("Clima", inputline); + LoadFIZ_Clima(inputline); + return true; + } + + if (issection("Power:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Power", inputline); + LoadFIZ_Power(inputline); + return true; + } + + if (issection("SpeedControl:", inputline)) + { + startBPT = false; + fizlines.try_emplace("SpeedControl", inputline); + LoadFIZ_SpeedControl(inputline); + return true; + } + + if (issection("Engine:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Engine", inputline); + LoadFIZ_Engine(inputline); + return true; + } + + if (issection("Switches:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Switches", inputline); + LoadFIZ_Switches(inputline); + return true; + } + + if (issection("Circuit:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Circuit", inputline); + LoadFIZ_Circuit(inputline); + return true; + } + + if (issection("AI:", inputline)) + { + startBPT = false; + fizlines.try_emplace("AI", inputline); + LoadFIZ_AI(inputline); + return true; + } + + return false; +} + +// a section of the definition opening a table, kept in fizlines by its name; returns whether the line is one +bool TMoverParameters::LoadFIZ_TableSection(std::string const &inputline, std::map> &fizlines) +{ + if (issection("MotorParamTable:", inputline)) + { + startBPT = false; + startMPT = true; + LISTLINE = 0; + fizlines.try_emplace("MotorParamTable", inputline); + LoadFIZ_MotorParamTable(inputline); + return true; + } + + if (issection("MotorParamTable0:", inputline)) + { + startBPT = false; + startMPT0 = true; + LISTLINE = 0; + return true; + } + + if (issection("RList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("RList", inputline); + startRLIST = true; + LISTLINE = 0; + LoadFIZ_RList(inputline); + return true; + } + + if (issection("UCList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("UCList", inputline); + startUCLIST = true; + LISTLINE = 0; + LoadFIZ_UCList(inputline); + return true; + } + + if (issection("DList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("DList", inputline); + startDLIST = true; + LISTLINE = 0; + LoadFIZ_DList(inputline); + return true; + } + + if (issection("DMList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("DMList", inputline); + startDIZELMOMENTUMLIST = true; + LISTLINE = 0; + return true; + } + + if (issection("HTCList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("HTCList", inputline); + startHYDROTCLIST = true; + LISTLINE = 0; + return true; + } + + if (issection("PmaxList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("PmaxList", inputline); + startPMAXLIST = true; + LISTLINE = 0; + return true; + } + + if (issection("V2NList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("V2NList", inputline); + startDIZELV2NMAXLIST = true; + LISTLINE = 0; + return true; + } + + if (issection("ffList:", inputline)) + { + startBPT = false; + startFFLIST = true; + LISTLINE = 0; + LoadFIZ_FFList(inputline); + return true; + } + + if (issection("ffBrakeList:", inputline)) + { + startBPT = false; + startFFEDLIST = true; + LISTLINE = 0; + LoadFIZ_FFEDList(inputline); + return true; + } + + if (issection("WWList:", inputline)) + { + startBPT = false; + startWWLIST = true; + LISTLINE = 0; + + return true; + } + + if (issection("WiperList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("WiperList", inputline); + startWiperList = true; + LISTLINE = 0; + LoadFIZ_WiperList(inputline); + + return true; + } + + if (issection("DimmerList:", inputline)) + { + dimPositions.clear(); // uzywamy customowej listy + startBPT = false; + startDimmerList = true; + fizlines.try_emplace("DimmerList", inputline); + LoadFIZ_DimmerList(inputline); + return true; + } + + if (issection("LightsList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("LightsList", inputline); + startLIGHTSLIST = true; + LISTLINE = 0; + LoadFIZ_LightsList(inputline); + return true; + } + + if (issection("CompressorList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("CompressorList", inputline); + startCOMPRESSORLIST = true; + LISTLINE = 0; + LoadFIZ_CompressorList(inputline); + return true; + } + return false; +} + +// a row of the table being read +void TMoverParameters::LoadFIZ_TableRow(std::string const &inputline) +{ + // ...and finally, table parsers. + // NOTE: once table parsing is enabled it lasts until switched off, when another section is recognized + if (true == startBPT) + { + readBPT(inputline); + return; + } + if (true == startMPT) + { + readMPT(inputline); + return; + } + if (true == startMPT0) + { + readMPT0(inputline); + return; + } + if (true == startRLIST) + { + readRList(inputline); + return; + } + if (true == startUCLIST) + { + readUCList(inputline); + return; + } + if (true == startDLIST) + { + readDList(inputline); + return; + } + if (true == startDIZELMOMENTUMLIST) + { + readDMList(inputline); + return; + } + if (true == startDIZELV2NMAXLIST) + { + readV2NMAXList(inputline); + return; + } + if (true == startHYDROTCLIST) + { + readHTCList(inputline); + return; + } + if (true == startPMAXLIST) + { + readPmaxList(inputline); + return; + } + if (true == startFFLIST) + { + readFFList(inputline); + return; + } + if (true == startFFEDLIST) + { + readFFEDList(inputline); + return; + } + if (true == startWWLIST) + { + readWWList(inputline); + return; + } + if (true == startWiperList) + { + readWiperList(inputline); + return; + } + if (true == startDimmerList) + { + readDimmerList(inputline); + } + if (true == startLIGHTSLIST) + { + readLightsList(inputline); + return; + } + if (true == startCOMPRESSORLIST) + { + readCompressorList(inputline); + return; + } +} + void TMoverParameters::LoadFIZ_Param(std::string const &line) { @@ -11007,6 +12820,8 @@ void TMoverParameters::LoadFIZ_Dimensions(std::string const &line) extract_value(Dim.L, "L", line, ""); extract_value(Dim.H, "H", line, ""); extract_value(Dim.W, "W", line, ""); + // height of the centre of gravity of the empty vehicle [m], for the criteria of derailment + extract_value(CentreOfGravity, "CoGH", line, ""); extract_value(Cx, "Cx", line, "0.3"); if (Dim.H <= 2.0) @@ -11360,6 +13175,45 @@ void scale_strength(coupler_physics::link_strength &Link, double const Factor) Link.ultimate *= Factor; } +// the optional keys of the collisions past the buffers (physics.collisions new, see collision.h), what's not given +// comes from the kind of the vehicle: +// FcrushPeak, FcrushPlateau [kN] the force the end starts to crush at, and keeps crushing at +// CrushOnset, CrushDensify, CrushLimit [m] the crush the peak drops at, it packs down past, it can't go past +// CrushHardening [1/m] the growth of the force past CrushDensify, to the plateau for each metre +// CrashZone [yes/no] built to EN 15227: energy absorbers and anticlimbers; AntiClimber [yes/no] on its own +// BufferHeight [m] of the empty vehicle above the rail +// BufferCategory [A/B/C/L/P] the buffers of EN 15551 (P those of the coaches) in place of kB and DmaxB +collision::end_definition collision_definition(std::string const &Line) +{ + collision::end_definition definition; + auto const number = [&Line](std::string const &Key, double const Scale) -> std::optional { + auto value{0.0}; + if (extract_value(value, Key, Line, "") && value >= 0.0) + { + return value * Scale; + } + return std::nullopt; + }; + auto const flag = [&Line](std::string const &Key) -> std::optional { + auto value{false}; + if (extract_value(value, Key, Line, "")) + { + return value; + } + return std::nullopt; + }; + definition.peak = number("FcrushPeak", 1000.0); + definition.plateau = number("FcrushPlateau", 1000.0); + definition.onset = number("CrushOnset", 1.0); + definition.densify = number("CrushDensify", 1.0); + definition.hardening = number("CrushHardening", 1.0); + definition.limit = number("CrushLimit", 1.0); + definition.crash_zone = flag("CrashZone"); + definition.anticlimber = flag("AntiClimber"); + definition.buffer_height = number("BufferHeight", 1.0); + return definition; +} + } // namespace void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Index) @@ -11440,7 +13294,23 @@ void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Inde thiscoupler->DmaxB = std::max(0.05, thiscoupler->FmaxC / thiscoupler->SpringKB); } + // the buffers of a category of EN 15551 in place of the springs given + auto const categoryname{extract_value("BufferCategory", line)}; + auto const category{categoryname.empty() ? std::nullopt : collision::buffer_category_of(categoryname.front())}; + auto const buffered{thiscoupler->CouplerType != TCouplerType::NoCoupler && thiscoupler->CouplerType != TCouplerType::Bare && thiscoupler->CouplerType != TCouplerType::Articulated}; + if (category && buffered) + { + auto const linear{collision::buffer_curve(*category, 0.0)}; + thiscoupler->SpringKB = linear.stiffness; + thiscoupler->DmaxB = linear.travel; + } thiscoupler->physics = coupler_physics_parameters(*thiscoupler, line); + if (category && buffered) + { + thiscoupler->physics.buffers = collision::buffer_curve(*category, thiscoupler->physics.buffers.progression); + } + thiscoupler->collision = collision_definition(line); + thiscoupler->collision.buffers = category; if (Index == 0) { @@ -11466,6 +13336,14 @@ void TMoverParameters::LoadFIZ_TurboPos(std::string const &Input) void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) { + LoadFIZ_CntrlBrakes(line); + LoadFIZ_CntrlControllers(line); + LoadFIZ_CntrlStarts(line); +} + +// Cntrl.: the brake system, the handles, the brake delays and the local and manual brakes +void TMoverParameters::LoadFIZ_CntrlBrakes(std::string const &line) +{ { using enum TBrakeSystem; std::map> brakesystems{{"Pneumatic", Pneumatic}, {"ElectroPneumatic", ElectroPneumatic}}; @@ -11474,93 +13352,7 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) } if (BrakeSystem != TBrakeSystem::Individual) { - using enum TBrakeHandle; - - extract_value(BrakeCtrlPosNo, "BCPN", line, ""); - for (int idx = 0; idx < 4; ++idx) - { - - extract_value(BrakeDelay[idx], std::format("BDelay{}", idx + 1), line, ""); - } - // brakedelays, brakedelayflag - { - std::map> brakedelays{{"GPR", bdelay_G + bdelay_P + bdelay_R}, - {"PR", bdelay_P + bdelay_R}, - {"GP", bdelay_G + bdelay_P}, - {"R", bdelay_R}, - {"P", bdelay_P}, - {"G", bdelay_G}, - {"GPR+Mg", bdelay_G + bdelay_P + bdelay_R + bdelay_M}, - {"PR+Mg", bdelay_P + bdelay_R + bdelay_M}}; - std::map> brakedelayflags{{"R", bdelay_R}, {"P", bdelay_P}, {"G", bdelay_G}}; - std::string brakedelay; - extract_value(brakedelay, "BrakeDelays", line, ""); - auto lookup = brakedelays.find(brakedelay); - BrakeDelays = lookup != brakedelays.end() ? lookup->second : 0; - lookup = brakedelayflags.find(brakedelay); - BrakeDelayFlag = lookup != brakedelayflags.end() ? lookup->second : 0; - } - // brakeopmode - { - std::map> brakeopmodes{{"PN", bom_PS + bom_PN}, {"PNEP", bom_PS + bom_PN + bom_EP}, {"PNEPMED", bom_PS + bom_PN + bom_EP + bom_MED}}; - auto lookup = brakeopmodes.find(extract_value("BrakeOpModes", line)); - BrakeOpModes = lookup != brakeopmodes.end() ? lookup->second : 0; - } - // brakehandle - { - std::map> brakehandles{ - {"FV4a", FV4a}, {"test", testH}, {"D2", D2}, {"MHZ_EN57", MHZ_EN57}, {"MHZ_K5P", MHZ_K5P}, - {"MHZ_K8P", MHZ_K8P}, {"MHZ_6P", MHZ_6P}, {"M394", M394}, {"Knorr", Knorr}, {"Westinghouse", West}, - {"FVel6", FVel6}, {"FVE408", FVE408}, {"St113", St113}}; - auto lookup = brakehandles.find(extract_value("BrakeHandle", line)); - BrakeHandle = lookup != brakehandles.end() ? lookup->second : NoHandle; - } - extract_value(Handle_AutomaticOverload, "HAO", line, ""); - extract_value(Handle_ManualOverload, "HMO", line, ""); - extract_value(Handle_GenericDoubleParameter1, "HGDP1", line, ""); - extract_value(Handle_GenericDoubleParameter2, "HGDP2", line, ""); - extract_value(Handle_OverloadMaxPressure, "OMP", line, ""); - extract_value(Handle_OverloadPressureDecrease, "OPD", line, ""); - // brakelochandle - { - std::map> locbrakehandles{{"FD1", FD1}, {"Knorr", Knorr}, {"Westinghouse", West}}; - auto lookup = locbrakehandles.find(extract_value("LocBrakeHandle", line)); - BrakeLocHandle = lookup != locbrakehandles.end() ? lookup->second : NoHandle; - } - - // mbpm - if (true == extract_value(MBPM, "MaxBPMass", line, "")) - { - // NOTE: only convert the value from tons to kilograms if the entry is present in the config file - MBPM *= 1000.0; - } - - // asbtype - std::string const asb{ToLower(extract_value("ASB", line))}; - if (BrakeCtrlPosNo > 0) - { - - if (asb == "manual") - { - ASBType = 1; - } - else if (asb == "automatic") - { - ASBType = 2; - } - else if (asb == "yes") - { - ASBType = 128; - } - } - else - { - - if (asb == "yes") - { - ASBType = 128; - } - } + LoadFIZ_CntrlTrainBrake(line); } // brakesystem != individual // localbrake @@ -11572,7 +13364,96 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) } // mbrake extract_value(MBrake, "ManualBrake", line, ""); +} +// Cntrl.: of a vehicle with a train brake, its positions, delays, modes, handles, load weighing and anti-slip brake +void TMoverParameters::LoadFIZ_CntrlTrainBrake(std::string const &line) +{ + using enum TBrakeHandle; + + extract_value(BrakeCtrlPosNo, "BCPN", line, ""); + for (int idx = 0; idx < 4; ++idx) + { + + extract_value(BrakeDelay[idx], std::format("BDelay{}", idx + 1), line, ""); + } + // brakedelays, brakedelayflag + { + std::map> brakedelays{{"GPR", bdelay_G + bdelay_P + bdelay_R}, + {"PR", bdelay_P + bdelay_R}, + {"GP", bdelay_G + bdelay_P}, + {"R", bdelay_R}, + {"P", bdelay_P}, + {"G", bdelay_G}, + {"GPR+Mg", bdelay_G + bdelay_P + bdelay_R + bdelay_M}, + {"PR+Mg", bdelay_P + bdelay_R + bdelay_M}}; + std::map> brakedelayflags{{"R", bdelay_R}, {"P", bdelay_P}, {"G", bdelay_G}}; + std::string brakedelay; + extract_value(brakedelay, "BrakeDelays", line, ""); + auto lookup = brakedelays.find(brakedelay); + BrakeDelays = lookup != brakedelays.end() ? lookup->second : 0; + lookup = brakedelayflags.find(brakedelay); + BrakeDelayFlag = lookup != brakedelayflags.end() ? lookup->second : 0; + } + // brakeopmode + { + std::map> brakeopmodes{{"PN", bom_PS + bom_PN}, {"PNEP", bom_PS + bom_PN + bom_EP}, {"PNEPMED", bom_PS + bom_PN + bom_EP + bom_MED}}; + auto lookup = brakeopmodes.find(extract_value("BrakeOpModes", line)); + BrakeOpModes = lookup != brakeopmodes.end() ? lookup->second : 0; + } + // brakehandle + { + std::map> brakehandles{ + {"FV4a", FV4a}, {"test", testH}, {"D2", D2}, {"MHZ_EN57", MHZ_EN57}, {"MHZ_K5P", MHZ_K5P}, + {"MHZ_K8P", MHZ_K8P}, {"MHZ_6P", MHZ_6P}, {"M394", M394}, {"Knorr", Knorr}, {"Westinghouse", West}, + {"FVel6", FVel6}, {"FVE408", FVE408}, {"St113", St113}}; + auto lookup = brakehandles.find(extract_value("BrakeHandle", line)); + BrakeHandle = lookup != brakehandles.end() ? lookup->second : NoHandle; + } + extract_value(Handle_AutomaticOverload, "HAO", line, ""); + extract_value(Handle_ManualOverload, "HMO", line, ""); + extract_value(Handle_GenericDoubleParameter1, "HGDP1", line, ""); + extract_value(Handle_GenericDoubleParameter2, "HGDP2", line, ""); + extract_value(Handle_OverloadMaxPressure, "OMP", line, ""); + extract_value(Handle_OverloadPressureDecrease, "OPD", line, ""); + // brakelochandle + { + std::map> locbrakehandles{{"FD1", FD1}, {"Knorr", Knorr}, {"Westinghouse", West}}; + auto lookup = locbrakehandles.find(extract_value("LocBrakeHandle", line)); + BrakeLocHandle = lookup != locbrakehandles.end() ? lookup->second : NoHandle; + } + + // mbpm + if (true == extract_value(MBPM, "MaxBPMass", line, "")) + { + // NOTE: only convert the value from tons to kilograms if the entry is present in the config file + MBPM *= 1000.0; + } + + // asbtype + LoadFIZ_CntrlAntiSlipBrake(ToLower(extract_value("ASB", line))); +} + +// Cntrl.: the kind of the anti-slip brake, by hand or automatic only for a vehicle with a brake handle +void TMoverParameters::LoadFIZ_CntrlAntiSlipBrake(std::string_view const asb) +{ + if (asb == "yes") + { + ASBType = 128; + } + else if (BrakeCtrlPosNo > 0 && asb == "manual") + { + ASBType = 1; + } + else if (BrakeCtrlPosNo > 0 && asb == "automatic") + { + ASBType = 2; + } +} + +// Cntrl.: the controllers, their delays, the cab and the switches of the driver's desk +void TMoverParameters::LoadFIZ_CntrlControllers(std::string const &line) +{ // maksymalna predkosc dostepna na tarczce predkosciomierza extract_value(maxTachoSpeed, "MaxTachoSpeed", line, ""); @@ -11623,6 +13504,9 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) { AutoRelayType = 0; } + // a key of its own rather than a new AutoRelay value: an exe that doesn't know it reads the line as before, and the value + // stays Optional, which every check of the switch looks for + extract_value(FieldShuntSwitch, "FieldShuntSwitch", line, ""); extract_value(CoupledCtrl, "CoupledCtrl", line, ""); extract_value(HasCamshaft, "Camshaft", line, ""); @@ -11658,6 +13542,7 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) extract_value(InactiveCabFlag, "InactiveCabFlag", line, ""); extract_value(StopBrakeDecc, "SBD", line, ""); + extract_value(StopBrakeReleaseDelay, "SBDReleaseDelay", line, ""); // the holding brake waits for the power demand this long, s extract_value(ReleaseParkingBySpringBrake, "ReleaseParkingBySpringBrake", line, ""); extract_value(ReleaseParkingBySpringBrakeWhenDoorIsOpen, "ReleaseParkingBySpringBrakeWhenDoorIsOpen", line, ""); extract_value(SpringBrakeCutsOffDrive, "SpringBrakeCutsOffDrive", line, ""); @@ -11671,38 +13556,46 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) extract_value(isBatteryButtonImpulse, "IBTB", line, ""); extract_value(shouldHoldBatteryButton, "SBBBH", line, ""); extract_value(BatteryButtonHoldTime, "BBHT", line, ""); +} - std::map> starts{{"Disabled", start_t::disabled}, {"Manual", start_t::manual}, {"Automatic", start_t::automatic}, {"Mixed", start_t::manualwithautofallback}, - {"Battery", start_t::battery}, {"Converter", start_t::converter}, {"Direction", start_t::direction}}; +// Cntrl.: how the devices start (MainStart, BatteryStart, ...) and their relays +void TMoverParameters::LoadFIZ_CntrlStarts(std::string const &line) +{ + using enum start_t; + std::map> starts{{"Disabled", disabled}, {"Manual", manual}, {"Automatic", automatic}, {"Mixed", manualwithautofallback}, + {"Battery", battery}, {"Converter", converter}, {"Direction", direction}}; // main circuit extract_value(MainsInitTime, "MainInitTime", line, ""); { auto lookup = starts.find(extract_value("MainStart", line)); - MainsStart = lookup != starts.end() ? lookup->second : start_t::manual; + MainsStart = lookup != starts.end() ? lookup->second : manual; } extract_value(PantographsRequireMains, "PantRequiresMain", line, ""); + // the brake pipe pressure of an emergency brake application, which opens the line breaker under power + extract_value(EmergencyBrakeMainOffPressure, "EmergencyBrakeMainOff", line, ""); + EmergencyBrakeMainOffPressure = std::max(0.0, EmergencyBrakeMainOffPressure); // battery { auto lookup = starts.find(extract_value("BatteryStart", line)); - BatteryStart = lookup != starts.end() ? lookup->second : start_t::manual; + BatteryStart = lookup != starts.end() ? lookup->second : manual; } // converter { auto lookup = starts.find(extract_value("ConverterStart", line)); - ConverterStart = lookup != starts.end() ? lookup->second : start_t::manual; + ConverterStart = lookup != starts.end() ? lookup->second : manual; } extract_value(ConverterStartDelay, "ConverterStartDelay", line, ""); extract_value(ConverterOverloadRelayOffWhenMainIsOff, "ConverterOverloadWhenMainIsOff", line, TrainType == dt_EZT ? "yes" : "no"); // compressor { auto lookup = starts.find(extract_value("CompressorStart", line)); - CompressorStart = lookup != starts.end() ? lookup->second : start_t::manual; + CompressorStart = lookup != starts.end() ? lookup->second : manual; } // pantograph compressor { auto lookup = starts.find(extract_value("PantCompressorStart", line)); - PantographCompressorStart = lookup != starts.end() ? lookup->second : start_t::manual; + PantographCompressorStart = lookup != starts.end() ? lookup->second : manual; } // pantograph compressor valve PantAutoValve = TrainType == dt_EZT; // legacy code behaviour, automatic valve was initially installed in all EMUs @@ -11710,13 +13603,13 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) // pantographs valve { auto lookup = starts.find(extract_value("PantEPValveStart", line)); - PantsValve.start_type = lookup != starts.end() ? lookup->second : start_t::automatic; // legacy code behaviour, there was no pantographs valve + PantsValve.start_type = lookup != starts.end() ? lookup->second : automatic; // legacy code behaviour, there was no pantographs valve extract_value(PantsValve.spring, "PantEPValveSpring", line, ""); } // pantograph valve configuration { auto lookup = starts.find(extract_value("PantValveStart", line)); - auto valvestarttype = lookup != starts.end() ? lookup->second : start_t::manual; + auto valvestarttype = lookup != starts.end() ? lookup->second : manual; auto valvespring{true}; extract_value(valvespring, "PantValveSpring", line, ""); auto valvesolenoid{true}; @@ -11731,22 +13624,27 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) // fuel pump { auto lookup = starts.find(extract_value("FuelStart", line)); - FuelPump.start_type = lookup != starts.end() ? lookup->second : start_t::manual; + FuelPump.start_type = lookup != starts.end() ? lookup->second : manual; } // oil pump { auto lookup = starts.find(extract_value("OilStart", line)); - OilPump.start_type = lookup != starts.end() ? lookup->second : start_t::manual; + OilPump.start_type = lookup != starts.end() ? lookup->second : manual; + } + // genset of a dual-mode vehicle: Manual (the default) needs GensetSwitch, Automatic runs whenever the selector is on it + { + auto lookup = starts.find(extract_value("GensetStart", line)); + Genset.start_type = lookup != starts.end() ? lookup->second : manual; } // water pump { auto lookup = starts.find(extract_value("WaterStart", line)); - WaterPump.start_type = lookup != starts.end() ? lookup->second : start_t::manual; + WaterPump.start_type = lookup != starts.end() ? lookup->second : manual; } // traction motor fans { auto lookup = starts.find(extract_value("MotorBlowersStart", line)); - MotorBlowers[end::rear].start_type = lookup != starts.end() ? lookup->second : start_t::manual; + MotorBlowers[end::rear].start_type = lookup != starts.end() ? lookup->second : manual; MotorBlowers[end::front].start_type = MotorBlowers[end::rear].start_type; } // what else the line contactors need to close @@ -11760,19 +13658,19 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) // compartment lights { auto lookup = starts.find(extract_value("CompartmentLightsStart", line)); - CompartmentLights.start_type = lookup != starts.end() ? lookup->second : start_t::automatic; // legacy behaviour + CompartmentLights.start_type = lookup != starts.end() ? lookup->second : automatic; // legacy behaviour } // ground relay { auto lookup = starts.find(extract_value("GroundRelayStart", line)); - auto const defaultstart{TrainType == dt_EZT ? start_t::automatic : start_t::manual}; + auto const defaultstart{TrainType == dt_EZT ? automatic : manual}; GroundRelayStart = lookup != starts.end() ? lookup->second : defaultstart; } // converter overload relay { auto lookup = starts.find(extract_value("ConverterOverloadRelayStart", line)); // the relay of a multiple unit activates when the converter is switched off - auto const defaultstart{TrainType == dt_EZT ? start_t::converter : start_t::manual}; + auto const defaultstart{TrainType == dt_EZT ? converter : manual}; ConverterOverloadRelayStart = lookup != starts.end() ? lookup->second : defaultstart; } } @@ -11865,11 +13763,40 @@ void TMoverParameters::LoadFIZ_Power(std::string const &Line) // jeśli nie ma mocy, np. rozrządcze EZT EnginePowerSource.SourceType = TPowerSource::NotDefined; } + else + { + LoadFIZ_Genset(Line); + } SystemPowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("SystemPower", Line)); LoadFIZ_PowerParamsDecode(SystemPowerSource, "", Line); } +// the genset of a dual-mode vehicle (eu07/maszyna#536), on the Power: line; all optional, no genset without GensetPower +void TMoverParameters::LoadFIZ_Genset(std::string const &Line) +{ + extract_value(Genset.power, "GensetPower", Line, ""); + if (false == Genset.fitted()) + { + return; + } + extract_value(Genset.voltage_nominal, "GensetVoltage", Line, ""); + if (Genset.voltage_nominal <= 0.0) + { + Genset.voltage_nominal = EnginePowerSource.MaxVoltage > 0.0 ? 0.65 * EnginePowerSource.MaxVoltage : 3000.0; + } + extract_value(Genset.revolutions_idle, "GensetIdleRPM", Line, "600"); + extract_value(Genset.revolutions_max, "GensetMaxRPM", Line, "1800"); + Genset.revolutions_max = std::max(Genset.revolutions_max, 1.0) / 60.0; + Genset.revolutions_idle = std::clamp(Genset.revolutions_idle / 60.0, 1.0 / 60.0, Genset.revolutions_max); + extract_value(Genset.start_time, "GensetStartTime", Line, "8"); + extract_value(Genset.spinup_time, "GensetSpinUpTime", Line, "3"); + extract_value(Genset.traction_share, "GensetPmaxRatio", Line, "1"); + Genset.start_time = std::max(Genset.start_time, 0.0); + Genset.spinup_time = std::max(Genset.spinup_time, 0.01); + Genset.traction_share = std::clamp(Genset.traction_share, 0.0, 1.0); +} + void TMoverParameters::LoadFIZ_SpeedControl(std::string const &Line) { // speed control @@ -11961,153 +13888,17 @@ void TMoverParameters::LoadFIZ_Engine(std::string const &Input) } case TEngineType::DieselEngine: { - - extract_value(dizel_nmin, "nmin", Input, ""); - dizel_nmin /= 60.0; - dizel_nreg_min = dizel_nmin * 0.98; - extract_value(dizel_nmin_hdrive, "nmin_hdrive", Input, ""); - dizel_nmin_hdrive /= 60.0; - if (dizel_nmin_hdrive == 0.0) - { - dizel_nmin_hdrive = dizel_nmin; - } - extract_value(dizel_nmin_hdrive_factor, "nmin_hdrive_factor", Input, ""); - dizel_nmin_hdrive_factor /= 60.0; - extract_value(dizel_nmin_retarder, "nmin_retarder", Input, ""); - dizel_nmin_retarder /= 60.0; - if (dizel_nmin_retarder == 0.0) - { - dizel_nmin_retarder = dizel_nmin; - } - // TODO: unify naming scheme and sort out which diesel engine params are used where and how - extract_value(nmax, "nmax", Input, ""); - nmax /= 60.0; - extract_value(dizel_nmax_cutoff, "nmax_cutoff", Input, "0.0"); - dizel_nmax_cutoff /= 60.0; - extract_value(dizel_nreg_acc, "nreg_acc", Input, ""); - dizel_nreg_acc /= 60.0; - extract_value(dizel_AIM, "AIM", Input, "1.0"); - extract_value(dizel_RevolutionsDecreaseRate, "RPMDecRate", Input, ""); - - extract_value(engageupspeed, "EUS", Input, "0.5"); - extract_value(engagedownspeed, "EDS", Input, "0.9"); - - if (true == extract_value(AnPos, "ShuntMode", Input, "")) - { - // dodatkowa przekładnia dla SM03 (2Ls150) - ShuntModeAllow = true; - ShuntMode = false; - if (AnPos < 1.0) - { - //"rozruch wysoki" ma dawać większą siłę - AnPos = 1.0 / AnPos; // im większa liczba, tym wolniej jedzie - } - } - extract_value(hydro_TC, "IsTC", Input, ""); - if (true == hydro_TC) - { - extract_value(hydro_TC_TMMax, "TC_TMMax", Input, ""); - extract_value(hydro_TC_CouplingPoint, "TC_CP", Input, ""); - extract_value(hydro_TC_LockupTorque, "TC_LT", Input, ""); - extract_value(hydro_TC_LockupRate, "TC_LR", Input, ""); - extract_value(hydro_TC_UnlockRate, "TC_ULR", Input, ""); - extract_value(hydro_TC_FillRateInc, "TC_FRI", Input, ""); - extract_value(hydro_TC_FillRateDec, "TC_FRD", Input, ""); - extract_value(hydro_TC_TorqueInIn, "TC_TII", Input, ""); - extract_value(hydro_TC_TorqueInOut, "TC_TIO", Input, ""); - extract_value(hydro_TC_TorqueOutOut, "TC_TOO", Input, ""); - extract_value(hydro_TC_LockupSpeed, "TC_LS", Input, ""); - extract_value(hydro_TC_UnlockSpeed, "TC_ULS", Input, ""); - extract_value(dizel_maxVelANS, "MaxVelANS", Input, ""); - - extract_value(hydro_R, "IsRetarder", Input, ""); - if (true == hydro_R) - { - extract_value(hydro_R_Placement, "R_Place", Input, ""); - extract_value(hydro_R_TorqueInIn, "R_TII", Input, ""); - extract_value(hydro_R_MaxTorque, "R_MT", Input, ""); - extract_value(hydro_R_MaxPower, "R_MP", Input, ""); - extract_value(hydro_R_FillRateInc, "R_FRI", Input, ""); - extract_value(hydro_R_FillRateDec, "R_FRD", Input, ""); - extract_value(hydro_R_MinVel, "R_MinVel", Input, ""); - extract_value(hydro_R_EngageVel, "R_EngageVel", Input, ""); - extract_value(hydro_R_Clutch, "R_IsClutch", Input, ""); - extract_value(hydro_R_ClutchSpeed, "R_ClutchSpeed", Input, ""); - extract_value(hydro_R_WithIndividual, "R_WithIndividual", Input, ""); - } - } + LoadFIZ_EngineDiesel(Input); break; } case TEngineType::DieselElectric: { // youBy - - extract_value(Ftmax, "Ftmax", Input, ""); - Flat = extract_value("Flat", Input) == "1"; - extract_value(Vhyp, "Vhyp", Input, ""); - Vhyp /= 3.6; - extract_value(Vadd, "Vadd", Input, ""); - Vadd /= 3.6; - extract_value(PowerCorRatio, "Cr", Input, ""); - extract_value(RelayType, "RelayType", Input, ""); - if (extract_value("ShuntMode", Input) == "1") - { - - ShuntModeAllow = true; - ShuntMode = false; - AnPos = 0.0; - ImaxHi = 2; - ImaxLo = 1; - } - extract_value(EngineHeatingRPM, "HeatingRPM", Input, ""); - extract_value(dizel_AIM, "AIM", Input, "1.25"); - extract_value(dizel_RevolutionsDecreaseRate, "RPMDecRate", Input, ""); + LoadFIZ_EngineDieselElectric(Input); break; } case TEngineType::ElectricInductionMotor: { - - RVentnmax = 1.0; - extract_value(NominalVoltage, "Volt", Input, ""); - - extract_value(eimc[eimc_s_dfic], "dfic", Input, ""); - extract_value(eimc[eimc_s_dfmax], "dfmax", Input, ""); - extract_value(eimc[eimc_s_p], "p", Input, ""); - extract_value(eimc[eimc_s_cfu], "cfu", Input, ""); - extract_value(eimc[eimc_s_cim], "cim", Input, ""); - extract_value(eimc[eimc_s_icif], "icif", Input, ""); - extract_value(eimc[eimc_f_Uzmax], "Uzmax", Input, ""); - extract_value(eimc[eimc_f_Uzh], "Uzh", Input, ""); - extract_value(eimc[eimc_f_DU], "DU", Input, ""); - extract_value(eimc[eimc_f_I0], "I0", Input, ""); - extract_value(eimc[eimc_f_cfu], "fcfu", Input, ""); - extract_value(eimc[eimc_f_cfuH], "fcfuH", Input, std::to_string(eimc[eimc_f_cfu])); - extract_value(eimc[eimc_p_F0], "F0", Input, ""); - extract_value(eimc[eimc_p_a1], "a1", Input, ""); - extract_value(eimc[eimc_p_Pmax], "Pmax", Input, ""); - extract_value(eimc[eimc_p_Fh], "Fh", Input, ""); - extract_value(eimc[eimc_p_Ph], "Ph", Input, ""); - extract_value(eimc[eimc_p_Vh0], "Vh0", Input, ""); - extract_value(eimc[eimc_p_Vh1], "Vh1", Input, ""); - extract_value(eimc[eimc_p_Imax], "Imax", Input, ""); - extract_value(eimc[eimc_p_abed], "abed", Input, ""); - extract_value(eimc[eimc_p_eped], "edep", Input, ""); - extract_value(EIMCLogForce, "eimclf", Input, ""); - extract_value(InvertersNo, "InvNo", Input, ""); - extract_value(InverterControlCouplerFlag, "InvCtrCplFlag", Input, ""); - extract_value(Imaxrpc, "Imaxrpc", Input, ""); - extract_value(BRVto, "BRVto", Input, ""); - extract_value(Flat, "Flat", Input, ""); - - if (eimc[eimc_p_Pmax] > 0 && Power > 0 && InvertersNo == 0) - { - InvertersNo = 1; - } - Inverters.resize(InvertersNo); - /*for (int i = 0; i > InvertersNo; i++) - { - inverter x; - Inverters.emplace_back(x); - }*/ + LoadFIZ_EngineInductionMotor(Input); break; } default: @@ -12119,40 +13910,7 @@ void TMoverParameters::LoadFIZ_Engine(std::string const &Input) // NOTE: elements shared by both diesel engine variants; crude but, eh if (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) { - // oil pump - extract_value(OilPump.pressure_minimum, "OilMinPressure", Input, ""); - extract_value(OilPump.pressure_maximum, "OilMaxPressure", Input, ""); - // the time the starter turns the engine before it fires and smokes (eu07/maszyna#523) - extract_value(dizel_SmokeDelay, "SmokeDelay", Input, "0"); - dizel_SmokeDelay = std::max(0.0, dizel_SmokeDelay); - // engine cooling factore - extract_value(dizel_heat.kw, "HeatKW", Input, ""); - extract_value(dizel_heat.kv, "HeatKV", Input, ""); - extract_value(dizel_heat.kfe, "HeatKFE", Input, ""); - extract_value(dizel_heat.kfs, "HeatKFS", Input, ""); - extract_value(dizel_heat.kfo, "HeatKFO", Input, ""); - extract_value(dizel_heat.kfo2, "HeatKFO2", Input, ""); - // engine cooling systems - extract_value(dizel_heat.water.config.temp_min, "WaterMinTemperature", Input, ""); - extract_value(dizel_heat.water.config.temp_max, "WaterMaxTemperature", Input, ""); - extract_value(dizel_heat.water.config.temp_flow, "WaterFlowTemperature", Input, ""); - extract_value(dizel_heat.water.config.temp_cooling, "WaterCoolingTemperature", Input, ""); - extract_value(dizel_heat.water.config.shutters, "WaterShutters", Input, ""); - extract_value(dizel_heat.auxiliary_water_circuit, "WaterAuxCircuit", Input, ""); - extract_value(dizel_heat.water_aux.config.temp_min, "WaterAuxMinTemperature", Input, ""); - extract_value(dizel_heat.water_aux.config.temp_max, "WaterAuxMaxTemperature", Input, ""); - extract_value(dizel_heat.water_aux.config.temp_cooling, "WaterAuxCoolingTemperature", Input, ""); - extract_value(dizel_heat.water_aux.config.shutters, "WaterAuxShutters", Input, ""); - extract_value(dizel_heat.oil.config.temp_min, "OilMinTemperature", Input, ""); - extract_value(dizel_heat.oil.config.temp_max, "OilMaxTemperature", Input, ""); - extract_value(dizel_heat.engine_max_temp, "EngineMaxTemperature", Input, ""); - extract_value(dizel_heat.fan_speed, "WaterCoolingFanSpeed", Input, ""); - // water heater - extract_value(WaterHeater.config.temp_min, "HeaterMinTemperature", Input, ""); - extract_value(WaterHeater.config.temp_max, "HeaterMaxTemperature", Input, ""); - float pf{ 1235.f }; - extract_value(pf, "NominalCoolingPower", Input, "1235"); - dizel_heat.powerfactor = 1235 / pf; + LoadFIZ_EngineDieselShared(Input); } // traction motors @@ -12162,6 +13920,206 @@ void TMoverParameters::LoadFIZ_Engine(std::string const &Input) MotorBlowers[end::rear] = MotorBlowers[end::front]; // pressure switch extract_value(HasControlPressureSwitch, "PressureSwitch", Input, TrainType != dt_EZT ? "yes" : "no"); + // its brake cylinder half; the brake pipe one stays + extract_value(PressureSwitchBrakeCylinder, "PressureSwitchBrakeCylinder", Input, ""); +} + +// Engine: of a diesel engine, its revolutions, gears, hydraulic transmission and retarder +void TMoverParameters::LoadFIZ_EngineDiesel(std::string const &Input) +{ + + extract_value(dizel_nmin, "nmin", Input, ""); + dizel_nmin /= 60.0; + dizel_nreg_min = dizel_nmin * 0.98; + extract_value(dizel_nmin_hdrive, "nmin_hdrive", Input, ""); + dizel_nmin_hdrive /= 60.0; + if (dizel_nmin_hdrive == 0.0) + { + dizel_nmin_hdrive = dizel_nmin; + } + extract_value(dizel_nmin_hdrive_factor, "nmin_hdrive_factor", Input, ""); + dizel_nmin_hdrive_factor /= 60.0; + extract_value(dizel_nmin_retarder, "nmin_retarder", Input, ""); + dizel_nmin_retarder /= 60.0; + if (dizel_nmin_retarder == 0.0) + { + dizel_nmin_retarder = dizel_nmin; + } + // TODO: unify naming scheme and sort out which diesel engine params are used where and how + extract_value(nmax, "nmax", Input, ""); + nmax /= 60.0; + extract_value(dizel_nmax_cutoff, "nmax_cutoff", Input, "0.0"); + dizel_nmax_cutoff /= 60.0; + extract_value(dizel_nreg_acc, "nreg_acc", Input, ""); + dizel_nreg_acc /= 60.0; + extract_value(dizel_AIM, "AIM", Input, "1.0"); + extract_value(dizel_RevolutionsDecreaseRate, "RPMDecRate", Input, ""); + + extract_value(engageupspeed, "EUS", Input, "0.5"); + extract_value(engagedownspeed, "EDS", Input, "0.9"); + + if (true == extract_value(AnPos, "ShuntMode", Input, "")) + { + // dodatkowa przekładnia dla SM03 (2Ls150) + ShuntModeAllow = true; + ShuntMode = false; + if (AnPos < 1.0) + { + //"rozruch wysoki" ma dawać większą siłę + AnPos = 1.0 / AnPos; // im większa liczba, tym wolniej jedzie + } + } + extract_value(hydro_TC, "IsTC", Input, ""); + if (true == hydro_TC) + { + extract_value(hydro_TC_TMMax, "TC_TMMax", Input, ""); + extract_value(hydro_TC_CouplingPoint, "TC_CP", Input, ""); + extract_value(hydro_TC_LockupTorque, "TC_LT", Input, ""); + extract_value(hydro_TC_LockupRate, "TC_LR", Input, ""); + extract_value(hydro_TC_UnlockRate, "TC_ULR", Input, ""); + extract_value(hydro_TC_FillRateInc, "TC_FRI", Input, ""); + extract_value(hydro_TC_FillRateDec, "TC_FRD", Input, ""); + extract_value(hydro_TC_TorqueInIn, "TC_TII", Input, ""); + extract_value(hydro_TC_TorqueInOut, "TC_TIO", Input, ""); + extract_value(hydro_TC_TorqueOutOut, "TC_TOO", Input, ""); + extract_value(hydro_TC_LockupSpeed, "TC_LS", Input, ""); + extract_value(hydro_TC_UnlockSpeed, "TC_ULS", Input, ""); + extract_value(dizel_maxVelANS, "MaxVelANS", Input, ""); + + extract_value(hydro_R, "IsRetarder", Input, ""); + if (true == hydro_R) + { + extract_value(hydro_R_Placement, "R_Place", Input, ""); + extract_value(hydro_R_TorqueInIn, "R_TII", Input, ""); + extract_value(hydro_R_MaxTorque, "R_MT", Input, ""); + extract_value(hydro_R_MaxPower, "R_MP", Input, ""); + extract_value(hydro_R_FillRateInc, "R_FRI", Input, ""); + extract_value(hydro_R_FillRateDec, "R_FRD", Input, ""); + extract_value(hydro_R_MinVel, "R_MinVel", Input, ""); + extract_value(hydro_R_EngageVel, "R_EngageVel", Input, ""); + extract_value(hydro_R_Clutch, "R_IsClutch", Input, ""); + extract_value(hydro_R_ClutchSpeed, "R_ClutchSpeed", Input, ""); + extract_value(hydro_R_WithIndividual, "R_WithIndividual", Input, ""); + } + } +} + +// Engine: of a diesel-electric +void TMoverParameters::LoadFIZ_EngineDieselElectric(std::string const &Input) +{ + + extract_value(Ftmax, "Ftmax", Input, ""); + Flat = extract_value("Flat", Input) == "1"; + extract_value(Vhyp, "Vhyp", Input, ""); + Vhyp /= 3.6; + extract_value(Vadd, "Vadd", Input, ""); + Vadd /= 3.6; + extract_value(PowerCorRatio, "Cr", Input, ""); + extract_value(RelayType, "RelayType", Input, ""); + if (extract_value("ShuntMode", Input) == "1") + { + + ShuntModeAllow = true; + ShuntMode = false; + AnPos = 0.0; + ImaxHi = 2; + ImaxLo = 1; + } + extract_value(EngineHeatingRPM, "HeatingRPM", Input, ""); + extract_value(dizel_AIM, "AIM", Input, "1.25"); + extract_value(dizel_RevolutionsDecreaseRate, "RPMDecRate", Input, ""); + LoadFIZ_DieselElectricDynamicBrake(Input); +} + +// Engine: of an induction motor drive +void TMoverParameters::LoadFIZ_EngineInductionMotor(std::string const &Input) +{ + + RVentnmax = 1.0; + extract_value(NominalVoltage, "Volt", Input, ""); + + extract_value(eimc[eimc_s_dfic], "dfic", Input, ""); + extract_value(eimc[eimc_s_dfmax], "dfmax", Input, ""); + extract_value(eimc[eimc_s_p], "p", Input, ""); + extract_value(eimc[eimc_s_cfu], "cfu", Input, ""); + extract_value(eimc[eimc_s_cim], "cim", Input, ""); + extract_value(eimc[eimc_s_icif], "icif", Input, ""); + extract_value(eimc[eimc_f_Uzmax], "Uzmax", Input, ""); + extract_value(eimc[eimc_f_Uzh], "Uzh", Input, ""); + extract_value(eimc[eimc_f_DU], "DU", Input, ""); + extract_value(eimc[eimc_f_I0], "I0", Input, ""); + extract_value(eimc[eimc_f_cfu], "fcfu", Input, ""); + if (false == extract_value(eimc[eimc_f_cfuH], "fcfuH", Input, "")) + { + // without its own figure the dynamic brake takes the one of the traction + eimc[eimc_f_cfuH] = eimc[eimc_f_cfu]; + } + extract_value(eimc[eimc_p_F0], "F0", Input, ""); + extract_value(eimc[eimc_p_a1], "a1", Input, ""); + extract_value(eimc[eimc_p_Pmax], "Pmax", Input, ""); + extract_value(eimc[eimc_p_Fh], "Fh", Input, ""); + extract_value(eimc[eimc_p_Ph], "Ph", Input, ""); + extract_value(eimc[eimc_p_Vh0], "Vh0", Input, ""); + extract_value(eimc[eimc_p_Vh1], "Vh1", Input, ""); + extract_value(eimc[eimc_p_Imax], "Imax", Input, ""); + extract_value(eimc[eimc_p_abed], "abed", Input, ""); + extract_value(eimc[eimc_p_eped], "edep", Input, ""); + extract_value(EIMCLogForce, "eimclf", Input, ""); + extract_value(InvertersNo, "InvNo", Input, ""); + extract_value(InverterControlCouplerFlag, "InvCtrCplFlag", Input, ""); + extract_value(Imaxrpc, "Imaxrpc", Input, ""); + extract_value(BRVto, "BRVto", Input, ""); + extract_value(Flat, "Flat", Input, ""); + + if (eimc[eimc_p_Pmax] > 0 && Power > 0 && InvertersNo == 0) + { + InvertersNo = 1; + } + Inverters.resize(InvertersNo); + /*for (int i = 0; i > InvertersNo; i++) + { + inverter x; + Inverters.emplace_back(x); + }*/ +} + +// Engine: what both kinds of diesels have, their heat among it +void TMoverParameters::LoadFIZ_EngineDieselShared(std::string const &Input) +{ + // oil pump + extract_value(OilPump.pressure_minimum, "OilMinPressure", Input, ""); + extract_value(OilPump.pressure_maximum, "OilMaxPressure", Input, ""); + // the time the starter turns the engine before it fires and smokes (eu07/maszyna#523) + extract_value(dizel_SmokeDelay, "SmokeDelay", Input, "0"); + dizel_SmokeDelay = std::max(0.0, dizel_SmokeDelay); + // engine cooling factore + extract_value(dizel_heat.kw, "HeatKW", Input, ""); + extract_value(dizel_heat.kv, "HeatKV", Input, ""); + extract_value(dizel_heat.kfe, "HeatKFE", Input, ""); + extract_value(dizel_heat.kfs, "HeatKFS", Input, ""); + extract_value(dizel_heat.kfo, "HeatKFO", Input, ""); + extract_value(dizel_heat.kfo2, "HeatKFO2", Input, ""); + // engine cooling systems + extract_value(dizel_heat.water.config.temp_min, "WaterMinTemperature", Input, ""); + extract_value(dizel_heat.water.config.temp_max, "WaterMaxTemperature", Input, ""); + extract_value(dizel_heat.water.config.temp_flow, "WaterFlowTemperature", Input, ""); + extract_value(dizel_heat.water.config.temp_cooling, "WaterCoolingTemperature", Input, ""); + extract_value(dizel_heat.water.config.shutters, "WaterShutters", Input, ""); + extract_value(dizel_heat.auxiliary_water_circuit, "WaterAuxCircuit", Input, ""); + extract_value(dizel_heat.water_aux.config.temp_min, "WaterAuxMinTemperature", Input, ""); + extract_value(dizel_heat.water_aux.config.temp_max, "WaterAuxMaxTemperature", Input, ""); + extract_value(dizel_heat.water_aux.config.temp_cooling, "WaterAuxCoolingTemperature", Input, ""); + extract_value(dizel_heat.water_aux.config.shutters, "WaterAuxShutters", Input, ""); + extract_value(dizel_heat.oil.config.temp_min, "OilMinTemperature", Input, ""); + extract_value(dizel_heat.oil.config.temp_max, "OilMaxTemperature", Input, ""); + extract_value(dizel_heat.engine_max_temp, "EngineMaxTemperature", Input, ""); + extract_value(dizel_heat.fan_speed, "WaterCoolingFanSpeed", Input, ""); + // water heater + extract_value(WaterHeater.config.temp_min, "HeaterMinTemperature", Input, ""); + extract_value(WaterHeater.config.temp_max, "HeaterMaxTemperature", Input, ""); + float pf{1235.f}; + extract_value(pf, "NominalCoolingPower", Input, "1235"); + dizel_heat.powerfactor = 1235 / pf; } void TMoverParameters::LoadFIZ_Switches(std::string const &Input) @@ -12269,6 +14227,35 @@ void TMoverParameters::LoadFIZ_RList(std::string const &Input) extract_value(DynamicBrakeRes2, "DynBrakeRes2", Input, ""); } +// the dynamic brake of a diesel-electric vehicle, from its Engine section: none without EDBrake +void TMoverParameters::LoadFIZ_DieselElectricDynamicBrake(std::string const &Input) +{ + using enum diesel_electric_dynamic_brake::control; + std::map> const sources{{"Controller", controller}, {"Lever", lever}}; + auto const lookup{sources.find(extract_value("EDBrake", Input))}; + if (lookup == sources.end()) + { + return; + } + auto &brake{DEDynamicBrake}; + brake.source = lookup->second; + auto force{0.0}; // [kN] + auto power{0.0}; // [kW] + extract_value(force, "EDBrakeFmax", Input, ""); + extract_value(power, "EDBrakePmax", Input, ""); + brake.max_force = force * 1000.0; + brake.max_power = power * 1000.0; + extract_value(brake.fade_low, "EDBrakeV0", Input, ""); + extract_value(brake.fade_high, "EDBrakeV1", Input, ""); + extract_value(brake.rate, "EDBrakeRate", Input, ""); + extract_value(brake.blending, "EDBrakeBlending", Input, ""); + if (brake.source == lever) + { + // the lever of its own, which the commands of the dynamic brake controller move + SplitEDPneumaticBrake = true; + } +} + void TMoverParameters::LoadFIZ_UCList(std::string const &Input) { @@ -12557,6 +14544,143 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) } // WriteLog("BVV = " + FloatToStr(BrakeVVolume)); + CreateBrakeValve(); + + CreateBrakeHandles(); + + CreateBrakePipes(); + + if (LightsPosNo > 0) + LightsPos = LightsDefPos; + + // set default wiper switch position + wiperSwitchPos = WiperDefaultPos; + + if (CompressorListPosNo > 0) + CompressorListPos = CompressorListDefPos; + + // the genset of a dual-mode vehicle is a second source of the traction circuit of an induction motor vehicle + if (Genset.fitted() && (EngineType != TEngineType::ElectricInductionMotor || EnginePowerSource.SourceType != TPowerSource::CurrentCollector)) + { + WriteLog("GensetPower ignored: a genset works only with EngineType=ElectricInductionMotor and EnginePower=CurrentCollector"); + Genset = genset_device{}; + } + + // NOTE: legacy compatibility behaviour for vehicles without defined heating power source + if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector && HeatingPowerSource.SourceType == TPowerSource::NotDefined) + { + HeatingPowerSource.SourceType = TPowerSource::Main; + } + if (HeatingPowerSource.SourceType == TPowerSource::NotDefined && HeatingPower > 0) + { + HeatingPowerSource.SourceType = TPowerSource::PowerCable; + HeatingPowerSource.PowerType = TPowerType::ElectricPower; + } + + // checking ready flag + // to dac potem do init + if (ReadyFlag) // gotowy do drogi + { + SetReadyToDepart(); + } + else + { // zahamowany} + SetBraked(); + } + + ActFlowSpeed = 0.0; + BrakeCtrlPosR = BrakeCtrlPos; + + if (BrakeLocHandle == TBrakeHandle::Knorr) + LocalBrakePosA = 0.5; + + Pipe->CreatePress(PipePress); + Pipe2->CreatePress(ScndPipePress); + Pipe->Act(); + Pipe2->Act(); + + EqvtPipePress = PipePress; + + Handle->Init(PipePress); + + ComputeConstans(); + + if (LoadFlag > 0) + { + + if (LoadAmount < MaxLoad * 0.45) + { + IncBrakeMult(); + IncBrakeMult(); + DecBrakeMult(); // TODO: przeinesiono do mover.cpp + if (LoadAmount < MaxLoad * 0.35) + DecBrakeMult(); + } + else + { + IncBrakeMult(); // TODO: przeinesiono do mover.cpp + if (LoadAmount >= MaxLoad * 0.55) + IncBrakeMult(); + } + } + + // taki mini automat - powinno byc ladnie dobrze :) + BrakeDelayFlag = bdelay_P; + if (TestFlag(BrakeDelays, bdelay_G) && !TestFlag(BrakeDelays, bdelay_R)) + BrakeDelayFlag = bdelay_G; + if (TestFlag(BrakeDelays, bdelay_R) && !TestFlag(BrakeDelays, bdelay_G)) + BrakeDelayFlag = bdelay_R; + /* + // disabled, as test mode is used in specific situations and not really a default + if (BrakeOpModes & bom_PS) + BrakeOpModeFlag = bom_PS; + else + */ + BrakeOpModeFlag = bom_PN; + + // yB: jesli pojazdy nie maja zadeklarowanych czasow, to wsadz z przepisow +-16,(6)% + std::array const DefBrakeTable{15, 4, 25, 25, 13, 3, 12, 2}; + + for (int b = 1; b < 4; b++) + { + if (BrakeDelay[b] == 0) + BrakeDelay[b] = DefBrakeTable[b]; + BrakeDelay[b] = BrakeDelay[b] * (2.5 + Random(0.0, 0.2)) / 3.0; + } + + Hamulec->Init(PipePress, HighPipePress, LowPipePress, BrakePress, BrakeDelayFlag); + /* + ScndPipePress = Compressor; + */ + // WriteLogSS("OK=", BoolTo10(OK)); + // WriteLog(""); + + if (EIMCtrlType == 3) + { + for (auto idx = 0; idx < MainCtrlPosNo; ++idx) + { + if (UniCtrlList[idx].MaxCtrlVal > 0.0) + { + UniCtrlNoPowerPos = std::max(0, idx - 1); + break; + } + } + } + + // security system + // by default place the magnet in the vehicle centre + if (SecuritySystem.MagnetLocation == 0) + { + SecuritySystem.MagnetLocation = Dim.L / 2 - 0.5; + } + SecuritySystem.MagnetLocation = safe_clamp(SecuritySystem.MagnetLocation, 0.0, Dim.L); + + return OK; +} + +// the distributor valve of the vehicle's kind +void TMoverParameters::CreateBrakeValve() +{ switch (BrakeValve) { case TBrakeValve::W: @@ -12651,7 +14775,11 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) Hamulec->SetASBP(MaxBrakePress[4]); Hamulec->SetRV(RapidVel); +} +// the driver's handle and the local brake handle of the vehicle's kinds +void TMoverParameters::CreateBrakeHandles() +{ switch (BrakeHandle) { using enum TBrakeHandle; @@ -12713,7 +14841,11 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) default: LocHandle = std::make_shared(); } +} +// the brake pipe, the main pipe and the spring brake's cylinder +void TMoverParameters::CreateBrakePipes() +{ if (true == TestFlag(BrakeDelays, bdelay_G) && (false == TestFlag(BrakeDelays, bdelay_R) || Power > 1.0)) // ustalanie srednicy przewodu glownego (lokomotywa lub napędowy Spg = 0.792; else @@ -12729,173 +14861,73 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) SpringBrake.Cylinder = std::make_shared(); SpringBrake.Cylinder->CreateCap(1); } +} - if (LightsPosNo > 0) - LightsPos = LightsDefPos; - - // set default wiper switch position - wiperSwitchPos = WiperDefaultPos; - - if (CompressorListPosNo > 0) - CompressorListPos = CompressorListDefPos; - - // NOTE: legacy compatibility behaviour for vehicles without defined heating power source - if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector && HeatingPowerSource.SourceType == TPowerSource::NotDefined) +// the pressure of the main pipe at the start: the main reservoir's, or HosePressure fed through a main hose, or none +double TMoverParameters::InitialScndPipePress(double const HosePressure) const +{ + if (VeselVolume > 0.0) { - HeatingPowerSource.SourceType = TPowerSource::Main; + return CompressedVolume / VeselVolume; } - if (HeatingPowerSource.SourceType == TPowerSource::NotDefined && HeatingPower > 0) + if ((Couplers[end::front].AllowedFlag & coupling::mainhose) != 0 || (Couplers[end::rear].AllowedFlag & coupling::mainhose) != 0) { - HeatingPowerSource.SourceType = TPowerSource::PowerCable; - HeatingPowerSource.PowerType = TPowerType::ElectricPower; + return HosePressure; } + return 0.0; +} - // checking ready flag - // to dac potem do init - if (ReadyFlag) // gotowy do drogi - { - WriteLog("Ready to depart"); - CompressedVolume = VeselVolume * MinCompressor * 9.8 / 10.0; - ScndPipePress = VeselVolume > 0.0 ? CompressedVolume / VeselVolume : - (Couplers[end::front].AllowedFlag & coupling::mainhose) != 0 ? 5.0 : - (Couplers[end::rear].AllowedFlag & coupling::mainhose) != 0 ? 5.0 : - 0.0; - PipePress = CntrlPipePress; - BrakePress = 0.0; - LocalBrakePosA = 0.0; - if (CabActive == 0) - BrakeCtrlPos = static_cast(Handle->GetPos(bh_NP)); - else - BrakeCtrlPos = static_cast(Handle->GetPos(bh_RP)); - /* - // NOTE: disabled and left up to the driver, if there's any - MainSwitch( false ); - PantFront( true ); - PantRear( true ); - MainSwitch( true ); - */ - DirActive = 0; // Dir; //nastawnik kierunkowy - musi być ustawiane osobno! - DirAbsolute = DirActive * CabActive; // kierunek jazdy względem sprzęgów - LimPipePress = CntrlPipePress; - - Battery = BatteryStart != start_t::disabled; - } - else - { // zahamowany} - WriteLog("Braked"); - Volume = BrakeVVolume * MaxBrakePress[3]; - CompressedVolume = VeselVolume * MinCompressor * 0.55; - /* - ScndPipePress = 5.1; - */ - ScndPipePress = VeselVolume > 0.0 ? CompressedVolume / VeselVolume : - (Couplers[end::front].AllowedFlag & coupling::mainhose) != 0 ? 5.1 : - (Couplers[end::rear].AllowedFlag & coupling::mainhose) != 0 ? 5.1 : - 0.0; - PipePress = LowPipePress; - PipeBrakePress = MaxBrakePress[3] * 0.5; - BrakePress = MaxBrakePress[3] * 0.5; - LocalBrakePosA = 0.0; +// the air and the controls of a vehicle ready to depart +void TMoverParameters::SetReadyToDepart() +{ + WriteLog("Ready to depart"); + CompressedVolume = VeselVolume * MinCompressor * 9.8 / 10.0; + ScndPipePress = InitialScndPipePress(5.0); + PipePress = CntrlPipePress; + BrakePress = 0.0; + LocalBrakePosA = 0.0; + if (CabActive == 0) BrakeCtrlPos = static_cast(Handle->GetPos(bh_NP)); - LimPipePress = LowPipePress; - if (LocalBrake == TLocalBrake::ManualBrake || MBrake == true) - { - IncManualBrakeLevel(ManualBrakePosNo); - } - if (SpringBrake.MaxBrakeForce > 0.0) - { - SpringBrake.Activate = true; - } - } - - ActFlowSpeed = 0.0; - BrakeCtrlPosR = BrakeCtrlPos; - - if (BrakeLocHandle == TBrakeHandle::Knorr) - LocalBrakePosA = 0.5; - - Pipe->CreatePress(PipePress); - Pipe2->CreatePress(ScndPipePress); - Pipe->Act(); - Pipe2->Act(); - - EqvtPipePress = PipePress; - - Handle->Init(PipePress); - - ComputeConstans(); - - if (LoadFlag > 0) - { - - if (LoadAmount < MaxLoad * 0.45) - { - IncBrakeMult(); - IncBrakeMult(); - DecBrakeMult(); // TODO: przeinesiono do mover.cpp - if (LoadAmount < MaxLoad * 0.35) - DecBrakeMult(); - } - else - { - IncBrakeMult(); // TODO: przeinesiono do mover.cpp - if (LoadAmount >= MaxLoad * 0.55) - IncBrakeMult(); - } - } - - // taki mini automat - powinno byc ladnie dobrze :) - BrakeDelayFlag = bdelay_P; - if (TestFlag(BrakeDelays, bdelay_G) && !TestFlag(BrakeDelays, bdelay_R)) - BrakeDelayFlag = bdelay_G; - if (TestFlag(BrakeDelays, bdelay_R) && !TestFlag(BrakeDelays, bdelay_G)) - BrakeDelayFlag = bdelay_R; + else + BrakeCtrlPos = static_cast(Handle->GetPos(bh_RP)); /* - // disabled, as test mode is used in specific situations and not really a default - if (BrakeOpModes & bom_PS) - BrakeOpModeFlag = bom_PS; - else + // NOTE: disabled and left up to the driver, if there's any + MainSwitch( false ); + PantFront( true ); + PantRear( true ); + MainSwitch( true ); */ - BrakeOpModeFlag = bom_PN; + DirActive = 0; // Dir; //nastawnik kierunkowy - musi być ustawiane osobno! + DirAbsolute = DirActive * CabActive; // kierunek jazdy względem sprzęgów + LimPipePress = CntrlPipePress; - // yB: jesli pojazdy nie maja zadeklarowanych czasow, to wsadz z przepisow +-16,(6)% - std::array const DefBrakeTable{15, 4, 25, 25, 13, 3, 12, 2}; + Battery = BatteryStart != start_t::disabled; +} - for (int b = 1; b < 4; b++) - { - if (BrakeDelay[b] == 0) - BrakeDelay[b] = DefBrakeTable[b]; - BrakeDelay[b] = BrakeDelay[b] * (2.5 + Random(0.0, 0.2)) / 3.0; - } - - Hamulec->Init(PipePress, HighPipePress, LowPipePress, BrakePress, BrakeDelayFlag); +// the air and the brakes of a vehicle standing braked +void TMoverParameters::SetBraked() +{ + WriteLog("Braked"); + Volume = BrakeVVolume * MaxBrakePress[3]; + CompressedVolume = VeselVolume * MinCompressor * 0.55; /* - ScndPipePress = Compressor; + ScndPipePress = 5.1; */ - // WriteLogSS("OK=", BoolTo10(OK)); - // WriteLog(""); - - if (EIMCtrlType == 3) + ScndPipePress = InitialScndPipePress(5.1); + PipePress = LowPipePress; + PipeBrakePress = MaxBrakePress[3] * 0.5; + BrakePress = MaxBrakePress[3] * 0.5; + LocalBrakePosA = 0.0; + BrakeCtrlPos = static_cast(Handle->GetPos(bh_NP)); + LimPipePress = LowPipePress; + if (LocalBrake == TLocalBrake::ManualBrake || MBrake == true) { - for (auto idx = 0; idx < MainCtrlPosNo; ++idx) - { - if (UniCtrlList[idx].MaxCtrlVal > 0.0) - { - UniCtrlNoPowerPos = std::max(0, idx - 1); - break; - } - } + IncManualBrakeLevel(ManualBrakePosNo); } - - // security system - // by default place the magnet in the vehicle centre - if (SecuritySystem.MagnetLocation == 0) + if (SpringBrake.MaxBrakeForce > 0.0) { - SecuritySystem.MagnetLocation = Dim.L / 2 - 0.5; + SpringBrake.Activate = true; } - SecuritySystem.MagnetLocation = safe_clamp(SecuritySystem.MagnetLocation, 0.0, Dim.L); - - return OK; } // ************************************************************************************************* @@ -12991,8 +15023,26 @@ bool TMoverParameters::SendCtrlToNext(std::string const &CtrlCommand, double con // jakiejś zmiany (np. IncMainCtrl) lepiej wywołać funkcję, czy od razu wysłać komendę. bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype) { - bool OK{false}; + // the group of the command sets OK; a command none of them knows isn't done + if (bool OK{false}; RunControllerCommand(Command, CValue1, CValue2, Couplertype, OK) || RunRelaysCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunCabCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunBrakeCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunBrakeEquipmentCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunAuxiliariesCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunPumpsCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunBlowersCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunPowerCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunDoorsCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunLoadCommand(Command, CValue1, CValue2, Couplertype, OK)) + { + return OK; // dla true komenda będzie usunięta, dla false wykonana ponownie + } + return false; +} +// RunCommand() for the controllers; returns whether the command is one of them +bool TMoverParameters::RunControllerCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ if (Command == "MainCtrl") { // sent as MainCtrlPosForCoupled(), passed on unchanged @@ -13032,7 +15082,102 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do eimic_real = CValue1; OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "Brake") // youBy - jak sie EP hamuje, to trza sygnal wyslac... + else + { + return false; + } + return true; +} + +// RunCommand() for the direction, the automatic start and the current relays; returns whether the command is one of them +bool TMoverParameters::RunRelaysCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "Direction") + { + DirActive = static_cast(floor(CValue1)); + DirAbsolute = DirActive * CabActive; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "AutoRelaySwitch") + { + if (CValue1 == 1 && AutoRelayType == 2) + AutoRelayFlag = true; + else + AutoRelayFlag = false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "MaxCurrentSwitch") + { + MaxCurrentSwitch(CValue1 == 1, range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "MinCurrentSwitch") + { + OK = MinCurrentSwitch(CValue1 == 1); + } + /*test komend oddzialywujacych na tabor*/ + else + { + return false; + } + return true; +} + +// RunCommand() for the cab and the speed control; returns whether the command is one of them +bool TMoverParameters::RunCabCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "CabActivisation") + { + // OK:=Power>0.01; + switch (static_cast(CValue1 * CValue2)) + { // CValue2 ma zmieniany znak przy niezgodności sprzęgów + case 1: + { + CabActive = 1; + break; + } + case -1: + { + CabActive = -1; + break; + } + default: + { + CabActive = 0; // gdy CValue1==0 + break; + } + } + if (PulleeMode) + { + // a vehicle prepared for hauling takes no cab, the command only passes through it + CabActive = 0; + } + DirAbsolute = DirActive * CabActive; + CabMaster = false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "SpeedCntrl") + { + if (EngineType == TEngineType::ElectricInductionMotor || SpeedCtrl) + SpeedCtrlValue = static_cast(round(CValue1)); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "SpeedCtrlUnit.Parking") + { + SpeedCtrlUnit.Parking = static_cast(CValue1); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + { + return false; + } + return true; +} + +// RunCommand() for the train brake, the releaser and the emergency brake; returns whether the command is one of them +bool TMoverParameters::RunBrakeCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "Brake") // youBy - jak sie EP hamuje, to trza sygnal wyslac... { if (CValue1 < 0.001) DynamicBrakeEMUStatus = true; @@ -13055,7 +15200,119 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do OK = BrakeReleaser(static_cast(Round(CValue1))); // samo się przesyła dalej // OK:=SendCtrlToNext(command,CValue1,CValue2); //to robiło kaskadę 2^n } - else if (Command == "WaterPumpBreakerSwitch") + else if (Command == "Emergency_brake") + { + if (RadiostopSwitch(floor(CValue1) == 1)) // YB: czy to jest potrzebne? + OK = true; + else + OK = false; + } + else + { + return false; + } + return true; +} + +// RunCommand() for the brake delays, the spring brake, the sand and the cab signalling; returns whether the command is one of them +bool TMoverParameters::RunBrakeEquipmentCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "BrakeDelay") + { + if (auto const brakesetting = static_cast(std::floor(CValue1)); true == Hamulec->SetBDF(brakesetting)) + { + BrakeDelayFlag = brakesetting; + OK = true; + } + else + { + OK = false; + } + SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "SpringBrakeActivate") + { + if (Power24vIsAvailable || Power110vIsAvailable) + { + SpringBrake.Activate = CValue1 > 0; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + OK = true; + } + + else if (Command == "Sandbox") + { + OK = Sandbox(CValue1 == 1, range_t::local); + } + else if (Command == "CabSignal") /*SHP,Indusi*/ + { // Ra: to powinno działać tylko w członie obsadzonym + SecuritySystem.set_cabsignal(); + // else OK:=false; + OK = true; // true, gdy można usunąć komendę + } + /*naladunek/rozladunek*/ + // TODO: have these commands leverage load exchange system instead + // TODO: CValue1 defines amount to load/unload + else + { + return false; + } + return true; +} + +// RunCommand() for the heating, the converter, the battery and the compressor; returns whether the command is one of them +bool TMoverParameters::RunAuxiliariesCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "HeatingSwitch") + { + HeatingSwitch_(CValue1 > 0.0); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "ConverterSwitch") /*NBMX*/ + { + if (ConverterStart == start_t::manual) + { + ConverterAllow = CValue1 > 0.0; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "BatterySwitch") /*NBMX*/ + { + // the battery of a vehicle prepared for hauling (PulleeMode) stays off + if (BatteryStart == start_t::manual && (false == PulleeMode || CValue1 <= 0.0)) + { + Battery = CValue1 > 0.0; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + // else if command='EpFuseSwitch' then {NBMX} + // begin + // if (CValue1=1) then EpFuse:=true + // else if (CValue1=0) then EpFuse:=false; + // OK:=SendCtrlToNext(command,CValue1,CValue2); + // end + else if (Command == "CompressorSwitch") /*NBMX*/ + { + CompressorSwitch(CValue1 == 1, range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "CompressorPreset") + { + CompressorListPos = safe_clamp(static_cast(CValue1), 0, CompressorListPosNo); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + { + return false; + } + return true; +} + +// RunCommand() for the water, fuel and oil pumps and the water heater; returns whether the command is one of them +bool TMoverParameters::RunPumpsCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "WaterPumpBreakerSwitch") { /* if( FuelPump.start_type != start::automatic ) { @@ -13156,7 +15413,17 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "MotorBlowersFrontSwitch") + else + { + return false; + } + return true; +} + +// RunCommand() for the motor blowers and the compartment lights; returns whether the command is one of them +bool TMoverParameters::RunBlowersCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "MotorBlowersFrontSwitch") { if (MotorBlowers[end::front].start_type != start_t::manual && MotorBlowers[end::front].start_type != start_t::manualwithautofallback) { @@ -13212,170 +15479,26 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "MainSwitch") + else + { + return false; + } + return true; +} + +// RunCommand() for the line breaker, the relays and the pantographs; returns whether the command is one of them +bool TMoverParameters::RunPowerCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "MainSwitch") { MainSwitch_(CValue1 > 0.0); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "HeatingSwitch") - { - HeatingSwitch_(CValue1 > 0.0); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "Direction") - { - DirActive = static_cast(floor(CValue1)); - DirAbsolute = DirActive * CabActive; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "CabActivisation") - { - // OK:=Power>0.01; - switch (static_cast(CValue1 * CValue2)) - { // CValue2 ma zmieniany znak przy niezgodności sprzęgów - case 1: - { - CabActive = 1; - break; - } - case -1: - { - CabActive = -1; - break; - } - default: - { - CabActive = 0; // gdy CValue1==0 - break; - } - } - DirAbsolute = DirActive * CabActive; - CabMaster = false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "AutoRelaySwitch") - { - if (CValue1 == 1 && AutoRelayType == 2) - AutoRelayFlag = true; - else - AutoRelayFlag = false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } else if (Command == "RelayReset") { RelayReset(static_cast(CValue1), range_t::local); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "ConverterSwitch") /*NBMX*/ - { - if (ConverterStart == start_t::manual) - { - ConverterAllow = CValue1 > 0.0; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "BatterySwitch") /*NBMX*/ - { - if (BatteryStart == start_t::manual) - { - Battery = CValue1 > 0.0; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - // else if command='EpFuseSwitch' then {NBMX} - // begin - // if (CValue1=1) then EpFuse:=true - // else if (CValue1=0) then EpFuse:=false; - // OK:=SendCtrlToNext(command,CValue1,CValue2); - // end - else if (Command == "CompressorSwitch") /*NBMX*/ - { - CompressorSwitch(CValue1 == 1, range_t::local); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "CompressorPreset") - { - CompressorListPos = safe_clamp(static_cast(CValue1), 0, CompressorListPosNo); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorPermit") - { - - auto const leftside{CValue2 > 0 ? 1 : 2}; - - if (auto const rightside{3 - leftside}; std::abs(static_cast(CValue1)) & rightside) - { - PermitDoors_(side::right, CValue1 > 0); - } - if (std::abs(static_cast(CValue1)) & leftside) - { - PermitDoors_(side::left, CValue1 > 0); - } - - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorOpen") /*NBMX*/ - { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów - // ignore remote command if the door is only operated locally - if ((Doors.open_control == control_t::conductor || Doors.open_control == control_t::driver || Doors.open_control == control_t::mixed) && (Power24vIsAvailable || Power110vIsAvailable)) - { - - auto const leftside{CValue2 > 0 ? 1 : 2}; - - if (auto const rightside{3 - leftside}; static_cast(CValue1) & rightside) - { - Doors.instances[side::right].remote_open = true; - Doors.instances[side::right].remote_close = false; - } - if (static_cast(CValue1) & leftside) - { - Doors.instances[side::left].remote_open = true; - Doors.instances[side::left].remote_close = false; - } - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorClose") /*NBMX*/ - { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów - // ignore remote command if the door is only operated locally - if ((Doors.close_control == control_t::conductor || Doors.close_control == control_t::driver || Doors.close_control == control_t::mixed) && (Power24vIsAvailable || Power110vIsAvailable)) - { - - auto const leftside{CValue2 > 0 ? 1 : 2}; - - if (auto const rightside{3 - leftside}; static_cast(CValue1) & rightside) - { - Doors.instances[side::right].remote_close = true; - Doors.instances[side::right].remote_open = false; - } - if (static_cast(CValue1) & leftside) - { - Doors.instances[side::left].remote_close = true; - Doors.instances[side::left].remote_open = false; - } - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorLock") - { - Doors.lock_enabled = CValue1 == 1 ? true : false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorStep") - { - Doors.step_enabled = CValue1 == 1 ? true : false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorMode") - { - Doors.remote_only = CValue1 == 1 ? true : false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DepartureSignal") - { - DepartureSignal = CValue1 == 1 ? true : false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } else if (Command == "PantValve") // Winger 160204 { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów auto const inputend{(static_cast(CValue1) & 0x80) != 0 ? 1 : 0}; @@ -13400,57 +15523,104 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do DropAllPantographs(CValue1 == 1, range_t::local); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "MaxCurrentSwitch") + else if (Command == "TractionMode") { - MaxCurrentSwitch(CValue1 == 1, range_t::local); + TractionModeSwitch(CValue1 > 0.5 ? traction_mode::genset : traction_mode::catenary, range_t::local); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "MinCurrentSwitch") + else if (Command == "GensetSwitch") { - OK = MinCurrentSwitch(CValue1 == 1); + GensetSwitch(CValue1 > 0.5, range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - /*test komend oddzialywujacych na tabor*/ - else if (Command == "SetDamage") + else { - if (CValue2 == 1) - OK = SetFlag(DamageFlag, static_cast(floor(CValue1))); - if (CValue2 == -1) - OK = SetFlag(DamageFlag, static_cast(-floor(CValue1))); + return false; } - else if (Command == "Emergency_brake") + return true; +} + +// RunCommand() for the doors and the departure signal; returns whether the command is one of them +bool TMoverParameters::RunDoorsCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "DoorPermit") { - if (RadiostopSwitch(floor(CValue1) == 1)) // YB: czy to jest potrzebne? - OK = true; - else - OK = false; + DoorPermitCommand(CValue1, CValue2); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "BrakeDelay") + else if (Command == "DoorOpen" || Command == "DoorClose") /*NBMX*/ + { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów + DoorRemoteCommand(Command == "DoorOpen", CValue1, CValue2); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "DoorLock") { - if (auto const brakesetting = static_cast(std::floor(CValue1)); true == Hamulec->SetBDF(brakesetting)) - { - BrakeDelayFlag = brakesetting; - OK = true; - } - else - { - OK = false; - } - SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + Doors.lock_enabled = CValue1 == 1 ? true : false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "Sandbox") + else if (Command == "DoorStep") { - OK = Sandbox(CValue1 == 1, range_t::local); + Doors.step_enabled = CValue1 == 1 ? true : false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "CabSignal") /*SHP,Indusi*/ - { // Ra: to powinno działać tylko w członie obsadzonym - SecuritySystem.set_cabsignal(); - // else OK:=false; - OK = true; // true, gdy można usunąć komendę + else if (Command == "DoorMode") + { + Doors.remote_only = CValue1 == 1 ? true : false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - /*naladunek/rozladunek*/ - // TODO: have these commands leverage load exchange system instead - // TODO: CValue1 defines amount to load/unload - else if (issection("Load=", Command)) + else if (Command == "DepartureSignal") + { + DepartureSignal = CValue1 == 1 ? true : false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + { + return false; + } + return true; +} + +// the doors' permits, on the sides the command names: CValue1 the sides, negative to take the permit back, CValue2 the +// direction the command comes from +void TMoverParameters::DoorPermitCommand(double const CValue1, double const CValue2) +{ + auto const leftside{CValue2 > 0 ? 1 : 2}; + if (auto const rightside{3 - leftside}; std::abs(static_cast(CValue1)) & rightside) + { + PermitDoors_(side::right, CValue1 > 0); + } + if (std::abs(static_cast(CValue1)) & leftside) + { + PermitDoors_(side::left, CValue1 > 0); + } +} + +// the doors opened or closed from afar on the sides the command names, unless they're only worked locally +void TMoverParameters::DoorRemoteCommand(bool const Open, double const CValue1, double const CValue2) +{ + using enum control_t; + if (auto const doorcontrol{Open ? Doors.open_control : Doors.close_control}; + (doorcontrol != conductor && doorcontrol != driver && doorcontrol != mixed) || (false == Power24vIsAvailable && false == Power110vIsAvailable)) + { + return; + } + auto const leftside{CValue2 > 0 ? 1 : 2}; + if (auto const rightside{3 - leftside}; static_cast(CValue1) & rightside) + { + Doors.instances[side::right].remote_open = Open; + Doors.instances[side::right].remote_close = false == Open; + } + if (static_cast(CValue1) & leftside) + { + Doors.instances[side::left].remote_open = Open; + Doors.instances[side::left].remote_close = false == Open; + } +} + +// RunCommand() for the load and the damage; returns whether the command is one of them +bool TMoverParameters::RunLoadCommand(std::string const &Command, double CValue1, double CValue2, int const /*Couplertype*/, bool &OK) +{ + if (issection("Load=", Command)) { OK = false; // będzie powtarzane aż się załaduje if (Vel < 0.1 // tolerance margin for small vehicle movements in the consist @@ -13487,29 +15657,24 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do LastLoadChangeTime = 0.0; } } - else if (Command == "SpeedCntrl") + else if (Command == "SetDamage") { - if (EngineType == TEngineType::ElectricInductionMotor || SpeedCtrl) - SpeedCtrlValue = static_cast(round(CValue1)); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "SpeedCtrlUnit.Parking") - { - SpeedCtrlUnit.Parking = static_cast(CValue1); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "SpringBrakeActivate") - { - if (Power24vIsAvailable || Power110vIsAvailable) + if (CValue2 == 1) + OK = SetFlag(DamageFlag, static_cast(floor(CValue1))); + if (CValue2 == -1) { - SpringBrake.Activate = CValue1 > 0; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + auto const derailed{TestFlag(DamageFlag, dtrain_out)}; + OK = SetFlag(DamageFlag, static_cast(-floor(CValue1))); + // taking the derailment off puts the vehicle back on the rails, with what the criteria of derailment held + if (derailed && false == TestFlag(DamageFlag, dtrain_out)) + rerail(); } - else - OK = true; } - - return OK; // dla true komenda będzie usunięta, dla false wykonana ponownie + else + { + return false; + } + return true; } // ************************************************************************************************* diff --git a/McZapkie/collision.cpp b/McZapkie/collision.cpp new file mode 100644 index 000000000..2fb085e69 --- /dev/null +++ b/McZapkie/collision.cpp @@ -0,0 +1,401 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "collision.h" + +#include +#include +#include + +#include "derailment.h" + +namespace collision { + +namespace { + +// the hit is integrated in slices of this length at most, and in no more than so many of them [s] +constexpr double slice{0.0005}; +constexpr double slices_max{200.0}; + +// the force of a curve over a range of crush within one of its parts, the force linear in it there [J] +double linear_work(double const ForceFrom, double const ForceTo, double const Length) { + return 0.5 * (ForceFrom + ForceTo) * std::max(Length, 0.0); +} + +} // namespace + +double crush_curve::force(double const Crush) const { + if (Crush >= limit) { + return std::numeric_limits::infinity(); + } + if (Crush < onset) { + return peak; + } + if (Crush < densify) { + return plateau; + } + return plateau * (1.0 + hardening * (Crush - densify)); +} + +double crush_curve::energy(double const From, double const To) const { + auto const from{std::max(From, 0.0)}; + auto const to{std::min(To, limit)}; + if (to <= from) { + return 0.0; + } + auto work{0.0}; + // the peak + work += peak * std::max(0.0, std::min(to, onset) - from); + // the plateau + auto const plateaufrom{std::max(from, onset)}; + auto const plateauto{std::min(to, std::max(densify, onset))}; + work += plateau * std::max(0.0, plateauto - plateaufrom); + // packing down + auto const densefrom{std::max(from, std::max(densify, onset))}; + if (to > densefrom) { + work += linear_work(force(densefrom), plateau * (1.0 + hardening * (to - densify)), to - densefrom); + } + return work; +} + +crush_curve default_crush(vehicle_kind const Kind) { + switch (Kind) { + case vehicle_kind::locomotive: + return {4.0e6, 3.0e6, 0.05, 0.6, 2.0, 1.2}; + case vehicle_kind::crash_zone: + return {2.0e6, 2.0e6, 0.0, 0.8, 2.5, 1.2}; + case vehicle_kind::wagon: + case vehicle_kind::coach: + default: + return {3.0e6, 2.0e6, 0.05, 0.8, 2.0, 1.5}; + } +} + +vehicle_kind kind_of(bool const Powered, bool const Passenger, bool const CrashZone) { + if (CrashZone) { + return vehicle_kind::crash_zone; + } + if (Passenger) { + return vehicle_kind::coach; + } + return Powered ? vehicle_kind::locomotive : vehicle_kind::wagon; +} + +crush_curve crush_of(end_definition const &Definition, vehicle_kind const Kind) { + auto curve{default_crush(Definition.crash_zone.value_or(false) ? vehicle_kind::crash_zone : Kind)}; + curve.peak = std::max(Definition.peak.value_or(curve.peak), 1.0); + curve.plateau = std::max(Definition.plateau.value_or(curve.plateau), 1.0); + curve.onset = std::max(Definition.onset.value_or(curve.onset), 0.0); + curve.densify = std::max(Definition.densify.value_or(curve.densify), curve.onset); + curve.hardening = std::max(Definition.hardening.value_or(curve.hardening), 0.0); + curve.limit = std::max(Definition.limit.value_or(curve.limit), curve.onset); + return curve; +} + +bool anticlimber_of(end_definition const &Definition, vehicle_kind const Kind) { + return Definition.anticlimber.value_or(Definition.crash_zone.value_or(Kind == vehicle_kind::crash_zone)); +} + +double buffer_height(end_definition const &Definition, vehicle_kind const Kind, double const LoadShare) { + auto const wagon{Kind == vehicle_kind::wagon}; + auto const empty{Definition.buffer_height.value_or(wagon ? 1.065 : 1.040)}; + // the springs of a wagon give 125 mm under its full load + return wagon ? empty - 0.125 * std::clamp(LoadShare, 0.0, 1.0) : empty; +} + +buffer_rating rating(buffer_category const Category) { + switch (Category) { + case buffer_category::B: + return {0.105, 50.0e3}; + case buffer_category::C: + return {0.105, 70.0e3}; + case buffer_category::L: + return {0.150, 70.0e3}; + case buffer_category::passenger: + return {0.110, 30.0e3}; + case buffer_category::A: + default: + return {0.105, 30.0e3}; + } +} + +coupler_physics::spring_curve buffer_curve(buffer_category const Category, double const Progression) { + auto const buffer{rating(Category)}; + auto const progression{std::clamp(Progression, 0.0, 0.9)}; + // the energy of the curve to the end of the stroke is F_end * stroke * ((1 - p) / 2 + p / 4), of two buffers + auto const endforce{2.0 * buffer.energy / (buffer.stroke * ((1.0 - progression) / 2.0 + progression / 4.0))}; + return {endforce / buffer.stroke, buffer.stroke, progression}; +} + +std::optional buffer_category_of(char const Name) { + switch (Name) { + case 'A': + case 'a': + return buffer_category::A; + case 'B': + case 'b': + return buffer_category::B; + case 'C': + case 'c': + return buffer_category::C; + case 'L': + case 'l': + return buffer_category::L; + case 'P': + case 'p': + return buffer_category::passenger; + default: + return std::nullopt; + } +} + +buffer_category default_buffers(vehicle_kind const Kind) { + return Kind == vehicle_kind::coach ? buffer_category::passenger : buffer_category::A; +} + +double buffer_capacity(end_definition const &Definition, vehicle_kind const Kind) { + // two buffers side by side + return 2.0 * rating(Definition.buffers.value_or(default_buffers(Kind))).energy; +} + +void contact_energy::update(bool const Pressed, bool const Solid, double const Closing, double const Force, double const Compression, double const Dt) { + if (false == Pressed) { + // the buffers apart, the contact is over + reset(); + return; + } + if (Solid || m_inside) { + // pressed all the way, the buffers take in nothing more; nor do those of vehicles inside each other + return; + } + auto const force{std::max(Force, 0.0)}; + if (Closing > 0.0) { + m_absorbed += force * Closing * std::max(Dt, 0.0); + } + else if (Closing < 0.0) { + // springing back, they hold no more than their springs pressed in so far + m_absorbed = std::min(m_absorbed, 0.5 * force * std::max(Compression, 0.0)); + } +} + +void contact_energy::inside() { + m_absorbed = 0.0; + m_inside = true; +} + +void contact_energy::crushed(double const Work) { + m_crushed += std::max(Work, 0.0); +} + +double contact_energy::budget(double const Mass, double const Closing, double const Capacity) const { + auto const closing{std::max(Closing, 0.0)}; + // what the buffers of EN 15551 would still take in: the springs of the .fiz taking in more leave no more energy past + // the buffers than the hit has + return 0.5 * std::max(Mass, 0.0) * closing * closing - std::max(0.0, Capacity - m_absorbed); +} + +void contact_energy::reset() { + m_absorbed = 0.0; + m_crushed = 0.0; + m_inside = false; +} + +hit_result hit(end_state const &First, end_state const &Second, hit_input const &Input) { + hit_result result; + if (Input.velocity <= 0.0 || Input.mass1 <= 0.0 || Input.mass2 <= 0.0 || Input.dt <= 0.0) { + return result; + } + auto const mass{Input.mass1 * Input.mass2 / (Input.mass1 + Input.mass2)}; + auto const restitution{std::clamp(Input.restitution, 0.0, 0.95)}; + // the elastic hit on the steel at the closing velocity adds root * velocity to the force of the springs + auto const root{std::sqrt(std::max(Input.stiffness, 1.0) * mass)}; + auto const springs{std::max(Input.springs, 0.0)}; + // the closing velocity the step started with: the springs slow the pair over the step as well, the hit adds what + // they don't carry of the force the end gives at + auto velocity{Input.start_velocity > 0.0 ? std::max(Input.start_velocity, Input.velocity) : Input.velocity + springs * Input.dt / mass}; + // where the forces of the step alone would take the pair + auto const unhit{velocity - springs * Input.dt / mass}; + + auto crush1{First.crush}; + auto crush2{Second.crush}; + auto const elastic_limit = [&](double const Force) { return std::max(0.0, Force - springs) / root; }; + { + auto const force{std::min(First.curve.force(crush1), Second.curve.force(crush2))}; + if (false == std::isfinite(force) || velocity <= elastic_limit(force) || false == (Input.budget > 0.0)) { + // the steel takes it all: the legacy elastic exchange + return result; + } + } + result.crushing = true; + + auto const slices{std::clamp(std::ceil(Input.dt / slice), 1.0, slices_max)}; + auto const length{Input.dt / slices}; + auto time{0.0}; + auto rebound{false}; + auto crushtime{0.0}; + auto work{0.0}; + auto cap{0.0}; // the force the crush went at last + while (Input.dt - time > 1e-12) { + auto const force1{First.curve.force(crush1)}; + auto const force2{Second.curve.force(crush2)}; + auto const force{std::min(force1, force2)}; + if (false == std::isfinite(force) || velocity <= elastic_limit(force)) { + // both ends crushed all the way, or the pair slowed down to what the steel takes back + rebound = true; + break; + } + auto const limit{elastic_limit(force)}; + auto step{std::min(length, Input.dt - time)}; + auto change{force * step / mass}; + if (velocity - change < limit) { + step = (velocity - limit) * mass / force; + change = velocity - limit; + } + auto crush{(velocity - 0.5 * change) * step}; + auto spent{false}; + if (work + force * crush > Input.budget) { + // the energy of the hit past the buffers runs out in the slice: the crush goes as far as it takes, the + // buffers of EN 15551 would take in the rest + auto const share{std::clamp((Input.budget - work) / std::max(force * crush, 1e-12), 0.0, 1.0)}; + step *= share; + change *= share; + crush *= share; + spent = true; + } + work += force * crush; + cap = force; + // the weaker end gives, both alike when they're alike + if (std::abs(force1 - force2) <= 1e-9 * force) { + crush1 += 0.5 * crush; + crush2 += 0.5 * crush; + } + else if (force1 < force2) { + crush1 += crush; + } + else { + crush2 += crush; + } + velocity -= change; + time += step; + crushtime += step; + result.force = std::max(result.force, force); + if (spent) { + result.spent = true; + rebound = true; + break; + } + } + + auto after{velocity}; + auto duration{crushtime}; + if (rebound) { + // the steel springs back with the restitution, the springs push the pair apart over the rest of the step + // under the force the weaker end gives at, as the slices stopped there. a crush stopped at the budget: the + // buffers of EN 15551 would have taken in the rest, its force no more than what crushes the end + result.force = std::max(result.force, result.spent ? std::min(springs + velocity * root, cap) : springs + velocity * root); + if (velocity > 0.0) { + duration += (1.0 + restitution) * velocity * mass / std::max(velocity * root, 1.0); + } + after = -restitution * velocity - springs * (Input.dt - time) / mass; + } + result.velocity = after; + result.impulse = mass * (unhit - after); + result.duration = std::min(duration, Input.dt); + result.crush1 = crush1 - First.crush; + result.crush2 = crush2 - Second.crush; + result.work = work; + return result; +} + +override_result override_of(override_input const &Input) { + override_result result; + if (Input.anticlimbers) { + // interlocked, they keep the ends level until the crush zone of one of them is used up + auto const spent1{Input.zone1 <= 0.0 || Input.crush1 >= Input.zone1}; + auto const spent2{Input.zone2 <= 0.0 || Input.crush2 >= Input.zone2}; + if (false == spent1 && false == spent2) { + return result; + } + } + auto const crush{Input.crush1 + Input.crush2}; + if (crush > override_both) { + result.first = true; + result.second = true; + return result; + } + if (crush <= override_crush) { + return result; + } + if (Input.mass1 * override_mass_ratio < Input.mass2) { + result.first = true; + } + else if (Input.mass2 * override_mass_ratio < Input.mass1) { + result.second = true; + } + else if (false == Input.anticlimbers && std::abs(Input.height1 - Input.height2) >= override_height - 1e-9) { + // the higher one rides up + result.first = Input.height1 > Input.height2; + result.second = false == result.first; + } + return result; +} + +double pushed_wheel::ratio() const { + if (q > 0.0) { + return y / q; + } + return y > 0.0 ? 1e9 : 0.0; +} + +double pushed_ratio(pushed_vehicle const &Vehicle, pushed_end const &End, double const Radius) { + return pushed_forces(Vehicle, End, Radius).ratio(); +} + +pushed_wheel pushed_forces(pushed_vehicle const &Vehicle, pushed_end const &End, double const Radius) { + pushed_wheel result; + if (Vehicle.mass <= 0.0 || End.force <= 0.0) { + return result; + } + auto const axles{static_cast(std::max(Vehicle.axles, 1))}; + // the axles of the half of the vehicle at the end: its bogie, or its axle + auto const half{std::max(axles / 2.0, 1.0)}; + auto const wheelload{Vehicle.mass * gravity / (2.0 * axles)}; + auto const halflength{std::max(0.5 * Vehicle.length, 1.0)}; + auto const angle{straight_angle + derailment::coupling_angle(Vehicle.length, End.other_length, Radius) + crush_angle * std::max(End.crush, 0.0) / halflength}; + // in a curve the leading axle meets the rail at an angle, the creep force of its inner wheel at most the friction + auto guiding{0.0}; + if (std::abs(Radius) > 1e-3) { + auto const attack{Vehicle.axle_base / (2.0 * std::abs(Radius))}; + guiding = derailment::tread_friction * wheelload * std::min(1.0, attack / derailment::saturated_attack); + } + auto const lateral{End.force * angle / half + guiding}; + // the force off the height it's carried at pitches the vehicle: the bogie at the end pressed in takes the load off + auto const pivots{Vehicle.pivots > 0.0 ? Vehicle.pivots : halflength}; + result.y = lateral; + result.q = wheelload - End.force * eccentricity / (2.0 * half * pivots); + return result; +} + +bool pushed_monitor::update(bool const Climbs, double const Distance, bool const Lifted, double const Duration) { + auto const climbed{m_climbing.update(Climbs, Distance, climb_distance)}; + if (false == Lifted) { + m_lifted = 0.0; + return climbed; + } + m_lifted += std::max(Duration, 0.0); + return climbed || m_lifted >= lift_time - 1e-9; +} + +void pushed_monitor::reset() { + m_climbing.reset(); + m_lifted = 0.0; +} + +} // namespace collision diff --git a/McZapkie/collision.h b/McZapkie/collision.h new file mode 100644 index 000000000..01239a3cd --- /dev/null +++ b/McZapkie/collision.h @@ -0,0 +1,297 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include + +#include "couplerphysics.h" +#include "derailment.h" + +// what a collision of two vehicles does to them past their buffers (physics.collisions new in eu07.ini, see +// TMoverParameters::CollisionDetect()), as plain functions of the vehicles and the hit: +// +// crush: once the buffers of the pair are pressed all the way, the underframes carry the rest of the hit, up to the +// force the weaker end gives at. only the energy the hit brings past what the buffers of EN 15551 of both ends take +// in can crush them (contact_energy): a hit the buffers would take, or the push of a train at a stand, never does. past it the end crushes for good: a short peak of force, then a lower plateau as +// the structure folds, then it packs down and stiffens (the force-crush curves of the full scale tests of the FRA: +// Tyrell et al., IMECE2002-33247). the hit is an impulse limited to that force over the step, so the force never +// goes past it and the depth of the crush is the same with any step; the depth stays with the end +// override: an end crushed deep enough no longer holds the other one down: the lighter of the two vehicles, or the +// one with its buffers higher (40 mm, the vertical offset of the design collision of EN 15227), climbs onto the +// other one and leaves the rails; past a deeper crush both do. interlocked anticlimbers hold them until the crush +// zone of an end is used up +// pushed off the track: the force pressing a vehicle's end acts at an angle to it, the more in a curve and the +// deeper the end is crushed, which gives a lateral force on its wheels; acting off the height of the centre of the +// vehicle it lifts its leading wheels. Y / Q over Nadal's limit while the wheels roll on over the window of +// EN 14363 and the flange climbs the rail (the light wagon between heavy ones goes first, in a curve sooner than +// on a straight track: EN 15566 takes 250 kN of the pair of buffers in a curve of 150 m as the safe push). a wheel +// which doesn't roll doesn't climb: Nadal's limit is that of a wheel rolling under its angle of attack, the creep of +// the flange contact turning the friction upwards; standing, the friction holds the flange down, and with a flange +// of 70 degrees and a friction over 1 / tan 70 = 0.36 no lateral force gets it up. so a train pushing at a stand, +// or the short peak of the springs of a hit, never pushes a wheel off. a push that takes the whole load off the +// leading wheels lifts them off the rail, rolling or not: that holding for a short time is enough +namespace collision { + +inline constexpr double gravity{9.81}; // [m/s2] + +// ---- the crush of an end + +// force-crush characteristic of the underframe at one end of a vehicle +struct crush_curve { + double peak{3.0e6}; // the force the crushing starts at [N] + double plateau{2.0e6}; // of the crushing past the onset [N] + double onset{0.05}; // the crush past which the peak drops to the plateau [m] + double densify{0.8}; // the crush past which the crushed structure packs down and stiffens [m] + double hardening{2.0}; // the growth of the force past it, to the plateau for each metre [1/m] + double limit{1.5}; // the end can't be crushed past it, it's rigid from there [m] + + // the force the end gives at with the crush [N]; past the limit there's no force it gives at + double force(double Crush) const; + // the work it takes to crush the end from the one depth to the other one [J] + double energy(double From, double To) const; +}; + +// what the vehicle is, for its defaults +enum class vehicle_kind { + wagon, // a freight wagon + coach, // a passenger coach, or a car of a unit + locomotive, + crash_zone // a vehicle built to EN 15227, with the energy absorbers and the anticlimbers at its ends +}; +// the defaults of the kind: a wagon or a coach gives at 1.5 times the force of the proof test of EN 12663 at the +// height of the buffers (2 MN), a locomotive at 4 MN; the plateau is the 2 MN of the crush of the cab car of the FRA +// test. the absorbers of a crash zone give a steady 2 MN over 0.8 m, as the deformation tubes and the crash buffers +// do (2 MN of the crash buffers in service) +crush_curve default_crush(vehicle_kind Kind); + +// the buffers of EN 15551, by their category +enum class buffer_category { + A, // 105 mm, 30 kJ + B, // 105 mm, 50 kJ + C, // 105 mm, 70 kJ + L, // the long stroke, 150 mm + passenger // 110 mm, of the coaches +}; + +// the optional keys of the .fiz for an end (BuffCoupl): what's not given comes from the kind of the vehicle +struct end_definition { + std::optional peak; // FcrushPeak [N] + std::optional plateau; // FcrushPlateau [N] + std::optional onset; // CrushOnset [m] + std::optional densify; // CrushDensify [m] + std::optional hardening; // CrushHardening [1/m] + std::optional limit; // CrushLimit [m] + std::optional crash_zone; // CrashZone: built to EN 15227 + std::optional anticlimber; // AntiClimber + std::optional buffer_height; // BufferHeight, of the empty vehicle above the rail [m] + std::optional buffers; // BufferCategory +}; +vehicle_kind kind_of(bool Powered, bool Passenger, bool CrashZone); +crush_curve crush_of(end_definition const &Definition, vehicle_kind Kind); +bool anticlimber_of(end_definition const &Definition, vehicle_kind Kind); +// height of the buffers above the rail [m]: UIC 940 to 1065 mm. without a given one, a wagon has them at the top of +// the range empty and lower by 125 mm fully loaded on its springs, a locomotive or a coach at 1040 mm +double buffer_height(end_definition const &Definition, vehicle_kind Kind, double LoadShare); + +// ---- the buffers, EN 15551 + +struct buffer_rating { + double stroke{0.105}; // [m] + double energy{30.0e3}; // dynamic energy of one buffer [J] +}; +buffer_rating rating(buffer_category Category); +// the spring curve of the two buffers of an end side by side, of the progression given, which takes in their energy +// over the stroke +coupler_physics::spring_curve buffer_curve(buffer_category Category, double Progression); +std::optional buffer_category_of(char Name); +// the buffers of an end without the category given: of category A, those of a coach of its own category (EN 15551, +// 30 kJ a buffer either way) +buffer_category default_buffers(vehicle_kind Kind); +// the energy the two buffers of an end take in over their stroke, of the category given or the default of the kind [J] +double buffer_capacity(end_definition const &Definition, vehicle_kind Kind); + +// vehicles pressed onto each other past the stop of their buffers and the crush of their ends by more than this, more +// than a hit could have taken them in a step, are inside each other: a scenery put them down overlapping. no hit the +// crush could tell anything of, the legacy collision handles them [m] +inline constexpr double inside_margin{0.5}; + +// ---- the energy of a hit, for the crush + +// the energy budget of the crush in a contact of two ends. what a hit brings to the stop of the buffers is the kinetic +// energy of the relative motion of the pair there, and what its buffers took in on the way (the springs of the .fiz, +// which may take less than the buffers of EN 15551 would). the buffers of EN 15551 of both ends take in their +// capacity of it first, the crush may take only the rest: +// budget = 1/2 mu v^2 - max(0, capacity - absorbed) +// over the steps of a crush the crush done already is in neither term, so the crush of the whole hit never takes more +// than the hit brought past the buffers. the train behind the pair pushing it on through the crush brings in more: +// it's in the velocity the pair closes in with in the next step. the buffers take in in the stroke under way: the +// buffers pressed and the pair closing in. springing back they keep what they still hold, so a train pushing at a +// stand never builds up what it feeds into their damping. the buffers pressed all the way from the start of the +// contact took in nothing: vehicles put down inside each other, or knocked onto each other by a hit elsewhere, bring +// in only the kinetic energy they close in with. nor do the buffers of vehicles found inside each other in the +// contact (inside_margin) take in anything until they part: their springs pressed past the stop and back throw the +// pair about, which is no hit +class contact_energy { +public: + // the step of the pair: whether its buffers press, and all the way; the closing velocity [m/s] and the force + // pressing the buffers [N] at the start of the step; how far they're pressed in [m]; the length of the step [s] + void update(bool Pressed, bool Solid, double Closing, double Force, double Compression, double Dt); + // the vehicles of the pair are inside each other: what the buffers took in is gone, and they take in nothing more + // until the contact is over + void inside(); + // the crush of the hit took the energy [J] + void crushed(double Work); + // the energy the crush may take now, closing in at the velocity [m/s] with the reduced mass [kg], the buffers of + // both ends taking in the capacity [J]; zero or less, the hit stays elastic + double budget(double Mass, double Closing, double Capacity) const; + // what the buffers took in in the stroke under way [J], and the crush in the contact + double absorbed() const { return m_absorbed; } + double crush_work() const { return m_crushed; } + void reset(); + +private: + double m_absorbed{0.0}; + double m_crushed{0.0}; + bool m_inside{false}; +}; + +// ---- the hit past the buffers + +// an end of the pair, as the hit sees it +struct end_state { + crush_curve curve; + double crush{0.0}; // the depth it's crushed to already [m] +}; + +struct hit_input { + double velocity{0.0}; // the pair closes in on the stop at [m/s] + double mass1{0.0}; // [kg] + double mass2{0.0}; + double restitution{0.2}; // coefficient of restitution of the elastic rest of the hit + double stiffness{1.0e8}; // of the steel parts of both ends in series, past the springs [N/m] + double springs{0.0}; // the force the springs of the pair carry at the stop over the step [N] + double dt{0.01}; // the length of the step [s] + // the closing velocity the pair started the step with, before the forces of the step [m/s]; without it (0), the + // velocity with what the springs took off it over the step + double start_velocity{0.0}; + // the energy the crush may take at most [J] (contact_energy::budget()); none left, the hit stays elastic, and the + // crush stops once it took it, the rest springs back as the buffers would have taken it + double budget{std::numeric_limits::infinity()}; +}; + +struct hit_result { + bool crushing{false}; // false: the hit stays elastic, it's the legacy exchange of momentum + double impulse{0.0}; // the hit adds to the forces of the step, pushing the vehicles apart [N s] + double velocity{0.0}; // the closing velocity after the step [m/s], negative as they part + double force{0.0}; // the peak force between the ends, with the springs [N] + double duration{0.0}; // how long that force acted over the step [s] + double crush1{0.0}; // added to the end of the first vehicle [m] + double crush2{0.0}; // of the second one + double work{0.0}; // the crush took [J] + bool spent{false}; // the crush stopped at the budget +}; + +// the hit of the step: the steel takes the hit elastically up to the force the weaker end gives at, past that the end +// crushes at that force until the pair closes in no faster than the steel takes back. the motion over the step is +// integrated in short slices, with the springs slowing the pair as well, so the crush doesn't depend on the step +hit_result hit(end_state const &First, end_state const &Second, hit_input const &Input); + +// a crush of an end deeper than this is a damage worth the log [m] +inline constexpr double crush_mark{0.05}; +// the draw gear sits behind the headstock: crushed this deep, the coupling of the end is torn off [m] +inline constexpr double draw_gear_crush{0.15}; + +// ---- override + +// the crush of the contact of both ends past which the lighter (or the higher) vehicle climbs onto the other one, +// and past which both leave the rails [m] +inline constexpr double override_crush{0.35}; +inline constexpr double override_both{0.6}; +// the masses differ enough for the lighter one to climb +inline constexpr double override_mass_ratio{1.3}; +// the buffers differ in height enough for the higher one to climb: the vertical offset of the design collision of +// EN 15227 [m] +inline constexpr double override_height{0.04}; + +struct override_input { + double crush1{0.0}; // of the end of the first vehicle [m] + double crush2{0.0}; + double mass1{0.0}; // [kg] + double mass2{0.0}; + double height1{1.0}; // of its buffers [m] + double height2{1.0}; + bool anticlimbers{false}; // both ends have them, interlocked + double zone1{0.0}; // the crush zone of the end with the anticlimber, its densify [m] + double zone2{0.0}; +}; +struct override_result { + bool first{false}; // the first vehicle left the rails + bool second{false}; +}; +override_result override_of(override_input const &Input); + +// ---- pushed off the track + +// the angle of the force at the end of a vehicle to it on a straight track: the play of the wheelsets and of the +// bogies, the buffer heads off the middle [rad] +inline constexpr double straight_angle{0.006}; +// the crushed end no longer keeps the ends in line: the angle grows by this share of the crush to the half length +inline constexpr double crush_angle{0.1}; +// the height the force acts at off the height it's carried at, the buffers of the pair not at the same height [m] +inline constexpr double eccentricity{0.10}; +// the distance the wheels have to roll with Y / Q over the limit for the flange to climb the rail: the window of the +// criteria of derailment [m] +inline constexpr double climb_distance{derailment::window}; +// the time the push has to hold the leading wheels off the rail, without any load on them, to lift them over the +// rail [s] +inline constexpr double lift_time{0.05}; + +struct pushed_vehicle { + double mass{0.0}; // with the load, without the rotating masses [kg] + int axles{4}; + double length{0.0}; // over the buffers [m] + double pivots{0.0}; // the distance of the bogie pivots, of the axles without bogies [m] + double axle_base{0.0}; // the wheelbase of a bogie, of the vehicle without bogies [m] +}; +struct pushed_end { + double force{0.0}; // pressing the end in [N] + double other_length{0.0}; // of the vehicle at that end [m] + double crush{0.0}; // of the end [m] +}; +// the forces of the leading wheel at the end pressed in by the force, in a curve of the radius [m] (0 straight): its +// lateral force, and its vertical one, none or less when the push lifts it off the rail +struct pushed_wheel { + double y{0.0}; // [N] + double q{0.0}; // [N] + double ratio() const; + bool lifted() const { return q <= 0.0 && y > 0.0; } +}; +pushed_wheel pushed_forces(pushed_vehicle const &Vehicle, pushed_end const &End, double Radius); +// Y / Q of that wheel +double pushed_ratio(pushed_vehicle const &Vehicle, pushed_end const &End, double Radius); + +// the push off the track step by step: how far the wheels rolled with Y / Q over the limit without a break, and how +// long the push held the leading wheels lifted off the rail +class pushed_monitor { +public: + // true once the flange climbed the rail, given whether Y / Q held over the limit in the step and the distance the + // wheels rolled while it held [m], and whether the push lifted the wheels and for how long in the step [s] + bool update(bool Climbs, double Distance, bool Lifted, double Duration); + void reset(); + double distance() const { return m_climbing.distance(); } + double time() const { return m_lifted; } + +private: + derailment::stretch m_climbing; + double m_lifted{0.0}; +}; + +} // namespace collision diff --git a/McZapkie/couplerphysics.cpp b/McZapkie/couplerphysics.cpp index f6a226b55..31afd26fe 100644 --- a/McZapkie/couplerphysics.cpp +++ b/McZapkie/couplerphysics.cpp @@ -235,7 +235,7 @@ pair_result update_pair(end_parameters const &First, end_parameters const &Secon else { State.draw_gear.reset(); } - auto const pushed{press(buffers_of(First, Second, Input.adapter), State.buffers, -Input.gap, -Input.gap_rate)}; + auto const pushed{press(buffers_of(First, Second, Input.adapter), State.buffers, -Input.gap - std::max(Input.crush, 0.0), -Input.gap_rate)}; result.tension = pulled.force; result.compression = pushed.force; diff --git a/McZapkie/couplerphysics.h b/McZapkie/couplerphysics.h index 47789aba2..8d7f9b06e 100644 --- a/McZapkie/couplerphysics.h +++ b/McZapkie/couplerphysics.h @@ -112,6 +112,7 @@ struct pair_input { bool coupled{false}; bool adapter{false}; // an adapter on either end: the buffers don't meet, the coupler takes the push alone bool damage{false}; // the link can stretch and break (crash damage on) + double crush{0.0}; // the ends of both crushed for good (collision.h), the buffers meet that much closer [m] }; struct pair_result { diff --git a/McZapkie/derailment.cpp b/McZapkie/derailment.cpp new file mode 100644 index 000000000..e9cfa452e --- /dev/null +++ b/McZapkie/derailment.cpp @@ -0,0 +1,285 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "derailment.h" + +#include +#include +#include + +namespace derailment { + +namespace { + +// a curve with a radius under this is taken for a straight track [m] +constexpr double straight{1e-3}; + +bool curved(double const Radius) { + return std::abs(Radius) > straight; +} + +// the height the lateral force on the body acts at, with the lean of the body on its suspension [m] +double leaning_height(double const CentreOfGravity, suspension const &Suspension) { + return CentreOfGravity + Suspension.flexibility * std::max(0.0, CentreOfGravity - Suspension.roll_centre); +} + +bool has(int const Flags, int const Flag) { + return (Flags & Flag) != 0; +} + +// the acceleration [m/s2] of what moves with the track sideways, besides the curve: the sway of the body and the +// short waves of an uneven track +double dynamic_acceleration(track_state const &Track, double const Velocity) { + return body_vibration(Velocity) + uneven_share * Velocity * Velocity * std::abs(Track.uneven_curvature); +} + +// the sideways force of the couplings of both ends on the vehicle, positive out of the curve [N]: pushed in, the +// ends go out of the curve, pulled out, they go into it +double coupling_force(vehicle_state const &Vehicle, track_state const &Track) { + auto force{0.0}; + for (auto const &end : Vehicle.ends) { + force += end.compression * std::sin(coupling_angle(Vehicle.length, end.other_length, Track.radius)); + } + return force; +} + +} // namespace + +double contact_spacing(double const Gauge) { + return Gauge + rail_head_width; +} + +double default_centre_of_gravity(double const BodyHeight, vehicle_class const Class) { + auto const body{BodyHeight > 2.0 ? BodyHeight : 4.0}; + return body * (Class == vehicle_class::powered ? 0.38 : 0.35); +} + +double loaded_centre_of_gravity(double const EmptyHeight, double const EmptyMass, double const LoadMass, double const LoadShare, double const Floor, double const BodyHeight) { + if (LoadMass <= 0.0 || EmptyMass + LoadMass <= 0.0) { + return EmptyHeight; + } + auto const body{BodyHeight > 2.0 ? BodyHeight : 4.0}; + // a floor not given (or the older meaning of the keys) is that of a wagon + auto const floor{Floor > 0.3 ? Floor : 1.2}; + auto const load{floor + 0.5 * std::max(0.0, body - floor) * std::clamp(LoadShare, 0.0, 1.0)}; + return (EmptyHeight * EmptyMass + load * LoadMass) / (EmptyMass + LoadMass); +} + +double unbalanced_acceleration(double const Velocity, double const Radius, double const Cant) { + auto const cant{gravity * std::sin(std::abs(Cant))}; + if (false == curved(Radius)) { + return -cant; + } + return Velocity * Velocity / std::abs(Radius) - cant; +} + +double line_curvature(track_state const &Track) { + auto const buckle{buckle_share * Track.buckle_curvature}; + if (false == curved(Track.radius)) { + return std::abs(buckle); + } + return 1.0 / std::abs(Track.radius) + buckle; +} + +double line_acceleration(track_state const &Track, double const Velocity) { + if (Track.buckle_curvature == 0.0) { + return unbalanced_acceleration(Velocity, Track.radius, Track.cant); + } + // bent against the curve, out of the bend is into the curve, where the cant leans the vehicle too + return Velocity * Velocity * line_curvature(Track) - gravity * std::sin(std::abs(Track.cant)); +} + +double unloading_ratio(double const Acceleration, double const CentreOfGravity, double const ContactSpacing, suspension const &Suspension) { + return 2.0 / ContactSpacing * std::abs(Acceleration) / gravity * leaning_height(CentreOfGravity, Suspension); +} + +double overturning_acceleration(double const CentreOfGravity, double const ContactSpacing, suspension const &Suspension) { + return gravity * ContactSpacing / (2.0 * leaning_height(CentreOfGravity, Suspension)); +} + +double body_vibration(double const Velocity) { + return vibration * std::min(1.0, std::abs(Velocity) / (100.0 / 3.6)); +} + +double overturning_speed(double const Radius, double const Cant, double const CentreOfGravity, double const Gauge) { + if (false == curved(Radius)) { + return 0.0; + } + vehicle_state vehicle; + vehicle.mass = 1.0; + vehicle.centre_of_gravity = CentreOfGravity; + track_state track; + track.radius = Radius; + track.cant = Cant; + track.gauge = Gauge; + auto const spacing{contact_spacing(Gauge)}; + // the unloading grows with the speed: halve the range until the speed of D = 1 is found + auto low{0.0}; + auto high{200.0}; + for (int iteration = 0; iteration < 60; ++iteration) { + auto const middle{0.5 * (low + high)}; + auto const acceleration{body_acceleration(vehicle, track, middle)}; + // below the balancing speed the cant leans the vehicle the other way + auto const outwards{unbalanced_acceleration(middle, Radius, Cant) > 0.0}; + if (outwards && unloading_ratio(acceleration, CentreOfGravity, spacing) >= 1.0) { + high = middle; + } + else { + low = middle; + } + } + return high; +} + +double nadal_limit(double const FlangeAngle, double const Friction) { + auto const slope{std::tan(FlangeAngle)}; + return (slope - Friction) / (1.0 + Friction * slope); +} + +track_condition condition_of(track_state const &Track) { + track_condition condition; + // the flags make the ride rougher: the sway of the vehicles and the short waves of the track grow, the curve and + // the cant stay what they are. sceneries set them for the jolts of a worn track (damage 31 on all of line 107), + // not for broken rails. a loose rail sways the vehicles 1.4 times as much, as the legacy criterion had it + condition.lateral = 1.0 + 0.4 * has(Track.damage, track_damage::freerail) + 0.5 * has(Track.damage, track_damage::railbend) + 0.1 * has(Track.damage, track_damage::railwear) + + 0.1 * has(Track.damage, track_damage::thinrail); + // the twist of the track lifts a wheel: 1 % of its load for each mm of cross level, up to the 0.6 the twist test + // of EN 14363 lets the load drop by + condition.unloading = std::min(0.6, 0.01 * std::max(0.0, Track.uneven_cross)); + return condition; +} + +double coupling_angle(double const Length, double const OtherLength, double const Radius) { + if (false == curved(Radius) || OtherLength <= 0.0) { + return 0.0; + } + return (Length + OtherLength) / (4.0 * std::abs(Radius)); +} + +wheel_forces flange_forces(vehicle_state const &Vehicle, track_state const &Track, double const Velocity) { + wheel_forces result; + if (Vehicle.mass <= 0.0) { + return result; + } + auto const axles{static_cast(std::max(Vehicle.axles, 1))}; + auto const condition{condition_of(Track)}; + auto const spacing{contact_spacing(Track.gauge)}; + auto const height{leaning_height(Vehicle.centre_of_gravity, suspension{})}; + auto const staticload{Vehicle.mass * gravity / (2.0 * axles)}; + + auto const inertia{Vehicle.mass * line_acceleration(Track, Velocity)}; + auto const couplings{coupling_force(Vehicle, Track)}; + auto const quasistatic{inertia + couplings}; + // the sway and the uneven track push the worst way: towards the rail the vehicle already leans on + auto const direction{quasistatic >= 0.0 ? 1.0 : -1.0}; + auto const dynamic{Vehicle.mass * dynamic_acceleration(Track, Velocity) * condition.lateral}; + result.lateral = direction * (std::abs(quasistatic) + dynamic); + + // the leading axle meets the rail at an angle in a curve, the creep force of its inner wheel at most the friction + auto guiding{0.0}; + if (auto const curvature{std::abs(line_curvature(Track))}; curvature > 0.0) { + auto const attack{0.5 * Vehicle.axle_base * curvature}; + guiding = tread_friction * staticload * std::min(1.0, attack / saturated_attack); + } + result.y = std::abs(result.lateral) / axles + guiding; + + // the lateral forces at their heights move the load onto the wheels they push towards + auto const moment{direction * (inertia * height + couplings * buffer_height) + dynamic * height}; + auto const shift{moment / (spacing * axles)}; + result.q = std::max(0.0, (staticload + shift) * (1.0 - condition.unloading)); + return result; +} + +double body_acceleration(vehicle_state const &Vehicle, track_state const &Track, double const Velocity) { + if (Vehicle.mass <= 0.0) { + return 0.0; + } + auto const height{leaning_height(Vehicle.centre_of_gravity, suspension{})}; + // the couplings pull at the height of the buffers: as much of a lean as their moment gives + auto const moment{Vehicle.mass * line_acceleration(Track, Velocity) * height + coupling_force(Vehicle, Track) * buffer_height}; + return std::abs(moment) / (Vehicle.mass * height) + dynamic_acceleration(Track, Velocity) * condition_of(Track).lateral; +} + +bool stretch::update(bool const Holds, double const Distance, double const Window) { + if (false == Holds) { + m_distance = 0.0; + return false; + } + m_distance += std::abs(Distance); + return m_distance >= Window; +} + +verdict monitor::update(vehicle_state const &Vehicle, track_state const &Track, double const Velocity, double const Distance) { + verdict result; + result.acceleration = body_acceleration(Vehicle, Track, Velocity); + result.unloading = unloading_ratio(result.acceleration, Vehicle.centre_of_gravity, contact_spacing(Track.gauge)); + result.flange_ratio = flange_forces(Vehicle, Track, Velocity).ratio(); + auto const overturns{m_overturning.update(result.unloading >= 1.0, Distance)}; + auto const climbs{m_climbing.update(result.flange_ratio >= climbing_limit, Distance)}; + if (overturns) { + result.result = outcome::overturned; + } + else if (climbs) { + result.result = outcome::off_rails; + } + return result; +} + +void monitor::reset() { + m_overturning.reset(); + m_climbing.reset(); +} + +double sliding_friction(outcome const Outcome) { + switch (Outcome) { + case outcome::off_rails: + return off_rails_friction; + case outcome::overturned: + return overturned_friction; + default: + return 0.0; + } +} + +std::optional climbing_speed(vehicle_state const &Vehicle, track_state const &Track) { + auto const climbs = [&](double const Velocity) { return flange_forces(Vehicle, Track, Velocity).ratio() >= climbing_limit; }; + // from the speed the cant balances, where the vehicle starts to lean on the outer rail + auto const balancing{curved(Track.radius) ? std::sqrt(gravity * std::abs(Track.radius) * std::sin(std::abs(Track.cant))) : 0.0}; + if (climbs(balancing)) { + return balancing; + } + // in steps of 1 m/s up to the first speed it climbs at, which needn't hold above it, then halving the step + constexpr double fastest{200.0}; + auto const steps{static_cast(std::ceil(fastest - balancing))}; + for (auto step = 0; step < steps; ++step) { + auto low{balancing + step}; + auto high{std::min(low + 1.0, fastest)}; + if (false == climbs(high)) { + continue; + } + for (int iteration = 0; iteration < 30; ++iteration) { + auto const middle{0.5 * (low + high)}; + (climbs(middle) ? high : low) = middle; + } + return high; + } + return std::nullopt; +} + +std::string report(verdict const &Verdict, vehicle_state const &Vehicle, track_state const &Track, double const Velocity, std::string_view const TrackName) { + auto const cant{1000.0 * contact_spacing(Track.gauge) * std::sin(std::abs(Track.cant))}; + return std::format("{} at {:.0f} km/h on track {}, curve radius {:.0f} m, cant {:.0f} mm: lateral acceleration {:.2f} m/s2, wheel unloading {:.2f}, Y/Q {:.2f}" + " (mass {:.1f} t, centre of gravity {:.2f} m, couplings pushing {:.0f} / {:.0f} kN, track damage {}, cross level {:.0f} mm)", + Verdict.result == outcome::overturned ? "overturned" : "derailed, the flange climbed the rail", std::abs(Velocity) * 3.6, TrackName.empty() ? "(none)" : TrackName, + std::abs(Track.radius), cant, Verdict.acceleration, Verdict.unloading, Verdict.flange_ratio, Vehicle.mass / 1000.0, Vehicle.centre_of_gravity, + Vehicle.ends[0].compression / 1000.0, Vehicle.ends[1].compression / 1000.0, Track.damage, Track.uneven_cross); +} + +} // namespace derailment diff --git a/McZapkie/derailment.h b/McZapkie/derailment.h new file mode 100644 index 000000000..50a3d84cb --- /dev/null +++ b/McZapkie/derailment.h @@ -0,0 +1,229 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include +#include + +// the criteria of a vehicle leaving the rails, as plain functions of what the vehicle and the track under it are +// like, so the collisions and the buckled track can use them as well as the speed in a curve does +// (physics.derailment new in eu07.ini, see TMoverParameters::check_derailment()). two ways off the rails: +// +// overturning: the lateral acceleration the cant doesn't balance, a = v^2 / R - g * sin(cant), takes the load off the +// inner wheels; the unloading ratio D = dQ / Q = 2 / s * a / g * (h + s_flex * (h - h_c)) reaches 1 when they lift. +// s the distance between the contact points of the wheels, h the height of the centre of gravity, s_flex and h_c the +// flexibility coefficient and the roll centre height of the suspension, which lets the body lean out of the curve +// (the reference values of the kinematic gauge, EN 15273-2 / UIC 505-1). the body sways on top of that: a lateral +// vibration of 0.05 g at speed (as Kunieda's overturning formula of the Japanese railways adds one) and what the +// uneven track adds +// flange climbing: the ratio of the lateral to the vertical force of the flanging wheel, Y / Q, over Nadal's limit +// (tan d - mu) / (1 + mu * tan d). Y from the force the cant doesn't balance and the sideways part of the forces of +// the couplings in the curve, shared by the axles, plus the guiding force of the leading axle under its angle of +// attack; Q the static wheel load, with what the lateral forces at their heights move onto the wheel +// +// either has to hold over a stretch of track, not at an instant: EN 14363 takes the Y / Q of a 2 m sliding window, so +// a peak shorter than that, or the length of a simulation step, doesn't derail the vehicle +namespace derailment { + +inline constexpr double gravity{9.81}; // [m/s2] + +// the distance between the contact points of the wheels of a wheelset [m]: the gauge and the width of the rail head +// (1.5 m on the standard gauge) +inline constexpr double rail_head_width{0.065}; +double contact_spacing(double Gauge); + +// the suspension of the body, the reference vehicle of the kinematic gauge (EN 15273-2, UIC 505-1) +struct suspension { + double flexibility{0.4}; // roll of the body to the angle of the force on it, s0 + double roll_centre{0.5}; // height of the roll centre above the rail [m], h_c0 +}; + +// ---- the centre of gravity + +// what the vehicle is, for its centre of gravity when its definition gives none +enum class vehicle_class { + powered, // a locomotive, a motor car of a unit + unpowered // a coach, a wagon +}; +// height of the centre of gravity of the empty vehicle above the rail [m], from the height of the body: 0.38 of it for +// a locomotive or a motor car, 0.35 for a coach or a wagon (EU07: 1.65 m, the 430W coal wagon: 1.13 m, a 4 m high +// coach: 1.4 m). a body height up to 2 m in the definition is the height of the floor, the older meaning of the key: +// a 4 m high body is taken then +double default_centre_of_gravity(double BodyHeight, vehicle_class Class); +// the load raises it: the load lies on the floor, its centre half way up to the share of the height of the body +// above the floor it fills (the share of the load it can take), and the heights weigh with the masses [m] +double loaded_centre_of_gravity(double EmptyHeight, double EmptyMass, double LoadMass, double LoadShare, double Floor, double BodyHeight); + +// ---- overturning + +// the lateral acceleration [m/s2] the cant doesn't balance, positive out of the curve: v^2 / R - g sin(cant). the +// sign of the radius and of the cant is left out: the cant lifts the outer rail of a curve. on a straight piece of a +// transition the cant leans the vehicle into the curve to come +double unbalanced_acceleration(double Velocity, double Radius, double Cant); +// D = dQ / Q of the wheels on the inner side, at the lateral acceleration [m/s2] +double unloading_ratio(double Acceleration, double CentreOfGravity, double ContactSpacing, suspension const &Suspension = {}); +// the lateral acceleration [m/s2] which lifts the inner wheels off the rail (D = 1) +double overturning_acceleration(double CentreOfGravity, double ContactSpacing, suspension const &Suspension = {}); +// lateral vibration of the body on a good track [m/s2], growing with the speed up to 100 km/h +inline constexpr double vibration{0.05 * gravity}; +double body_vibration(double Velocity); +// the speed [m/s] at which the vehicle overturns in a curve of the radius [m] and the cant [rad], on a good track +double overturning_speed(double Radius, double Cant, double CentreOfGravity, double Gauge); + +// ---- flange climbing + +// Nadal's limit of Y / Q for the flange angle [rad] and the friction of the flange on the rail +double nadal_limit(double FlangeAngle, double Friction); +// 70 degrees, the flange of the S1002 and the Polish 1:40 profiles +inline constexpr double flange_angle{1.2217304763960306}; +// 1.2: Nadal with 70 degrees and a friction of 0.36 on a dry rail; the limit of EN 14363 for the flange climbing test +// in a tight curve on a twisted track. its 0.8 for the tests on the line is that with a margin for the acceptance of +// a vehicle, and a simulator wants the derailment itself +inline constexpr double climbing_limit{1.2}; +// friction of the tread of the inner wheel of the leading axle, the guiding force it gives under the angle of attack +inline constexpr double tread_friction{0.3}; +// angle of attack [rad] at which the creep force of the tread saturates +inline constexpr double saturated_attack{0.005}; +// height of the buffers and the couplings above the rail [m] (UIC: 940 to 1065 mm) +inline constexpr double buffer_height{1.0}; + +// one end of the vehicle in a train +struct end_force { + double compression{0.0}; // force of the coupling along the vehicle, pushing in [N]; negative pulls out + double other_length{0.0}; // length of the vehicle at that end [m], 0 without one +}; + +// the vehicle as the flange climbing sees it +struct vehicle_state { + double mass{0.0}; // with the load, without the rotating masses [kg] + int axles{4}; + double length{0.0}; // over the buffers [m] + double axle_base{0.0}; // the wheelbase of a bogie, or of the vehicle without bogies [m] + double centre_of_gravity{1.5}; // [m] + std::array ends{}; +}; + +// the dtrack_* flags of the track (MOVER.h) the criteria look at +namespace track_damage { +inline constexpr int railwear{2}; +inline constexpr int freerail{4}; +inline constexpr int thinrail{8}; +inline constexpr int railbend{16}; +} // namespace track_damage + +// the track under the vehicle +struct track_state { + double radius{0.0}; // [m], 0 on a straight one + double cant{0.0}; // [rad] + double gauge{1.435}; // [m] + double uneven_curvature{0.0}; // the lateral curvature of the unevenness under the vehicle [1/m] + double uneven_cross{0.0}; // the cross level unevenness of the track [mm] + // the curvature a buckle of the track adds under the vehicle [1/m], see world/TrackBuckle.h: positive bending with + // the curve, on a straight track either way + double buckle_curvature{0.0}; + int damage{0}; // dtrack_* flags +}; + +// what the state of the track does to the lateral forces and the wheel loads +struct track_condition { + double lateral{1.0}; // multiplier of the sway of the vehicle and of the short waves of an uneven track + double unloading{0.0}; // share of the wheel load the twist of the track (its cross level) takes off +}; +track_condition condition_of(track_state const &Track); +// share of the vehicle that follows the short waves of an uneven track: the wheelsets and the bogies, the body not +inline constexpr double uneven_share{0.3}; +// and the long wave of a buckle, which the body follows whole, as it does the curve +inline constexpr double buckle_share{1.0}; +// the curvature of the line under the vehicle [1/m], positive towards the centre of the curve: the curve, and a +// buckle on it. negative where a buckle bends the line the other way more than the curve does +double line_curvature(track_state const &Track); +// the lateral acceleration [m/s2] the cant doesn't balance on that line, positive out of the curve: +// unbalanced_acceleration() with a buckle +double line_acceleration(track_state const &Track, double Velocity); + +// the angle [rad] between the vehicle and the line of the force of the coupling at the end, in a curve: half the +// angle between the two vehicles, whose middles are half their lengths apart along the curve +double coupling_angle(double Length, double OtherLength, double Radius); + +struct wheel_forces { + double lateral{0.0}; // the lateral force on the vehicle, positive out of the curve [N] + double y{0.0}; // lateral force of the flanging wheel [N] + double q{0.0}; // its vertical force [N] + // a wheel lifted off the rail with a force on it is past any limit; no force at all (a vehicle without a mass) none + double ratio() const { return q > 0.0 ? y / q : (y > 0.0 ? 1e9 : 0.0); } +}; +// the forces of the flanging wheel of the leading axle, at the speed [m/s] +wheel_forces flange_forces(vehicle_state const &Vehicle, track_state const &Track, double Velocity); +// the lateral acceleration of the body the overturning goes by [m/s2]: what the cant doesn't balance, the sideways +// pull of the couplings, the vibration and the uneven track, by the state of the track +double body_acceleration(vehicle_state const &Vehicle, track_state const &Track, double Velocity); + +// ---- the stretch a condition holds over + +// the distance [m] a condition has to hold over: the window of EN 14363 +inline constexpr double window{2.0}; + +// the distance travelled while the condition held, without a break. the same distance with any step: a step the +// condition holds at counts with its whole length +class stretch { +public: + // true once the condition held over the window, given the distance of the step [m] + bool update(bool Holds, double Distance, double Window = window); + double distance() const { return m_distance; } + void reset() { m_distance = 0.0; } + +private: + double m_distance{0.0}; +}; + +enum class outcome { + none, + off_rails, // the flange climbed the rail: the vehicle runs off the rails, upright + overturned // the vehicle fell over out of the curve +}; + +// what the vehicle came to in a step, with the values the decision went by +struct verdict { + outcome result{outcome::none}; + double unloading{0.0}; // D + double flange_ratio{0.0}; // Y / Q + double acceleration{0.0}; // of the body, [m/s2] +}; + +// both criteria of a vehicle, step by step +class monitor { +public: + // the step travelled the distance [m]; the condition at its end goes for the whole of it + verdict update(vehicle_state const &Vehicle, track_state const &Track, double Velocity, double Distance); + void reset(); + +private: + stretch m_overturning; + stretch m_climbing; +}; + +// the friction of a derailed vehicle sliding along [-]: on its wheels on the sleepers and the ballast, or on its side +inline constexpr double off_rails_friction{0.3}; +inline constexpr double overturned_friction{0.5}; +double sliding_friction(outcome Outcome); + +// the lowest speed [m/s] from the one the cant balances at which the flange of the leading axle climbs the rail (Y / Q +// at the climbing limit); none when it doesn't climb up to 200 m/s: a lone vehicle on a good track mostly overturns +// first, its Y / Q goes to the ratio of the contact spacing to the height of the centre of gravity at speed +std::optional climbing_speed(vehicle_state const &Vehicle, track_state const &Track); + +// what the criteria found, for the log: "overturned at 113 km/h on track t1, curve radius 300 m, cant 0 mm: lateral +// acceleration ..., wheel unloading ..., Y/Q ... (mass ..., centre of gravity ..., couplings pushing ... / ... kN, +// track damage ..., cross level ... mm)" +std::string report(verdict const &Verdict, vehicle_state const &Vehicle, track_state const &Track, double Velocity, std::string_view TrackName); + +} // namespace derailment diff --git a/McZapkie/hamulce.cpp b/McZapkie/hamulce.cpp index b30372e5e..4a2029af5 100644 --- a/McZapkie/hamulce.cpp +++ b/McZapkie/hamulce.cpp @@ -855,25 +855,7 @@ void TESt::CheckState(double const BCP, double & /*dV1*/) if ((BrakeStatus & b_hld) == b_hld) { - - if (VVP + 0.003 + BCP / BVM < CVP) - { - // hamowanie stopniowe - BrakeStatus |= b_on; - } - else - { - if (VVP + BCP / BVM > CVP) - { - // zatrzymanie napelaniania - BrakeStatus &= ~b_on; - } - if (VVP - 0.003 + (BCP - 0.1) / BVM > CVP) - { - // luzowanie - BrakeStatus &= ~(b_on | b_hld); - } - } + CheckStateHeld(BCP, VVP, CVP); } else { @@ -908,6 +890,29 @@ void TESt::CheckState(double const BCP, double & /*dV1*/) } } +// the state of a valve holding: braking on in steps, the filling stopped, or released +void TESt::CheckStateHeld(double const BCP, double const VVP, double const CVP) +{ + if (VVP + 0.003 + BCP / BVM < CVP) + { + // hamowanie stopniowe + BrakeStatus |= b_on; + } + else + { + if (VVP + BCP / BVM > CVP) + { + // zatrzymanie napelaniania + BrakeStatus &= ~b_on; + } + if (VVP - 0.003 + (BCP - 0.1) / BVM > CVP) + { + // luzowanie + BrakeStatus &= ~(b_on | b_hld); + } + } +} + /// /// Returns the dimensionless opening factor of the ZS-filling slide valve /// (control reservoir <-> brake pipe) for the current pre-chamber/auxiliary @@ -1164,33 +1169,7 @@ double TEStEP2::GetPF(double const PP, double const dt, double const Vel) // odluzniacz CheckReleaser(dt); - // sprawdzanie stanu - if ((BrakeStatus & b_hld) == b_hld && BCP > 0.25) - { - if (VVP + 0.003 + BCP / BVM < CVP - 0.12) - BrakeStatus |= b_on; // hamowanie stopniowe; - else if (VVP - 0.003 + BCP / BVM > CVP - 0.12) - BrakeStatus &= ~(b_on | b_hld); // luzowanie; - else if (VVP + BCP / BVM > CVP - 0.12) - BrakeStatus &= ~b_on; // zatrzymanie napelaniania; - } - else if (VVP + 0.10 < CVP - 0.12 && BCP < 0.25) // poczatek hamowania - { - // if ((BrakeStatus & 1) == 0) - //{ - // // ValveRes.CreatePress(0.5*VVP); //110115 - konsultacje warszawa1 - // // SoundFlag:=SoundFlag or sf_Acc; - // // ValveRes.Act; - //} - BrakeStatus |= b_on | b_hld; - } - else if (VVP + BCP / BVM < CVP - 0.12 && BCP > 0.25) // zatrzymanie luzowanie - BrakeStatus |= b_hld; - - if ((BrakeStatus & b_hld) == 0) - { - SoundFlag |= sf_CylU; - } + UpdateStatusEP2(BCP, VVP, CVP); // przeplyw ZS <-> PG if (BVP < CVP - 0.2 || BrakeStatus != b_off || BCP > 0.25) @@ -1258,6 +1237,38 @@ double TEStEP2::GetPF(double const PP, double const dt, double const Vel) return result; } +// the state of the valve: braking in steps, holding or releasing, the start of braking +void TEStEP2::UpdateStatusEP2(double const BCP, double const VVP, double const CVP) +{ + // sprawdzanie stanu + if ((BrakeStatus & b_hld) == b_hld && BCP > 0.25) + { + if (VVP + 0.003 + BCP / BVM < CVP - 0.12) + BrakeStatus |= b_on; // hamowanie stopniowe; + else if (VVP - 0.003 + BCP / BVM > CVP - 0.12) + BrakeStatus &= ~(b_on | b_hld); // luzowanie; + else if (VVP + BCP / BVM > CVP - 0.12) + BrakeStatus &= ~b_on; // zatrzymanie napelaniania; + } + else if (VVP + 0.10 < CVP - 0.12 && BCP < 0.25) // poczatek hamowania + { + // if ((BrakeStatus & 1) == 0) + //{ + // // ValveRes.CreatePress(0.5*VVP); //110115 - konsultacje warszawa1 + // // SoundFlag:=SoundFlag or sf_Acc; + // // ValveRes.Act; + //} + BrakeStatus |= b_on | b_hld; + } + else if (VVP + BCP / BVM < CVP - 0.12 && BCP > 0.25) // zatrzymanie luzowanie + BrakeStatus |= b_hld; + + if ((BrakeStatus & b_hld) == 0) + { + SoundFlag |= sf_CylU; + } +} + /// /// Recomputes the load-weighing coefficient LoadC for the current vehicle /// mass (linear between TareBP/MaxBP for TareM..LoadM, capped at 1.0). @@ -1672,58 +1683,8 @@ double TLSt::GetPF(double const PP, double const dt, double const Vel) double dV{0.0}; double dV1{0.0}; - // sprawdzanie stanu - // NOTE: partial copypaste from checkstate() of base class - // TODO: clean inheritance for checkstate() and checkreleaser() and reuse these instead of manual copypaste - if ((BrakeStatus & b_hld) == b_hld && BCP > 0.25) - { - if (VVP + 0.003 + BCP / BVM < CVP) - { - // hamowanie stopniowe - BrakeStatus |= b_on; - } - else if (VVP - 0.003 + (BCP - 0.1) / BVM > CVP) - { - // luzowanie - BrakeStatus &= ~(b_on | b_hld); - } - else if (VVP + BCP / BVM > CVP) - { - // zatrzymanie napelaniania - BrakeStatus &= ~b_on; - } - } - else if (VVP + 0.10 < CVP && BCP < 0.25) - { - // poczatek hamowania - if ((BrakeStatus & b_hld) == b_off) - { - SoundFlag |= sf_Acc; - } - BrakeStatus |= b_on | b_hld; - } - else if (VVP + (BCP - 0.1) / BVM < CVP && (CVP - VVP) * BVM > 0.25 && BCP > 0.25) - { - // zatrzymanie luzowanie - BrakeStatus |= b_hld; - } - if ((BrakeStatus & b_hld) == 0) - { - SoundFlag |= sf_CylU; - } - // equivalent of checkreleaser() in the base class? - if (bool is_releasing = BrakeStatus & b_rls || UniversalFlag & TUniversalBrake::ub_Release; is_releasing) - { - if (CVP < 0.0) - { - BrakeStatus &= ~b_rls; - } - else - { // 008 - dV = PF1(CVP, BCP, 0.024) * dt; - CntrlRes->Flow(dV); - } - } + UpdateStatusLSt(BCP, VVP, CVP); + ReleaserLSt(BCP, CVP, dt); // przeplyw ZS <-> PG double temp; @@ -1770,6 +1731,87 @@ double TLSt::GetPF(double const PP, double const dt, double const Vel) // if Vel>55 then temp:=0.72 else // temp:=1;{R} // cisnienie PP + CylinderFlowLSt(BCP, BVP, CVP, dt, Vel); + + ImplsRes->Act(); + ValveRes->Act(); + BrakeCyl->Act(); + BrakeRes->Act(); + CntrlRes->Act(); + // LBP:=ValveRes->P(); + // ValveRes.CreatePress(ImplsRes->P()); + return result; +} + +// the state of the valve: braking in steps, holding or releasing, the start of braking +void TLSt::UpdateStatusLSt(double const BCP, double const VVP, double const CVP) +{ + // sprawdzanie stanu + // NOTE: partial copypaste from checkstate() of base class + // TODO: clean inheritance for checkstate() and checkreleaser() and reuse these instead of manual copypaste + if ((BrakeStatus & b_hld) == b_hld && BCP > 0.25) + { + if (VVP + 0.003 + BCP / BVM < CVP) + { + // hamowanie stopniowe + BrakeStatus |= b_on; + } + else if (VVP - 0.003 + (BCP - 0.1) / BVM > CVP) + { + // luzowanie + BrakeStatus &= ~(b_on | b_hld); + } + else if (VVP + BCP / BVM > CVP) + { + // zatrzymanie napelaniania + BrakeStatus &= ~b_on; + } + } + else if (VVP + 0.10 < CVP && BCP < 0.25) + { + // poczatek hamowania + if ((BrakeStatus & b_hld) == b_off) + { + SoundFlag |= sf_Acc; + } + BrakeStatus |= b_on | b_hld; + } + else if (VVP + (BCP - 0.1) / BVM < CVP && (CVP - VVP) * BVM > 0.25 && BCP > 0.25) + { + // zatrzymanie luzowanie + BrakeStatus |= b_hld; + } + if ((BrakeStatus & b_hld) == 0) + { + SoundFlag |= sf_CylU; + } +} + +// the releaser, or the universal button set to release, letting the control reservoir out into the impulse chamber +void TLSt::ReleaserLSt(double const BCP, double const CVP, double const dt) +{ + double dV; + // equivalent of checkreleaser() in the base class? + if (bool is_releasing = BrakeStatus & b_rls || UniversalFlag & TUniversalBrake::ub_Release; is_releasing) + { + if (CVP < 0.0) + { + BrakeStatus &= ~b_rls; + } + else + { // 008 + dV = PF1(CVP, BCP, 0.024) * dt; + CntrlRes->Flow(dV); + } + } +} + +// the cylinders filled from the auxiliary reservoir or let out to the pressure the relay is set to: by the pilot +// pressure, the anti-slip brake and the rapid setting, at least the local brake's +void TLSt::CylinderFlowLSt(double const BCP, double const BVP, double const CVP, double const dt, double const Vel) +{ + double dV; + double temp; RapidTemp = RapidTemp + (RM * int(Vel > 55 && (BrakeDelayFlag & bdelay_R) == bdelay_R) - RapidTemp) * dt / 2; temp = 1 - RapidTemp; if (EDFlag > 0.2) @@ -1795,15 +1837,6 @@ double TLSt::GetPF(double const PP, double const dt, double const Vel) dV = 0; BrakeRes->Flow(dV); BrakeCyl->Flow(-dV); - - ImplsRes->Act(); - ValveRes->Act(); - BrakeCyl->Act(); - BrakeRes->Act(); - CntrlRes->Act(); - // LBP:=ValveRes->P(); - // ValveRes.CreatePress(ImplsRes->P()); - return result; } /// @@ -1916,33 +1949,7 @@ double TEStED::GetPF(double const PP, double const dt, double const Vel) nastG = BrakeDelayFlag & bdelay_G; - // sprawdzanie stanu - if (BCP < 0.25 && VVP + 0.08 > CVP) - Przys_blok = false; - - // sprawdzanie stanu - if (VVP + 0.002 + BCP / BVM < CVP - 0.05 && Przys_blok) - BrakeStatus |= b_on | b_hld; // hamowanie stopniowe; - else if (VVP - 0.002 + (BCP - 0.1) / BVM > CVP - 0.05) - BrakeStatus &= ~(b_on | b_hld); // luzowanie; - else if (VVP + BCP / BVM > CVP - 0.05) - BrakeStatus &= ~b_on; // zatrzymanie napelaniania; - else if (VVP + (BCP - 0.1) / BVM < CVP - 0.05 && BCP > 0.25) // zatrzymanie luzowania - BrakeStatus |= b_hld; - - // poczatek hamowania - if (VVP + 0.10 < CVP && BCP < 0.25 && !Przys_blok) - { - ValveRes->CreatePress(0.75 * VVP); - SoundFlag |= sf_Acc; - ValveRes->Act(); - Przys_blok = true; - } - - if (BCP > 0.5) - Zamykajacy = true; - else if (VVP - 0.6 < MPP) - Zamykajacy = false; + UpdateStatus(BCP, VVP, CVP, MPP); if ((BrakeStatus & b_rls) == b_rls) { @@ -1963,60 +1970,9 @@ double TEStED::GetPF(double const PP, double const dt, double const Vel) ImplsRes->Flow(-dv); BrakeRes->Flow(dv); - // przeplyw testowy miedzypojemnosci - if (MPP < CVP - 0.3) - temp = Nozzles[4]; - else if (BCP < 0.5) - if (Zamykajacy) - temp = Nozzles[8]; // 1.25; - else - temp = Nozzles[7]; - else - temp = 0; - dv = PF(MPP, VVP, temp); + Miedzypoj->Flow(IntermediateFlow(BCP, VVP, CVP, MPP, BVP, nastG) * dt * 0.15); - if (MPP < CVP - 0.17) - temp = 0; - else if (MPP > CVP - 0.08) - temp = Nozzles[5]; - else - temp = Nozzles[6]; - dv = dv + PF(MPP, CVP, temp); - - if (MPP - 0.05 > BVP) - dv = dv + PF(MPP - 0.05, BVP, Nozzles[10] * nastG + (1 - nastG) * Nozzles[9]); - if (MPP > VVP) - dv = dv + PF(MPP, VVP, 0.02); - Miedzypoj->Flow(dv * dt * 0.15); - - RapidTemp = RapidTemp + (RM * int(Vel > RV && (BrakeDelayFlag & bdelay_R) == bdelay_R) - RapidTemp) * dt / 2; - temp = std::max(1 - RapidTemp, 0.001); - // if EDFlag then temp:=1000; - // temp:=temp/(1-); - - // powtarzacz — podwojny zawor zwrotny - temp = std::max(LoadC * BCP / temp * std::clamp(1 - EDFlag, 0., 1.), LBP); - - if ((UniversalFlag & TUniversalBrake::ub_AntiSlipBrake) > 0) - temp = std::max(temp, ASBP); - - double speed = 1; - if (ASBP < 0.1 && (BrakeStatus & b_asb_unbrake) == b_asb_unbrake) - { - temp = 0; - speed = 3; - } - - if (BrakeCyl->P() > temp) - dv = -PFVd(BrakeCyl->P(), 0, 0.05 * SizeBC * speed, temp) * dt; - else if (BrakeCyl->P() < temp && (BrakeStatus & b_asb) == 0) - dv = PFVa(BVP, BrakeCyl->P(), 0.05 * SizeBC, temp) * dt; - else - dv = 0; - - BrakeCyl->Flow(dv); - if (dv > 0) - BrakeRes->Flow(-dv); + CylinderFlow(BCP, BVP, dt, Vel); // przeplyw ZS <-> PG if (MPP < CVP - 0.17) @@ -2051,6 +2007,107 @@ double TEStED::GetPF(double const PP, double const dt, double const Vel) return dv - dV1; } +// the state of the valve: braking in steps, holding or releasing, the accelerator at the start of braking, and the +// closing valve +void TEStED::UpdateStatus(double const BCP, double const VVP, double const CVP, double const MPP) +{ + // sprawdzanie stanu + if (BCP < 0.25 && VVP + 0.08 > CVP) + Przys_blok = false; + + // sprawdzanie stanu + if (VVP + 0.002 + BCP / BVM < CVP - 0.05 && Przys_blok) + BrakeStatus |= b_on | b_hld; // hamowanie stopniowe; + else if (VVP - 0.002 + (BCP - 0.1) / BVM > CVP - 0.05) + BrakeStatus &= ~(b_on | b_hld); // luzowanie; + else if (VVP + BCP / BVM > CVP - 0.05) + BrakeStatus &= ~b_on; // zatrzymanie napelaniania; + else if (VVP + (BCP - 0.1) / BVM < CVP - 0.05 && BCP > 0.25) // zatrzymanie luzowania + BrakeStatus |= b_hld; + + // poczatek hamowania + if (VVP + 0.10 < CVP && BCP < 0.25 && !Przys_blok) + { + ValveRes->CreatePress(0.75 * VVP); + SoundFlag |= sf_Acc; + ValveRes->Act(); + Przys_blok = true; + } + + if (BCP > 0.5) + Zamykajacy = true; + else if (VVP - 0.6 < MPP) + Zamykajacy = false; +} + +// the flow into the intermediate reservoir from the pipe and the control reservoir, less the flow filling the auxiliary one +double TEStED::IntermediateFlow(double const BCP, double const VVP, double const CVP, double const MPP, double const BVP, double const nastG) const +{ + double dv; + double temp; + // przeplyw testowy miedzypojemnosci + if (MPP < CVP - 0.3) + temp = Nozzles[4]; + else if (BCP < 0.5) + if (Zamykajacy) + temp = Nozzles[8]; // 1.25; + else + temp = Nozzles[7]; + else + temp = 0; + dv = PF(MPP, VVP, temp); + + if (MPP < CVP - 0.17) + temp = 0; + else if (MPP > CVP - 0.08) + temp = Nozzles[5]; + else + temp = Nozzles[6]; + dv = dv + PF(MPP, CVP, temp); + + if (MPP - 0.05 > BVP) + dv = dv + PF(MPP - 0.05, BVP, Nozzles[10] * nastG + (1 - nastG) * Nozzles[9]); + if (MPP > VVP) + dv = dv + PF(MPP, VVP, 0.02); + return dv; +} + +// the cylinders filled or let out to the pressure the relay is set to: by the pilot pressure and the load, at least the +// local brake's, the anti-slip brake's, faster at the rapid setting +void TEStED::CylinderFlow(double const BCP, double const BVP, double const dt, double const Vel) +{ + double dv; + double temp; + RapidTemp = RapidTemp + (RM * int(Vel > RV && (BrakeDelayFlag & bdelay_R) == bdelay_R) - RapidTemp) * dt / 2; + temp = std::max(1 - RapidTemp, 0.001); + // if EDFlag then temp:=1000; + // temp:=temp/(1-); + + // powtarzacz — podwojny zawor zwrotny + temp = std::max(LoadC * BCP / temp * std::clamp(1 - EDFlag, 0., 1.), LBP); + + if ((UniversalFlag & TUniversalBrake::ub_AntiSlipBrake) > 0) + temp = std::max(temp, ASBP); + + double speed = 1; + if (ASBP < 0.1 && (BrakeStatus & b_asb_unbrake) == b_asb_unbrake) + { + temp = 0; + speed = 3; + } + + if (BrakeCyl->P() > temp) + dv = -PFVd(BrakeCyl->P(), 0, 0.05 * SizeBC * speed, temp) * dt; + else if (BrakeCyl->P() < temp && (BrakeStatus & b_asb) == 0) + dv = PFVa(BVP, BrakeCyl->P(), 0.05 * SizeBC, temp) * dt; + else + dv = 0; + + BrakeCyl->Flow(dv); + if (dv > 0) + BrakeRes->Flow(-dv); +} + /// /// Initialises the EStED: chains TLSt::Init, sizes Miedzypoj (5 l), pre-charges /// pressures, computes BVM with a 0.05 bar offset on HPP, configures the @@ -2509,25 +2566,7 @@ void TKE::CheckState(double const BCP, double & /*dV1*/) if ((BrakeStatus & b_hld) == b_hld) { - - if (VVP + 0.003 + BCP / BVM < CVP) - { - // hamowanie stopniowe; - BrakeStatus |= b_on; - } - else - { - if (VVP + BCP / BVM > CVP) - { - // zatrzymanie napelaniania; - BrakeStatus &= ~b_on; - } - if (VVP - 0.003 + BCP / BVM > CVP) - { - // luzowanie; - BrakeStatus &= ~(b_on | b_hld); - } - } + CheckStateHeld(BCP, VVP, CVP); } else { @@ -2562,6 +2601,29 @@ void TKE::CheckState(double const BCP, double & /*dV1*/) } } +// the state of a valve holding: braking on in steps, the filling stopped, or released +void TKE::CheckStateHeld(double const BCP, double const VVP, double const CVP) +{ + if (VVP + 0.003 + BCP / BVM < CVP) + { + // hamowanie stopniowe; + BrakeStatus |= b_on; + } + else + { + if (VVP + BCP / BVM > CVP) + { + // zatrzymanie napelaniania; + BrakeStatus &= ~b_on; + } + if (VVP - 0.003 + BCP / BVM > CVP) + { + // luzowanie; + BrakeStatus &= ~(b_on | b_hld); + } + } +} + /// /// Returns the KE ZS-filling slide valve opening factor: closed once /// any pneumatic braking is requested, slightly attenuated when the @@ -2681,6 +2743,36 @@ double TKE::GetPF(double const PP, double const dt, double const Vel) BrakeRes->Flow(dv); ImplsRes->Flow(-dv); + IMP = CylinderFlowKE(IMP, BCP, BVP, Vel, dt); + + // przeplyw ZP <-> rozdzielacz + temp = BVs(IMP); + // if(BrakeStatus and b_hld)=b_off then + if (IMP < 0.25 || VVP + 0.05 > BVP) + dv = PF(BVP, VVP, 0.02 * SizeBR * temp / 1.87) * dt; + else + dv = 0; + BrakeRes->Flow(dv); + dV1 = dV1 + dv * 0.96; + ValveRes->Flow(-0.04 * dv); + // przeplyw PG <-> rozdzielacz + dv = PF(PP, VVP, 0.01) * dt; + ValveRes->Flow(-dv); + + ValveRes->Act(); + BrakeCyl->Act(); + BrakeRes->Act(); + CntrlRes->Act(); + ImplsRes->Act(); + return dv - dV1; +} + +// the cylinders filled from the auxiliary reservoir or let out to the pressure of the impulse chamber IMP, by the load +// and the rapid setting, at least the local brake's and the anti-slip brake's; returns that pressure +double TKE::CylinderFlowKE(double IMP, double const BCP, double const BVP, double const Vel, double const dt) +{ + double dv; + double temp; // rapid auto const &frictionmaterial{*FM}; if (auto const &frictionmaterialtype{typeid(frictionmaterial)}; !(frictionmaterialtype == typeid(TDisk1) || frictionmaterialtype == typeid(TDisk2))) // jesli zeliwo to schodz @@ -2715,27 +2807,7 @@ double TKE::GetPF(double const PP, double const dt, double const Vel) dv = 0; BrakeRes->Flow(-dv); BrakeCyl->Flow(+dv); - - // przeplyw ZP <-> rozdzielacz - temp = BVs(IMP); - // if(BrakeStatus and b_hld)=b_off then - if (IMP < 0.25 || VVP + 0.05 > BVP) - dv = PF(BVP, VVP, 0.02 * SizeBR * temp / 1.87) * dt; - else - dv = 0; - BrakeRes->Flow(dv); - dV1 = dV1 + dv * 0.96; - ValveRes->Flow(-0.04 * dv); - // przeplyw PG <-> rozdzielacz - dv = PF(PP, VVP, 0.01) * dt; - ValveRes->Flow(-dv); - - ValveRes->Act(); - BrakeCyl->Act(); - BrakeRes->Act(); - CntrlRes->Act(); - ImplsRes->Act(); - return dv - dV1; + return IMP; } /// @@ -3034,32 +3106,7 @@ double TFV4aM::GetPF(double i_bcp, double PP, double HP, double dt, double ep) // na wszelki wypadek, zeby nie wyszlo poza zakres i_bcp = std::clamp(i_bcp, -1.999, 5.999); - double DP{0.0}; - if (TP > 0.0) - { - // jesli czasowy jest niepusty - DP = 0.045; // 2.5 w 55 sekund (5,35->5,15 w PG) - TP -= DP * dt; - Sounds[s_fv4a_t] = DP; - } - else - { - //.08 - TP = 0.0; - } - - if (XP > 0) - { - // jesli komora pod niepusta jest niepusty - DP = 2.5; - Sounds[s_fv4a_x] = DP * XP; - XP -= dt * DP * 2.0; // od cisnienia 5 do 0 w 10 sekund ((5-0)*dt/10) - } - else - { - // jak pusty, to pusty - XP = 0.0; - } + DischargeChambers(dt); double pom; if (EQ(i_bcp, -1.0)) @@ -3071,21 +3118,7 @@ double TFV4aM::GetPF(double i_bcp, double PP, double HP, double dt, double ep) pom = std::min(CP, HP); } - if (pom > RP + 0.25) - { - Fala = true; - } - if (Fala) - { - if (pom > RP + 0.3) - { - XP = XP - 20.0 * PR(pom, XP) * dt; - } - else - { - Fala = false; - } - } + UpdateWave(pom, dt); double LimPP = std::min(LPP_RP(i_bcp) + TP * 0.08 + RedAdj, HP); // pozycja + czasowy lub zasilanie @@ -3127,28 +3160,12 @@ double TFV4aM::GetPF(double i_bcp, double PP, double HP, double dt, double ep) } ep = dpPipe; - if (EQ(i_bcp, 0) || RP > ep) - { - // powolne wzrastanie, ale szybsze na jezdzie; - RP += PF(RP, ep, 0.0007) * dt; - } - else - { - // powolne wzrastanie i to bardzo - RP += PF(RP, ep, 0.000093 / 2 * 2) * dt; - } - // jednak trzeba wydluzyc, bo obecnie zle dziala - if (RP < ep && RP < BPT[std::lround(i_bcpno) + 2][1]) - { - // jesli jestesmy ponizej cisnienia w sterujacym (2.9 bar) - // przypisz cisnienie w PG - wydluzanie napelniania o czas potrzebny do napelnienia PG - RP += PF(RP, CP, 0.005) * dt; - } + UpdateReductor(i_bcp, ep, dt); if (EQ(i_bcp, i_bcpno) || EQ(i_bcp, -2)) { - DP = PF(0.0, PP, ActFlowSpeed / LBDelay); + auto const DP{PF(0.0, PP, ActFlowSpeed / LBDelay)}; dpMainValve = DP; Sounds[s_fv4a_e] = DP; Sounds[s_fv4a_u] = 0.0; @@ -3171,6 +3188,80 @@ double TFV4aM::GetPF(double i_bcp, double PP, double HP, double dt, double ep) return dpMainValve * dt; } +// the time reservoir and the reductor's air chamber let out, and their sounds +void TFV4aM::DischargeChambers(double const dt) +{ + double DP{0.0}; + if (TP > 0.0) + { + // jesli czasowy jest niepusty + DP = 0.045; // 2.5 w 55 sekund (5,35->5,15 w PG) + TP -= DP * dt; + Sounds[s_fv4a_t] = DP; + } + else + { + //.08 + TP = 0.0; + } + + if (XP > 0) + { + // jesli komora pod niepusta jest niepusty + DP = 2.5; + Sounds[s_fv4a_x] = DP * XP; + XP -= dt * DP * 2.0; // od cisnienia 5 do 0 w 10 sekund ((5-0)*dt/10) + } + else + { + // jak pusty, to pusty + XP = 0.0; + } +} + +// the release pressure wave: on while the supply is well over the reductor's pressure, its chamber filled meanwhile +void TFV4aM::UpdateWave(double const pom, double const dt) +{ + if (pom > RP + 0.25) + { + Fala = true; + } + if (Fala) + { + if (pom > RP + 0.3) + { + XP = XP - 20.0 * PR(pom, XP) * dt; + } + else + { + Fala = false; + } + } +} + +// the reductor reservoir following the pressure ep the pipe is driven to, slowly, faster at running, and filled from +// the control reservoir under the lowest pressure of the handle +void TFV4aM::UpdateReductor(double const i_bcp, double const ep, double const dt) +{ + if (EQ(i_bcp, 0) || RP > ep) + { + // powolne wzrastanie, ale szybsze na jezdzie; + RP += PF(RP, ep, 0.0007) * dt; + } + else + { + // powolne wzrastanie i to bardzo + RP += PF(RP, ep, 0.000093 / 2 * 2) * dt; + } + // jednak trzeba wydluzyc, bo obecnie zle dziala + if (RP < ep && RP < BPT[std::lround(i_bcpno) + 2][1]) + { + // jesli jestesmy ponizej cisnienia w sterujacym (2.9 bar) + // przypisz cisnienie w PG - wydluzanie napelniania o czas potrzebny do napelnienia PG + RP += PF(RP, CP, 0.005) * dt; + } +} + /// Initialises CP and RP to the supplied pressure. /// Initial pressure [bar]. void TFV4aM::Init(double Press) @@ -3259,7 +3350,6 @@ double TMHZ_EN57::GetPF(double i_bcp, double PP, double HP, double dt, double ep double dpPipe; double dpMainValve; double ActFlowSpeed; - double DP; double pom; for (auto &soundvalue : Sounds) @@ -3270,30 +3360,12 @@ double TMHZ_EN57::GetPF(double i_bcp, double PP, double HP, double dt, double ep i_bcp = std::clamp(i_bcp, -0.999, 9.999); // na wszelki wypadek, zeby nie wyszlo poza zakres - if (TP > 0 && CP > 4.9) - { - DP = OverloadPressureDecrease; - if (EQ(i_bcp, 0)) - TP = TP - DP * dt; - Sounds[s_fv4a_t] = DP; - } - else - { - TP = 0; - } + DischargeTimedReservoir(i_bcp, dt); LimPP = std::min(LPP_RP(i_bcp) + TP * 0.08 + RedAdj, HP); // pozycja + czasowy lub zasilanie ActFlowSpeed = 4; - double uop = UnbrakeOverPressure; // unbrake over pressure in actual state - ManualOvrldActive = UniversalFlag & TUniversalBrake::ub_HighPressure; // button is pressed - if (ManualOvrld && !ManualOvrldActive) // no overpressure for not pressed button if it does not exists - uop = 0; - - if (EQ(i_bcp, -1) && uop > 0) - pom = std::min(HP, 5.4 + RedAdj + uop); - else - pom = std::min(CP, HP); + pom = SupplyPressure(i_bcp, HP); if (LimPP > CP) // podwyzszanie szybkie CP = CP + 60 * std::min(abs(LimPP - CP), 0.05) * PR(CP, LimPP) * dt; // zbiornik sterujacy; @@ -3313,15 +3385,12 @@ double TMHZ_EN57::GetPF(double i_bcp, double PP, double HP, double dt, double ep if ((EQ(i_bcp, -1) && AutoOvrld) || (i_bcp < 0.5 && UniversalFlag & TUniversalBrake::ub_Overload)) { - if (TP < 5) - TP = TP + dt; // 5/10 - if (TP < OverloadMaxPressure) - TP = TP - 0.5 * dt; // 5/10 + ChargeTimedReservoir(dt); } if (EQ(i_bcp, 10) || EQ(i_bcp, -2)) { - DP = PF(0, PP, 2 * ActFlowSpeed / LBDelay); + auto const DP{PF(0, PP, 2 * ActFlowSpeed / LBDelay)}; dpMainValve = DP; Sounds[s_fv4a_e] = DP; Sounds[s_fv4a_u] = 0; @@ -3344,6 +3413,45 @@ double TMHZ_EN57::GetPF(double i_bcp, double PP, double HP, double dt, double ep return dpMainValve * dt; } +// the time reservoir let out of the overload, at the running position, while the control reservoir is charged +void TMHZ_EN57::DischargeTimedReservoir(double const i_bcp, double const dt) +{ + if (TP > 0 && CP > 4.9) + { + auto const DP{OverloadPressureDecrease}; + if (EQ(i_bcp, 0)) + TP = TP - DP * dt; + Sounds[s_fv4a_t] = DP; + } + else + { + TP = 0; + } +} + +// the time reservoir charged by the overload, up to its highest pressure +void TMHZ_EN57::ChargeTimedReservoir(double const dt) +{ + if (TP < 5) + TP = TP + dt; // 5/10 + if (TP < OverloadMaxPressure) + TP = TP - 0.5 * dt; // 5/10 +} + +// the pressure the handle feeds the pipe from: the supply's over the running pressure at the filling stroke, where the +// handle has the overpressure (with its button pressed, for a button worked one), the control reservoir's otherwise +double TMHZ_EN57::SupplyPressure(double const i_bcp, double const HP) +{ + double uop = UnbrakeOverPressure; // unbrake over pressure in actual state + ManualOvrldActive = UniversalFlag & TUniversalBrake::ub_HighPressure; // button is pressed + if (ManualOvrld && !ManualOvrldActive) // no overpressure for not pressed button if it does not exists + uop = 0; + + if (EQ(i_bcp, -1) && uop > 0) + return std::min(HP, 5.4 + RedAdj + uop); + return std::min(CP, HP); +} + /// Initialises CP to the supplied pressure. /// Initial pressure [bar]. void TMHZ_EN57::Init(double Press) diff --git a/McZapkie/hamulce.h b/McZapkie/hamulce.h index 2539250a5..b8be1733c 100644 --- a/McZapkie/hamulce.h +++ b/McZapkie/hamulce.h @@ -249,6 +249,8 @@ class TReservoir /// /// Pressure in bar (atm). void CreatePress(double Press); + /// Returns reservoir capacity in liters. + double GetCap() const { return Cap; } /// /// Returns absolute (atmospheric) pressure inside the reservoir. /// @@ -611,6 +613,8 @@ class TESt : public TBrake /// Brake cylinder (or impulse) pressure. /// In/out accumulator for the brake pipe flow correction. void CheckState(double BCP, double &dV1); // glowny przyrzad rozrzadczy + /// The state of a valve holding: braking on in steps, the filling stopped, or released. + void CheckStateHeld(double BCP, double VVP, double CVP); /// Drives the releaser logic — bleeds the control reservoir while the releaser is engaged. /// Time step [s]. void CheckReleaser(double dt); // odluzniacz @@ -769,6 +773,12 @@ class TLSt : public TESt4R /// Constructs the LSt distributor. using TESt4R::TESt4R; + + private: + // the parts of GetPF() + void UpdateStatusLSt(double BCP, double VVP, double CVP); + void ReleaserLSt(double BCP, double CVP, double dt); + void CylinderFlowLSt(double BCP, double BVP, double CVP, double dt, double Vel); }; /// @@ -809,6 +819,13 @@ class TEStED : public TLSt /// Stores the load-weighing parameters. void SetLP(double const TM, double const LM, double const TBP) override; // parametry przystawki wazacej + private: + // the parts of GetPF() + void UpdateStatus(double BCP, double VVP, double CVP, double MPP); + double IntermediateFlow(double BCP, double VVP, double CVP, double MPP, double BVP, double nastG) const; + void CylinderFlow(double BCP, double BVP, double dt, double Vel); + + public: /// Constructs the distributor and creates the intermediate reservoir. inline TEStED(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TLSt(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) { @@ -835,6 +852,10 @@ class TEStEP2 : public TLSt /// EP intensity (-1..1). double EPS = 0.0; + private: + // the part of GetPF() + void UpdateStatusEP2(double BCP, double VVP, double CVP); + public: /// Initialises the EP2-equipped distributor (impulse chamber, P delay). void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; // inicjalizacja @@ -992,6 +1013,10 @@ class TKE : public TBrake /// Auxiliary (local) brake pressure feeding the DCV. double LBP = 0.0; // cisnienie hamulca pomocniczego + // the parts of GetPF() and CheckState() + double CylinderFlowKE(double IMP, double BCP, double BVP, double Vel, double dt); + void CheckStateHeld(double BCP, double VVP, double CVP); + public: /// Initialises the KE distributor (control / impulse / auxiliary reservoirs and BVM). void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; @@ -1170,6 +1195,10 @@ class TFV4aM : public TDriverHandle double LPP_RP(double pos) const; /// Returns true if pos is within ±0.5 of i_pos (detent comparison). bool EQ(double pos, double i_pos) const; + // the parts of GetPF() + void DischargeChambers(double dt); + void UpdateWave(double pom, double dt); + void UpdateReductor(double i_bcp, double ep, double dt); public: /// Computes brake pipe flow for the FV4a/M handle (interpolated BPT, wave modelling, accelerator). @@ -1220,6 +1249,10 @@ class TMHZ_EN57 : public TDriverHandle double LPP_RP(double pos) const; /// Returns true if pos is within ±0.5 of i_pos. bool EQ(double pos, double i_pos) const; + // the parts of GetPF() + void DischargeTimedReservoir(double i_bcp, double dt); + void ChargeTimedReservoir(double dt); + double SupplyPressure(double i_bcp, double HP); public: /// Computes brake pipe flow for MHZ_EN57 (covers handle positions -1..10 with EP/pneumatic mix). @@ -1464,8 +1497,6 @@ class TSt113 : public TH14K1 static double const BEP_K[/*?*/ /*-1..5*/ 5 - -1 + 1]; /// Lookup of bh_* function codes to handle position values. static double const pos_table[11]; // = {-1, 5, -1, 0, 2, 3, 4, 5, 0, 0, 1}; - /// Local control pressure (mirrors PP). - double CP = 0; public: /// Computes brake pipe flow for the St113 handle (with EP). diff --git a/README.md b/README.md index d733db765..208526b0b 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,7 @@ MaSzyna compiles and runs natively on **Linux** and **Windows**. Other platforms | `-DCMAKE_BUILD_TYPE=Debug` | Debug build | | `-DCMAKE_BUILD_TYPE=Release` | Release build | | `-DCMAKE_BUILD_TYPE=RelWithDebInfo` | Release build with debug symbols | +| `-DUSE_SYSTEM_JSON=ON/OFF` | Use an installed **nlohmann_json** 3.9 or newer (e.g. `nlohmann-json3-dev`, vcpkg `nlohmann-json`) instead of the `ref/json` submodule (default `OFF`) | | `-DPython3_ROOT_DIR=` | Root of the **Python 3.14** install on Windows (`python.exe`, `Lib`, `DLLs`) for embed/copy steps; on Linux, optional if CMake picks the wrong interpreter | > **macOS note:** macOS provides OpenGL only up to 4.1, so the OpenGL 4.6 renderer does not run there. @@ -226,7 +227,7 @@ If detection still fails, padding the file (with comments) up to ~1 MB may hel ## Minimum requirements - OS: **Windows 10 64-bit** -- Processor: **2 core at least 2 GHz (e.g. Intel Core i3-2100 / AMD Athlon II X2)** +- Processor: **4 cores with AVX2 support (e.g. Intel Core i5-4430 / AMD Ryzen 3 1200)** - RAM: **6 GB RAM** - Graphics Card: **supporting OpenGL 4.6 with at least 1GB VRAM** - **150 GB of free disk space** diff --git a/application/application.cpp b/application/application.cpp index 145106b62..f89eaf77e 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -25,6 +25,7 @@ http://mozilla.org/MPL/2.0/. #include "rendering/renderer.h" #include "application/uilayer.h" #include "utilities/Logs.h" +#include "utilities/logfiles.h" #include "world/SleeperWorker.h" #include "rendering/screenshot.h" #include "utilities/translation.h" @@ -32,6 +33,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "utilities/memorystats.h" #include "utilities/framepacer.h" +#include "utilities/hardwareprobe.h" #include "utilities/dictionary.h" #include "version_info.h" #include "simulation/simulationtest.h" @@ -414,8 +416,10 @@ int eu07_application::init(int Argc, char *Argv[]) Global.threads.emplace("LogService", std::move(sLoggingService)); init_debug(); + result = init_settings(Argc, Argv); + // the log files are named by the settings (multiplelogs), so they are cleared and opened once those are read init_files(); - if ((result = init_settings(Argc, Argv)) != 0) + if (result != 0) { ErrorLog("Failed to initialize settings! Maybe you're missing eu07.ini file?"); return result; @@ -426,7 +430,7 @@ int eu07_application::init(int Argc, char *Argv[]) // the run's seed, settled once and kept in Globals: the engines come out of it. // narrowed on purpose - mt19937 and seed_of() both work on 32 bits, and that is // the seed somebody can write down and pass on - if (!Global.random_seed) + if (false == Global.random_seed_given) Global.random_seed = static_cast(true_random_seed()); Global.random_engine.seed(Global.random_seed); Global.local_random_engine.seed(Global.random_seed); @@ -452,6 +456,9 @@ int eu07_application::init(int Argc, char *Argv[]) WriteLog(settingspipe.str()); } + // the cpu, the memory and the graphics adapters, for the bug reports + hardware::log_system(); + WriteLog("// startup"); if ((result = init_glfw()) != 0) @@ -1274,16 +1281,19 @@ void eu07_application::init_console() void eu07_application::init_files() { - + // without multiplelogs the run writes the shared log.txt / errors.txt, and those of the run before go. with it the + // run writes files of its own in logs/, and the shared ones are left to whoever ran the game last without it + for (auto const &file : stale_log_files(Global.MultipleLogs)) + { + std::error_code error; // not there is fine + std::filesystem::remove(file, error); + } #ifdef _WIN32 - DeleteFile("log.txt"); - DeleteFile("errors.txt"); CreateDirectory("logs", nullptr); #elif __unix__ - unlink("log.txt"); - unlink("errors.txt"); mkdir("logs", 0750); #endif + OpenLogFiles(); } namespace fs = std::filesystem; @@ -1366,11 +1376,16 @@ int eu07_application::init_settings(int Argc, char *Argv[]) else if (token == "-seed") { // a number is the seed; anything else is a word that stands for one. said in the - // log as it was given, because that is what gets passed on to somebody else + // log as it was given, because that is what gets passed on to somebody else. 0 is a seed + // too; an empty word gives none, as randomseed with nothing after it if (i + 1 < Argc) { - Global.random_seed = seed_of(Argv[++i]); - WriteLog(std::format("seed given on the command line: {} -> {}", Argv[i], Global.random_seed)); + if (auto const seed{seed_given(Argv[++i])}) + { + Global.random_seed = *seed; + Global.random_seed_given = true; + WriteLog(std::format("seed given on the command line: {} -> {}", Argv[i], Global.random_seed)); + } } } else if (token == "--test") diff --git a/application/consistviews.cpp b/application/consistviews.cpp new file mode 100644 index 000000000..49815f6e8 --- /dev/null +++ b/application/consistviews.cpp @@ -0,0 +1,316 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "application/consistviews.h" + +#include +#include + +#include "vehicle/Camera.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" + +namespace { + +// more vehicles than any train has: a guard against a loop in the couplings +std::size_t constexpr train_limit{1000}; +// metres the vehicle picked moves before the trackside view takes the way it went for the way of the train +double constexpr direction_step{0.5}; + +cameraviews::vehicle_pose pose_of(TDynamicObject const *Vehicle) { + cameraviews::vehicle_pose pose; + pose.position = Vehicle->GetPosition(); + pose.front = Vehicle->VectorFront(); + pose.length = Vehicle->MoverParameters->Dim.L; + pose.width = Vehicle->MoverParameters->Dim.W; + pose.height = Vehicle->MoverParameters->Dim.H; + return pose; +} + +// the end of the Vehicle the Other vehicle is beyond, -1 when it's beyond neither +int end_towards(TDynamicObject const *Vehicle, TDynamicObject const *Other) { + for (auto const side : {end::front, end::rear}) { + if (Vehicle->MoverParameters->Neighbours[side].vehicle == Other) { + return side; + } + } + return -1; +} + +// the end of the Vehicle at an end of the train, away from the Inner vehicle next to it (nullptr when it's alone) +int outer_end(TDynamicObject const *Vehicle, TDynamicObject const *Inner, int const Alone) { + if (Inner == nullptr) { + return Alone; + } + auto const inner{end_towards(Vehicle, Inner)}; + return inner < 0 ? Alone : 1 - inner; +} + +cameraviews::coupler coupler_of(TDynamicObject const *Vehicle, int const End) { + cameraviews::coupler coupler; + coupler.position = Vehicle->CouplerPosition(static_cast(End)); + coupler.outward = Vehicle->VectorFront() * (End == end::front ? 1.0 : -1.0); + coupler.width = Vehicle->MoverParameters->Dim.W; + return coupler; +} + +// the driver's way: the front (1) or the rear (-1) of the Driven vehicle, as the user drives it +int driven_way(TDynamicObject const *Driven) { + auto const cab{Driven->MoverParameters->CabOccupied < 0 ? -1 : 1}; + auto const direction{Driven->MoverParameters->DirActive < 0 ? -1 : 1}; + return cab * direction; +} + +// the coupler of the Vehicle furthest along the Way (or furthest back, with a negative Way) +glm::dvec3 end_along(TDynamicObject const *Vehicle, glm::dvec3 const &Way) { + auto const front{Vehicle->CouplerPosition(end::front)}; + auto const rear{Vehicle->CouplerPosition(end::rear)}; + return glm::dot(front - rear, Way) >= 0.0 ? front : rear; +} + +// the front of the Vehicle, or its rear when that faces the Way +glm::dvec3 facing_along(TDynamicObject const *Vehicle, glm::dvec3 const &Way) { + auto const front{cameraviews::flat_front(Vehicle->VectorFront())}; + return glm::dot(front, Way) < 0.0 ? -front : front; +} + +bool usable(cameraviews::placement const &Place) { + auto const finite{[](glm::dvec3 const &Value) { return std::isfinite(Value.x) && std::isfinite(Value.y) && std::isfinite(Value.z); }}; + if (false == (finite(Place.eye) && finite(Place.target) && finite(Place.up))) { + return false; + } + auto const look{Place.target - Place.eye}; + if (glm::length(look) < 0.01 || glm::length(Place.up) < 0.5) { + return false; + } + // a camera looking along its own up has no way to tell left from right + return std::abs(glm::dot(glm::normalize(look), glm::normalize(Place.up))) < 0.999; +} + +} // namespace + +std::vector consist_views::train_of(TDynamicObject *Driven) { + std::vector train; + if (Driven == nullptr) { + return train; + } + auto const *controller{Driven->Mechanik != nullptr ? Driven->Mechanik : Driven->ctOwner}; + auto *first{controller != nullptr ? controller->Vehicle(end::front) : nullptr}; + if (first == nullptr) { + first = Driven; + } + for (auto *vehicle{first}; vehicle != nullptr && train.size() < train_limit; vehicle = vehicle->Next()) { + if (std::ranges::find(train, vehicle) != train.end()) { + break; + } + train.push_back(vehicle); + } + if (std::ranges::find(train, Driven) == train.end()) { + // the controller's list is behind the couplings: the driven vehicle alone, until it catches up + train.assign(1, Driven); + } + return train; +} + +TDynamicObject *consist_views::pick(std::vector const &Train, TDynamicObject *Driven) { + auto picked{std::ranges::find(Train, m_vehicle)}; + if (m_vehicle == nullptr || picked == Train.end()) { + picked = std::ranges::find(Train, Driven); + } + if (picked == Train.end()) { + picked = Train.begin(); + } + auto index{static_cast(picked - Train.begin())}; + if (m_view != kind::coupling) { + index = cameraviews::step_index(index, static_cast(Train.size()), m_step); + m_step = 0; + } + if (Train[index] != m_vehicle) { + // m_lastposition is of the vehicle before: the way the train goes is set again from the way the user drives, + // or the step between the two vehicles would be taken for a move + m_moved = false; + } + m_vehicle = Train[index]; + return m_vehicle; +} + +double consist_views::gap_beyond(TDynamicObject const *Vehicle, int const End) { + auto const &neighbour{Vehicle->MoverParameters->Neighbours[End]}; + if (neighbour.vehicle == nullptr || Vehicle->MoverParameters->Couplers[End].CouplingFlag != 0) { + return -1.0; + } + if (neighbour.distance > cameraviews::coupler_watch_range) { + return -1.0; + } + return std::max(0.0, static_cast(neighbour.distance)); +} + +consist_views::coupling_place consist_views::coupling_at(std::vector const &Train, int const Index) { + auto const count{static_cast(Train.size())}; + coupling_place place; + if (Index > 0 && Index < count) { + // between two vehicles of the train + auto *ahead{Train[Index - 1]}; + auto const *behind{Train[Index]}; + auto const aheadend{end_towards(ahead, behind)}; + auto const behindend{end_towards(behind, ahead)}; + place.vehicle = ahead; + place.coupler = coupler_of(ahead, aheadend < 0 ? end::rear : aheadend); + place.other = true; + place.otherposition = behind->CouplerPosition(static_cast(behindend < 0 ? end::front : behindend)); + return place; + } + // an end of the train, perhaps with another vehicle coming closer to it + auto const front{Index <= 0}; + auto *vehicle{front ? Train.front() : Train.back()}; + auto const *inner{count > 1 ? Train[front ? 1 : count - 2] : nullptr}; + auto const outer{outer_end(vehicle, inner, front ? end::front : end::rear)}; + place.vehicle = vehicle; + place.coupler = coupler_of(vehicle, outer); + auto const &neighbour{vehicle->MoverParameters->Neighbours[outer]}; + place.gap = gap_beyond(vehicle, outer); + if (place.gap >= 0.0 && (neighbour.vehicle_end == end::front || neighbour.vehicle_end == end::rear)) { + place.other = true; + place.otherposition = neighbour.vehicle->CouplerPosition(static_cast(neighbour.vehicle_end)); + } + return place; +} + +cameraviews::train_motion consist_views::motion_of(std::vector const &Train, TDynamicObject const *Driven) { + auto const position{m_vehicle->GetPosition()}; + if (false == m_moved) { + // standing, the train is to go the way the user drives + m_direction = cameraviews::flat_front(m_vehicle->VectorFront()) * + static_cast(cameraviews::driving_facing(m_vehicle->VectorFront(), Driven->VectorFront(), driven_way(Driven))); + m_lastposition = position; + m_moved = true; + } + else if (std::hypot(position.x - m_lastposition.x, position.z - m_lastposition.z) > direction_step) { + m_direction = cameraviews::flat_front(position - m_lastposition); + m_lastposition = position; + } + std::vector positions; + positions.reserve(Train.size()); + for (auto const *vehicle : Train) { + positions.emplace_back(vehicle->GetPosition()); + } + auto const [head, tail]{cameraviews::train_ends(positions, m_direction)}; + cameraviews::train_motion motion; + motion.direction = m_direction; + motion.head = end_along(Train[head], m_direction); + motion.tail = end_along(Train[tail], -m_direction); + motion.speed = std::abs(m_vehicle->GetVelocity()) / 3.6; + motion.width = m_vehicle->MoverParameters->Dim.W; + if (Train.size() > 1) { + auto const *behind{Train[head == 0 ? 1 : head - 1]}; + motion.curvature = cameraviews::line_curvature(Train[head]->GetPosition(), facing_along(Train[head], m_direction), behind->GetPosition(), facing_along(behind, m_direction)); + } + return motion; +} + +cameraviews::placement consist_views::place_orbit(TCamera &Camera, double const Seconds) { + auto const pose{pose_of(m_vehicle)}; + if (m_orbit.radius <= 0.0) { + m_orbit = cameraviews::orbit_start(pose); + } + // the mouse turns the camera around the vehicle rather than the view away from it + glm::dvec2 const turn{Camera.Angle.x, Camera.Angle.y}; + Camera.Angle = {}; + m_orbit = cameraviews::orbit_moved(m_orbit, Camera.Velocity, turn, Seconds, pose); + return cameraviews::orbit_placement(m_orbit, pose); +} + +cameraviews::placement consist_views::place_shunting(TCamera const &Camera, std::vector const &Train, TDynamicObject const *Driven, double const Seconds) { + auto const pose{pose_of(m_vehicle)}; + auto length{0.0}; + for (auto const *vehicle : Train) { + length += vehicle->MoverParameters->Dim.L; + } + m_topdown = cameraviews::topdown_moved(m_topdown, Camera.Velocity, Seconds, pose, 0.5 * length + 50.0); + auto const facing{cameraviews::driving_facing(m_vehicle->VectorFront(), Driven->VectorFront(), Driven->MoverParameters->CabOccupied)}; + return cameraviews::topdown_placement(m_topdown, pose, facing); +} + +cameraviews::placement consist_views::place_coupling(TCamera const &Camera, std::vector const &Train, double const Seconds) { + auto const count{static_cast(Train.size())}; + if (m_coupling < 0) { + auto const front{coupling_at(Train, 0)}; + auto const rear{coupling_at(Train, count)}; + m_coupling = cameraviews::first_coupling(front.gap, rear.gap, count); + } + m_coupling = cameraviews::step_index(std::min(m_coupling, count), count + 1, m_step); + m_step = 0; + auto const place{coupling_at(Train, m_coupling)}; + m_vehicle = place.vehicle; + m_coupler = cameraviews::coupler_moved(m_coupler, Camera.Velocity, Seconds); + return cameraviews::coupler_placement(m_coupler, place.coupler, place.other ? &place.otherposition : nullptr); +} + +cameraviews::placement consist_views::place_trackside(std::vector const &Train, TDynamicObject const *Driven) { + auto const motion{motion_of(Train, Driven)}; + if (cameraviews::trackside_expired(m_trackside, motion)) { + m_trackside = cameraviews::trackside_next(m_trackside, motion); + } + return cameraviews::trackside_placement(m_trackside, cameraviews::orbit_centre(pose_of(m_vehicle))); +} + +TDynamicObject *consist_views::enter(kind const View, TDynamicObject *Driven) { + m_view = View; + m_step = 0; + if (View == kind::coupling) { + // each time the view starts at the end of the train something comes closer to, or at its front + m_coupling = -1; + } + if (View == kind::trackside) { + // and the railfan finds a new spot ahead of the train + m_trackside.placed = false; + m_moved = false; + } + auto const train{train_of(Driven)}; + if (train.empty()) { + return nullptr; + } + return pick(train, Driven); +} + +void consist_views::select(int const Step) { + m_step += Step; +} + +TDynamicObject *consist_views::update(TCamera &Camera, TDynamicObject *Driven, double const Seconds) { + auto const train{train_of(Driven)}; + if (train.empty()) { + return nullptr; + } + pick(train, Driven); + cameraviews::placement place; + switch (m_view) { + case kind::orbit: + place = place_orbit(Camera, Seconds); + break; + case kind::shunting: + // straight down, the mouse would only tilt it off the train + Camera.Angle = {}; + place = place_shunting(Camera, train, Driven, Seconds); + break; + case kind::coupling: + place = place_coupling(Camera, train, Seconds); + break; + case kind::trackside: + place = place_trackside(train, Driven); + break; + } + if (usable(place)) { + Camera.Pos = place.eye; + Camera.LookAt = place.target; + Camera.vUp = place.up; + } + return m_vehicle; +} diff --git a/application/consistviews.h b/application/consistviews.h new file mode 100644 index 000000000..1c86345c0 --- /dev/null +++ b/application/consistviews.h @@ -0,0 +1,74 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include + +#include "vehicle/cameraviews.h" + +class TCamera; +class TDynamicObject; + +// The outside views of the user's train that go with one of its vehicles (eu07/maszyna#551), after the four views +// [Shift]+[F4] had before: the orbit around a vehicle, the shunting view from above, the view beside a coupling +// and the trackside view of a railfan. [ and ] pick the vehicle (the coupling) the view goes with. The camera +// follows from cameraviews.h; this class hands over the vehicles of the train and keeps what the user set. +class consist_views { + +public: + enum class kind { orbit, shunting, coupling, trackside }; + + // starts the View of the train of the Driven vehicle, with the vehicle (or the coupling) picked before when it's + // still in the train; returns the vehicle the camera goes with, nullptr when there's no train + TDynamicObject *enter(kind View, TDynamicObject *Driven); + // picks the vehicle Step places towards the rear of the train (towards its front for a negative Step); the + // coupling in the coupling view + void select(int Step); + // places the Camera for this frame of Seconds (real time): the movement keys come from its Velocity, the mouse of + // the orbit from its Angle. returns the vehicle the camera goes with, nullptr when the train is gone + TDynamicObject *update(TCamera &Camera, TDynamicObject *Driven, double Seconds); + +private: + struct coupling_place { + TDynamicObject *vehicle{nullptr}; // the vehicle the coupler is on + cameraviews::coupler coupler; + bool other{false}; + glm::dvec3 otherposition{}; // the facing coupler of the vehicle beyond, coupled or coming closer + double gap{-1.0}; // at an end of the train: the distance to a vehicle coming closer, negative for none + }; + + // the vehicles of the train of the Driven vehicle, from its front to its rear + static std::vector train_of(TDynamicObject *Driven); + // the vehicle the camera goes with in the Train: the one picked before, or the Driven one + TDynamicObject *pick(std::vector const &Train, TDynamicObject *Driven); + // the Index coupling of the Train, 0 its front end, Train.size() its rear end + static coupling_place coupling_at(std::vector const &Train, int Index); + // the distance to a vehicle not coupled beyond the End of the Vehicle, negative for none + static double gap_beyond(TDynamicObject const *Vehicle, int End); + // keeps up the way the train goes and works out where its ends are, for the trackside view + cameraviews::train_motion motion_of(std::vector const &Train, TDynamicObject const *Driven); + + cameraviews::placement place_orbit(TCamera &Camera, double Seconds); + cameraviews::placement place_shunting(TCamera const &Camera, std::vector const &Train, TDynamicObject const *Driven, double Seconds); + cameraviews::placement place_coupling(TCamera const &Camera, std::vector const &Train, double Seconds); + cameraviews::placement place_trackside(std::vector const &Train, TDynamicObject const *Driven); + + kind m_view{kind::orbit}; + TDynamicObject *m_vehicle{nullptr}; // the vehicle picked; only compared with the vehicles of the train, never followed + int m_step{0}; // vehicles to step over in the next update, from [ and ] + int m_coupling{-1}; // the coupling picked in the coupling view, -1 not yet + cameraviews::orbit m_orbit; + cameraviews::topdown m_topdown; + cameraviews::coupler_view m_coupler; + cameraviews::trackside m_trackside; + glm::dvec3 m_lastposition{}; // of the vehicle picked, where the trackside view last saw it move + glm::dvec3 m_direction{0.0, 0.0, -1.0}; // the way the train goes, for the trackside view + bool m_moved{false}; // m_lastposition is known +}; diff --git a/application/driverhints.cpp b/application/driverhints.cpp index 0c6f02cc8..cd1967aa2 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -762,6 +762,14 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) return mvPantographUnit->PantPress >= (is_emu() ? (mvPantographUnit->PantPressLockActive ? 4.6 : 2.6) : 4.2); } ); break; } + case driver_hint::waitbrakecharge: { + // NOTE: this action doesn't have AI component: the ai waits through Ready and DecBrake() + hint( + Action, + [this](float const /*Parameter*/) { + return IsConsistCharged; } ); + break; + } case driver_hint::waitloadexchange: { // NOTE: this action doesn't have AI component hint( @@ -1150,6 +1158,29 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) return IsAnyDoorPermitActive[side::left] == false; } ); break; } + // doorsteps, as the timetable asks (eu07/maszyna#95) + case driver_hint::doorstepon: { + if( AIControllFlag ) { + mvOccupied->PermitDoorStep( true ); + } + remove_hint( driver_hint::doorstepoff ); + hint( + Action, + [this](float const /*Parameter*/) { + return mvOccupied->Doors.step_enabled == true; } ); + break; + } + case driver_hint::doorstepoff: { + if( AIControllFlag ) { + mvOccupied->PermitDoorStep( false ); + } + remove_hint( driver_hint::doorstepon ); + hint( + Action, + [this](float const /*Parameter*/) { + return mvOccupied->Doors.step_enabled == false; } ); + break; + } // consist lights case driver_hint::consistlightson: { if( AIControllFlag ) { diff --git a/application/driverhints_def.h b/application/driverhints_def.h index 2ce896679..2e0556968 100644 --- a/application/driverhints_def.h +++ b/application/driverhints_def.h @@ -59,6 +59,7 @@ DRIVER_HINT_DEF(directionother, STRN("Switch reverser to opposite direction")) DRIVER_HINT_DEF(directionnone, STRN("Set reverser to neutral")) DRIVER_HINT_DEF(waitpressuretoolow, STRN("Wait for main reservoir to fill")) DRIVER_HINT_DEF(waitpantographpressuretoolow, STRN("Wait for sufficient air pressure in pantograph subsystem")) +DRIVER_HINT_DEF(waitbrakecharge, STRN("Wait for the train brakes to charge")) DRIVER_HINT_DEF(sandingon, STRN("Switch on sanding")) DRIVER_HINT_DEF(sandingoff, STRN("Switch off sanding")) DRIVER_HINT_DEF(consistdoorlockson, STRN("Switch on door locks")) @@ -72,6 +73,8 @@ DRIVER_HINT_DEF(doorrightpermiton, STRN("Grant permit to open doors")) DRIVER_HINT_DEF(doorrightpermitoff, STRN("Revoke permit to open doors")) DRIVER_HINT_DEF(doorleftpermiton, STRN("Grant permit to open doors")) DRIVER_HINT_DEF(doorleftpermitoff, STRN("Revoke permit to open doors")) +DRIVER_HINT_DEF(doorstepon, STRN("Switch on doorsteps")) +DRIVER_HINT_DEF(doorstepoff, STRN("Switch off doorsteps")) DRIVER_HINT_DEF(hornon, STRN("Sound the horn")) DRIVER_HINT_DEF(hornoff, STRN("Switch off horn")) DRIVER_HINT_DEF(consistlightson, STRN("Switch on consist lights")) diff --git a/application/drivermode.cpp b/application/drivermode.cpp index aeb4a5635..e76baec1c 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -777,7 +777,12 @@ void driver_mode::update_camera(double const Deltatime) // reset window state, it'll be set again if applicable in a check below Global.CabWindowOpen = false; - if (simulation::Train != nullptr && controlled != nullptr && Camera.m_owner != nullptr && false == DebugCameraFlag) + if (consist_view_active()) + { + // the orbit, shunting, coupling and trackside views place the camera themselves + update_consist_view(Deltatime); + } + else if (simulation::Train != nullptr && controlled != nullptr && Camera.m_owner != nullptr && false == DebugCameraFlag) { // jeśli jazda w kabinie, przeliczyć trzeba parametry kamery /* @@ -1142,6 +1147,17 @@ void driver_mode::OnKeyDown(int cKey) } break; } + case GLFW_KEY_LEFT_BRACKET: + case GLFW_KEY_RIGHT_BRACKET: + { + // in the orbit, shunting, coupling and trackside views: the vehicle (coupling) towards the front, or the rear, + // of the train. [Ctrl] with them moves the train in the debug mode, bound in the keyboard settings + if (false == Global.ctrlState && consist_view_active()) + { + m_consistviews.select(cKey == GLFW_KEY_LEFT_BRACKET ? -1 : 1); + } + break; + } default: { break; @@ -1151,6 +1167,18 @@ void driver_mode::OnKeyDown(int cKey) return; // nie są przekazywane do pojazdu wcale } +bool driver_mode::consist_view_active() const +{ + return FreeFlyModeFlag && m_externalview && m_externalviewmode >= view::orbit && Camera.m_owner != nullptr && false == DebugCameraFlag; +} + +void driver_mode::update_consist_view(double const Deltatime) +{ + auto *controlled{simulation::Train != nullptr ? simulation::Train->Dynamic() : nullptr}; + // the camera goes with the vehicle picked, or stays where it is once the train is gone + Camera.m_owner = m_consistviews.update(Camera, controlled, Deltatime); +} + // places camera outside the controlled vehicle, or nearest if nothing is under control // depending on provided switch the view is placed right outside, or at medium distance void driver_mode::DistantView(bool const Near) @@ -1199,7 +1227,8 @@ void driver_mode::ExternalView() if (true == m_externalview) { // we're already in some external view mode, so select next one on the list - m_externalviewmode = clamp_circular(++m_externalviewmode, static_cast(view::count_)); + // the views of the train's vehicles come after the four older ones, unless they're turned off in eu07.ini + m_externalviewmode = clamp_circular(++m_externalviewmode, static_cast(Global.ConsistViews ? view::count_ : view::orbit)); } FreeFlyModeFlag = true; @@ -1302,6 +1331,17 @@ void driver_mode::ExternalView() DistantView(false); break; } + case view::orbit: + case view::shunting: + case view::coupling: + case view::trackside: + { + // the camera goes with a vehicle of the train, placed by update_consist_view() from the next frame on + auto const kind{static_cast(m_externalviewmode - view::orbit)}; + Camera.m_owner = m_consistviews.enter(kind, vehicle); + Camera.m_owneroffset = {}; + break; + } default: { break; diff --git a/application/drivermode.h b/application/drivermode.h index 06ce32ee4..7e5b48573 100644 --- a/application/drivermode.h +++ b/application/drivermode.h @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "input/gamepadinput.h" #include "Console.h" #include "vehicle/Camera.h" +#include "application/consistviews.h" #include "utilities/Classes.h" #ifdef WITH_UART #include "utilities/uart.h" @@ -55,6 +56,11 @@ private: consistrear, bogie, driveby, + // the views of consist_views (eu07/maszyna#551), left out of the cycle with consistviews off in eu07.ini + orbit, + shunting, + coupling, + trackside, count_ }; @@ -98,6 +104,10 @@ private: void CabView(); void ExternalView(); void DistantView( bool const Near = false ); + // whether the camera shows one of the views of consist_views now + bool consist_view_active() const; + // places the camera of the view of consist_views for the frame + void update_consist_view( double const Deltatime ); void set_picking( bool const Picking ); // members @@ -108,6 +118,7 @@ private: int m_externalviewmode { view::consistfront }; // selected external view mode bool m_externalview { true }; std::array m_externalviewconfigs; + consist_views m_consistviews; // the orbit, shunting, coupling and trackside views TDynamicObject *pDynamicNearest { nullptr }; // vehicle nearest to the active camera. TODO: move to camera double fTime50Hz { 0.0 }; // bufor czasu dla komunikacji z PoKeys double const m_primaryupdaterate { 1.0 / 100.0 }; diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 91fb2ff62..d7d9d6bca 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -23,8 +23,10 @@ http://mozilla.org/MPL/2.0/. #include "world/catenary_span.h" #include "vehicle/Camera.h" #include "world/mtable.h" +#include "world/stationnames.h" #include "vehicle/Train.h" #include "vehicle/Driver.h" +#include "vehicle/drivingaid.h" #include "model/AnimModel.h" #include "vehicle/DynObj.h" #include "model/Model3d.h" @@ -41,6 +43,10 @@ http://mozilla.org/MPL/2.0/. #endif #include +#include +#include + +#include "audio/audiorenderer.h" namespace { @@ -78,6 +84,13 @@ drivingaid_panel::update() { auto const *mover = controlled->MoverParameters; auto const *vehicledriver = controlled->Mechanik; auto const *owner = controlled->ctOwner != nullptr ? controlled->ctOwner : controlled->Mechanik; + // the numbers of the throttle and brakes lines, with the controls of the cab the driver is in + auto const readout { drivingaid::compute( drivingaid::from_movers( + *mover, + *vehicledriver->Controlling(), + drivingaid::cab_controls { + train->ggLocalBrake.SubModel != nullptr, + train->ggJointCtrl.SubModel != nullptr } ) ) }; { // throttle, velocity, speed limits and grade std::string expandedtext; @@ -118,8 +131,8 @@ drivingaid_panel::update() { std::snprintf( m_buffer.data(), m_buffer.size(), STR_C("Throttle: %3d+%d %c%s"), - mover->EIMCtrlType > 0 ? std::max(0, static_cast(100.4 * mover->eimic_real)) : vehicledriver->Controlling()->MainCtrlPos, - mover->EIMCtrlType > 0 ? vehicledriver->Controlling()->MainCtrlPos : vehicledriver->Controlling()->ScndCtrlPos, + readout.throttle_first, + readout.throttle_second, mover->SpeedCtrlUnit.IsActive ? 'T' : mover->DirActive > 0 ? 'D' : mover->DirActive < 0 ? 'R' : @@ -139,16 +152,32 @@ drivingaid_panel::update() { mover->PipePress * 100 ); expandedtext = m_buffer.data(); } - auto const basicbraking { mover->fBrakeCtrlPos }; - auto const eimicbraking { std::max( 0.0, -100.0 * mover->eimic_real ) }; - std::snprintf( - m_buffer.data(), m_buffer.size(), - STR_C("Brakes: %5.1f+%-2.0f%c%s"), -// ( mover->EIMCtrlType == 0 ? basicbraking : mover->EIMCtrlType == 3 ? ( mover->UniCtrlIntegratedBrakeCtrl ? eimicbraking : basicbraking ) : eimicbraking ), - mover->UniCtrlIntegratedBrakeCtrl ? eimicbraking : basicbraking, - mover->LocalBrakePosA * LocalBrakePosNo, - mover->SlippingWheels ? '!' : ' ', - expandedtext.c_str() ); + if( readout.ed_percent ) { + // the ED braking demand, ahead of the expanded data (eu07/maszyna#558) + std::snprintf( + m_buffer.data(), m_buffer.size(), + STR_C(" ED brake: %d%%%%"), + *readout.ed_percent ); + expandedtext.insert( 0, m_buffer.data() ); + } + if( readout.show_local_brake ) { + std::snprintf( + m_buffer.data(), m_buffer.size(), + STR_C("Brakes: %5.1f+%-2.0f%c%s"), + readout.brake_first, + readout.local_brake, + mover->SlippingWheels ? '!' : ' ', + expandedtext.c_str() ); + } + else { + // the cab has no local brake control: its setting is left out (eu07/maszyna#555) + std::snprintf( + m_buffer.data(), m_buffer.size(), + STR_C("Brakes: %5.1f%c%s"), + readout.brake_first, + mover->SlippingWheels ? '!' : ' ', + expandedtext.c_str() ); + } text_lines.emplace_back( m_buffer.data(), Global.UITextColor ); } @@ -328,9 +357,10 @@ timetable_panel::update() { // destination { - auto textline = Bezogonkow( owner->Relation(), true ); + // the names with the letters their files have, in utf-8 as the user interface takes it + auto textline = table.relation_caption(); if( false == textline.empty() ) { - textline += " (" + Bezogonkow( owner->TrainName(), true ) + ")"; + textline += " (" + data_name_to_utf8( owner->TrainName(), true ) + ")"; } text_lines.emplace_back( textline, Global.UITextColor ); } @@ -397,10 +427,9 @@ timetable_panel::update() { vmax += to_string( tableline->vmax, 0 ); vmax = vmax.substr( vmax.size() - 3, 3 ); // z wyrównaniem do prawej } - auto const station { ( - Bezogonkow( tableline->StationName, true ) - + " " ) - .substr( 0, 34 ) }; + // the name as the timetable spells it; in utf-8 a letter can take more than one byte, the column is + // 34 characters wide + auto const station { utf8_fit( timetable::station_caption( tableline->StationLabel ), 34 ) }; auto const location { ( ( tableline->km > 0.0 ? to_string( tableline->km, 2 ) : @@ -1159,7 +1188,7 @@ debug_panel::update_section_ai( std::vector &Output ) const { if( mechanik.VelNext == 0.0 && mechanik.eSignNext ) { // jeśli ma zapamiętany event semafora, nazwa eventu semafora - Output.emplace_back( "Current signal: " + Bezogonkow( mechanik.eSignNext->m_name ), Global.UITextColor ); + Output.emplace_back( "Current signal: " + data_name_to_utf8( mechanik.eSignNext->m_name ), Global.UITextColor ); } // distances @@ -1270,7 +1299,7 @@ debug_panel::update_section_scantable( std::vector &Output ) const { do { auto const scanline = mechanik.TableText( i ); if( scanline.empty() ) { break; } - Output.emplace_back( Bezogonkow( scanline ), Global.UITextColor ); + Output.emplace_back( data_name_to_utf8( scanline ), Global.UITextColor ); ++i; } while( i < speedtablesize ); if( Output.size() == 1 ) { @@ -1721,6 +1750,81 @@ bool debug_panel::render_section_developer() const return true; } +namespace { + +// a combo choosing one of the names, the first entry standing for the library's own choice. the names are asked for +// each time the list opens, as devices come and go. returns: true if the choice changed +template +bool name_combo( char const *Label, std::string &Value, Names_ const &Names, char const *Defaultlabel, std::string_view const Defaultvalue ) { + + auto const preview { Value == Defaultvalue ? std::string{ Defaultlabel } : Value }; + if( false == ImGui::BeginCombo( Label, preview.c_str() ) ) { return false; } + + static std::vector names; // one list per call site, as each passes its own lambda + if( ImGui::IsWindowAppearing() ) { + names = Names(); + } + auto changed { false }; + if( ImGui::Selectable( Defaultlabel, Value == Defaultvalue ) ) { + Value = Defaultvalue; + changed = true; + } + for( auto const &name : names ) { + if( ImGui::Selectable( name.c_str(), name == Value ) ) { + Value = name; + changed = true; + } + } + ImGui::EndCombo(); + return changed; +} + +// options of the audio device, applied by reopening it: output device, output mode, HRTF, limiter, mixing rate, sources +void render_audio_device_settings() { + + auto changed { false }; + changed |= name_combo( "Output device###audiodevice", Global.AudioRenderer, + [] { return audio::renderer.output_devices(); }, "System default", "" ); + changed |= name_combo( "Output mode###audiooutputmode", Global.AudioOutputMode, + [] { return std::vector{ "mono", "stereo", "stereo-basic", "uhj", "headphones", "quad", "5.1", "6.1", "7.1" }; }, + "Automatic", "auto" ); + changed |= name_combo( "HRTF###audiohrtf", Global.AudioHrtf, + [] { return std::vector{ "on", "off" }; }, "Automatic", "auto" ); + changed |= name_combo( "HRTF data set###audiohrtfprofile", Global.AudioHrtfProfile, + [] { return audio::renderer.hrtf_profiles(); }, "Library's choice", "" ); + changed |= name_combo( "Limiter###audiolimiter", Global.AudioLimiter, + [] { return std::vector{ "on", "off" }; }, "Automatic", "auto" ); + + auto frequency { Global.AudioFrequency > 0 ? std::to_string( Global.AudioFrequency ) : std::string{} }; + if( name_combo( "Mixing rate###audiofrequency", frequency, + [] { return std::vector{ "22050", "32000", "44100", "48000", "96000" }; }, "Device's", "" ) ) { + Global.AudioFrequency = ( frequency.empty() ? 0 : std::stoi( frequency ) ); + changed = true; + } + + if( changed ) { + audio::renderer.apply_device_settings(); + } +} + +// options of the sources, applied to the playing ones right away: resampler, Doppler effect, EFX +void render_audio_source_settings() { + + auto changed { false }; + changed |= name_combo( "Resampler###audioresampler", Global.AudioResampler, + [] { return audio::renderer.resamplers(); }, "Library's default", "" ); + changed |= ImGui::SliderFloat( ( to_string( Global.AudioDoppler, 2 ) + "###audiodoppler" ).c_str(), &Global.AudioDoppler, 0.0f, 1.0f, "Doppler effect" ); + changed |= ImGui::Checkbox( "Soundproofing muffles high frequencies###audiolowpass", &Global.AudioLowpass ); + changed |= ImGui::SliderFloat( ( to_string( Global.AudioAirAbsorption, 1 ) + "###audioairabsorption" ).c_str(), &Global.AudioAirAbsorption, 0.0f, 10.0f, "Air absorption" ); + + if( changed ) { + audio::renderer.apply_source_settings(); + } + ImGui::TextWrapped( "%s", audio::renderer.device_status().c_str() ); +} + +} // namespace + bool debug_panel::render_section_settings() const { @@ -1775,6 +1879,10 @@ debug_panel::render_section_settings() const { commandrelay.post(user_command::radiovolumeset, val, 0.0, GLFW_PRESS, 0); } } + if( Global.bSoundEnabled ) { + render_audio_device_settings(); + render_audio_source_settings(); + } return true; } diff --git a/application/editormode.cpp b/application/editormode.cpp index 42d6ea00f..a7c2b6ab9 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -8027,7 +8027,12 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in } if (is_press(Action)) { + // in the road window the first Esc gives up the road being drawn, the next one goes back to the selection + auto const &road{m_roadtool}; + auto const next{editor_road::tool_after_escape(road.tool, road.chain || road.branchroad != nullptr || road.branchjunction != nullptr, road.lifting)}; road_cancel(); + if (road.window && ui()->mode() != nodebank_panel::TRACK) + road_choose_tool(next); } // the first Esc drops what is going on in the track mode, the next one goes back to the selection if (is_press(Action) && ui()->mode() == nodebank_panel::TRACK) diff --git a/application/editormode.h b/application/editormode.h index 900d84383..7277872b4 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -40,6 +40,7 @@ http://mozilla.org/MPL/2.0/. #include "editor/editorSwitchStore.hpp" #include "editor/editorFillStore.hpp" #include "editor/editorSwitchCurve.hpp" +#include "editor/editorSwitchDrives.hpp" #include "editor/editorKilometrage.hpp" #include "editor/editorSpeed.hpp" #include "editor/editorRoad.hpp" @@ -2811,7 +2812,7 @@ class editor_mode : public application_mode, private editor_track::observer, pri // "a".."d" for one of a double switch, whose switches are named a..d. none for a template which isn't a drive. the ones not // described for the editor have no family (-1) std::vector const &drive_switches(std::string const &File, std::map, std::less<>> const &Variants); - std::map, std::less<>> m_drive_templates; // read once for each file + switch_drives::template_switches m_drive_templates; // read once for each file, again when the templates change // a drive set to a switch the scenery hasn't got: left by a switch deleted or renamed by hand or in an earlier editor, its events // throw nothing struct stray_drive @@ -2830,10 +2831,19 @@ class editor_mode : public application_mode, private editor_track::observer, pri std::size_t instances{0}; }; std::optional m_drives_named; + // the drives whose switch isn't in the scenery, told once a frame for the list in the switch tool and the marks in the view, and again + // after a step made, undone or redone in the frame + struct drives_stray + { + std::vector drives; + std::optional frame; // none: to be told again + std::size_t history{0}; // the revision of the undo history + }; + drives_stray m_drives_stray; // the include of a drive or a template changed: what's kept of the drives standing is read again void drives_changed(); - // the drives whose switch isn't in the scenery, checked against the tracks each time - std::vector stray_drives(bool Wait = false); + // the drives whose switch isn't in the scenery, checked against the tracks once a frame. the list holds until the next call + std::vector const &stray_drives(bool Wait = false); void render_stray_drives(); void draw_stray_drives(); scene::layer_handle output_layer(std::string const &Part) override; diff --git a/application/editormodeminimap.cpp b/application/editormodeminimap.cpp index 2717cd447..e11fe57d4 100644 --- a/application/editormodeminimap.cpp +++ b/application/editormodeminimap.cpp @@ -122,16 +122,19 @@ void minimap_tool::gather_stations() if (false == stale(m_stations_seen)) return; std::map found; - // the texts are in windows-1250; the ones of the events lost their polish letters as they were read - auto const add = [&](std::string const &Text, bool const Letters, glm::dvec3 const &Point, TTrack *Track) { + // the texts are in windows-1250; the stop points of a station can spell it with or without its polish letters + std::unordered_set lettered; + auto const add = [&](std::string const &Text, glm::dvec3 const &Point, TTrack *Track) { auto const name{stop_name(Text)}; if (name.empty()) return; auto const key{folded(name)}; auto &entry{found[key]}; entry.key = key; + // the station is shown by a spelling with the letters, when any of its stop points has one + auto const letters{std::ranges::any_of(name, [](char const Character) { return static_cast(Character) >= 0x80; })}; // the timetables join the words with underscores - if (entry.name.empty() || Letters) + if (entry.name.empty() || (letters && lettered.insert(key).second)) { entry.name = win1250_to_utf8(name); std::replace(entry.name.begin(), entry.name.end(), '_', ' '); @@ -145,10 +148,10 @@ void minimap_tool::gather_stations() }; for (auto *cell : simulation::Memory.sequence()) if (cell != nullptr && cell->Text().starts_with(stop_prefix)) - add(cell->Text(), true, cell->location(), cell->Track); + add(cell->Text(), cell->location(), cell->Track); for (auto *event : simulation::Events.sequence()) if (auto const *values{dynamic_cast(event)}; values != nullptr && values->input_command() == TCommandType::cm_PassengerStopPoint) - add(values->input_text(), false, values->input_location(), nullptr); + add(values->input_text(), values->input_location(), nullptr); std::vector stations; for (auto &entry : found) stations.push_back(std::move(entry.second)); diff --git a/application/editormoderoad.cpp b/application/editormoderoad.cpp index 7c2a69da3..917699037 100644 --- a/application/editormoderoad.cpp +++ b/application/editormoderoad.cpp @@ -1026,7 +1026,8 @@ editor_mode::road_plan editor_mode::road_preview(bool const Fresh) auto const centre{road != nullptr ? road->definition().point(t) : junction->definition().centre}; // seen from the junction the road comes from where it's being led from glm::dvec2 const from{tool.point.x - centre.x, tool.point.z - centre.z}; - if (false == (road != nullptr ? editor_road::branch_from(*road, t, from, arriving, leaving, lanewidth, plan.end, plan.error) : editor_road::branch_from(*junction, from, arriving, leaving, lanewidth, plan.end, plan.error))) + if (false == (road != nullptr ? editor_road::branch_from(*road, t, from, arriving, leaving, lanewidth, layout.surfacetype, plan.end, plan.error) : + editor_road::branch_from(*junction, from, arriving, leaving, lanewidth, layout.surfacetype, plan.end, plan.error))) return plan; plan.hasend = true; auto const &arm{plan.end.layout.arms[plan.end.arm]}; @@ -1057,8 +1058,9 @@ editor_mode::road_plan editor_mode::road_preview(bool const Fresh) return plan; } // the axis of the road goes away from the junction, so the lanes going against it are the ones leading into the junction - if (false == (tool.branchroad != nullptr ? editor_road::branch_from(*tool.branchroad, tool.branchat, away, layout.backward, layout.forward, lanewidth, plan.start, plan.error) : - editor_road::branch_from(*tool.branchjunction, away, layout.backward, layout.forward, lanewidth, plan.start, plan.error))) + if (false == (tool.branchroad != nullptr ? + editor_road::branch_from(*tool.branchroad, tool.branchat, away, layout.backward, layout.forward, lanewidth, layout.surfacetype, plan.start, plan.error) : + editor_road::branch_from(*tool.branchjunction, away, layout.backward, layout.forward, lanewidth, layout.surfacetype, plan.start, plan.error))) return plan; plan.hasstart = true; auto const &arm{plan.start.layout.arms[plan.start.arm]}; @@ -1091,7 +1093,8 @@ editor_mode::road_plan editor_mode::road_preview(bool const Fresh) plan.error = STR_C("Too far from the last point"); return plan; } - plan.pieces = editor_road::plan(start, hasdirection ? &direction : nullptr, target, tied ? &enddirection : nullptr, Global.ctrlState, plan.error); + plan.pieces = editor_road::plan(start, hasdirection ? &direction : nullptr, target, tied ? &enddirection : nullptr, Global.ctrlState, layout.surfacetype, + 0.5 * std::max(layout.span(0.0), layout.span(1.0)), plan.error); road_profile(plan.pieces, hasgrade ? &startgrade : nullptr, tied ? &endgrade : nullptr, Fresh); return plan; } @@ -2129,6 +2132,28 @@ bool editor_mode::render_road_layout(road_node::state &State) // appearance ImGui::Separator(); + // what the road is made of sets how tight it can be laid out, and a road made dirt gets the look of a field road + char const *surfacetypes[]{STR_C("paved"), STR_C("dirt")}; + int surfacetype{State.surfacetype == road_surface_type::dirt ? 1 : 0}; + ImGui::SetNextItemWidth(120.0f); + if (ImGui::Combo(STR_C("Road type"), &surfacetype, surfacetypes, 2)) + { + auto const previous{State.surfacetype}; + State.surfacetype = (surfacetype == 1 ? road_surface_type::dirt : road_surface_type::paved); + if (State.surfacetype != previous) + { + // a surface left as the other type has it goes with the type, a surface picked by hand stays + if (State.surface == road_surface::default_material(previous)) + State.surface = road_surface::default_material(State.surfacetype); + if (State.surfacetype == road_surface_type::dirt && State.markings == road_node::marking_colour::white) + State.markings = road_node::marking_colour::none; + changed = true; + } + } + item_tooltip("Paved: asphalt, concrete or setts, with the bends and the junction angles of a built road.\n" + "Dirt: a track between fields or through a forest. It bends tighter (3 m radius instead of 6 m), can be shorter (1 m instead of 2 m),\n" + "leaves other roads at sharper angles (15 degrees instead of 30) and can turn back in a hairpin.\n" + "Made dirt, a road with the default asphalt gets the field road texture and loses the white lines"); char const *colours[]{STR_C("no markings"), STR_C("white"), STR_C("orange")}; int colour{State.markings == road_node::marking_colour::white ? 1 : State.markings == road_node::marking_colour::orange ? 2 : 0}; ImGui::SetNextItemWidth(120.0f); diff --git a/application/editormodeswitchdrive.cpp b/application/editormodeswitchdrive.cpp index 931350af1..e9e6a6313 100644 --- a/application/editormodeswitchdrive.cpp +++ b/application/editormodeswitchdrive.cpp @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "application/editorprojection.h" #include "editor/editorFormat.hpp" #include "editor/editorIncludeInfo.hpp" +#include "editor/editorSwitchDrives.hpp" #include "world/Segment.h" #include "world/Track.h" @@ -35,15 +36,14 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include namespace { std::string drive_file(std::string Text) { - std::replace(Text.begin(), Text.end(), '\\', '/'); - std::transform(Text.begin(), Text.end(), Text.begin(), [](unsigned char Character) { return static_cast(std::tolower(Character)); }); - return Text; + return switch_drives::game_name(std::move(Text)); } // the track the events of a drive find by the name: the game reads the names of the tracks lower case, the parameters of an include as @@ -54,6 +54,30 @@ TTrack *track_named(std::string const &Name) return track != nullptr ? track : simulation::Paths.find(drive_file(Name)); } +// whether the track a name finds is removed, none when it finds no track +std::optional named_removed(std::string const &Name) +{ + auto const *track{track_named(Name)}; + return track != nullptr ? std::optional{track->m_editorremoved} : std::nullopt; +} + +// the names of all the tracks of the scenery not removed +std::vector standing_names() +{ + std::vector names; + for (auto const *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_editorremoved) + names.push_back(track->name()); + return names; +} + +// the switches standing, told by the names as the events of the drives find them in the game; with no track found by a name, a track of +// the name left by the deletion of the other of two is looked for in the whole scenery +switch_drives::standing_switches switches_standing() +{ + return switch_drives::standing_switches{named_removed, standing_names}; +} + // a template by the name of its file, with no folder: told to the user, who picks the drives by their names std::string file_name(std::string const &File) { @@ -307,10 +331,8 @@ std::vector const &editor_mode::drive_switches(std::string const &F static std::vector const single{std::string{}}; if (Variants.contains(File)) return single; - auto const [found, fresh]{m_drive_templates.try_emplace(File)}; - if (fresh) - editor_includes::switched_tracks(File, found->second); - return found->second; + // a template changed is read again with the next revision of the templates, one which couldn't be read in the next frame + return m_drive_templates.of(File, EditorIncludes.revision(), ImGui::GetFrameCount(), editor_includes::switched_tracks); } std::map, std::less<>> editor_mode::drive_variants() const @@ -330,7 +352,7 @@ void editor_mode::drives_changed() m_drives_named.reset(); } -std::vector editor_mode::stray_drives(bool const Wait) +std::vector const &editor_mode::stray_drives(bool const Wait) { scan_switch_drives(Wait); auto const instances{static_cast(scene::Layers.instance_count())}; @@ -348,31 +370,38 @@ std::vector editor_mode::stray_drives(bool const Wait) drive.switches.push_back(standing.values[0] + suffix); kept->drives.push_back(std::move(drive)); } + m_drives_stray.frame.reset(); } - // a switch is told by the name, as the events of the drive find it in the game; a drive of a double switch is stray with all of its - // switches gone, while one stands it still throws it - std::vector stray; + // the list in the switch tool and the marks in the view ask in each frame: told once, and again after a step in the frame + auto &stray{m_drives_stray}; + auto const frame{ImGui::GetFrameCount()}; + auto const history{history_revision()}; + if (stray.frame == frame && stray.history == history) + return stray.drives; + stray.frame = frame; + stray.history = history; + stray.drives.clear(); + // a switch is told by the name, as the events of the drive find it in the game, by the same test the deletion of a switch takes its + // drive away by; a drive of a double switch is stray with all of its switches gone, while one stands it still throws it + auto switches{switches_standing()}; for (auto const &drive : kept->drives) { auto const &included{scene::Layers.instance(drive.instance)}; // a gate, a derailer or a turntable of the same kind of template throws a track of another kind: only a track gone counts - if (included.removed || included.dead || std::any_of(drive.switches.begin(), drive.switches.end(), [](std::string const &Name) { - auto const *track{track_named(Name)}; - return track != nullptr && false == track->m_editorremoved; - })) + if (included.removed || included.dead || switches.any_stands(drive.switches)) continue; std::string missing; for (auto const &name : drive.switches) missing += (missing.empty() ? "" : ", ") + name; - stray.push_back(drive); - stray.back().name = std::move(missing); + stray.drives.push_back(drive); + stray.drives.back().name = std::move(missing); } - return stray; + return stray.drives; } void editor_mode::render_stray_drives() { - auto const stray{stray_drives()}; + auto const &stray{stray_drives()}; if (stray.empty()) return; ImGui::PushID("straydrives"); @@ -400,7 +429,7 @@ void editor_mode::render_stray_drives() // a red mark by each drive with no switch in sight, so it's seen in the view and over the photo, not only in the list void editor_mode::draw_stray_drives() { - auto const stray{stray_drives()}; + auto const &stray{stray_drives()}; if (stray.empty()) return; // the ones far off would only crowd the view of the whole line @@ -528,13 +557,8 @@ void editor_mode::drives_deleted(std::vector const &Switches) auto const named = [&](std::string const &Name) { return std::find(deleted.begin(), deleted.end(), drive_file(Name)) != deleted.end(); }; // an older scenery may have two tracks of a name, the name finding the later; the earlier one, left by the deletion of the other, // still has the drive and the ballast, so it's looked for too - auto const stands = [](std::string const &Name) { - if (auto const *track{track_named(Name)}; track != nullptr) - return false == track->m_editorremoved; - auto const name{drive_file(Name)}; - auto const &tracks{simulation::Paths.sequence()}; - return std::any_of(tracks.begin(), tracks.end(), [&](TTrack const *Track) { return Track != nullptr && false == Track->m_editorremoved && drive_file(Track->name()) == name; }); - }; + auto switches{switches_standing()}; + auto const stands = [&switches](std::string const &Name) { return switches.stands(Name); }; auto const take_away = [&](scene::instance_handle const Instance) { if (false == scene::Layers.removable(Instance)) return; diff --git a/application/editoruipanels.cpp b/application/editoruipanels.cpp index fa78e645b..305508f4b 100644 --- a/application/editoruipanels.cpp +++ b/application/editoruipanels.cpp @@ -168,14 +168,14 @@ void itemproperties_panel::update(scene::basic_node *Node) } } */ - textline = format(STR_C("Name: %s"), (node->name().empty() ? std::string{STR_C("(no name)")} : Bezogonkow(node->name())).c_str()) + "\n" + format(STR_C("Type: %s"), node->node_type.c_str()); + textline = format(STR_C("Name: %s"), (node->name().empty() ? std::string{STR_C("(no name)")} : data_name_to_utf8(node->name())).c_str()) + "\n" + format(STR_C("Type: %s"), node->node_type.c_str()); text_lines.emplace_back(textline, Global.UITextColor); textline = format(STR_C("Location: %.2f, %.2f, %.2f (distance %.1f m)"), node->location().x, node->location().y, node->location().z, glm::length(glm::dvec3{node->location().x, 0.0, node->location().z} - glm::dvec3{camera.Pos.x, 0.0, camera.Pos.z})) + "\nUUID: " + node->uuid.to_string(); if (scene::Layers.valid(node->layer())) { - textline += "\n" + format(STR_C("Layer: %s"), Bezogonkow(scene::Layers.layer(node->layer()).name).c_str()); + textline += "\n" + format(STR_C("Layer: %s"), data_name_to_utf8(scene::Layers.layer(node->layer()).name).c_str()); } text_lines.emplace_back(textline, Global.UITextColor); @@ -288,7 +288,7 @@ void itemproperties_panel::update(scene::basic_node *Node) { textline += ", "; } - textline += event.second != nullptr ? Bezogonkow(event.second->m_name) : event.first + STR_C(" (missing)"); + textline += event.second != nullptr ? data_name_to_utf8(event.second->m_name) : event.first + STR_C(" (missing)"); } textline += "] "; } @@ -301,7 +301,7 @@ void itemproperties_panel::update(scene::basic_node *Node) textline = format(STR_C("Data: [%s] [%.2f] [%.2f]"), subnode->Text().c_str(), subnode->Value1(), subnode->Value2()); text_lines.emplace_back(textline, Global.UITextColor); - textline = format(STR_C("Track: %s"), (subnode->asTrackName.empty() ? std::string{STR_C("(none)")} : Bezogonkow(subnode->asTrackName)).c_str()); + textline = format(STR_C("Track: %s"), (subnode->asTrackName.empty() ? std::string{STR_C("(none)")} : data_name_to_utf8(subnode->asTrackName)).c_str()); text_lines.emplace_back(textline, Global.UITextColor); } @@ -890,7 +890,7 @@ void nodebank_panel::render_templates_list(std::string const &Filter) ImGui::TextDisabled(" %s", entry.category.c_str()); } category = &entry.category; - auto const label{(entry.category.empty() ? " " : " ") + entry.name + " (" + Bezogonkow(entry.file) + ")##inc" + std::to_string(entryidx)}; + auto const label{(entry.category.empty() ? " " : " ") + entry.name + " (" + data_name_to_utf8(entry.file) + ")##inc" + std::to_string(entryidx)}; if (list_item(label.c_str(), entry.statement == m_selectedtemplate)) m_selectedtemplate = entry.statement; ++listed; @@ -1706,7 +1706,7 @@ std::string layer_content(scene::basic_layer const &Layer) std::string layer_name(scene::layer_handle const Layer) { - return scene::Layers.valid(Layer) ? Bezogonkow(scene::Layers.layer(Layer).name) : std::string{STR_C("(none)")}; + return scene::Layers.valid(Layer) ? data_name_to_utf8(scene::Layers.layer(Layer).name) : std::string{STR_C("(none)")}; } // button which can be greyed out, with an explanation shown when it's hovered @@ -1750,7 +1750,7 @@ void itemproperties_panel::render_include() auto &include{*m_include}; include.active = false; - ImGui::Text(STR_C("include: %s"), Bezogonkow(include.target).c_str()); + ImGui::Text(STR_C("include: %s"), data_name_to_utf8(include.target).c_str()); if (false == include.info.name.empty()) { ImGui::TextDisabled("%s", include.info.name.c_str()); @@ -2282,7 +2282,7 @@ void includes_panel::render_list() { auto const &entry{entries[m_listed[row]]}; auto const marker{entry.complete ? std::string{STR_C("[ready]")} + " " : entry.described ? std::string{STR_C("[incomplete]")} + " " : std::string{}}; - auto const label{marker + Bezogonkow(entry.file) + (entry.name.empty() ? "" : " - " + entry.name) + "##" + std::to_string(m_listed[row])}; + auto const label{marker + data_name_to_utf8(entry.file) + (entry.name.empty() ? "" : " - " + entry.name) + "##" + std::to_string(m_listed[row])}; if (false == entry.described) { ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled)); @@ -2312,7 +2312,7 @@ void includes_panel::render_list() void includes_panel::render_description() { ImGui::Separator(); - ImGui::Text("%s", Bezogonkow(m_file).c_str()); + ImGui::Text("%s", data_name_to_utf8(m_file).c_str()); input_text(STR_C("Name"), m_info.name); input_text(STR_C("Category"), m_info.category); input_text(STR_C("Description"), m_info.description); @@ -2390,7 +2390,7 @@ void includes_panel::render_description() { std::string error; m_statuserror = false == editor_includes::save(m_file, m_info, error); - m_status = m_statuserror ? error : format(STR_C("Description saved in \"%s\""), Bezogonkow(m_file).c_str()); + m_status = m_statuserror ? error : format(STR_C("Description saved in \"%s\""), data_name_to_utf8(m_file).c_str()); if (false == m_statuserror) { EditorIncludes.update(m_file); diff --git a/application/uitranscripts.cpp b/application/uitranscripts.cpp index 7ce360530..dc0aec0eb 100644 --- a/application/uitranscripts.cpp +++ b/application/uitranscripts.cpp @@ -38,8 +38,8 @@ TTranscripts::Add( std::string const &txt, bool /*backgorund*/ ) { if( true == txt.empty() ) { return; } - std::string asciitext{ txt }; win1250_to_ascii( asciitext ); // TODO: launch relevant conversion table based on language - cParser parser( asciitext ); + // the captions are read as their files have them (windows-1250, the newer ones utf-8) and shown with their letters + cParser parser( txt ); while( true == parser.getTokens( 3, false, "[]\n" ) ) { float begin{ 0.f }; @@ -49,14 +49,14 @@ TTranscripts::Add( std::string const &txt, bool /*backgorund*/ ) { >> begin >> end >> transcript; - AddLine( transcript, static_cast(0.10 * begin), static_cast(0.12 * end), false ); + AddLine( data_text_to_utf8( transcript ), static_cast(0.10 * begin), static_cast(0.12 * end), false ); } // try to handle malformed(?) cases with no show/hide times std::string transcript; parser >> transcript; while( false == transcript.empty() ) { // WriteLog( "Transcript text with no display/hide times: \"" + transcript + "\"" ); - AddLine( transcript, 0.0, static_cast(0.12 * static_cast(transcript.size())), false ); + AddLine( data_text_to_utf8( transcript ), 0.0, static_cast(0.12 * static_cast(transcript.size())), false ); transcript = ""; parser >> transcript; } } diff --git a/audio/audio.cpp b/audio/audio.cpp index 9965909e1..7e3c3e44b 100644 --- a/audio/audio.cpp +++ b/audio/audio.cpp @@ -407,7 +407,7 @@ buffer_manager::find_file( std::string const &Filename ) const { auto const lookup { FileExists( { Filename }, - { ".ogg", ".flac", ".wav" } ) }; + { ".ogg", ".flac", ".wav", ".opus", ".mp3" } ) }; return lookup.first + lookup.second; } diff --git a/audio/audiorenderer.cpp b/audio/audiorenderer.cpp index 0d4c94ff2..b3a6f629c 100644 --- a/audio/audiorenderer.cpp +++ b/audio/audiorenderer.cpp @@ -14,14 +14,102 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Globals.h" #include "vehicle/Camera.h" #include "utilities/Logs.h" +#include "utilities/utilities.h" #include "simulation/simulation.h" #include "vehicle/Train.h" +#include +#include +#include +#include + namespace audio { openal_renderer renderer; bool event_volume_change { false }; +namespace { + +struct named_value { + std::string_view name; + ALCint value; +}; + +// values of sound.outputmode, as ALC_OUTPUT_MODE_SOFT takes them +constexpr std::array output_modes { + named_value{ "mono", ALC_MONO_SOFT }, + named_value{ "stereo", ALC_STEREO_SOFT }, + named_value{ "stereo-basic", ALC_STEREO_BASIC_SOFT }, + named_value{ "uhj", ALC_STEREO_UHJ_SOFT }, + named_value{ "headphones", ALC_STEREO_HRTF_SOFT }, + named_value{ "quad", ALC_QUAD_SOFT }, + named_value{ "5.1", ALC_SURROUND_5_1_SOFT }, + named_value{ "6.1", ALC_SURROUND_6_1_SOFT }, + named_value{ "7.1", ALC_SURROUND_7_1_SOFT } }; + +// returns: ALC_OUTPUT_MODE_SOFT value for given sound.outputmode, or nothing for auto +std::optional output_mode_value( std::string_view const Name ) { + + if( Name == "auto" ) { return std::nullopt; } + if( auto const lookup { std::ranges::find( output_modes, Name, &named_value::name ) }; lookup != std::end( output_modes ) ) { + return lookup->value; + } + WriteLog( std::format( "sound: unknown output mode \"{}\", left to the library", Name ) ); + return std::nullopt; +} + +// returns: name of given ALC_OUTPUT_MODE_SOFT value +std::string_view output_mode_name( ALCint const Value ) { + + if( auto const lookup { std::ranges::find( output_modes, Value, &named_value::value ) }; lookup != std::end( output_modes ) ) { + return lookup->name; + } + return "other"; +} + +// returns: ALC_TRUE or ALC_FALSE for given on/off option, or nothing for auto +std::optional switch_value( std::string_view const Name ) { + + if( Name == "on" ) { return ALC_TRUE; } + if( Name == "off" ) { return ALC_FALSE; } + return std::nullopt; +} + +// opens the output device of sound.openal.renderer. the library names devices in UTF-8, but the starter writes eu07.ini +// in code page 1250, so a name that fails as written is tried as 1250 text too. a device found neither way, unplugged +// say, leaves the default one rather than no sound at all. the name is set to what got opened, for a later reopen +ALCdevice *open_output_device() { + + if( Global.AudioRenderer.empty() ) { + return ::alcOpenDevice( nullptr ); + } + if( auto *device { ::alcOpenDevice( Global.AudioRenderer.c_str() ) } ) { + return device; + } + if( auto const utf8name { win1250_to_utf8( Global.AudioRenderer ) }; utf8name != Global.AudioRenderer ) { + if( auto *device { ::alcOpenDevice( utf8name.c_str() ) } ) { + Global.AudioRenderer = utf8name; + return device; + } + } + ErrorLog( std::format( "sound: audio device \"{}\" not found, the default one used", Global.AudioRenderer ) ); + Global.AudioRenderer.clear(); + return ::alcOpenDevice( nullptr ); +} + +// splits a list of null-terminated names ending with an empty name, as alcGetString gives device lists +std::vector split_name_list( ALCchar const *List ) { + + std::vector names; + while( List != nullptr && *List != '\0' ) { + auto const &name { names.emplace_back( List ) }; + List += name.size() + 1; + } + return names; +} + +} // namespace + float const EU07_SOUND_CUTOFFRANGE { 3000.f }; // 2750 m = max expected emitter spawn range, plus safety margin float const EU07_SOUND_VELOCITYLIMIT { 250 / 3.6f }; // 343 m/sec ~= speed of sound; arbitrary limit of 250 km/h @@ -94,18 +182,16 @@ openal_source::update( double const Deltatime, glm::vec3 const &Listenervelocity --sound_index; sound_change = true; // potentially adjust starting point of the last buffer (to reduce chance of reverb effect with multiple, looping copies playing) - if( controller->start() > 0.f && sounds.size() == 1 ) { - ALint bufferid; - ::alGetSourcei( - id, - AL_BUFFER, - &bufferid ); - ALint buffersize; - ::alGetBufferi( bufferid, AL_SIZE, &buffersize ); + if( controller->start() > 0.f && sounds.size() == 1 && last_buffer != audio::null_resource ) { + // NOTE: the buffer is the one queued last, not the one the source reports: for a source with queued + // buffers AL_BUFFER is 0 in OpenAL Soft 1.18 (the one the game comes with), and in the newer ones + // once the source has stopped. alGetBufferi() on buffer 0 fails with AL_INVALID_NAME + ALint buffersize { 0 }; + ::alGetBufferi( last_buffer, AL_SIZE, &buffersize ); ::alSourcei( id, AL_SAMPLE_OFFSET, - static_cast( controller->start() * ( buffersize / sizeof( std::int16_t ) ) ) ); + audio::start_sample( controller->start(), buffersize ) ); } } @@ -178,6 +264,7 @@ openal_source::sync_with( sound_properties const &State ) { sound_range : 5 ) }; // range of -1 means sound of unlimited range, positioned at the listener ::alSourcef( id, AL_REFERENCE_DISTANCE, range * ( 1.f / 16.f ) * State.soundproofing ); + renderer.soundproofing_filter( id, State.soundproofing_hf ); } if( sound_range != -1 ) { auto const rangesquared { sound_range * sound_range }; @@ -275,6 +362,7 @@ openal_renderer::~openal_renderer() { if( m_alcEventCallbackSOFT != nullptr ) { m_alcEventCallbackSOFT( nullptr, nullptr ); } // stop callbacks before teardown if( m_context != nullptr ) { m_fmradio.release(); } // the receiver owns implementation-side resources, which have to go before the context does + if( m_lowpassfilter != 0 ) { m_alDeleteFilters( 1, &m_lowpassfilter ); } ::alcMakeContextCurrent( nullptr ); @@ -327,7 +415,9 @@ openal_renderer::init() { return false; } ::alDistanceModel( AL_INVERSE_DISTANCE_CLAMPED ); - ::alDopplerFactor( 0.25f ); + ::alDopplerFactor( Global.AudioDoppler ); + m_resampler = resampler_index(); + WriteLog( "sound: " + device_status() ); // all done m_ready = true; return true; @@ -402,8 +492,9 @@ openal_renderer::update( double const Deltatime ) { // event-driven: the callback (any thread) flags default-output / device-removal changes needsreopen = m_outputchanged.exchange( false ); } - else if( m_candetectdisconnect ) { - // fallback without ALC_SOFT_system_events: poll for a hard disconnect at ~1 Hz + if( false == needsreopen && m_candetectdisconnect ) { + // poll for a hard disconnect at ~1 Hz: the fallback without ALC_SOFT_system_events, and a safety net + // with it, as not every backend reports the removal of a device m_devicechecktime += Deltatime; if( m_devicechecktime >= 1.0 ) { m_devicechecktime = 0.0; @@ -413,12 +504,15 @@ openal_renderer::update( double const Deltatime ) { } } if( needsreopen ) { - if( m_alcReopenDeviceSOFT( m_device, nullptr, m_contextattributes ) == ALC_TRUE ) { + if( m_alcReopenDeviceSOFT( m_device, nullptr, m_contextattributes.data() ) == ALC_TRUE ) { auto const *nowon { (char const *)::alcGetString( nullptr, ALC_DEFAULT_ALL_DEVICES_SPECIFIER ) }; WriteLog( "sound: audio output changed, reopened playback on \"" + std::string{ nowon ? nowon : "?" } + "\"" ); + m_reopenfailed = false; } - else { + else if( false == m_reopenfailed ) { + // with no output left the poll retries each second; the log gets it once ErrorLog( "sound: audio output changed but reopening on the default device failed (will retry)" ); + m_reopenfailed = true; } } } @@ -569,6 +663,7 @@ openal_renderer::fetch_source() { glm::vec3 zero_pos{ 0.f, 0.f, 0.f }; ::alSourcefv( newsource.id, AL_POSITION, glm::value_ptr( zero_pos ) ); ::alSourcefv( newsource.id, AL_VELOCITY, glm::value_ptr( zero_pos ) ); + configure_source( newsource.id ); } return newsource; @@ -590,7 +685,7 @@ openal_renderer::init_caps() { } // NOTE: default value of audio renderer variable is empty string, meaning argument of NULL i.e. 'preferred' device - m_device = ::alcOpenDevice( Global.AudioRenderer.empty() ? nullptr : Global.AudioRenderer.c_str() ); + m_device = open_output_device(); if( m_device == nullptr ) { ErrorLog( "Failed to obtain audio device" ); return false; @@ -611,10 +706,16 @@ openal_renderer::init_caps() { WriteLog( "Supported extensions: " + std::string{ (char *)::alcGetString( m_device, ALC_EXTENSIONS ) } ); - ALCint attr[3] = { ALC_MONO_SOURCES, Global.audio_max_sources, 0 }; // request more sounds - std::copy( std::begin( attr ), std::end( attr ), std::begin( m_contextattributes ) ); // cached for device reopen + // the device options (output mode, HRTF and the like) are known once the device is open + m_hasoutputmode = ( alcIsExtensionPresent( m_device, "ALC_SOFT_output_mode" ) == ALC_TRUE ); + m_haslimiter = ( alcIsExtensionPresent( m_device, "ALC_SOFT_output_limiter" ) == ALC_TRUE ); + if( alcIsExtensionPresent( m_device, "ALC_SOFT_HRTF" ) == ALC_TRUE ) { + m_alcGetStringiSOFT = (LPALCGETSTRINGISOFT)alcGetProcAddress( m_device, "alcGetStringiSOFT" ); + m_alcResetDeviceSOFT = (LPALCRESETDEVICESOFT)alcGetProcAddress( m_device, "alcResetDeviceSOFT" ); + } + m_contextattributes = device_attributes(); // cached for device reopen - m_context = ::alcCreateContext( m_device, attr ); + m_context = ::alcCreateContext( m_device, m_contextattributes.data() ); if( m_context == nullptr ) { ErrorLog( "Failed to create audio context" ); return false; @@ -671,7 +772,245 @@ openal_renderer::init_caps() { } } + init_extensions(); + return true; } +// resolves the entry points of the context extensions the settings use: source resampler, EFX filters +void +openal_renderer::init_extensions() { + + if( alIsExtensionPresent( "AL_SOFT_source_resampler" ) == AL_TRUE ) { + m_alGetStringiSOFT = (LPALGETSTRINGISOFT)alGetProcAddress( "alGetStringiSOFT" ); + } + if( alcIsExtensionPresent( m_device, "ALC_EXT_EFX" ) == ALC_TRUE ) { + m_alGenFilters = (LPALGENFILTERS)alGetProcAddress( "alGenFilters" ); + m_alDeleteFilters = (LPALDELETEFILTERS)alGetProcAddress( "alDeleteFilters" ); + m_alFilteri = (LPALFILTERI)alGetProcAddress( "alFilteri" ); + m_alFilterf = (LPALFILTERF)alGetProcAddress( "alFilterf" ); + m_hasefx = ( m_alGenFilters != nullptr && m_alDeleteFilters != nullptr && m_alFilteri != nullptr && m_alFilterf != nullptr ); + } + if( false == m_hasefx ) { + return; + } + ::alGetError(); + m_alGenFilters( 1, &m_lowpassfilter ); + m_alFilteri( m_lowpassfilter, AL_FILTER_TYPE, AL_FILTER_LOWPASS ); + if( ::alGetError() != AL_NO_ERROR ) { + WriteLog( "sound: warning: EFX low-pass filter not available" ); + m_lowpassfilter = 0; + } +} + +// returns: attributes of the device and the context made from the settings. with the defaults they are as before the +// settings existed, which leaves output mode, HRTF, limiter and mixing rate to the library +std::vector +openal_renderer::device_attributes() const { + + // sound.maxsources, kept for an OpenAL other than OpenAL Soft: that one gives at least 256 sources whatever is asked + std::vector attributes { ALC_MONO_SOURCES, Global.audio_max_sources }; + auto const add { [ &attributes ]( ALCint const Key, ALCint const Value ) { + attributes.push_back( Key ); + attributes.push_back( Value ); } }; + + if( auto const mode { output_mode_value( Global.AudioOutputMode ) }; mode && m_hasoutputmode ) { + add( ALC_OUTPUT_MODE_SOFT, *mode ); + } + if( m_alcGetStringiSOFT != nullptr ) { + if( auto const hrtf { switch_value( Global.AudioHrtf ) } ) { + add( ALC_HRTF_SOFT, *hrtf ); + } + if( auto const index { hrtf_index( Global.AudioHrtfProfile ) }; index >= 0 ) { + add( ALC_HRTF_ID_SOFT, index ); + } + } + if( auto const limiter { switch_value( Global.AudioLimiter ) }; limiter && m_haslimiter ) { + add( ALC_OUTPUT_LIMITER_SOFT, *limiter ); + } + if( Global.AudioFrequency > 0 ) { + add( ALC_FREQUENCY, Global.AudioFrequency ); + } + attributes.push_back( 0 ); + return attributes; +} + +// returns: index of the named HRTF data set, or -1 if the name is empty or unknown +int +openal_renderer::hrtf_index( std::string const &Name ) const { + + if( Name.empty() ) { return -1; } + auto const profiles { hrtf_profiles() }; + if( auto const lookup { std::ranges::find( profiles, Name ) }; lookup != std::end( profiles ) ) { + return static_cast( std::distance( std::begin( profiles ), lookup ) ); + } + WriteLog( std::format( "sound: unknown HRTF data set \"{}\", left to the library", Name ) ); + return -1; +} + +// returns: index of the resampler of the settings, the library's default with none set, or -1 without the extension +ALint +openal_renderer::resampler_index() const { + + if( m_alGetStringiSOFT == nullptr ) { return -1; } + if( false == Global.AudioResampler.empty() ) { + auto const names { resamplers() }; + if( auto const lookup { std::ranges::find( names, Global.AudioResampler ) }; lookup != std::end( names ) ) { + return static_cast( std::distance( std::begin( names ), lookup ) ); + } + WriteLog( std::format( "sound: unknown resampler \"{}\", the library's default used", Global.AudioResampler ) ); + } + return ::alGetInteger( AL_DEFAULT_RESAMPLER_SOFT ); +} + +// sets the options of the settings on a source +void +openal_renderer::configure_source( ALuint const Source ) const { + + if( m_resampler >= 0 ) { + ::alSourcei( Source, AL_SOURCE_RESAMPLER_SOFT, m_resampler ); + } + if( m_hasefx ) { + ::alSourcef( Source, AL_AIR_ABSORPTION_FACTOR, Global.AudioAirAbsorption ); + } +} + +// sets the EFX low-pass filter of a source for given soundproofing: the stronger the soundproofing, the more muffled +void +openal_renderer::soundproofing_filter( ALuint const Source, float const Soundproofing ) const { + + if( m_lowpassfilter == 0 ) { return; } + // a soundproofing left undefined by the data (-1, which OpenAL doesn't take as the gain either) isn't muffled + if( false == Global.AudioLowpass || Soundproofing < 0.f || Soundproofing >= 1.f ) { + ::alSourcei( Source, AL_DIRECT_FILTER, AL_FILTER_NULL ); + return; + } + // the level is set by the gain already, the filter takes away only the high frequencies + m_alFilterf( m_lowpassfilter, AL_LOWPASS_GAIN, 1.f ); + m_alFilterf( m_lowpassfilter, AL_LOWPASS_GAINHF, std::clamp( Soundproofing, 0.f, 1.f ) ); + ::alSourcei( Source, AL_DIRECT_FILTER, static_cast( m_lowpassfilter ) ); +} + +// returns: names of the output devices +std::vector +openal_renderer::output_devices() const { + + if( ::alcIsExtensionPresent( nullptr, "ALC_ENUMERATE_ALL_EXT" ) == ALC_TRUE ) { + return split_name_list( ::alcGetString( nullptr, ALC_ALL_DEVICES_SPECIFIER ) ); + } + return split_name_list( ::alcGetString( nullptr, ALC_DEVICE_SPECIFIER ) ); +} + +// returns: names of the HRTF data sets of the device +std::vector +openal_renderer::hrtf_profiles() const { + + std::vector names; + if( m_device == nullptr || m_alcGetStringiSOFT == nullptr ) { return names; } + ALCint count { 0 }; + ::alcGetIntegerv( m_device, ALC_NUM_HRTF_SPECIFIERS_SOFT, 1, &count ); + for( ALCint index = 0; index < count; ++index ) { + auto const *name { m_alcGetStringiSOFT( m_device, ALC_HRTF_SPECIFIER_SOFT, index ) }; + names.emplace_back( name != nullptr ? name : "" ); + } + return names; +} + +// returns: names of the resamplers +std::vector +openal_renderer::resamplers() const { + + std::vector names; + if( m_alGetStringiSOFT == nullptr ) { return names; } + auto const count { ::alGetInteger( AL_NUM_RESAMPLERS_SOFT ) }; + for( ALint index = 0; index < count; ++index ) { + auto const *name { m_alGetStringiSOFT( AL_RESAMPLER_NAME_SOFT, index ) }; + names.emplace_back( name != nullptr ? name : "" ); + } + return names; +} + +// returns: what the device ended up with +std::string +openal_renderer::device_status() const { + + if( m_device == nullptr ) { return "no audio device"; } + + auto const namequery { ::alcIsExtensionPresent( nullptr, "ALC_ENUMERATE_ALL_EXT" ) == ALC_TRUE ? ALC_ALL_DEVICES_SPECIFIER : ALC_DEVICE_SPECIFIER }; + auto const *devicename { ::alcGetString( m_device, namequery ) }; + ALCint frequency { 0 }; + ::alcGetIntegerv( m_device, ALC_FREQUENCY, 1, &frequency ); + auto status { std::format( "device \"{}\", {} Hz", devicename != nullptr ? devicename : "?", frequency ) }; + + if( m_hasoutputmode ) { + ALCint mode { 0 }; + ::alcGetIntegerv( m_device, ALC_OUTPUT_MODE_SOFT, 1, &mode ); + status += std::format( ", output {}", output_mode_name( mode ) ); + } + if( m_alcGetStringiSOFT != nullptr ) { + ALCint hrtf { ALC_FALSE }; + ::alcGetIntegerv( m_device, ALC_HRTF_SOFT, 1, &hrtf ); + if( hrtf == ALC_TRUE ) { + auto const *hrtfname { ::alcGetString( m_device, ALC_HRTF_SPECIFIER_SOFT ) }; + status += std::format( ", HRTF \"{}\"", hrtfname != nullptr ? hrtfname : "?" ); + } + else { + status += ", HRTF off"; + } + } + if( m_resampler >= 0 ) { + auto const *resamplername { m_alGetStringiSOFT( AL_RESAMPLER_NAME_SOFT, m_resampler ) }; + status += std::format( ", resampler {}", resamplername != nullptr ? resamplername : "?" ); + } + if( m_lowpassfilter != 0 ) { + status += ", EFX"; + } + return status; +} + +// applies changed device options without a restart: reopens the device, or resets it with an older library +bool +openal_renderer::apply_device_settings() { + + if( false == m_ready ) { return false; } + + m_contextattributes = device_attributes(); + auto applied { false }; + if( m_alcReopenDeviceSOFT != nullptr ) { + auto const *devicename { Global.AudioRenderer.empty() ? nullptr : Global.AudioRenderer.c_str() }; + applied = ( m_alcReopenDeviceSOFT( m_device, devicename, m_contextattributes.data() ) == ALC_TRUE ); + } + else if( m_alcResetDeviceSOFT != nullptr ) { + // without ALC_SOFT_reopen_device another output device takes a restart + applied = ( m_alcResetDeviceSOFT( m_device, m_contextattributes.data() ) == ALC_TRUE ); + if( applied ) { + WriteLog( "sound: this audio library can't switch the output device while running, a changed device takes a restart" ); + } + } + if( applied ) { + WriteLog( "sound: audio settings applied, " + device_status() ); + } + else { + ErrorLog( "sound: the audio device settings take a restart to apply" ); + } + return applied; +} + +// applies changed source options to every source; spare sources get them when taken +void +openal_renderer::apply_source_settings() { + + if( false == m_ready ) { return; } + + ::alDopplerFactor( Global.AudioDoppler ); + m_resampler = resampler_index(); + for( auto const &source : m_sources ) { + if( source.id != audio::null_resource ) { + configure_source( source.id ); + } + } + // the filters follow with the gain, which this flag makes every source set anew + audio::event_volume_change = true; +} + } // audio \ No newline at end of file diff --git a/audio/audiorenderer.h b/audio/audiorenderer.h index 9dbd8b168..f6e247104 100644 --- a/audio/audiorenderer.h +++ b/audio/audiorenderer.h @@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/. #include "audio/audio.h" #include "audio/fmradio.h" +#include "audio/startsample.h" #include "model/ResourceManager.h" #include "application/uitranscripts.h" @@ -48,6 +49,9 @@ struct sound_properties { sound_category category { sound_category::unknown }; float gain { 1.f }; float soundproofing { 1.f }; + // the soundproofing of what stands between the sound and the listener, without the volume trim of the sounds placed + // on top of the listener: what the low-pass filter muffles the sound by (sound.efx.lowpass) + float soundproofing_hf { 1.f }; std::uintptr_t soundproofing_stamp { ~std::uintptr_t{0} }; }; @@ -66,6 +70,7 @@ struct openal_source { using buffer_sequence = std::vector; ALuint id { audio::null_resource }; + ALuint last_buffer { audio::null_resource }; // the buffer queued last, the one left playing once those before it are done sound_source *controller { nullptr }; uint32_sequence sounds; int sound_index { 0 }; @@ -124,6 +129,20 @@ public: // provides access to the broadcast radio receiver audio::fm_radio &fmradio() { return m_fmradio; } + // choices the library offers, for the settings + std::vector output_devices() const; + std::vector hrtf_profiles() const; + std::vector resamplers() const; + // what the device ended up with: device, mixing rate, output mode, HRTF, resampler + std::string device_status() const; + // applies changed device options (sound.openal.renderer, outputmode, hrtf, limiter, frequency) + // without a restart. returns: false if the library can't do it + bool apply_device_settings(); + // applies changed source options (sound.resampler, doppler, efx.*) to every source + void apply_source_settings(); + // sets the EFX low-pass filter of a source for given soundproofing (sound.efx.lowpass) + void soundproofing_filter( ALuint const Source, float const Soundproofing ) const; + glm::dvec3 cached_camerapos; private: @@ -131,6 +150,11 @@ private: using source_sequence = std::stack; bool init_caps(); + void init_extensions(); + std::vector device_attributes() const; + int hrtf_index( std::string const &Name ) const; + ALint resampler_index() const; + void configure_source( ALuint const Source ) const; audio::openal_source fetch_source(); ALCdevice *m_device { nullptr }; @@ -152,10 +176,24 @@ private: LPALCDEVICEPAUSESOFT m_alcDevicePauseSOFT { nullptr }; LPALCDEVICERESUMESOFT m_alcDeviceResumeSOFT { nullptr }; LPALCREOPENDEVICESOFT m_alcReopenDeviceSOFT { nullptr }; + LPALCRESETDEVICESOFT m_alcResetDeviceSOFT { nullptr }; + LPALCGETSTRINGISOFT m_alcGetStringiSOFT { nullptr }; + LPALGETSTRINGISOFT m_alGetStringiSOFT { nullptr }; + LPALGENFILTERS m_alGenFilters { nullptr }; + LPALDELETEFILTERS m_alDeleteFilters { nullptr }; + LPALFILTERI m_alFilteri { nullptr }; + LPALFILTERF m_alFilterf { nullptr }; + + bool m_hasoutputmode { false }; // ALC_SOFT_output_mode + bool m_haslimiter { false }; // ALC_SOFT_output_limiter + bool m_hasefx { false }; // ALC_EXT_EFX, with its filter entry points + ALuint m_lowpassfilter { 0 }; // shared low-pass filter, its parameters are copied to a source when attached + ALint m_resampler { -1 }; // index of the resampler set on the sources, or -1 to leave the library's default bool m_candetectdisconnect { false }; - ALCint m_contextattributes[3] { 0, 0, 0 }; + std::vector m_contextattributes; // cached for device reopen double m_devicechecktime { 0.0 }; + bool m_reopenfailed { false }; // a failed reopen is retried each second, but logged once // ALC_SOFT_system_events: event-driven following of output-device / default-output changes. // Preferred over polling because it reliably catches both device removal and default changes diff --git a/audio/audiorenderer_extra.h b/audio/audiorenderer_extra.h index 430f594b3..fb38816fc 100644 --- a/audio/audiorenderer_extra.h +++ b/audio/audiorenderer_extra.h @@ -19,6 +19,7 @@ openal_source::bind( sound_source *Controller, uint32_sequence Sounds, Iterator_ if( id != audio::null_resource && !buffers.empty()) { ::alSourceQueueBuffers( id, static_cast( buffers.size() ), buffers.data() ); + last_buffer = buffers.back(); ::alSourceRewind( id ); // sound controller can potentially request playback to start from certain buffer point // for multipart sounds the offset is applied only to last piece during playback @@ -29,12 +30,12 @@ openal_source::bind( sound_source *Controller, uint32_sequence Sounds, Iterator_ } else { // move playback start to specified point in 0-1 range - ALint buffersize; + ALint buffersize { 0 }; ::alGetBufferi( buffers.front(), AL_SIZE, &buffersize ); ::alSourcei( id, AL_SAMPLE_OFFSET, - static_cast( controller->start() * ( buffersize / sizeof( std::int16_t ) ) ) ); + audio::start_sample( controller->start(), buffersize ) ); } } diff --git a/audio/sound.cpp b/audio/sound.cpp index 0cd17e0f7..426ee3cc4 100644 --- a/audio/sound.cpp +++ b/audio/sound.cpp @@ -1010,6 +1010,8 @@ sound_source::update_soundproofing() { occupiedcab ); } } + // the walls muffle the sound, the trim below only lowers its volume + m_properties.soundproofing_hf = m_properties.soundproofing; // for ambient sounds reduce their volume to account for their placement right on top of the listener if( m_range < -1 ) { m_properties.soundproofing *= 0.4f; diff --git a/audio/startsample.cpp b/audio/startsample.cpp new file mode 100644 index 000000000..673dda151 --- /dev/null +++ b/audio/startsample.cpp @@ -0,0 +1,28 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "audio/startsample.h" + +#include +#include + +namespace audio { + +int start_sample( float const Start, int const Buffersize ) { + + auto const samples { Buffersize / static_cast( sizeof( std::int16_t ) ) }; + if( samples <= 0 + || false == ( Start > 0.f ) ) { // also a NaN + return 0; + } + return std::min( static_cast( std::min( Start, 1.f ) * static_cast( samples ) ), samples - 1 ); +} + +} // audio diff --git a/audio/startsample.h b/audio/startsample.h new file mode 100644 index 000000000..e9837a3a9 --- /dev/null +++ b/audio/startsample.h @@ -0,0 +1,19 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +namespace audio { + +// the sample a sound set to start at Start (a fraction of its length, 0-1) begins to play from, in a buffer of +// Buffersize bytes of 16 bit mono samples (the sound buffers are all made so, see upload_sound()). always a sample +// the buffer has: OpenAL rejects an offset at or past the end with AL_INVALID_VALUE. 0 for an empty buffer +int start_sample( float const Start, int const Buffersize ); + +} // audio diff --git a/blackbox_doc.md b/blackbox_doc.md index 5dc8f7b71..ce2108484 100644 --- a/blackbox_doc.md +++ b/blackbox_doc.md @@ -411,7 +411,7 @@ moved more than 0.5 m or turned more than 0.05 rad. |---------|------------------------------------------------------------------------------| | `f64` | t | | `u8` | mode: 0 from the cab, 1 an outside view of the user's train, 2 the free camera, 3 the debug camera | -| `u8` | the outside view: 0 the front of the train, 1 its rear, 2 a bogie, 3 drive-by; 0 in the other modes | +| `u8` | the outside view: 0 the front of the train, 1 its rear, 2 a bogie, 3 drive-by, 4 the orbit around a vehicle, 5 the shunting view from above, 6 beside a coupling, 7 trackside; 0 in the other modes | | `u32` | number of the vehicle the camera goes with, 0 for none | | `dvec3` | position | | `f32` | heading [rad] of where it looks, as that of a vehicle: towards (sin, cos) in (x, z) | @@ -550,6 +550,26 @@ What is coupled: 0x01 the coupler, 0x02 the brake pipe, 0x04 the control (multip voltage, 0x10 the gangway, 0x20 the main reservoir pipe, 0x40 the train heating, 0x80 a coupling not to be undone in shunting (between the cars of a unit). +### 0x38 derailment + +A vehicle off the track, with `physics.derailment new` in `eu07.ini`: it doesn't follow the track any more +and moves on the ground by itself until it stops. Written when it leaves the track, and when it comes to +rest off it, looked at every second. A vehicle put back on the rails and derailed again is written again. + +| type | field | +|---------|--------------------------------------------------------------------------------| +| `f64` | t | +| `u32` | number of the vehicle | +| `u8` | 0 it left the track, 1 it came to rest off it | +| `u8` | what derailed it: 1 the flange climbed the rail, 2 it overturned in a curve, 3 the end of the track, 4 a coupling of a vehicle off the track pulled it off, 5 a collision | +| `dvec3` | position of the vehicle | +| `f32` | heading [rad] of its front, from +z towards +x | +| `f32` | speed [km/h], positive along its front | +| `f32` | offset [m] from the axis of the track at the place nearest to it, to the left of its front positive | +| `f32` | roll [rad] of its body, to the left positive: about 1.57 on its side | +| `f32` | distance [m] it went on the ground since it left the rails | +| `u8` | 1 lying on its side, 0 upright | + ### 0x3F end Last, when the simulator closes. diff --git a/directoryDescription.md b/directoryDescription.md index 6daf6a693..77d571771 100644 --- a/directoryDescription.md +++ b/directoryDescription.md @@ -21,3 +21,4 @@ | utilities/ | Logging, timing, parsing, math, globals, crash reporter | | world/ | Tracks, traction, events, memory cells, stations | | vehicle/ | Train, dynamic objects, driver, gauges, camera | +| docs/ | Documentation | diff --git a/docs/behaviour-changes.md b/docs/behaviour-changes.md new file mode 100644 index 000000000..069bb6e90 --- /dev/null +++ b/docs/behaviour-changes.md @@ -0,0 +1,135 @@ +# Behaviour changes + +Changes accepted in review that players, scenery authors or data makers can notice, for release notes and for +triaging new bug reports ("it worked differently before"). Each entry says what changed, who notices, what +data or eu07.ini it needs, and the pull request (#NNN, MaSzyna-EU07/maszyna). Written against `staging` as of +2026-11-24; the list starts at #266 (merged 2026-11-08). Keys marked "optional" change nothing until the data uses them. +#443 (2026-11-22) reverted #408 and merged `master` into `staging`; of the changes it brought from `master` only the +physics log ones, which replace those of #408, are listed here. + +The last section lists the new optional data keys, so that data makers can find them; they change nothing for +existing data. + +## Logs and files + +- **physicslog has a new last column `VehicleVelocity[km/h]`** (#266). The header line of every physics log + (`physicslog yes`, the black box tapes) changed: `WaterAuxTemp[Deg]` is now followed by a space and the new column, + the vehicle's speed (the second column is the speed of the wheels, which stays 0 while they are locked). + Notices: anyone parsing the logs by column count or by the exact header. The old columns keep their positions. + Needs: nothing. +- **Passing a signal at stop is logged in every session** (#266). The line ` passed signal at danger` + goes to the log for AI and player drivers alike, rail vehicles only, for a signal showing `SetVelocity 0 0` + (not an automatic block signal with `SetVelocity 0 x`). Before it was only counted in test runs. Notices: log.txt + of any scenery with trains running red signals. Needs: nothing. +- **The settings dump at the start of log.txt lists the `test.*` keys** (#266): `test.timeout`, `test.standstill`, + `test.pass_on_standstill`, `test.fail_if_stop_overran`, `test.no_movement_before_pass` (and `test.wall_timeout`, + `test.vehicle` when set), also in normal sessions, with their defaults. They are ignored outside the test mode. +- **The physics logs are written every 2 s by a thread of their own** (#385 on `master`, on `staging` with #443). + The files are opened only for the moment of writing; a crash loses the last 2 s. A log whose file can't be written + keeps its lines and is retried (up to 64 MB in all). `physicslog yes` still logs every driver, road vehicles + included. The closing writes out everything left, with no time limit; only the test mode stops waiting after 2 s. +- **Characters illegal in Windows file names are replaced by `_` in log file names, on every system** (#385, with + #443): a spawned vehicle `spawn_ezt:12` logs to `spawn_ezt_12.dat`. +- **`physicslog.trains yes`** (#385, with #443, new): `.dat` logs of the drivers of rail vehicles only (no passengers, + no road vehicles). **`blackbox yes|no`** (#385, with #443, new): the black box on its own; with no entry it goes with + `physicslog` (or `physicslog.trains`) as before. +- **A failed start ends with exit code 1 and the reason in the log** (#425); a closing from the player's side still + ends with 0. The crash dump written by the Windows crash handler is small by default (stacks and data segments, + tens of MB instead of the whole memory); `crashdump.full yes` brings back the full one. +- **The region cache `.sbt` is written through a temporary file and checked whole when read** (#351): a + damaged file is turned down ("Bad file: ... ignored") and the scenery loads from the text and writes the cache again. + Format unchanged. +- **Test mode** (#266, `--test`; see `tests/scenarios/README.md`): takes no input from outside, does not read the + player's own eu07.ini, writes only its verdict to the standard output, and has exit codes of its own (kept clear of 1 + and 3). + +## AI + +- **AI on a diesel with a shunting gear drives in the shunting mode** (#275). For a `DieselEngine` with + `ShuntModeAllow` (the SM03's 2Ls150 gear) the AI sets the shunting mode when its order is Shunt/Loose_shunt or the + consist is over 224 t. Before, `CurrentSwitch()` took the call for the motor overload relay threshold and the mode + was never set, so the AI always ran in the running mode. Notices: trains of SM03 on a shunting order or over 224 t + get another speed/power curve, so running times in timetables can change. The same PR makes the first move of the + SM42/SP42 switch set the shunt mode at once. Needs: nothing. +- **A Connect first order releases the hand brake** (#339). +- **The AI's wagon inspector sets G/P/R by Cw-1 par. 18-19 and cuts out the brake of wagons without G in a G train** + (#282 and its review commits). A cut-out skipped on the run is done once the train stands. `ai.brakesetting.cw1 no` + in eu07.ini restores the earlier behaviour (default yes). Notices: another brake setting of formed freight and + passenger trains, brakes cut out on some wagons. Needs: nothing. +- **Braking for a stop**: making for a passenger stop leaves room for the brake's fill time only, no look-ahead floor + (#297); the passenger-stop flag no longer flips on every scan (#295); the W4 stop point is shifted by the margin the + stop is judged by (#321); the shunting AI brakes for a stop point again (#409); gradients of 2.5 per mille and more + count as up gradients for the hold and the start (#265). Notices: stops at platforms and signals look different, + running times can move a little. +- **A reduced signal speed ends at a marked end of the interlocking area** (#305): only where the scenery puts the + `SignalAreaEnd` putvalues event. Without it the old rule holds. +- **No multiple-unit control between electric and diesel traction vehicles** (#279): `Attach()` leaves the control + connection out, also for the scenery and the AI (a Vectron and an SM42 no longer run in multiple); logged. + `controlcoupling.enginecheck no` in eu07.ini brings the old behaviour back (default yes). + +## Cab controls + +- **A lone two-state `main_sw` with a latch needs two presses to switch on after a trip** (#277). The single toggle + lever of the line breaker (no `main_on_bt`/`main_off_bt` in the cab) stays where it was put; after the breaker was + knocked out (the converter overload relay of the EP05) the first press puts the lever off, the second closes the + breaker. Applies to every cab with a lone two-state `main_sw`: e6act, ep03, ep05, et21, et22-2000, eu05, wmb10 (list + from the review; the cab files are in the SVN and were not checked here). Notices: whoever expects one press. +- **A `main_off_bt` declared `type: toggle` is the bistable hold coil lever of the ET22 and EP09** (#268): off opens the + breaker and keeps it from closing, back on only feeds the coil. Cabs keep a push button unless their `.mmd` says + `toggle`. +- **The cruise control has a switch of its own** where the secondary controller shunts the field (6Dg, ST45, BR285) + (#391): `tempomat_sw`/`tempomatoff_sw` follow the cruise control, not `ScndCtrl`. Vehicles with only one of the two + are unchanged. No new keys. +- **The compartment lights keyboard toggle** latches also in cabs without `compartmentlights_sw:` or with the on/off + push buttons (#353); the light preset selector with `Wrap=Yes` turns past its end with animation and sound (#345). +- **The HUD shows the radio channel only with the radio fuse closed**; the radio has a fuse and a hint "Close radio + fuse" (#280). +- **Door closure lamp (SOD) of the whole consist** (#291): the three-state lamp (lit locked, blinking released, dark + open) works only on vehicles with `Doors: DoorClosureSignal=Yes` in the `.fiz`. Old EN57/ED72 consists without + `DoorNeedPermit` do not get the key (they would blink at every standstill) and keep the old lamp that shows the lock + of the vehicle's own doors. The eu07.ini switch `doorclosuresignal` was removed: the data decides. Needs: the key + in the `.fiz` of the vehicle whose cab shows the lamp. +- **Separate engine start buttons work only with new data** (#294): the cab controls `mainb_*` and `mainc_*` + (`_sw`, `_on_bt`, `_off_bt`) start the second and third vehicle of a train in multiple, and `Engine: JointEngineStart=No` + stops the cab's `main_*` from touching the other vehicles. According to the data owners no cab in the SVN has + `mainb_*`/`mainc_*` yet (not checked here); without them and without `JointEngineStart=No` nothing changes + (default `Yes`). New commands `linebreakertoggleb/c`, `linebreakeropenb/c`, `linebreakercloseb/c`, no default keys. + +## Physics and scenery + +- **`physics.collisions` defaults to `new`** (#379, with #377 and #378): rail vehicle collisions past the buffers + crush the ends, a vehicle may ride up or be pushed off the track; road traffic keeps the old rule. `old` or + `monitor` in eu07.ini bring back the earlier behaviour. Notices: harder collisions, derailments of struck vehicles, + crushed ends that stay until repaired (resetconsist or repair). `physics.derailment` defaults to `monitor` (the + legacy draw decides, the log tells what the criteria would do); `new` is opt-in. `physics.trackcheck` and + `couplerphysics` (slack, hysteresis and breaking of the coupler; commits c85aab4f to 226155d4, no PR number) are + off by default. +- **Welded track buckles in the heat** (#378) when the scenery or an event sets it; no effect otherwise. +- **The cab shake is taken at the frame's moment** (#403, #414) and no longer moves in steps. +- **Station names keep their Polish letters** in the interface and timetables, a W4 finds its station by one key + (#418). A station of departure written in capitals is still a stop (#343). +- **Timetable service flags** (#398): the header row `[ Flagi AI | ... ]` and station entries such as + `kierownik=nie` change how the AI serves the train; a timetable without them drives as before. Old builds skip the + header row. +- **New putvalues commands** for sceneries: `Crew: ` puts an AI driver in a vehicle or takes + it off (#422); `SignalAreaEnd` (#305, above); the parameter `H` after the coupling of a vehicle prepares it for + hauling dead in a train, the "pullee mode" (#419). + +## Data keys that need new data + +All optional; without the key everything is as before. The data files are in the SVN, not here. + +| Key / file | What it does | Data to change | PR | +|---|---|---|---| +| `.fiz` Cntrl `SBDReleaseDelay` (s, default 0) | The holding brake of a unit with the MED (SBD) lets go only after power was demanded for that long. | Elf files with SBD would get `1.0` (its `IniCDelay`). | #424 | +| `.fiz` Engine `PressureSwitchBrakeCylinder=No`, Cntrl `EmergencyBrakeMainOff=` | Pressure switch of the EP05 with the brake pipe alone; an emergency application on a power position opens the line breaker (pantographs drop with `PantRequiresMain`). | `ep05_v2/ep05.fiz`, `ep05v1.fiz`: `No` and `2.5`. | #421 | +| `.fiz` Cntrl `PantRequiresMain=Yes` | Line breaker closes before the pantographs, on the low voltage; pantograph valve stays open only with the breaker closed; the AI closes the breaker first. | `ep05_v2`, `ep05v1`, `181_cz1.fiz`. | #272 | +| `.fiz` Cntrl `ScndCtrlResistiveLock=Yes` | The field shunt can't be stepped up or down at zero or on a resistive position; it drops to 0 there. | ET21, ET22, EP09 files. | #278 | +| `.fiz` AI `ShuntPantstate=1/2/3` | Pantographs the AI keeps up while shunting. | ET41 files (`203e-a.fiz`, `203e-b.fiz`, `_dsa150`). | #281 | +| `.fiz` Engine `EDBrake`, `EDBrakeFmax/Pmax/V0/V1/Rate/Blending` | Dynamic brake of diesel-electric vehicles. | BR285 and the like. | #394 | +| `.fiz` Doors `DoorClosureSignal=Yes` | SOD lamp of the whole consist, see above. | Vehicles with `DoorNeedPermit`. | #291 | +| `.fiz` Engine `JointEngineStart=No`, `.mmd` `mainb_*`, `mainc_*` | Separate engine start per vehicle (ST43, SP32, SN61), see above. | Cabs and `.fiz` of those vehicles. | #294 | +| `.fiz` security system `AwareOffInShuntMode=Yes` | The SM42's vigilance device (CA) is off in the shunt mode. | SM42/SP42 files. | #275 | +| `.mmd` `animdoor` per door wing | Door wings of different kinds on one side. | Vehicles with mixed doors. | #397 | +| `.mmd` `i-compartmentlights`, `radioon_sw:` etc. | New lamps and radio fuse switches. | Cabs that have them. | #352, #280 | +| eu07.ini `sound.*` | The OpenAL Soft options, each defaulting to what the simulator did before. | Optional. | #404 | diff --git a/docs/imgui_patches.md b/docs/imgui_patches.md new file mode 100644 index 000000000..3266158b5 --- /dev/null +++ b/docs/imgui_patches.md @@ -0,0 +1,52 @@ +# Local changes of the bundled ImGui + +`imgui/` holds Dear ImGui **v1.91.9b-docking** (`IMGUI_VERSION "1.91.9b"`, the docking branch: upstream tag +[`v1.91.9b-docking`](https://github.com/ocornut/imgui/tree/v1.91.9b-docking)), the GLFW, OpenGL 2 and OpenGL 3 backends +of the same tag, and ImGuizmo. The changes below are ours: an update of ImGui has to carry them over, or drop them on +purpose. Most of them are marked in the code with a `MaSzyna` comment (`grep -n MaSzyna imgui/*`), but not every +changed line is. + +Compared with the upstream tag, these files are unchanged: `imgui_demo.cpp`, `imgui_draw.cpp`, `imgui_internal.h`, +`imgui_tables.cpp`, `imstb_rectpack.h`, `imstb_textedit.h`, `imstb_truetype.h`, `LICENSE.txt` and the backend headers +(`imgui_impl_glfw.h`, `imgui_impl_opengl2.h`, `imgui_impl_opengl3.h`). The backends are in `backends/` upstream, here +next to the rest. + +## ImGui itself + +| Change | Files | Since | Used by | +|--------|-------|-------|---------| +| `io.ConfigViewportsNoAutoDetach` (default `false`): a floating window stays inside its host viewport. A resize stops at the viewport's edge, a window left past the edge or too big for it is moved back and shrunk, and it gets a viewport (an OS window) of its own only when dragged with the cursor outside the host viewport. Tooltips and popups over the main viewport, or begun outside any window, stay in the main viewport. Upstream has no such option ([#236](https://github.com/MaSzyna-EU07/maszyna/pull/236); the closest upstream report is [ocornut/imgui#9594](https://github.com/ocornut/imgui/issues/9594)) | `imgui.h` (`ImGuiIO` field), `imgui.cpp`: its default in `ImGuiIO::ImGuiIO()`; `WindowStaysInHostViewport()`, `IsWindowBeingMoved()`, `KeepWindowInsideRect()`; the resize limit in `UpdateWindowManualResize()`; two places in `Begin()` (no late viewport, window kept inside the work rect); the fallback and `ViewportAllowPlatformMonitorExtend` in `UpdateSelectWindowViewport()` | 5fa03304e (#236), be4000880, d0ca44cd6 | `application/uilayer.cpp`, with the viewports on | +| `io.ConfigTooltipsWrapWidth` (default `0`, no wrapping): the text of `SetTooltip()` / `SetItemTooltip()` wraps at that width. `BeginTooltip()` is not affected | `imgui.h` (`ImGuiIO` field), `imgui.cpp` (default, `SetTooltipV()`) | be4000880 | `application/uilayer.cpp` (40 font sizes) | +| `ImGui::BufferingBar()` and `ImGui::Spinner()`, by zfedoran from [ocornut/imgui#1901](https://github.com/ocornut/imgui/issues/1901) | `imgui.h`, end of `imgui_widgets.cpp` | ae3cecfa4 (2019, for the progress bar of the loading screen of the time), carried over in 344034ec7 | nothing at present: can be dropped | +| `#define IMGUI_IMPL_OPENGL_LOADER_CUSTOM`: the OpenGL 3 backend uses glad, loaded by the simulator, instead of its own loader | `imconfig.h` | 344034ec7 | the OpenGL 3 backend | + +## Backends + +| Change | File | Since | +|--------|------|-------| +| With multi-viewports, ImGui positions are relative to the simulator's main window instead of the desktop, so the main viewport stays at (0,0) and the overlays, picking and editor gizmo work in window coordinates as without viewports. `MainWindowOrigin` in the backend data, `ImGui_ImplGlfw_UpdateMainWindowOrigin()` called from `NewFrame()`; the origin is subtracted from the mouse position (callback and `UpdateMouseData()`), the monitors' `MainPos` / `WorkPos` and `GetWindowPos()`, and added back in `CreateWindow()` and `SetWindowPos()` | `imgui_impl_glfw.cpp` | 476f3bf1b | +| GL functions from glad (``) instead of the system's `GL/gl.h` | `imgui_impl_opengl2.cpp` | 344034ec7 | +| GL functions from glad, with `stdafx.h` and `utilities/Globals.h` included for the renderer's settings | `imgui_impl_opengl3.cpp` | 344034ec7 | +| `GlslVersionString` is 128 bytes instead of 32, for the longer GLES version string the simulator passes | `imgui_impl_opengl3.cpp` | 344034ec7 | +| Gamma of the UI follows the renderer: the vertex shaders linearise the vertex colour (`pow(Color.rgb, 2.2)`); each fragment shader's output goes through `FBOUT()`, which applies `1/2.2` when `Global.gfx_shadergamma` is set and passes it through otherwise; with desktop GL and no shader gamma `GL_FRAMEBUFFER_SRGB` is enabled while the UI is drawn and restored after | `imgui_impl_opengl3.cpp` (`RenderDrawData()`, the shader sources, `CreateDeviceObjects()`) | 344034ec7 | + +## ImGuizmo + +From [CedricGuillemet/ImGuizmo](https://github.com/CedricGuillemet/ImGuizmo), added in 5a39ed519; the upstream commit +it was taken from isn't recorded. Changed in 344034ec7 for the ImGui API of 1.91: + +- `IMGUI_DEFINE_MATH_OPERATORS` is defined before the first `#include "imgui.h"` (ImGui 1.86 and later want it so). +- `ImGui::CaptureMouseFromApp()` is replaced by `ImGui::SetNextFrameWantCaptureMouse(true)` (six places). + +And since 5a39ed519, for the ImGui of the time: + +- A compatibility shim, `#define ImAbs(X)` when `ImAbs` isn't a macro (`ImGuizmo.cpp:42-44`). ImGui 1.91 has `ImAbs` + as an inline function in `imgui_internal.h`, so the macro is always defined now and hides that function in + `ImGuizmo.cpp`. It can be dropped. + +## Checking an update + +Download the files of the new tag (`imgui*.cpp`, `imgui*.h`, `imstb_*.h`, `imconfig.h`, and from `backends/` +`imgui_impl_glfw.*`, `imgui_impl_opengl2.*`, `imgui_impl_opengl3.*`), diff the files here against the tag listed at the +top, and apply that diff to the new files. The diff of the files here against `v1.91.9b-docking` is exactly the list +above. diff --git a/track_uneven_doc.md b/docs/track_uneven_doc.md similarity index 100% rename from track_uneven_doc.md rename to docs/track_uneven_doc.md diff --git a/editor/editorHttp.cpp b/editor/editorHttp.cpp index cbda581f0..2a8c90c00 100644 --- a/editor/editorHttp.cpp +++ b/editor/editorHttp.cpp @@ -13,12 +13,20 @@ http://mozilla.org/MPL/2.0/. #if defined(_WIN32) #include #elif defined(EU07_WITH_CURL) +// of libcurl only the types and the constants: its functions are looked up at run time (libcurl() below), so the game +// starts on a system without libcurl and only the editor's downloads are off there. no deprecation warnings for the +// options kept for a libcurl older than these headers +#ifndef CURL_DISABLE_DEPRECATION +#define CURL_DISABLE_DEPRECATION +#endif #include +#include +#include +#include "utilities/Logs.h" #endif #include #include -#include #include namespace editor_http @@ -308,9 +316,10 @@ bool client::get(std::string const &Url, std::vector &Out, std::st namespace { -// the file of the certificates https is checked with. the libcurl bundled with the game knows only the one of the system it -// was built on (/etc/ssl/certs/ca-certificates.crt of Debian and Ubuntu), which Fedora, RHEL and openSUSE don't have: there -// every download failed. the file named by the user first, then the ones the distributions keep; empty leaves libcurl's own +// the file of the certificates https is checked with. a libcurl built elsewhere (as the one once bundled with the game) knows +// only the one of the system it was built on (/etc/ssl/certs/ca-certificates.crt of Debian and Ubuntu), which Fedora, RHEL +// and openSUSE don't have: there every download failed. the file named by the user first, then the ones the distributions +// keep; empty leaves libcurl's own std::string const &certificates_file() { static std::string const file{[]() { @@ -335,30 +344,99 @@ std::string const &certificates_file() }()}; return file; } + +// the functions of libcurl the client uses, looked up in the system's libcurl. their types are those the headers declare +// them with, so a call through them is the call of the function itself +struct curl_library +{ + decltype(&::curl_global_init) global_init{nullptr}; + decltype(&::curl_easy_init) easy_init{nullptr}; + decltype(&::curl_easy_cleanup) easy_cleanup{nullptr}; + decltype(&::curl_easy_reset) easy_reset{nullptr}; + decltype(&::curl_easy_setopt) easy_setopt{nullptr}; + decltype(&::curl_easy_perform) easy_perform{nullptr}; + decltype(&::curl_easy_getinfo) easy_getinfo{nullptr}; + decltype(&::curl_easy_strerror) easy_strerror{nullptr}; + bool loaded{false}; // all of them found +}; + +// the system's libcurl: the name of its runtime package (libcurl4 of Debian and Ubuntu, libcurl of Fedora and Arch), that of +// the GnuTLS build of Debian and Ubuntu, then that of its development files. null when there's none +void *open_curl() +{ + for (char const *const name : {"libcurl.so.4", "libcurl-gnutls.so.4", "libcurl.so"}) + { + if (void *const library{::dlopen(name, RTLD_NOW | RTLD_LOCAL)}; library != nullptr) + return library; + } + return nullptr; +} + +// the function Name of the library into Function, false when the library has none +template +bool resolve(void *const Library, char const *const Name, Function &Into) +{ + // dlsym() gives a function's address as void *, which POSIX lets be converted back to the function's type + Into = reinterpret_cast(::dlsym(Library, Name)); + if (Into == nullptr) + WriteLog(std::format("Editor: the libcurl of the system has no {}, the downloads of the editor are off", Name)); + return Into != nullptr; +} + +// the system's libcurl, opened and initialised once, when the editor first needs it, and kept for the rest of the run +curl_library load_curl() +{ + curl_library curl; + void *const library{open_curl()}; + if (library == nullptr) + { + WriteLog("Editor: no libcurl (libcurl.so.4) on this system, the downloads of the editor (orthophoto, terrain model, topo map) are off"); + return curl; + } + curl.loaded = resolve(library, "curl_global_init", curl.global_init) && resolve(library, "curl_easy_init", curl.easy_init) && + resolve(library, "curl_easy_cleanup", curl.easy_cleanup) && resolve(library, "curl_easy_reset", curl.easy_reset) && + resolve(library, "curl_easy_setopt", curl.easy_setopt) && resolve(library, "curl_easy_perform", curl.easy_perform) && + resolve(library, "curl_easy_getinfo", curl.easy_getinfo) && resolve(library, "curl_easy_strerror", curl.easy_strerror); + if (false == curl.loaded) + { + ::dlclose(library); + return curl_library{}; + } + curl.global_init(CURL_GLOBAL_DEFAULT); + return curl; +} + +curl_library const &libcurl() +{ + static curl_library const curl{load_curl()}; + return curl; +} } // namespace client::client() : m_platform(std::make_unique()) { - static std::once_flag initialized; - std::call_once(initialized, []() { ::curl_global_init(CURL_GLOBAL_DEFAULT); }); - m_platform->curl = ::curl_easy_init(); + if (auto const &curl{libcurl()}; curl.loaded) + m_platform->curl = curl.easy_init(); } client::~client() { + // set only with libcurl loaded if (m_platform->curl != nullptr) - ::curl_easy_cleanup(m_platform->curl); + libcurl().easy_cleanup(m_platform->curl); } bool client::get(std::string const &Url, std::vector &Out, std::string &Error, stop_check const &Stop) { Out.clear(); + auto const &curl{libcurl()}; if (m_platform->curl == nullptr) { - Error = "curl_easy_init failed"; + Error = (curl.loaded ? "curl_easy_init failed" : "no libcurl on this system"); return false; } + CURL *const handle{m_platform->curl}; struct sink { @@ -378,47 +456,52 @@ bool client::get(std::string const &Url, std::vector &Out, std::st }; auto const progress = +[](void *User, curl_off_t, curl_off_t, curl_off_t, curl_off_t) -> int { return (*static_cast(User))() ? 1 : 0; }; - ::curl_easy_reset(m_platform->curl); - ::curl_easy_setopt(m_platform->curl, CURLOPT_URL, Url.c_str()); - ::curl_easy_setopt(m_platform->curl, CURLOPT_USERAGENT, "MaSzyna-editor"); + curl.easy_reset(handle); + curl.easy_setopt(handle, CURLOPT_URL, Url.c_str()); + curl.easy_setopt(handle, CURLOPT_USERAGENT, "MaSzyna-editor"); if (auto const &certificates{certificates_file()}; false == certificates.empty()) { - ::curl_easy_setopt(m_platform->curl, CURLOPT_CAINFO, certificates.c_str()); + curl.easy_setopt(handle, CURLOPT_CAINFO, certificates.c_str()); #if LIBCURL_VERSION_NUM >= 0x073400 // an https proxy is checked with the same file - ::curl_easy_setopt(m_platform->curl, CURLOPT_PROXY_CAINFO, certificates.c_str()); + curl.easy_setopt(handle, CURLOPT_PROXY_CAINFO, certificates.c_str()); #endif } - ::curl_easy_setopt(m_platform->curl, CURLOPT_FOLLOWLOCATION, 1L); - ::curl_easy_setopt(m_platform->curl, CURLOPT_MAXREDIRS, 10L); - // http kept for the services the user types; nothing else, also where a redirect leads + curl.easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1L); + curl.easy_setopt(handle, CURLOPT_MAXREDIRS, 10L); + // http kept for the services the user types; nothing else, also where a redirect leads. the system's libcurl can be older + // than the headers: one without the options by name (before 7.85.0) refuses them, and takes the bit masks #if LIBCURL_VERSION_NUM >= 0x075500 - ::curl_easy_setopt(m_platform->curl, CURLOPT_PROTOCOLS_STR, "https,http"); - ::curl_easy_setopt(m_platform->curl, CURLOPT_REDIR_PROTOCOLS_STR, "https,http"); + bool const named{(curl.easy_setopt(handle, CURLOPT_PROTOCOLS_STR, "https,http") == CURLE_OK) && + (curl.easy_setopt(handle, CURLOPT_REDIR_PROTOCOLS_STR, "https,http") == CURLE_OK)}; #else - ::curl_easy_setopt(m_platform->curl, CURLOPT_PROTOCOLS, static_cast(CURLPROTO_HTTPS | CURLPROTO_HTTP)); - ::curl_easy_setopt(m_platform->curl, CURLOPT_REDIR_PROTOCOLS, static_cast(CURLPROTO_HTTPS | CURLPROTO_HTTP)); + bool const named{false}; #endif - ::curl_easy_setopt(m_platform->curl, CURLOPT_MAXFILESIZE_LARGE, static_cast(kLargest)); - ::curl_easy_setopt(m_platform->curl, CURLOPT_NOSIGNAL, 1L); - ::curl_easy_setopt(m_platform->curl, CURLOPT_CONNECTTIMEOUT, 10L); - ::curl_easy_setopt(m_platform->curl, CURLOPT_LOW_SPEED_LIMIT, 1L); - ::curl_easy_setopt(m_platform->curl, CURLOPT_LOW_SPEED_TIME, 20L); - ::curl_easy_setopt(m_platform->curl, CURLOPT_WRITEFUNCTION, write); - ::curl_easy_setopt(m_platform->curl, CURLOPT_WRITEDATA, &received); - ::curl_easy_setopt(m_platform->curl, CURLOPT_NOPROGRESS, 0L); - ::curl_easy_setopt(m_platform->curl, CURLOPT_XFERINFOFUNCTION, progress); - ::curl_easy_setopt(m_platform->curl, CURLOPT_XFERINFODATA, const_cast(&Stop)); + if (false == named) + { + curl.easy_setopt(handle, CURLOPT_PROTOCOLS, static_cast(CURLPROTO_HTTPS | CURLPROTO_HTTP)); + curl.easy_setopt(handle, CURLOPT_REDIR_PROTOCOLS, static_cast(CURLPROTO_HTTPS | CURLPROTO_HTTP)); + } + curl.easy_setopt(handle, CURLOPT_MAXFILESIZE_LARGE, static_cast(kLargest)); + curl.easy_setopt(handle, CURLOPT_NOSIGNAL, 1L); + curl.easy_setopt(handle, CURLOPT_CONNECTTIMEOUT, 10L); + curl.easy_setopt(handle, CURLOPT_LOW_SPEED_LIMIT, 1L); + curl.easy_setopt(handle, CURLOPT_LOW_SPEED_TIME, 20L); + curl.easy_setopt(handle, CURLOPT_WRITEFUNCTION, write); + curl.easy_setopt(handle, CURLOPT_WRITEDATA, &received); + curl.easy_setopt(handle, CURLOPT_NOPROGRESS, 0L); + curl.easy_setopt(handle, CURLOPT_XFERINFOFUNCTION, progress); + curl.easy_setopt(handle, CURLOPT_XFERINFODATA, const_cast(&Stop)); - CURLcode const code = ::curl_easy_perform(m_platform->curl); + CURLcode const code = curl.easy_perform(handle); if (code != CURLE_OK) { - Error = (received.over || code == CURLE_FILESIZE_EXCEEDED ? kTooLarge : ::curl_easy_strerror(code)); + Error = (received.over || code == CURLE_FILESIZE_EXCEEDED ? kTooLarge : curl.easy_strerror(code)); Out.clear(); return false; } long status{0}; - ::curl_easy_getinfo(m_platform->curl, CURLINFO_RESPONSE_CODE, &status); + curl.easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &status); if (status != 200) { Error = "HTTP " + std::to_string(status); @@ -443,8 +526,11 @@ bool client::get(std::string const &, std::vector &Out, std::strin bool available() { -#if defined(_WIN32) || defined(EU07_WITH_CURL) +#if defined(_WIN32) return true; +#elif defined(EU07_WITH_CURL) + // libcurl opened here when nothing needed it yet + return libcurl().loaded; #else return false; #endif diff --git a/editor/editorOrthophoto.cpp b/editor/editorOrthophoto.cpp index d3254a2c1..7ea68acae 100644 --- a/editor/editorOrthophoto.cpp +++ b/editor/editorOrthophoto.cpp @@ -739,11 +739,8 @@ editor_orthophoto::service_info editor_orthophoto::describe(std::string const &S bool editor_orthophoto::can_download() { -#if defined(_WIN32) || defined(EU07_WITH_CURL) - return true; -#else - return false; -#endif + // on Linux, whether the system has libcurl as well + return editor_http::available(); } std::string editor_orthophoto::cache_directory() diff --git a/editor/editorRingRoom.hpp b/editor/editorRingRoom.hpp new file mode 100644 index 000000000..9051da616 --- /dev/null +++ b/editor/editorRingRoom.hpp @@ -0,0 +1,63 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include + +// the room a road leaving the side of a roundabout takes of the ring, seen from above. on a straight road the edge of the road +// leaving meets the edge of the road it leaves where the two straight lines cross; the ring bends away from the road leaving it +// to the outside, so there the edges meet sooner; and a road leaving at a slant meets the edge of the ring sooner on the side +// it leans away from than on the side it leans towards +namespace editor_ring +{ + +// the shortest piece of the ring a junction leaves before the next junction, or before the end of the arc it's cut from. +// the ring goes on past it, so it can be much shorter than a road of its own; a junction which would leave less takes +// the rest of the arc, and the shorter this is the less a junction grows next to the end of an arc +double constexpr shortest_piece{0.5}; + +// how far along the axis of the ring, from the point a road leaves it, the edge of that road meets the outer edge of the ring. +// Centre: of the ring, Radius: of its axis, Point: where the axis of the road leaving meets the axis of the ring, +// Direction: the way the road leaves, Along: the way along the ring the room is measured, Halfwidth: of the ring, +// Branchhalfwidth: of the road leaving. returns: the distance along the axis of the ring, 0 if the edges cross before they get +// past the point the road leaves, or a negative value if there's no such point: the road doesn't leave towards the outside, +// or it leans so far that the edge on that side stays outside the ring all along +inline double edge_room(glm::dvec2 const &Centre, double const Radius, glm::dvec2 const &Point, glm::dvec2 const &Direction, glm::dvec2 const &Along, double const Halfwidth, + double const Branchhalfwidth) +{ + if (Radius <= 0.0 || glm::length(Direction) < 1e-9 || glm::length(Point - Centre) < 1e-9) + return -1.0; + auto const direction{glm::normalize(Direction)}; + auto const outwards{glm::normalize(Point - Centre)}; + if (glm::dot(direction, outwards) < 1e-6) + return -1.0; + // the edge of the road leaving on the side the room is measured for + glm::dvec2 side{-direction.y, direction.x}; + if (glm::dot(side, Along) < 0.0) + side = -side; + auto const start{Point - Centre + side * Branchhalfwidth}; + auto const edge{Radius + Halfwidth}; + // start + direction * t on the circle of the outer edge, where the edge leaves it going out. a road wide enough, or leaning + // far enough, has the start of that edge outside the circle already: the edges crossed before it + auto const b{glm::dot(start, direction)}; + auto const discriminant{b * b + edge * edge - glm::dot(start, start)}; + if (discriminant < 0.0) + return -1.0; + auto const t{-b + std::sqrt(discriminant)}; + auto const meet{start + direction * t}; + // the angle from the point the road leaves to that point, around the centre and the way the room is measured, carried onto the axis + auto const turn{outwards.x * Along.y - outwards.y * Along.x < 0.0 ? -1.0 : 1.0}; + auto const angle{std::atan2(turn * (outwards.x * meet.y - outwards.y * meet.x), glm::dot(outwards, meet))}; + return std::max(0.0, Radius * angle); +} + +} // namespace editor_ring diff --git a/editor/editorRoad.cpp b/editor/editorRoad.cpp index 530b9bb2a..8d6ee10c7 100644 --- a/editor/editorRoad.cpp +++ b/editor/editorRoad.cpp @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "editor/editorRoad.hpp" #include "editor/editorFormat.hpp" +#include "editor/editorRingRoom.hpp" #include "editor/editorTrack.hpp" #include "world/Track.h" @@ -19,6 +20,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Globals.h" #include "utilities/utilities.h" #include "utilities/translation.h" +#include "editor/editorRoadLimits.hpp" #include #include @@ -29,10 +31,8 @@ namespace double const kSamePoint{0.25}; // ends of two pieces this close are taken for joined double const kPieceLength{50.0}; // longest piece the planner makes double const kPieceTurn{glm::radians(30.0)}; // largest turn of a single piece -double const kShortestRoad{2.0}; -double const kTightestRadius{6.0}; +// the shortest road, the tightest bend and the sharpest angle between roads go by what the road is made of: road_limits_for() double const kCornerRoom{4.0}; // length of an arm of a junction past the point where its edge meets the edge of the next one, taken by the rounded corner -double const kSharpestBranch{glm::radians(30.0)}; // smallest angle between two roads leaving a junction double const kWidestCorner{glm::radians(120.0)}; // arms further apart than this don't have to make room for each other double const kTransitionLength{30.0}; // length of the road taken by a change of its lanes @@ -274,7 +274,9 @@ bool follow(road_node &Road, double const T, bool const Forward, double const Di auto const lengths{stations(state)}; auto const here{station_at(lengths, from)}; auto const available{forward ? lengths.back() - here : here}; - if (remaining <= 0.0 || available >= remaining + kShortestRoad) + // what's left of a piece of a roundabout carries on round, so it can be shorter than a road of its own + auto const shortest{state.roundabout ? editor_ring::shortest_piece : road_limits_for(state.surfacetype).shortest_road}; + if (remaining <= 0.0 || available >= remaining + shortest) { // the cut is put here; with nothing left to go the piece is kept whole Cut.road = piece; @@ -339,6 +341,27 @@ double edge_reach(double const Halfwidth, double const Otherhalfwidth, double co return (Otherhalfwidth + Halfwidth * std::cos(Angle)) / std::sin(Angle); } +// the circle the axis of a piece bends along at specified value of its curve parameter, seen from above. returns: false if it's straight there +bool ring_circle(road_node::state const &State, double const T, glm::dvec2 &Centre, double &Radius) +{ + auto const points{curve_points(State.axis)}; + auto const u{1.0 - T}; + auto const first{3.0 * u * u * (points[1] - points[0]) + 6.0 * u * T * (points[2] - points[1]) + 3.0 * T * T * (points[3] - points[2])}; + auto const second{6.0 * u * (points[2] - 2.0 * points[1] + points[0]) + 6.0 * T * (points[3] - 2.0 * points[2] + points[1])}; + glm::dvec2 const velocity{first.x, first.z}; + auto const speed{glm::length(velocity)}; + if (speed < 1e-9) + return false; + auto const curvature{(velocity.x * second.z - velocity.y * second.x) / (speed * speed * speed)}; + if (std::abs(curvature) < 1e-5) + return false; + auto const point{curve_point(points, T)}; + auto const tangent{velocity / speed}; + Centre = glm::dvec2{point.x, point.z} + glm::dvec2{-tangent.y, tangent.x} / curvature; + Radius = 1.0 / std::abs(curvature); + return true; +} + // the look of a junction goes after the road it's made on void dress(junction_node::state &Junction, road_node::state const &Road) { @@ -1363,12 +1386,15 @@ editor_road::loose_end editor_road::find_end(glm::dvec3 const &Point, double con return result; } -std::vector editor_road::plan(glm::dvec3 const &Start, glm::dvec2 const *Direction, glm::dvec3 const &Target, glm::dvec2 const *Enddirection, bool const Straight, std::string &Error) +std::vector editor_road::plan(glm::dvec3 const &Start, glm::dvec2 const *Direction, glm::dvec3 const &Target, glm::dvec2 const *Enddirection, bool const Straight, + road_surface_type const Type, double const Halfwidth, std::string &Error) { std::vector pieces; glm::dvec2 const chord{Target.x - Start.x, Target.z - Start.z}; auto const span{glm::length(chord)}; - if (span < kShortestRoad) + auto const limits{road_limits_for(Type)}; + auto const tightest{editor_road_limits::tightest_bend(limits, Halfwidth)}; + if (span < limits.shortest_road) { Error = "Too short"; return pieces; @@ -1388,7 +1414,7 @@ std::vector editor_road::plan(glm::dvec3 const &Start, glm::dvec2 if (Direction != nullptr && Enddirection != nullptr) { // both ends are tied, which leaves a single curve with the tangents set - if (glm::dot(*Direction, chord) < 0.1 * span || glm::dot(*Enddirection, chord) < 0.1 * span) + if (glm::dot(*Direction, chord) < limits.tied_lead * span || glm::dot(*Enddirection, chord) < limits.tied_lead * span) { Error = "The road would have to turn back to meet the end"; return pieces; @@ -1406,7 +1432,7 @@ std::vector editor_road::plan(glm::dvec3 const &Start, glm::dvec2 straight(Target); return pieces; } - if (radius < kTightestRadius) + if (radius < tightest) { Error = "The bend is too tight"; return pieces; @@ -1419,7 +1445,7 @@ std::vector editor_road::plan(glm::dvec3 const &Start, glm::dvec2 { // only the far end is tied: the same road as the one leading back from there, turned around glm::dvec2 const back{-*Enddirection}; - auto reversed{plan(Target, &back, Start, nullptr, Straight, Error)}; + auto reversed{plan(Target, &back, Start, nullptr, Straight, Type, Halfwidth, Error)}; for (auto &piece : reversed) { std::swap(piece.points[segment_data::point::start], piece.points[segment_data::point::end]); @@ -1441,7 +1467,7 @@ std::vector editor_road::plan(glm::dvec3 const &Start, glm::dvec2 auto const side{glm::dot(chord, left)}; if (Straight || std::abs(side) < 0.02 * span) { - if (along < kShortestRoad) + if (along < limits.shortest_road) { Error = "The target is behind the start"; return pieces; @@ -1451,12 +1477,12 @@ std::vector editor_road::plan(glm::dvec3 const &Start, glm::dvec2 } auto const turn{2.0 * std::atan2(side, along)}; // positive to the left auto const radius{span * span / (2.0 * side)}; // likewise - if (std::abs(turn) > glm::radians(170.0)) + if (std::abs(turn) > limits.widest_turn) { Error = "The road would have to turn back to reach the target"; return pieces; } - if (std::abs(radius) < kTightestRadius) + if (std::abs(radius) < tightest) { Error = "The bend is too tight"; return pieces; @@ -1817,7 +1843,8 @@ bool editor_road::lane_width(road_node::state const &State, double const T, floa return true; } -bool editor_road::branch_from(road_node &Road, double const T, glm::dvec2 const &Direction, int const Incoming, int const Outgoing, float const Width, branch &Result, std::string &Error) +bool editor_road::branch_from(road_node &Road, double const T, glm::dvec2 const &Direction, int const Incoming, int const Outgoing, float const Width, road_surface_type const Type, branch &Result, + std::string &Error) { Result = branch{}; auto const &layout{Road.definition()}; @@ -1826,7 +1853,7 @@ bool editor_road::branch_from(road_node &Road, double const T, glm::dvec2 const auto const direction{glm::length(Direction) > 1e-9 ? glm::normalize(Direction) : glm::dvec2{0.0, 1.0}}; // the sharper the angle the road leaves at, the further from the centre the edges of the roads part auto const angle{std::acos(std::clamp(std::abs(glm::dot(direction, along)), 0.0, 1.0))}; - if (angle < kSharpestBranch) + if (angle < road_limits_for(Type).sharpest_branch) { Error = "The road would leave at too sharp an angle"; return false; @@ -1846,11 +1873,27 @@ bool editor_road::branch_from(road_node &Road, double const T, glm::dvec2 const auto const branchhalfwidth{0.5 * (Incoming + Outgoing) * Width}; auto const reach{edge_reach(halfwidth, branchhalfwidth, angle) + kCornerRoom}; auto const branchreach{edge_reach(branchhalfwidth, halfwidth, angle) + kCornerRoom}; + // how far the junction takes the road back along it and ahead of the centre + std::array reaches{reach, reach}; + glm::dvec2 ringcentre{0.0}; + double ringradius{0.0}; + if (layout.roundabout && ring_circle(layout, T, ringcentre, ringradius)) + { + // the ring bends away from a road leaving it to the outside, so their edges meet sooner than on a straight road; and a road + // leaving at a slant meets the edge of the ring sooner on the side it leans away from. the room of a straight road, measured + // on the side the road leans towards, is the most a side takes + for (int side = 0; side < 2; ++side) + { + auto const room{editor_ring::edge_room(ringcentre, ringradius, glm::dvec2{centre.x, centre.z}, direction, side == 0 ? -along : along, halfwidth, branchhalfwidth)}; + if (room >= 0.0) + reaches[side] = std::min(reach, room + kCornerRoom); + } + } // where the road is cut on both sides of the centre road_cut cuts[2]; std::vector consumed; - if (false == follow(Road, T, false, reach, cuts[0], consumed, Error) || false == follow(Road, T, true, reach, cuts[1], consumed, Error)) + if (false == follow(Road, T, false, reaches[0], cuts[0], consumed, Error) || false == follow(Road, T, true, reaches[1], cuts[1], consumed, Error)) return false; if (cuts[0].road == cuts[1].road && cuts[0].road != &Road) { @@ -1928,7 +1971,8 @@ bool editor_road::branch_from(road_node &Road, double const T, glm::dvec2 const return true; } -bool editor_road::branch_from(junction_node &Junction, glm::dvec2 const &Direction, int const Incoming, int const Outgoing, float const Width, branch &Result, std::string &Error) +bool editor_road::branch_from(junction_node &Junction, glm::dvec2 const &Direction, int const Incoming, int const Outgoing, float const Width, road_surface_type const Type, branch &Result, + std::string &Error) { Result = branch{}; auto const &layout{Junction.definition()}; @@ -1951,7 +1995,7 @@ bool editor_road::branch_from(junction_node &Junction, glm::dvec2 const &Directi { auto const &other{layout.arms[idx]}; auto const angle{std::acos(std::clamp(glm::dot(direction, other.direction), -1.0, 1.0))}; - if (angle < kSharpestBranch) + if (angle < road_limits_for(Type).sharpest_branch) { Error = "The road would leave too close to another road of the junction"; return false; diff --git a/editor/editorRoad.hpp b/editor/editorRoad.hpp index c1b23433f..fc70f846f 100644 --- a/editor/editorRoad.hpp +++ b/editor/editorRoad.hpp @@ -142,11 +142,14 @@ class editor_road // width shared by all lanes of the road at specified value of the curve parameter of its axis. returns: false if the lanes differ in width static bool lane_width(road_node::state const &State, double const T, float &Width); // lays out a junction for a road leaving the side of specified piece at specified value of the curve parameter of its axis. - // Direction: the way the road leaves; Incoming, Outgoing: lanes of that road leading into the junction and out of it. + // Direction: the way the road leaves; Incoming, Outgoing: lanes of that road leading into the junction and out of it; + // Type: what that road is made of, which sets how sharp an angle it can leave at. // nothing is changed until the result is carried out. returns: false if it can't be done, with the reason in Error - static bool branch_from(road_node &Road, double const T, glm::dvec2 const &Direction, int const Incoming, int const Outgoing, float const Width, branch &Result, std::string &Error); + static bool branch_from(road_node &Road, double const T, glm::dvec2 const &Direction, int const Incoming, int const Outgoing, float const Width, road_surface_type const Type, branch &Result, + std::string &Error); // the same for a road leaving a junction between its arms, which gives the junction another arm - static bool branch_from(junction_node &Junction, glm::dvec2 const &Direction, int const Incoming, int const Outgoing, float const Width, branch &Result, std::string &Error); + static bool branch_from(junction_node &Junction, glm::dvec2 const &Direction, int const Incoming, int const Outgoing, float const Width, road_surface_type const Type, branch &Result, + std::string &Error); // makes the junction laid out for a branch, or gives the existing one its new arm, and cuts the roads to fit. what it does is added to Record. // returns: the junction static junction_node *carry_out(branch const &Branch, record &Record); @@ -156,8 +159,11 @@ class editor_road static loose_end find_end(glm::dvec3 const &Point, double const Radius, bool const Junctions = true); // lays out axes of the pieces for a road leading from a point to another. the directions are optional requirements // for the road at its ends; without them it starts straight at the target, with them it bends to meet them. + // Type: what the road is made of, which sets how tight it can bend and how short it can be; Halfwidth: of the road on each side + // of its axis, which no bend is tighter than (with some room). // returns: the axes in order, or nothing if there's no reasonable road to make, with the reason in Error - static std::vector plan(glm::dvec3 const &Start, glm::dvec2 const *Direction, glm::dvec3 const &Target, glm::dvec2 const *Enddirection, bool const Straight, std::string &Error); + static std::vector plan(glm::dvec3 const &Start, glm::dvec2 const *Direction, glm::dvec3 const &Target, glm::dvec2 const *Enddirection, bool const Straight, + road_surface_type const Type, double const Halfwidth, std::string &Error); // cuts the pieces so none is longer than specified static std::vector refine(std::vector const &Pieces, double const Length); // gives a string of pieces a smooth profile running through provided heights. @@ -173,6 +179,13 @@ class editor_road // Radius: of the axis of that road; Layout: what the road is like. the lanes it has along its axis are the ones the roundabout gets. // Island: what the middle is covered with, "none" to leave the ground showing static std::vector roundabout(glm::dvec3 const &Centre, double const Radius, road_node::state const &Layout, std::string const &Island); + // the tool of the road window (0 select, 1 build, 2 place) Esc leaves. while a road is being drawn, or led out of the side of + // a road or a junction, or the selected points are dragged up or down, the tool in use stays and Esc gives that up; with + // nothing going on Esc goes back to the selection + static constexpr int tool_after_escape(int const Tool, bool const Drawing, bool const Lifting) + { + return (Drawing || Lifting) ? Tool : 0; + } private: // takes down what depends on the listed pieces and junctions, lets the caller change them, then builds it all again diff --git a/editor/editorRoadLimits.hpp b/editor/editorRoadLimits.hpp new file mode 100644 index 000000000..11822c6a8 --- /dev/null +++ b/editor/editorRoadLimits.hpp @@ -0,0 +1,52 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include "world/RoadSurfaceType.h" + +#include +#include + +// how tight a road the road editor lays out, by what the road is made of +struct road_limits +{ + double tightest_radius; // smallest radius of a bend [m] + double shortest_road; // shortest road, and shortest piece left of a road cut for a junction [m] + double sharpest_branch; // smallest angle between two roads leaving a junction [rad] + // a road with both ends tied to a direction: the least part of the distance between the ends each end has to lead towards the other + double tied_lead; + double widest_turn; // a road with its start tied to a direction: the largest turn of the arc leading to the target [rad] +}; + +namespace editor_road_limits +{ + +inline constexpr double degree{std::numbers::pi / 180.0}; +// a paved road: the limits the editor had for every road before the types +inline constexpr road_limits paved{6.0, 2.0, 30.0 * degree, 0.1, 170.0 * degree}; +// a dirt road follows the ground between the fields: a tractor's bend, short stretches between the bends, a fork at a sharp angle, +// a hairpin, an end leading off square to the way to the other end +inline constexpr road_limits dirt{3.0, 1.0, 15.0 * degree, 0.0, 240.0 * degree}; +// room the inner edge of a bend keeps from the centre of the bend, as on a roundabout [m] +inline constexpr double inner_edge_room{1.0}; + +// smallest radius of a bend of a road with these limits, Halfwidth [m] wide on each side of its axis: the limit, and no less than +// leaves the inner edge of the road short of the centre of the bend, where the surface would fold over itself +inline double tightest_bend(road_limits const &Limits, double const Halfwidth) +{ + return std::max(Limits.tightest_radius, Halfwidth + inner_edge_room); +} + +} // namespace editor_road_limits + +inline constexpr road_limits road_limits_for(road_surface_type const Type) +{ + return Type == road_surface_type::dirt ? editor_road_limits::dirt : editor_road_limits::paved; +} diff --git a/editor/editorSwitchDrives.cpp b/editor/editorSwitchDrives.cpp new file mode 100644 index 000000000..8a6bbecfe --- /dev/null +++ b/editor/editorSwitchDrives.cpp @@ -0,0 +1,68 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "editor/editorSwitchDrives.hpp" + +#include +#include +#include + +namespace switch_drives +{ + +std::string game_name(std::string Name) +{ + std::ranges::replace(Name, '\\', '/'); + std::ranges::transform(Name, Name.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + return Name; +} + +standing_switches::standing_switches(finder Find, lister Names) : m_find{std::move(Find)}, m_names{std::move(Names)} {} + +bool standing_switches::stands(std::string const &Name) +{ + if (auto const removed{m_find(Name)}; removed.has_value()) + return false == *removed; + if (false == m_standing.has_value()) + { + m_standing.emplace(); + for (auto const &name : m_names()) + m_standing->insert(game_name(name)); + } + return m_standing->contains(game_name(Name)); +} + +bool standing_switches::any_stands(std::vector const &Names) +{ + return std::ranges::any_of(Names, [this](std::string const &Name) { return stands(Name); }); +} + +std::vector const &template_switches::of(std::string const &File, int const Revision, int const Frame, reader const &Read) +{ + if (m_revision != Revision) + { + m_files.clear(); + m_revision = Revision; + } + auto const [found, fresh]{m_files.try_emplace(File)}; + auto &entry{found->second}; + // read once; one that couldn't be read again in each frame at most, as each include of it asks + if (false == fresh && (false == entry.failed.has_value() || *entry.failed == Frame)) + return entry.suffixes; + entry.failed.reset(); + if (false == Read(File, entry.suffixes)) + { + entry.suffixes.clear(); + entry.failed = Frame; + } + return entry.suffixes; +} + +} // namespace switch_drives diff --git a/editor/editorSwitchDrives.hpp b/editor/editorSwitchDrives.hpp new file mode 100644 index 000000000..d21df9bec --- /dev/null +++ b/editor/editorSwitchDrives.hpp @@ -0,0 +1,76 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include +#include +#include +#include + +// what the switch tool of the editor tells of the drives of the switches, with no track and no window of its own +namespace switch_drives +{ + +// a name as the game finds a track by it: '/' for '\', lower case +std::string game_name(std::string Name); + +// whether the switches a drive throws stand in the scenery, told by their names as the events of the drive find them in the game +class standing_switches +{ + public: + // nullopt when the name finds no track, else whether the track it finds is removed + using finder = std::function(std::string const &Name)>; + // the names of all the tracks of the scenery not removed, as they're written + using lister = std::function()>; + + standing_switches(finder Find, lister Names); + + // the track the name finds stands while it isn't removed. an older scenery may have two tracks of a name, the name finding the later + // one; deleted, it takes the name away, and the earlier one left still stands, so with no track found by the name any track of this + // name not removed counts + bool stands(std::string const &Name); + // a drive of a double switch throws four of them: it still throws one while one of them stands + bool any_stands(std::vector const &Names); + + private: + finder m_find; + lister m_names; + // the game names of the tracks not removed, read once, at the first name finding none + std::optional> m_standing; +}; + +// the switches each template of a drive throws, read once from each file while the templates found stay the same: a template changed +// on the disk is found again by a rescan or by its save in the editor, either changing the revision of the templates. a file which +// can't be read is read again, in a later frame, so a template missing for a moment isn't taken for one that isn't a drive until the +// next rescan +class template_switches +{ + public: + // what follows the first parameter in the names of the switches File throws, as editor_includes::switched_tracks() tells it. + // returns: false if the file can't be read + using reader = std::function &Suffixes)>; + + // the switches File throws, none for a template which isn't a drive or can't be read. Revision: of the templates found, Frame: the + // frame asked in. the reference holds until a call with another revision + std::vector const &of(std::string const &File, int Revision, int Frame, reader const &Read); + + private: + struct entry + { + std::vector suffixes; + std::optional failed; // the frame the file couldn't be read in + }; + std::map> m_files; + std::optional m_revision; +}; + +} // namespace switch_drives diff --git a/editor/editorTrack.cpp b/editor/editorTrack.cpp index f7237655e..2504e7c5d 100644 --- a/editor/editorTrack.cpp +++ b/editor/editorTrack.cpp @@ -3397,6 +3397,9 @@ void write_ending(std::ostream &Text, TTrack const &Style, bool const Switch) if ((Style.iCategoryFlag & 15) == 1 && false == Style.m_profile1.first.empty()) Text << "railprofile " << Style.m_profile1.first << ' '; Text << track_uneven::write_attribute(Style.m_uneven, Switch); + // the welded rail goes on in the piece; a buckle stays where it was + if (false == Switch && (Style.iCategoryFlag & 15) == 1) + Text << track_buckle::write_cwr(Style.m_cwr); // a piece of the track made from another one stays in its track circuit and under the same overhead line for (auto const *isolated : Style.Isolated) Text << "isolated " << isolated->asName << ' '; diff --git a/input/command.cpp b/input/command.cpp index 30cd9e5b3..35d7f546e 100644 --- a/input/command.cpp +++ b/input/command.cpp @@ -423,6 +423,42 @@ commanddescription_sequence Commands_descriptions = { {"linebreakeropenc", command_target::vehicle, command_mode::oneoff}, {"linebreakerclosec", command_target::vehicle, command_mode::oneoff}, {"repaircoupler", command_target::simulation, command_mode::oneoff}, + {"genericset0", command_target::vehicle, command_mode::oneoff}, + {"genericset1", command_target::vehicle, command_mode::oneoff}, + {"genericset2", command_target::vehicle, command_mode::oneoff}, + {"genericset3", command_target::vehicle, command_mode::oneoff}, + {"genericset4", command_target::vehicle, command_mode::oneoff}, + {"genericset5", command_target::vehicle, command_mode::oneoff}, + {"genericset6", command_target::vehicle, command_mode::oneoff}, + {"genericset7", command_target::vehicle, command_mode::oneoff}, + {"genericset8", command_target::vehicle, command_mode::oneoff}, + {"genericset9", command_target::vehicle, command_mode::oneoff}, + {"genericset10", command_target::vehicle, command_mode::oneoff}, + {"genericset11", command_target::vehicle, command_mode::oneoff}, + {"genericset12", command_target::vehicle, command_mode::oneoff}, + {"genericset13", command_target::vehicle, command_mode::oneoff}, + {"genericset14", command_target::vehicle, command_mode::oneoff}, + {"genericset15", command_target::vehicle, command_mode::oneoff}, + {"genericset16", command_target::vehicle, command_mode::oneoff}, + {"genericset17", command_target::vehicle, command_mode::oneoff}, + {"genericset18", command_target::vehicle, command_mode::oneoff}, + {"genericset19", command_target::vehicle, command_mode::oneoff}, + {"genericset20", command_target::vehicle, command_mode::oneoff}, + {"genericset21", command_target::vehicle, command_mode::oneoff}, + {"genericset22", command_target::vehicle, command_mode::oneoff}, + {"genericset23", command_target::vehicle, command_mode::oneoff}, + {"genericset24", command_target::vehicle, command_mode::oneoff}, + {"genericset25", command_target::vehicle, command_mode::oneoff}, + {"genericset26", command_target::vehicle, command_mode::oneoff}, + {"genericset27", command_target::vehicle, command_mode::oneoff}, + {"genericset28", command_target::vehicle, command_mode::oneoff}, + {"genericset29", command_target::vehicle, command_mode::oneoff}, + {"tractionmodetoggle", command_target::vehicle, command_mode::oneoff}, + {"tractionmodecatenary", command_target::vehicle, command_mode::oneoff}, + {"tractionmodegenset", command_target::vehicle, command_mode::oneoff}, + {"gensettoggle", command_target::vehicle, command_mode::oneoff}, + {"gensetenable", command_target::vehicle, command_mode::oneoff}, + {"gensetdisable", command_target::vehicle, command_mode::oneoff}, }; // Maps of command and coresponding strings @@ -825,6 +861,42 @@ std::unordered_map const commandMap = { {"linebreakeropenc", user_command::linebreakeropenc}, {"linebreakerclosec", user_command::linebreakerclosec}, {"repaircoupler", user_command::repaircoupler}, + {"genericset0", user_command::genericset0}, + {"genericset1", user_command::genericset1}, + {"genericset2", user_command::genericset2}, + {"genericset3", user_command::genericset3}, + {"genericset4", user_command::genericset4}, + {"genericset5", user_command::genericset5}, + {"genericset6", user_command::genericset6}, + {"genericset7", user_command::genericset7}, + {"genericset8", user_command::genericset8}, + {"genericset9", user_command::genericset9}, + {"genericset10", user_command::genericset10}, + {"genericset11", user_command::genericset11}, + {"genericset12", user_command::genericset12}, + {"genericset13", user_command::genericset13}, + {"genericset14", user_command::genericset14}, + {"genericset15", user_command::genericset15}, + {"genericset16", user_command::genericset16}, + {"genericset17", user_command::genericset17}, + {"genericset18", user_command::genericset18}, + {"genericset19", user_command::genericset19}, + {"genericset20", user_command::genericset20}, + {"genericset21", user_command::genericset21}, + {"genericset22", user_command::genericset22}, + {"genericset23", user_command::genericset23}, + {"genericset24", user_command::genericset24}, + {"genericset25", user_command::genericset25}, + {"genericset26", user_command::genericset26}, + {"genericset27", user_command::genericset27}, + {"genericset28", user_command::genericset28}, + {"genericset29", user_command::genericset29}, + {"tractionmodetoggle", user_command::tractionmodetoggle}, + {"tractionmodecatenary", user_command::tractionmodecatenary}, + {"tractionmodegenset", user_command::tractionmodegenset}, + {"gensettoggle", user_command::gensettoggle}, + {"gensetenable", user_command::gensetenable}, + {"gensetdisable", user_command::gensetdisable}, {"none", user_command::none}}; } // namespace simulation diff --git a/input/command.h b/input/command.h index 01da3c183..7571a8638 100644 --- a/input/command.h +++ b/input/command.h @@ -421,6 +421,44 @@ enum class user_command linebreakeropenc, linebreakerclosec, repaircoupler, // the broken coupler of the vehicle (payload) at the end (param1) + // sets universal control N to the position given in param1, 0-1 (MaSzyna-EU07/maszyna#62) + genericset0, + genericset1, + genericset2, + genericset3, + genericset4, + genericset5, + genericset6, + genericset7, + genericset8, + genericset9, + genericset10, + genericset11, + genericset12, + genericset13, + genericset14, + genericset15, + genericset16, + genericset17, + genericset18, + genericset19, + genericset20, + genericset21, + genericset22, + genericset23, + genericset24, + genericset25, + genericset26, + genericset27, + genericset28, + genericset29, + // the traction selector and the genset of a dual-mode vehicle (eu07/maszyna#536) + tractionmodetoggle, + tractionmodecatenary, + tractionmodegenset, + gensettoggle, + gensetenable, + gensetdisable, none = -1 }; diff --git a/input/driverkeyboardinput.cpp b/input/driverkeyboardinput.cpp index 047f3678c..566a07192 100644 --- a/input/driverkeyboardinput.cpp +++ b/input/driverkeyboardinput.cpp @@ -103,6 +103,12 @@ driverkeyboard_input::default_bindings() { { fuelpumptoggle, {GLFW_KEY_F, ""} }, // fuelpumpenable, // fuelpumpdisable, + { tractionmodetoggle, {GLFW_KEY_G | keymodifier::shift, ""} }, + // tractionmodecatenary, + // tractionmodegenset, + { gensettoggle, {GLFW_KEY_G | keymodifier::control, ""} }, + // gensetenable, + // gensetdisable, { oilpumptoggle, {GLFW_KEY_F | keymodifier::shift, ""} }, // oilpumpenable, // oilpumpdisable, diff --git a/input/drivermouseinput.cpp b/input/drivermouseinput.cpp index 9749024ac..47105ac22 100644 --- a/input/drivermouseinput.cpp +++ b/input/drivermouseinput.cpp @@ -28,6 +28,8 @@ void mouse_slider::bind( user_command const &Command ) { m_command = Command; + m_universal.reset(); + m_universaldrag.reset(); auto const *train { simulation::Train }; TMoverParameters const *vehicle { nullptr }; @@ -124,18 +126,47 @@ mouse_slider::bind( user_command const &Command ) { m_analogue ? controledge - m_value * controlsize : controledge - m_value * stepsize - 0.5 * stepsize ); } +void +mouse_slider::bind_universal( int const Index, universal_drag::direction const Drag, float const Position ) { + + m_command = static_cast( static_cast( user_command::genericset0 ) + Index ); + m_universal = Index; + m_universaldrag.emplace( Drag, Position ); + m_value = m_universaldrag->position(); + m_valuerange = 1.0; + m_analogue = true; + m_invertrange = false; + // the cursor is hidden for the drag and put back where it was when the drag ends; the drag follows its moves + // from wherever it is, so it isn't placed anywhere + m_cursorposition = glm::dvec2( Global.cursor_pos ); + Application.set_cursor( GLFW_CURSOR_DISABLED ); +} + void mouse_slider::release() { m_command = user_command::none; + m_universal.reset(); + m_universaldrag.reset(); Application.set_cursor_pos( m_cursorposition.x, m_cursorposition.y ); Application.set_cursor( GLFW_CURSOR_NORMAL ); } -void -mouse_slider::on_move( double const /*Mousex*/, double const Mousey ) { +bool +mouse_slider::on_move( double const Mousex, double const Mousey ) { auto const controlsize { Global.window_size.y * EU07_CONTROLLER_MOUSESLIDERSIZE }; + + if( m_universaldrag ) { + // a universal control, dragged the same way as the controllers: the move of the cursor over the size of the + // slider takes it from one end to the other + if( false == m_universaldrag->move( Mousex, Mousey, controlsize ) ) { + return false; + } + m_value = m_universaldrag->position(); + return true; + } + auto const controledge { Global.window_size.y * 0.5 + controlsize * 0.5 }; auto const stepsize { controlsize / m_valuerange }; @@ -143,6 +174,7 @@ mouse_slider::on_move( double const /*Mousex*/, double const Mousey ) { m_value = m_analogue ? (controledge - mousey) / controlsize : std::floor((controledge - mousey) / stepsize); if( m_invertrange ) { m_value = ( m_analogue ? 1.0 : m_valuerange ) - m_value; } + return true; } @@ -246,8 +278,8 @@ drivermouse_input::move( double Mousex, double Mousey ) { } else { // control picking mode - if( m_slider.command() != user_command::none ) { - m_slider.on_move( Mousex, Mousey ); + if( m_slider.command() != user_command::none + && true == m_slider.on_move( Mousex, Mousey ) ) { m_relay.post( m_slider.command(), m_slider.value(), @@ -341,7 +373,14 @@ drivermouse_input::button( int const Button, int const Action ) { else { m_pickwaiting = false; if (Button == GLFW_MOUSE_BUTTON_LEFT && m_slider.command() != user_command::none) { - m_relay.post( m_slider.command(), 0, 0, Action, 0 ); + if( auto const universal { m_slider.universal() }; + universal && m_slider.is_click() ) { + // a universal control clicked rather than dragged goes to its end, as a click on any universal does + toggle_universal( *universal ); + } + else { + m_relay.post( m_slider.command(), 0, 0, Action, 0 ); + } m_slider.release(); } // if it's the right mouse button that got released and we had no command active, we were potentially in view panning mode; stop it @@ -392,6 +431,25 @@ drivermouse_input::button( int const Button, int const Action ) { default: { break; } } } + // a universal control with drag: in its definition is dragged to any position between its ends, + // and a click without dragging toggles it as before (MaSzyna-EU07/maszyna#62) + if( Button == GLFW_MOUSE_BUTTON_LEFT ) { + auto const universal { universal_index( mousecommand ) }; + auto const drag { + universal ? + simulation::Train->universal_drag_direction( *universal ) : + universal_drag::direction::none }; + if( drag != universal_drag::direction::none ) { + mousecommand = none; + if( false == pickwaiting ) { + // the button was let go before the control was found under the cursor: a click + toggle_universal( *universal ); + return; + } + m_slider.bind_universal( *universal, drag, simulation::Train->universal_position( *universal ) ); + return; + } + } switch( mousecommand ) { case mastercontrollerincrease: @@ -558,6 +616,9 @@ drivermouse_input::default_bindings() { { "maxcurrent_sw:", { motoroverloadrelaythresholdtoggle, none } }, + { "autorelay_sw:", { + notchingrelaytoggle, + none } }, { "waterpumpbreaker_sw:", { waterpumpbreakertoggle, none } }, @@ -579,6 +640,12 @@ drivermouse_input::default_bindings() { { "oilfuelpump_sw:", { oilfuelpumptoggle, none } }, + { "tractionmode_sw:", { + tractionmodetoggle, + none } }, + { "genset_sw:", { + gensettoggle, + none } }, { "motorblowersfront_sw:", { motorblowerstogglefront, none } }, @@ -1171,4 +1238,23 @@ drivermouse_input::adjust_command( user_command Command ) const { return Command; } +std::optional +drivermouse_input::universal_index( user_command const Command ) { + + auto const index { static_cast( Command ) - static_cast( user_command::generictoggle0 ) }; + if( index < 0 + || index > static_cast( user_command::generictoggle29 ) - static_cast( user_command::generictoggle0 ) ) { + return std::nullopt; + } + return index; +} + +void +drivermouse_input::toggle_universal( int const Index ) const { + + auto const toggle { static_cast( static_cast( user_command::generictoggle0 ) + Index ) }; + m_relay.post( toggle, 0, 0, GLFW_PRESS, 0 ); + m_relay.post( toggle, 0, 0, GLFW_RELEASE, 0 ); +} + //--------------------------------------------------------------------------- diff --git a/input/drivermouseinput.h b/input/drivermouseinput.h index 180e0335c..aa2ac0ca3 100644 --- a/input/drivermouseinput.h +++ b/input/drivermouseinput.h @@ -9,8 +9,10 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include #include #include "input/command.h" +#include "vehicle/universaldrag.h" // virtual slider; value determined by position of the mouse class mouse_slider { @@ -21,9 +23,14 @@ public: // methods void bind( user_command const &Command ); + // binds the slider to universal control Index, which the mouse drags in the Drag direction from its Position + // to any position between its ends (MaSzyna-EU07/maszyna#62) + void + bind_universal( int const Index, universal_drag::direction const Drag, float const Position ); void release(); - void + // returns whether the value changed + bool on_move( double const Mousex, double const Mousey ); inline user_command @@ -32,10 +39,19 @@ public: double value() const { return m_value; } + // the universal control the slider drags, if any, and whether letting it go now is a click rather than a drag + std::optional + universal() const { + return m_universal; } + bool + is_click() const { + return m_universaldrag && m_universaldrag->is_click(); } private: // members user_command m_command { user_command::none }; + std::optional m_universal; // the universal control dragged, if any + std::optional m_universaldrag; double m_value { 0.0 }; double m_valuerange { 0.0 }; bool m_analogue { false }; @@ -92,6 +108,12 @@ private: // potentially replaces supplied command with a more relevant one user_command adjust_command( user_command Command ) const; + // the universal control a command toggles, if it toggles one + static std::optional + universal_index( user_command const Command ); + // toggles universal control Index, as a click on it does + void + toggle_universal( int const Index ) const; // members command_relay m_relay; diff --git a/lang/editor_pl.po b/lang/editor_pl.po index 34bceaf7b..402185a27 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -8123,6 +8123,18 @@ msgstr "Pas rozwidla się najwyżej na trzy: na pasy dodane ponad dwa nie da si msgid "Lane width [m]" msgstr "Szerokość pasa (m)" +msgid "paved" +msgstr "utwardzona" + +msgid "dirt" +msgstr "gruntowa" + +msgid "Road type" +msgstr "Rodzaj drogi" + +msgid "Paved: asphalt, concrete or setts, with the bends and the junction angles of a built road.\nDirt: a track between fields or through a forest. It bends tighter (3 m radius instead of 6 m), can be shorter (1 m instead of 2 m),\nleaves other roads at sharper angles (15 degrees instead of 30) and can turn back in a hairpin.\nMade dirt, a road with the default asphalt gets the field road texture and loses the white lines" +msgstr "Utwardzona: asfalt, beton albo kostka, z łukami i kątami skrzyżowań jak na drodze budowanej.\nGruntowa: droga polna albo leśna. Skręca ciaśniej (promień 3 m zamiast 6 m), może być krótsza (1 m zamiast 2 m),\nodchodzi od innych dróg pod ostrzejszym kątem (15 stopni zamiast 30) i może zawrócić serpentyną.\nDroga z domyślnym asfaltem zmieniona na gruntową dostaje teksturę drogi polnej i traci białe linie" + msgid "Left side" msgstr "Lewa strona" diff --git a/launcher/scenery_wizard.cpp b/launcher/scenery_wizard.cpp index 250ff508d..d7bfd7f5d 100644 --- a/launcher/scenery_wizard.cpp +++ b/launcher/scenery_wizard.cpp @@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/translation.h" #include "rendering/renderer.h" +#include "utilities/utilities.h" #include #include @@ -26,6 +27,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include namespace @@ -400,8 +402,8 @@ bool ui::scenerywizard_panel::create_scenery() return false; } auto const now{std::time(nullptr)}; - char date[32]; - std::strftime(date, sizeof(date), "%Y-%m-%d", std::localtime(&now)); + std::tm const local{local_tm(now)}; + auto const date{std::format("{:04}-{:02}-{:02}", local.tm_year + 1900, local.tm_mon + 1, local.tm_mday)}; char reference[96]; std::snprintf(reference, sizeof(reference), "//$g PUWG1992 %.3f %.3f", m_map.point().x / 1000.0, m_map.point().y / 1000.0); auto const area{range()}; diff --git a/launcher/textures_scanner.cpp b/launcher/textures_scanner.cpp index 741f978ca..480bd5671 100644 --- a/launcher/textures_scanner.cpp +++ b/launcher/textures_scanner.cpp @@ -9,8 +9,18 @@ void ui::vehicles_bank::scan_textures() if (f->path().filename() != "textures.txt") continue; + auto const folder{std::filesystem::relative(f->path().parent_path(), "dynamic/", error)}; + try { + // the vehicles are kept by narrow names. on Windows a folder named with a character the code page lacks + // can't be given one and would throw at the first vehicle; the game couldn't load it by that name anyway + [[maybe_unused]] auto const name{folder.generic_string()}; + } + catch (std::system_error const &) { + continue; + } + ctx_path = folder; + std::fstream stream(f->path(), std::ios_base::binary | std::ios_base::in); - ctx_path = std::filesystem::relative(f->path().parent_path(), "dynamic/", error); std::string line; while (std::getline(stream, line)) diff --git a/model/Model3d.cpp b/model/Model3d.cpp index 4fa3e0d5c..474c0f215 100644 --- a/model/Model3d.cpp +++ b/model/Model3d.cpp @@ -24,6 +24,7 @@ Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others #include "simulation/simulationtime.h" #include "world/mtable.h" #include "scene/sn_utils.h" +#include "utilities/wholefile.h" #include @@ -2837,20 +2838,8 @@ void TModel3d::LoadFromBinFile(std::string const &FileName, bool dynamic) WriteLog("Loading binary format 3d model data from \"" + FileName + "\"...", logtype::model); // the file is read whole in one go and parsed from memory - std::unique_ptr filedata; - std::size_t filesize{0}; - { - std::ifstream input(FileName, std::ios::binary | std::ios::ate); - auto const length{input.tellg()}; - if (length > 0) - { - filedata.reset(new char[static_cast(length)]); - input.seekg(0); - input.read(filedata.get(), length); - filesize = static_cast(input.gcount()); - } - } - e3d_memorybuffer buffer(filedata.get(), filedata.get() + filesize); + auto const filedata{read_whole_file(FileName)}; + e3d_memorybuffer buffer(filedata.data.get(), filedata.data.get() + filedata.size); std::istream file(&buffer); uint32_t type = sn_utils::ld_uint32(file); diff --git a/model/material.cpp b/model/material.cpp index 80f2f0657..4c94d1f7e 100644 --- a/model/material.cpp +++ b/model/material.cpp @@ -86,11 +86,11 @@ int opengl_material::texture_slot( std::string const &Key ) // named binding, the slot it fills is up to the shader key.erase( 0, 1 ); key.pop_back(); - if( shader && ( shader->texture_conf.find( key ) != shader->texture_conf.end() ) ) { + if( shader && shader->texture_conf.contains( key ) ) { return static_cast( shader->texture_conf[ key ].id ); } - auto const lookup { texture_bindings.find( key ) }; - if( ( shader == nullptr ) && ( lookup != texture_bindings.end() ) ) { + if( auto const lookup { texture_bindings.find( key ) }; + ( shader == nullptr ) && ( lookup != texture_bindings.end() ) ) { return lookup->second; } // ignore unrecognized texture bindings in legacy render mode, it's most likely data for more advanced shaders @@ -358,7 +358,7 @@ std::unordered_set seasons = { bool is_season( std::string const &String ) { - return seasons.find(String) != seasons.end(); + return seasons.contains(String); } std::unordered_set weather = { @@ -366,7 +366,7 @@ std::unordered_set weather = { bool is_weather( std::string const &String ) { - return weather.find(String) != weather.end(); + return weather.contains(String); } // imports member data pair from the config file @@ -402,7 +402,7 @@ void opengl_material::deserialize_texture_mapping( cParser &Input, std::string c value = variants.front(); } - auto const [ it, inserted ] { parse_info->tex_mapping.try_emplace( key, parse_info_s::tex_def{ value, Priority, variants } ) }; + auto const [ it, inserted ] { parse_info->tex_mapping.try_emplace( key, value, Priority, variants ) }; if( ( false == inserted ) && ( Priority > it->second.priority ) ) { it->second = parse_info_s::tex_def{ value, Priority, variants }; } @@ -429,7 +429,7 @@ opengl_material::deserialize_mapping( cParser &Input, int const Priority, bool c // skip the opening bracket auto const value { Input.getToken( true, "\n\r\t ;" ) }; while( true == deserialize_mapping( Input, Priority + 2, Loadnow ) ) { - ; // all work is done in the header + // all work is done in the header } } else if( key == Global.Season ) { @@ -437,7 +437,7 @@ opengl_material::deserialize_mapping( cParser &Input, int const Priority, bool c // skip the opening bracket auto const value { Input.getToken( true, "\n\r\t ;" ) }; while( true == deserialize_mapping( Input, Priority + 1, Loadnow ) ) { - ; // all work is done in the header + // all work is done in the header } } @@ -517,7 +517,7 @@ opengl_material::deserialize_mapping( cParser &Input, int const Priority, bool c // unrecognized or ignored token, but comes with attribute block and potential further nesting // go through it and discard the content while( true == deserialize_mapping( Input, -1, Loadnow ) ) { - ; // all work is done in the header + // all work is done in the header } } } @@ -529,7 +529,7 @@ opengl_material::deserialize_mapping( cParser &Input, int const Priority, bool c // ignored tokens can come with their own blocks, ignore these recursively // go through it and discard the content while( true == deserialize_mapping( Input, -1, Loadnow ) ) { - ; // all work is done in the header + // all work is done in the header } } } diff --git a/network/network.cpp b/network/network.cpp index b5eeced42..1bd02267d 100644 --- a/network/network.cpp +++ b/network/network.cpp @@ -244,6 +244,7 @@ void network::client::handle_message(std::shared_ptr Connection, con if (!Global.ready_to_load) { Global.random_seed = cmd.seed; + Global.random_seed_given = true; Global.random_engine.seed(Global.random_seed); Global.starting_timestamp = cmd.timestamp; // TODO: configure simulation settings according to received cmd.config diff --git a/nodebank_previews_standalone.cpp b/nodebank_previews_standalone.cpp index effceedc0..cff04b6c5 100644 --- a/nodebank_previews_standalone.cpp +++ b/nodebank_previews_standalone.cpp @@ -76,19 +76,21 @@ bool parse_arguments(int const Argc, char *Argv[], preview_settings &Settings) } else if (token == "-resolution") { - if ((i + 1 >= Argc) || (false == parse_number(Argv[++i], Settings.resolution)) || (Settings.resolution < 16)) + if ((i + 1 >= Argc) || (false == parse_number(Argv[i + 1], Settings.resolution)) || (Settings.resolution < 16)) { report("-resolution needs a number of pixels, 16 or more", true); return false; } + ++i; } else if (token == "-margin") { - if ((i + 1 >= Argc) || (false == parse_number(Argv[++i], Settings.margin)) || (Settings.margin < 0)) + if ((i + 1 >= Argc) || (false == parse_number(Argv[i + 1], Settings.margin)) || (Settings.margin < 0)) { report("-margin needs a number of pixels, 0 or more", true); return false; } + ++i; } else if (token == "-no-shadows") { @@ -290,6 +292,8 @@ int generate_nodebank_previews(int Argc, char *Argv[]) { Global.LoadIniFile("eu07.ini"); } + // the settings are read, so the log service writes as it goes instead of holding everything until it stops + OpenLogFiles(); // the progress goes to the console, the log keeps the details Global.iWriteLogEnabled &= ~2; std::thread logservice(LogService); diff --git a/ref/licenses/README.md b/ref/licenses/README.md new file mode 100644 index 000000000..10ff550eb --- /dev/null +++ b/ref/licenses/README.md @@ -0,0 +1,29 @@ +# License texts of the Windows audio DLLs + +The Windows build ships `OpenAL32.dll` (OpenAL Soft 1.25.2) and `libsndfile-1.dll` (libsndfile 1.2.2), and in +`licenses/` next to them the texts of those libraries and of what they have built in. The DLLs and OpenAL Soft's own +`COPYING` come from the release zips, which CI downloads; the texts below are kept here, so a build doesn't depend on +the servers they come from. CI copies them into `licenses/` and checks each one by the SHA-256 in +`.github/workflows/build_bin.yml` (step "Add the OpenAL Soft and libsndfile DLLs"). `.gitattributes` keeps them byte +for byte as upstream (`-text`), whatever the line ending settings of a checkout. What each text covers is in +`audio-libraries.txt`, which that step writes. + +| File | Taken from | SHA-256 | +|------|------------|---------| +| `libsndfile-COPYING.txt` | https://raw.githubusercontent.com/libsndfile/libsndfile/1.2.2/COPYING | `ad01ea5cd2755f6048383c8d54c88459cd6fcb17757c5c8892f8c5ea060f6140` | +| `libsndfile-ALAC-LICENSE.txt` | https://raw.githubusercontent.com/libsndfile/libsndfile/1.2.2/src/ALAC/LICENSE | `232efbd83786e157286b0b96c68ebb673541b69b33036287bf1e5ec5067a49d9` | +| `libsndfile-GSM610-COPYRIGHT.txt` | https://raw.githubusercontent.com/libsndfile/libsndfile/1.2.2/src/GSM610/COPYRIGHT | `1bbe7119b1bcd1489e0f36cb95b8902f7f0ceec9a2f3a67394bc9f4709a4e0a7` | +| `libogg-COPYING.txt` | https://raw.githubusercontent.com/xiph/ogg/v1.3.5/COPYING | `d2ab5758336489da61c12cc5bb757da5339c4ae9001f9bb0562b4370249af814` | +| `libvorbis-COPYING.txt` | https://raw.githubusercontent.com/xiph/vorbis/v1.3.7/COPYING | `ec1815db59fcd302846df949d7424876cb2e2dc5ed1606c5fb0b36787b1cf43a` | +| `flac-COPYING.Xiph.txt` | https://raw.githubusercontent.com/xiph/flac/1.4.2/COPYING.Xiph | `6e58d3036f05e2a0d58af854c12a505ddbe75011d71a598a2170987f3b15408d` | +| `opus-COPYING.txt` | https://raw.githubusercontent.com/xiph/opus/v1.4/COPYING | `8338ce8d922bb4416ce3dd1e5680173332435e3f0755007ac7801ccd674fe682` | +| `mpg123-COPYING.txt` | https://scm.orgis.org/view/mpg123/tags/1.31.3/COPYING?view=co | `c22482728a634a8dfdb4ff72a96d4c1ed64cd8f3e79335c401751ac591609366` | +| `lame-COPYING.txt` | https://sources.debian.org/data/main/l/lame/3.100-6/COPYING (the same file as in LAME 3.100) | `bfe4a52dc4645385f356a8e83cc54216a293e3b6f1cb4f79f5fc0277abf937fd` | +| `openal-soft-pffft-LICENSE.txt` | https://raw.githubusercontent.com/kcat/openal-soft/1.25.2/LICENSE-pffft | `64056328b3e7bc104e24ef96accc1a7abead156f0c02d1b87c97e3f3a28030de` | +| `openal-soft-gsl-LICENSE.txt` | https://raw.githubusercontent.com/kcat/openal-soft/1.25.2/gsl/LICENSE | `4c21dc82a1c7186ea754fd59d504c00947953a3401fe8e24eaa44109ef8e2555` | +| `openal-soft-BSD-3Clause.txt` | https://raw.githubusercontent.com/kcat/openal-soft/1.25.2/BSD-3Clause | `b5a08cf98996dd83aa906a72c163600f6cb17a65ce546a553815a1267abd43ff` | +| `openal-soft-winpthreads-COPYING.txt` | https://raw.githubusercontent.com/mingw-w64/mingw-w64/v13.0.0/mingw-w64-libraries/winpthreads/COPYING | `63263614cdd29f2f93cba85e992f041b31f9fc7b4033692f31269489a8a1b177` | +| `openal-soft-mingw-w64-runtime.txt` | https://raw.githubusercontent.com/mingw-w64/mingw-w64/v13.0.0/COPYING.MinGW-w64-runtime/COPYING.MinGW-w64-runtime.txt | `e9b2dc02451ea29092a1f25fa0f3c07207ed421f1807dffb0c4e6dce69dee7bd` | + +When a DLL is updated to another version, its texts here are replaced by those of the new version's source tree, and +their SHA-256 in the workflow with them. diff --git a/ref/licenses/flac-COPYING.Xiph.txt b/ref/licenses/flac-COPYING.Xiph.txt new file mode 100644 index 000000000..edd24f719 --- /dev/null +++ b/ref/licenses/flac-COPYING.Xiph.txt @@ -0,0 +1,29 @@ +Copyright (C) 2000-2009 Josh Coalson +Copyright (C) 2011-2022 Xiph.Org Foundation + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of the Xiph.Org Foundation nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/ref/licenses/lame-COPYING.txt b/ref/licenses/lame-COPYING.txt new file mode 100644 index 000000000..f5030495b --- /dev/null +++ b/ref/licenses/lame-COPYING.txt @@ -0,0 +1,481 @@ + GNU LIBRARY GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the library GPL. It is + numbered 2 because it goes with version 2 of the ordinary GPL.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Library General Public License, applies to some +specially designated Free Software Foundation software, and to any +other libraries whose authors decide to use it. You can use it for +your libraries, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if +you distribute copies of the library, or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link a program with the library, you must provide +complete object files to the recipients so that they can relink them +with the library, after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + Our method of protecting your rights has two steps: (1) copyright +the library, and (2) offer you this license which gives you legal +permission to copy, distribute and/or modify the library. + + Also, for each distributor's protection, we want to make certain +that everyone understands that there is no warranty for this free +library. If the library is modified by someone else and passed on, we +want its recipients to know that what they have is not the original +version, so that any problems introduced by others will not reflect on +the original authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that companies distributing free +software will individually obtain patent licenses, thus in effect +transforming the program into proprietary software. To prevent this, +we have made it clear that any patent must be licensed for everyone's +free use or not licensed at all. + + Most GNU software, including some libraries, is covered by the ordinary +GNU General Public License, which was designed for utility programs. This +license, the GNU Library General Public License, applies to certain +designated libraries. This license is quite different from the ordinary +one; be sure to read it in full, and don't assume that anything in it is +the same as in the ordinary license. + + The reason we have a separate public license for some libraries is that +they blur the distinction we usually make between modifying or adding to a +program and simply using it. Linking a program with a library, without +changing the library, is in some sense simply using the library, and is +analogous to running a utility program or application program. However, in +a textual and legal sense, the linked executable is a combined work, a +derivative of the original library, and the ordinary General Public License +treats it as such. + + Because of this blurred distinction, using the ordinary General +Public License for libraries did not effectively promote software +sharing, because most developers did not use the libraries. We +concluded that weaker conditions might promote sharing better. + + However, unrestricted linking of non-free programs would deprive the +users of those programs of all benefit from the free status of the +libraries themselves. This Library General Public License is intended to +permit developers of non-free programs to use free libraries, while +preserving your freedom as a user of such programs to change the free +libraries that are incorporated in them. (We have not seen how to achieve +this as regards changes in header files, but we have achieved it as regards +changes in the actual functions of the Library.) The hope is that this +will lead to faster development of free libraries. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, while the latter only +works together with the library. + + Note that it is possible for a library to be covered by the ordinary +General Public License rather than by this special one. + + GNU LIBRARY GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library which +contains a notice placed by the copyright holder or other authorized +party saying it may be distributed under the terms of this Library +General Public License (also called "this License"). Each licensee is +addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also compile or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + c) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + d) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the source code distributed need not include anything that is normally +distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Library General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/ref/licenses/libogg-COPYING.txt b/ref/licenses/libogg-COPYING.txt new file mode 100644 index 000000000..6111c6c5a --- /dev/null +++ b/ref/licenses/libogg-COPYING.txt @@ -0,0 +1,28 @@ +Copyright (c) 2002, Xiph.org Foundation + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of the Xiph.org Foundation nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/ref/licenses/libsndfile-ALAC-LICENSE.txt b/ref/licenses/libsndfile-ALAC-LICENSE.txt new file mode 100644 index 000000000..7d8595490 --- /dev/null +++ b/ref/licenses/libsndfile-ALAC-LICENSE.txt @@ -0,0 +1,170 @@ +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the +copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other +entities that control, are controlled by, or are under common control +with that entity. For the purposes of this definition, "control" means +(i) the power, direct or indirect, to cause the direction or management +of such entity, whether by contract or otherwise, or (ii) ownership +of fifty percent (50%) or more of the outstanding shares, or (iii) +beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising +permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, +including but not limited to software source code, documentation source, +and configuration files. + +"Object" form shall mean any form resulting from mechanical +transformation or translation of a Source form, including but not +limited to compiled object code, generated documentation, and +conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object +form, made available under the License, as indicated by a copyright +notice that is included in or attached to the work (an example is +provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object +form, that is based on (or derived from) the Work and for which the +editorial revisions, annotations, elaborations, or other modifications +represent, as a whole, an original work of authorship. For the purposes +of this License, Derivative Works shall not include works that remain +separable from, or merely link (or bind by name) to the interfaces of, +the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original +version of the Work and any modifications or additions to that Work or +Derivative Works thereof, that is intentionally submitted to Licensor +for inclusion in the Work by the copyright owner or by an individual +or Legal Entity authorized to submit on behalf of the copyright owner. +For the purposes of this definition, "submitted" means any form of +electronic, verbal, or written communication sent to the Licensor +or its representatives, including but not limited to communication +on electronic mailing lists, source code control systems, and issue +tracking systems that are managed by, or on behalf of, the Licensor +for the purpose of discussing and improving the Work, but excluding +communication that is conspicuously marked or otherwise designated in +writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity +on behalf of whom a Contribution has been received by Licensor and +subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions +of this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +copyright license to reproduce, prepare Derivative Works of, publicly +display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except +as stated in this section) patent license to make, have made, use, +offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such +Contributor that are necessarily infringed by their Contribution(s) +alone or by combination of their Contribution(s) with the Work to which +such Contribution(s) was submitted. If You institute patent litigation +against any entity (including a cross-claim or counterclaim in a +lawsuit) alleging that the Work or a Contribution incorporated within +the Work constitutes direct or contributory patent infringement, then +any patent licenses granted to You under this License for that Work +shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the +Work or Derivative Works thereof in any medium, with or without +modifications, and in Source or Object form, provided that You meet the +following conditions: + +You must give any other recipients of the Work or Derivative Works a +copy of this License; and + +You must cause any modified files to carry prominent notices stating +that You changed the files; and + +You must retain, in the Source form of any Derivative Works that You +distribute, all copyright, patent, trademark, and attribution notices +from the Source form of the Work, excluding those notices that do not +pertain to any part of the Derivative Works; and + +If the Work includes a "NOTICE" text file as part of its distribution, +then any Derivative Works that You distribute must include a readable +copy of the attribution notices contained within such NOTICE file, +excluding those notices that do not pertain to any part of the +Derivative Works, in at least one of the following places: within a +NOTICE text file distributed as part of the Derivative Works; within +the Source form or documentation, if provided along with the Derivative +Works; or, within a display generated by the Derivative Works, if and +wherever such third-party notices normally appear. The contents of the +NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative +Works that You distribute, alongside or as an addendum to the NOTICE +text from the Work, provided that such additional attribution notices +cannot be construed as modifying the License. You may add Your own +copyright statement to Your modifications and may provide additional +or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as +a whole, provided Your use, reproduction, and distribution of the Work +otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, +any Contribution intentionally submitted for inclusion in the Work by +You to the Licensor shall be under the terms and conditions of this +License, without any additional terms or conditions. Notwithstanding +the above, nothing herein shall supersede or modify the terms of any +separate license agreement you may have executed with Licensor regarding +such Contributions. + +6. Trademarks. This License does not grant permission to use the trade +names, trademarks, service marks, or product names of the Licensor, +except as required for reasonable and customary use in describing the +origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed +to in writing, Licensor provides the Work (and each Contributor +provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied, including, without +limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, +MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your +exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, +whether in tort (including negligence), contract, or otherwise, unless +required by applicable law (such as deliberate and grossly negligent +acts) or agreed to in writing, shall any Contributor be liable to You +for damages, including any direct, indirect, special, incidental, or +consequential damages of any character arising as a result of this +License or out of the use or inability to use the Work (including but +not limited to damages for loss of goodwill, work stoppage, computer +failure or malfunction, or any and all other commercial damages or +losses), even if such Contributor has been advised of the possibility of +such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the +Work or Derivative Works thereof, You may choose to offer, and charge a +fee for, acceptance of support, warranty, indemnity, or other liability +obligations and/or rights consistent with this License. However, in +accepting such obligations, You may act only on Your own behalf and +on Your sole responsibility, not on behalf of any other Contributor, +and only if You agree to indemnify, defend, and hold each Contributor +harmless for any liability incurred by, or claims asserted against, such +Contributor by reason of your accepting any such warranty or additional +liability. diff --git a/ref/licenses/libsndfile-COPYING.txt b/ref/licenses/libsndfile-COPYING.txt new file mode 100644 index 000000000..c396169ee --- /dev/null +++ b/ref/licenses/libsndfile-COPYING.txt @@ -0,0 +1,503 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + diff --git a/ref/licenses/libsndfile-GSM610-COPYRIGHT.txt b/ref/licenses/libsndfile-GSM610-COPYRIGHT.txt new file mode 100644 index 000000000..eba0e523b --- /dev/null +++ b/ref/licenses/libsndfile-GSM610-COPYRIGHT.txt @@ -0,0 +1,16 @@ +Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann, +Technische Universitaet Berlin + +Any use of this software is permitted provided that this notice is not +removed and that neither the authors nor the Technische Universitaet Berlin +are deemed to have made any representations as to the suitability of this +software for any purpose nor are held responsible for any defects of +this software. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. + +As a matter of courtesy, the authors request to be informed about uses +this software has found, about bugs in this software, and about any +improvements that may be of general interest. + +Berlin, 28.11.1994 +Jutta Degener +Carsten Bormann diff --git a/ref/licenses/libvorbis-COPYING.txt b/ref/licenses/libvorbis-COPYING.txt new file mode 100644 index 000000000..fb456a87b --- /dev/null +++ b/ref/licenses/libvorbis-COPYING.txt @@ -0,0 +1,28 @@ +Copyright (c) 2002-2020 Xiph.org Foundation + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of the Xiph.org Foundation nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/ref/licenses/mpg123-COPYING.txt b/ref/licenses/mpg123-COPYING.txt new file mode 100644 index 000000000..14e14f01c --- /dev/null +++ b/ref/licenses/mpg123-COPYING.txt @@ -0,0 +1,772 @@ +This is the file that contains the terms of use, copying, etc. for the mpg123 distribution package. + +Main message, to include in "About ..." boxes, etc: + + Copyright (c) 1995-2020 by Michael Hipp and others, + free software under the terms of the LGPL v2.1 + +There is an attempt to cover the actual list of authors in the AUTHORS file. +Project maintainer since 2006 is Thomas Orgis and many people have contributed +since the Michael Hipp era, but he stays the initial source and it would +be impractical to count them all individually, so it's "and others". +Source files contain the phrase "the mpg123 project" to the same effect +in their license boilerplate; especially those that were added after +maintainership changed. The person mainly responsible for the first version +is usually named in the phrase "initially written by ...". + +All files in the distribution that don't carry a license note on their own are +licensed under the terms of the LGPL 2.1; exceptions may apply, especially to +files not in the official distribution but in the revision control repository. + +The formal license text follows. + +======================= +1. The LGPL version 2.1 +======================= + + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + +==================== +2. The GPL version 2 +==================== + + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS diff --git a/ref/licenses/openal-soft-BSD-3Clause.txt b/ref/licenses/openal-soft-BSD-3Clause.txt new file mode 100644 index 000000000..b1c2dbd76 --- /dev/null +++ b/ref/licenses/openal-soft-BSD-3Clause.txt @@ -0,0 +1,31 @@ +Portions of this software are licensed under the BSD 3-Clause license. + +Copyright (c) 2015, Archontis Politis +Copyright (c) 2019, Anis A. Hireche +Copyright (c) 2019, Christopher Robinson +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of Spherical-Harmonic-Transform nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/ref/licenses/openal-soft-gsl-LICENSE.txt b/ref/licenses/openal-soft-gsl-LICENSE.txt new file mode 100644 index 000000000..aa58667a3 --- /dev/null +++ b/ref/licenses/openal-soft-gsl-LICENSE.txt @@ -0,0 +1,21 @@ +Copyright (c) 2015 Microsoft Corporation. All rights reserved. + +This code is licensed under the MIT License (MIT). + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/ref/licenses/openal-soft-mingw-w64-runtime.txt b/ref/licenses/openal-soft-mingw-w64-runtime.txt new file mode 100644 index 000000000..ca6a077e2 --- /dev/null +++ b/ref/licenses/openal-soft-mingw-w64-runtime.txt @@ -0,0 +1,240 @@ +MinGW-w64 runtime licensing +*************************** + +This program or library was built using MinGW-w64 and statically +linked against the MinGW-w64 runtime. Some parts of the runtime +are under licenses which require that the copyright and license +notices are included when distributing the code in binary form. +These notices are listed below. + + +======================== +Overall copyright notice +======================== + +Copyright (c) 2009, 2010, 2011, 2012, 2013 by the mingw-w64 project + +This license has been certified as open source. It has also been designated +as GPL compatible by the Free Software Foundation (FSF). + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions in source code must retain the accompanying copyright + notice, this list of conditions, and the following disclaimer. + 2. Redistributions in binary form must reproduce the accompanying + copyright notice, this list of conditions, and the following disclaimer + in the documentation and/or other materials provided with the + distribution. + 3. Names of the copyright holders must not be used to endorse or promote + products derived from this software without prior written permission + from the copyright holders. + 4. The right to distribute this software or to use it for any purpose does + not give you the right to use Servicemarks (sm) or Trademarks (tm) of + the copyright holders. Use of them is covered by separate agreement + with the copyright holders. + 5. If any files are modified, you must cause the modified files to carry + prominent notices stating that you changed the files and the date of + any change. + +Disclaimer + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED +OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO +EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +======================================== +getopt, getopt_long, and getop_long_only +======================================== + +Copyright (c) 2002 Todd C. Miller + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +Sponsored in part by the Defense Advanced Research Projects +Agency (DARPA) and Air Force Research Laboratory, Air Force +Materiel Command, USAF, under agreement number F39502-99-1-0512. + + * * * * * * * + +Copyright (c) 2000 The NetBSD Foundation, Inc. +All rights reserved. + +This code is derived from software contributed to The NetBSD Foundation +by Dieter Baron and Thomas Klausner. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + + +=============================================================== +gdtoa: Converting between IEEE floating point numbers and ASCII +=============================================================== + +The author of this software is David M. Gay. + +Copyright (C) 1997, 1998, 1999, 2000, 2001 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + + * * * * * * * + +The author of this software is David M. Gay. + +Copyright (C) 2005 by David M. Gay +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that the copyright notice and this permission notice and warranty +disclaimer appear in supporting documentation, and that the name of +the author or any of his current or former employers not be used in +advertising or publicity pertaining to distribution of the software +without specific, written prior permission. + +THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN +NO EVENT SHALL THE AUTHOR OR ANY OF HIS CURRENT OR FORMER EMPLOYERS BE +LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY +DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS +SOFTWARE. + + * * * * * * * + +The author of this software is David M. Gay. + +Copyright (C) 2004 by David M. Gay. +All Rights Reserved +Based on material in the rest of /netlib/fp/gdota.tar.gz, +which is copyright (C) 1998, 2000 by Lucent Technologies. + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + + +========================= +Parts of the math library +========================= + +Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + +Developed at SunSoft, a Sun Microsystems, Inc. business. +Permission to use, copy, modify, and distribute this +software is freely granted, provided that this notice +is preserved. + + * * * * * * * + +Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + +Developed at SunPro, a Sun Microsystems, Inc. business. +Permission to use, copy, modify, and distribute this +software is freely granted, provided that this notice +is preserved. + + * * * * * * * + +FIXME: Cephes math lib +Copyright (C) 1984-1998 Stephen L. Moshier + +It sounds vague, but as to be found at +, it gives an +impression that the author could be willing to give an explicit +permission to distribute those files e.g. under a BSD style license. So +probably there is no problem here, although it could be good to get a +permission from the author and then add a license into the Cephes files +in MinGW runtime. At least on follow-up it is marked that debian sees the +version a-like BSD one. As MinGW.org (where those cephes parts are coming +from) distributes them now over 6 years, it should be fine. + +=================================== +Headers and IDLs imported from Wine +=================================== + +Some header and IDL files were imported from the Wine project. These files +are prominent maked in source. Their copyright belongs to contributors and +they are distributed under LGPL license. + +Disclaimer + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. diff --git a/ref/licenses/openal-soft-pffft-LICENSE.txt b/ref/licenses/openal-soft-pffft-LICENSE.txt new file mode 100644 index 000000000..5f1a8493f --- /dev/null +++ b/ref/licenses/openal-soft-pffft-LICENSE.txt @@ -0,0 +1,38 @@ +A modified PFFFT is included, with the following license. + +Copyright (c) 2023 Christopher Robinson + +Copyright (c) 2013 Julien Pommier ( pommier@modartt.com ) + +Copyright (c) 2004 the University Corporation for Atmospheric +Research ("UCAR"). All rights reserved. Developed by NCAR's +Computational and Information Systems Laboratory, UCAR, +www.cisl.ucar.edu. + +Redistribution and use of the Software in source and binary forms, +with or without modification, is permitted provided that the +following conditions are met: + +- Neither the names of NCAR's Computational and Information Systems +Laboratory, the University Corporation for Atmospheric Research, +nor the names of its sponsors or contributors may be used to +endorse or promote products derived from this Software without +specific prior written permission. + +- Redistributions of source code must retain the above copyright +notices, this list of conditions, and the disclaimer below. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions, and the disclaimer below in the +documentation and/or other materials provided with the +distribution. + +THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE +SOFTWARE. diff --git a/ref/licenses/openal-soft-winpthreads-COPYING.txt b/ref/licenses/openal-soft-winpthreads-COPYING.txt new file mode 100644 index 000000000..350770123 --- /dev/null +++ b/ref/licenses/openal-soft-winpthreads-COPYING.txt @@ -0,0 +1,57 @@ +Copyright (c) 2011 mingw-w64 project + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +/* + * Parts of this library are derived by: + * + * Posix Threads library for Microsoft Windows + * + * Use at own risk, there is no implied warranty to this code. + * It uses undocumented features of Microsoft Windows that can change + * at any time in the future. + * + * (C) 2010 Lockless Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of Lockless Inc. nor the names of its contributors may be + * used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AN + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + */ diff --git a/ref/licenses/opus-COPYING.txt b/ref/licenses/opus-COPYING.txt new file mode 100644 index 000000000..9c739c34a --- /dev/null +++ b/ref/licenses/opus-COPYING.txt @@ -0,0 +1,44 @@ +Copyright 2001-2011 Xiph.Org, Skype Limited, Octasic, + Jean-Marc Valin, Timothy B. Terriberry, + CSIRO, Gregory Maxwell, Mark Borgerding, + Erik de Castro Lopo + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of Internet Society, IETF or IETF Trust, nor the +names of specific contributors, may be used to endorse or promote +products derived from this software without specific prior written +permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Opus is subject to the royalty-free patent licenses which are +specified at: + +Xiph.Org Foundation: +https://datatracker.ietf.org/ipr/1524/ + +Microsoft Corporation: +https://datatracker.ietf.org/ipr/1914/ + +Broadcom Corporation: +https://datatracker.ietf.org/ipr/1526/ diff --git a/rendering/opengl46/opengl46backend.cpp b/rendering/opengl46/opengl46backend.cpp index e050daa30..7956558f6 100644 --- a/rendering/opengl46/opengl46backend.cpp +++ b/rendering/opengl46/opengl46backend.cpp @@ -14,6 +14,7 @@ http://mozilla.org/MPL/2.0/. #include "rendering/opengl46/opengl46renderer.h" #include "utilities/Globals.h" #include "utilities/Logs.h" +#include "utilities/hardwareprobe.h" namespace { @@ -76,6 +77,9 @@ bool after_window(GLFWwindow *Window) return false; } + // which of the GPUs the context runs on, and its memory + hardware::log_gl_context(); + return true; } diff --git a/scene/regionfile.cpp b/scene/regionfile.cpp new file mode 100644 index 000000000..593e07e82 --- /dev/null +++ b/scene/regionfile.cpp @@ -0,0 +1,130 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "scene/regionfile.h" +#include "scene/sn_utils.h" + +#include +#include +#include +#include + +namespace scene::region_file { + +std::string +check_layout( std::istream &Input, std::uint32_t const Header, std::uint32_t const Version, std::uint32_t const Sectionlimit ) { + + Input.clear(); + Input.seekg( 0, std::ios::end ); + auto const end { Input.tellg() }; + Input.seekg( 0, std::ios::beg ); + if( ( end < 0 ) || ( false == Input.good() ) ) { + return "can't be read"; + } + auto const filesize { static_cast( end ) }; + + auto const headermain { sn_utils::ld_uint32( Input ) }; + if( auto const headertype { sn_utils::ld_uint32( Input ) }; ( false == Input.good() ) || ( headermain != Header ) || ( headertype != Version ) ) { + return "is of either unrecognized type or version"; + } + auto sectioncount { sn_utils::ld_uint32( Input ) }; + if( false == Input.good() ) { + return "ends before the section count"; + } + if( sectioncount > Sectionlimit ) { + return std::format( "holds {} sections, more than the {} a region has", sectioncount, Sectionlimit ); + } + std::vector present( Sectionlimit, false ); + std::uint64_t position { 3 * sizeof( std::uint32_t ) }; + std::uint32_t sectionnumber { 0 }; + while( sectionnumber < sectioncount ) { + if( filesize - position < section_header_size ) { + return std::format( "ends after {} of its {} sections", sectionnumber, sectioncount ); + } + std::uint32_t index; + std::uint32_t size; + if( auto const error { read_section_header( Input, Sectionlimit, index, size ) }; false == error.empty() ) { + return error; + } + if( true == present[ index ] ) { + return std::format( "holds section {} more than once", index ); + } + present[ index ] = true; + if( filesize - position < size ) { + return std::format( + "ends inside section {} ({} of {}), {} of its {} bytes are there", index, sectionnumber + 1, sectioncount, filesize - position, size ); + } + position += size; + Input.seekg( static_cast( position ), std::ios::beg ); + if( false == Input.good() ) { + return std::format( "can't be read past section {}", index ); + } + ++sectionnumber; + } + if( position != filesize ) { + return std::format( "has {} bytes past its last section", filesize - position ); + } + return {}; +} + +std::string +read_section_header( std::istream &Input, std::uint32_t const Sectionlimit, std::uint32_t &Index, std::uint32_t &Size ) { + + Index = sn_utils::ld_uint32( Input ); + Size = sn_utils::ld_uint32( Input ); + if( false == Input.good() ) { + return "ends inside a section header"; + } + if( Index >= Sectionlimit ) { + return std::format( "holds section {}, out of the {} a region has", Index, Sectionlimit ); + } + if( Size < section_header_size ) { + return std::format( "gives section {} the size of {} bytes, less than its header takes", Index, Size ); + } + return {}; +} + +std::string +open_temporary( std::string const &Filename, std::ofstream &Output ) { + + Output.open( Filename + ".tmp", std::ios::binary | std::ios::trunc ); + if( Output.fail() ) { + return "can't write to file \"" + Filename + ".tmp\""; + } + return {}; +} + +std::string +finish_temporary( std::string const &Filename, std::ofstream &Output, std::string Error ) { + + if( ( true == Error.empty() ) && ( Output.fail() ) ) { + Error = "can't write to file \"" + Filename + ".tmp\""; + } + Output.close(); + if( ( true == Error.empty() ) && ( Output.fail() ) ) { + Error = "can't write to file \"" + Filename + ".tmp\""; + } + std::filesystem::path const temporaryfile { Filename + ".tmp" }; + std::error_code result; + if( false == Error.empty() ) { + std::filesystem::remove( temporaryfile, result ); + return Error; + } + // the finished file replaces the previous version in one go, so an interrupted write doesn't leave a broken one behind + std::filesystem::rename( temporaryfile, Filename, result ); + if( result ) { + Error = "can't replace file \"" + Filename + "\": " + result.message(); + std::filesystem::remove( temporaryfile, result ); + return Error; + } + return {}; +} + +} // scene::region_file diff --git a/scene/regionfile.h b/scene/regionfile.h new file mode 100644 index 000000000..dd497a487 --- /dev/null +++ b/scene/regionfile.h @@ -0,0 +1,77 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include +#include +#include + +// the parts of the region file (.sbt, the static geometry of a scenery cached by basic_region) which need +// nothing of the scene: checking how a file is laid out, and writing it so that an interrupted write leaves no +// cut-short file behind. kept apart so the unit tests can check them +namespace scene::region_file { + +// layout of the file: the header (two uint32: the file type and its version), the section count (uint32), then for +// each section its index (uint32), its size (uint32, counted from the start of the index, so it covers the index, +// the size itself and the section data) and the section data. all numbers little endian + +// size of the index and the size of a section, the least a section can take +std::uint32_t constexpr section_header_size { 2 * sizeof( std::uint32_t ) }; + +// checks the layout of the file held by the stream, read from its start: the header has to match the provided type +// and version, the sections have to have indices below Sectionlimit, each one no more than once, and their sizes have +// to add up to the length of the file. the section data itself isn't read. returns: the empty string if the layout +// holds, the reason why not otherwise +std::string + check_layout( std::istream &Input, std::uint32_t const Header, std::uint32_t const Version, std::uint32_t const Sectionlimit ); + +// reads the index and the size of the next section, and checks them: the index has to be below Sectionlimit, and the +// section no smaller than its own index and size. returns: the empty string if both were read and are sound, the +// reason why not otherwise +std::string + read_section_header( std::istream &Input, std::uint32_t const Sectionlimit, std::uint32_t &Index, std::uint32_t &Size ); + +// opens the temporary file write_through_temporary() writes into. returns: the empty string on success, the reason of +// the failure otherwise +std::string + open_temporary( std::string const &Filename, std::ofstream &Output ); + +// closes the temporary file write_through_temporary() wrote into, and puts it in place of the file, unless Error holds +// the reason why the writing failed. the temporary file is removed on a failure. returns: the empty string on success, +// the reason of the failure otherwise +std::string + finish_temporary( std::string const &Filename, std::ofstream &Output, std::string Error ); + +// writes a file with the provided function (taking the std::ostream to write into) into a temporary file next to it +// (the name with .tmp added), which then replaces the file in one go. if the writing fails or is cut short, the +// previous file (or none) stays in place, rather than a partial one; the temporary file is removed when the failure is +// noticed. returns: the empty string on success, the reason of the failure otherwise +template +std::string + write_through_temporary( std::string const &Filename, Writer_ const &Write ) { + + std::ofstream output; + if( auto const openerror { open_temporary( Filename, output ) }; false == openerror.empty() ) { + return openerror; + } + std::string error; + try { + Write( output ); + output.flush(); + } + catch( std::exception const &Exception ) { + error = "can't write to file \"" + Filename + ".tmp\": " + Exception.what(); + } + return finish_temporary( Filename, output, std::move( error ) ); +} + +} // scene::region_file diff --git a/scene/scene.cpp b/scene/scene.cpp index e64bdc7fd..506b52d67 100644 --- a/scene/scene.cpp +++ b/scene/scene.cpp @@ -19,9 +19,13 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "utilities/Logs.h" #include "scene/sn_utils.h" +#include "scene/regionfile.h" #include "scene/sceneterrain.h" #include "rendering/renderer.h" #include "widgets/map_objects.h" +#include "vehicle/aiwire.h" + +#include namespace scene { @@ -29,6 +33,57 @@ std::string const EU07_FILEEXTENSION_REGION { ".sbt" }; std::uint32_t const EU07_FILEHEADER { MAKE_ID4( 'E','U','0','7' ) }; std::uint32_t const EU07_FILEVERSION_REGION { MAKE_ID4( 'S', 'B', 'T', '2' ) }; std::map Hierarchy; + +namespace { + +// name of the region file kept for specified scenario file +std::string +region_file_name( std::string const &Scenariofile ) { + + auto filename { Scenariofile }; + while( filename[ 0 ] == '$' ) { + // trim leading $ char rainsted utility may add to the base name for modified .scn files + filename.erase( 0, 1 ); + } + erase_extension( filename ); + filename = Global.asCurrentSceneryPath + filename; + filename += EU07_FILEEXTENSION_REGION; + + return filename; +} + +// reads the next section of a region file into the provided list. returns: the empty string on success, the reason +// of the failure otherwise +std::string +read_region_section( std::istream &Input, std::uint32_t const Sectionlimit, std::vector>> &Sections ) { + + // section index, followed by section data size (counted from the start of the index), followed by section data + std::uint32_t sectionindex; + std::uint32_t sectionsize; + if( auto const error { region_file::read_section_header( Input, Sectionlimit, sectionindex, sectionsize ) }; false == error.empty() ) { + return error; + } + // the section is read out of its own data, it can't reach into the next one + std::string data( sectionsize - region_file::section_header_size, '\0' ); + Input.read( data.data(), static_cast( data.size() ) ); + if( false == Input.good() ) { + return std::format( "ends inside section {}", sectionindex ); + } + std::istringstream sectioninput { std::move( data ) }; + auto section { std::make_unique() }; + section->deserialize( sectioninput ); + std::string error; + if( true == sectioninput.fail() ) { + error = std::format( "has section {} shorter than its content", sectionindex ); + } + else if( sectioninput.peek() != std::char_traits::eof() ) { + error = std::format( "has section {} longer than its content", sectionindex ); + } + Sections.emplace_back( sectionindex, std::move( section ) ); + return error; +} + +} // namespace // potentially activates event handler with the same name as provided node, and within handler activation range void @@ -57,25 +112,15 @@ basic_cell::update_traction( TDynamicObject *Vehicle, int const Pantographindex for( auto *traction : m_directories.traction ) { - // współczynniki równania parametrycznego - auto const paramfrontdot = glm::dot( traction->vParametric, vFront ); - auto const fRaParam = - -( glm::dot( traction->pPoint1, vFront ) - glm::dot( pantographposition, vFront ) ) - / ( paramfrontdot != 0.0 ? - paramfrontdot : - 0.001 ); // div0 trap - - if( fRaParam < -0.001 - || fRaParam > 1.001 ) { continue; } + // the span against the pantograph, the geometry the AI uses to find the wire as well + auto const contact = ai_wire::span_contact( + traction->pPoint1, traction->vParametric, pantographposition, vFront, vUp, vLeft, pantograph->fWidth ); // jeśli tylko jest w przedziale, wyznaczyć odległość wzdłuż wektorów vUp i vLeft - // punkt styku płaszczyzny z drutem (dla generatora łuku el.) - auto const vStyk = traction->pPoint1 + fRaParam * traction->vParametric; - // wektor musi się mieścić w przedziale ruchu pantografu - auto const vGdzie = vStyk - pantographposition; - auto fVertical = glm::dot( vGdzie, vUp ); + if( false == contact.within ) { continue; } + auto fVertical = contact.vertical; if( fVertical >= 0.0 ) { // jeśli ponad pantografem (bo może łapać druty spod wiaduktu) - auto const fHorizontal = std::abs( glm::dot( vGdzie, vLeft ) ) - pantograph->fWidth; + auto const fHorizontal = contact.horizontal; if (Global.bEnableTraction && fVertical < pantograph->PantWys - 0.15 ) { @@ -120,6 +165,24 @@ basic_cell::update_traction( TDynamicObject *Vehicle, int const Pantographindex } } +// checks whether a wire of the cell, not broken, is within reach of a pantograph at specified point +bool +basic_cell::wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double const Halfwidth, double const Minheight, double const Maxheight ) const { + + for( auto const *traction : m_directories.traction ) { + if( ( traction->DamageFlag & 128 ) != 0 ) { + // a broken wire powers nothing + continue; + } + if( ai_wire::reaches( + ai_wire::span_contact( traction->pPoint1, traction->vParametric, Point, Front, Up, Left, Halfwidth ), + Minheight, Maxheight ) ) { + return true; + } + } + return false; +} + // legacy method, updates sounds and polls event launchers within radius around specified point void basic_cell::update_events() { @@ -232,22 +295,38 @@ basic_cell::deserialize( std::istream &Input ) { m_area.deserialize( Input ); // cell shapes // shape count followed by opaque shape data + // NOTE: a damaged count is cut short by the end of the data rather than followed auto itemcount { sn_utils::ld_uint32( Input ) }; - while( itemcount-- ) { + while( ( itemcount-- ) && ( true == Input.good() ) ) { m_shapesopaque.emplace_back( shape_node().deserialize( Input ) ); } itemcount = sn_utils::ld_uint32( Input ); - while( itemcount-- ) { + while( ( itemcount-- ) && ( true == Input.good() ) ) { m_shapestranslucent.emplace_back( shape_node().deserialize( Input ) ); } itemcount = sn_utils::ld_uint32( Input ); - while( itemcount-- ) { + while( ( itemcount-- ) && ( true == Input.good() ) ) { m_lines.emplace_back( lines_node().deserialize( Input ) ); } // cell activation flag m_active = true == m_active || false == m_shapesopaque.empty() || false == m_shapestranslucent.empty() || false == m_lines.empty(); } +// takes over the content restored from a file into another cell, as deserialize() would have added it to this one +void +basic_cell::merge( basic_cell &&Other ) { + + m_area.center = Other.m_area.center; + m_area.radius = std::max( m_area.radius, Other.m_area.radius ); + m_shapesopaque.insert( m_shapesopaque.end(), std::make_move_iterator( Other.m_shapesopaque.begin() ), std::make_move_iterator( Other.m_shapesopaque.end() ) ); + m_shapestranslucent.insert( m_shapestranslucent.end(), std::make_move_iterator( Other.m_shapestranslucent.begin() ), std::make_move_iterator( Other.m_shapestranslucent.end() ) ); + m_lines.insert( m_lines.end(), std::make_move_iterator( Other.m_lines.begin() ), std::make_move_iterator( Other.m_lines.end() ) ); + m_active = true == m_active || true == Other.m_active; + Other.m_shapesopaque.clear(); + Other.m_shapestranslucent.clear(); + Other.m_lines.clear(); +} + // sends content of the class in legacy (text) format to provided stream void basic_cell::export_as_text( std::ostream &Output ) const { @@ -782,6 +861,22 @@ basic_section::update_traction( TDynamicObject *Vehicle, int const Pantographind } } +// checks whether a wire of the section's cells around specified point is within reach of a pantograph at the point +bool +basic_section::wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double const Halfwidth, double const Minheight, double const Maxheight ) const { + + auto const radius { EU07_CELLSIZE * 0.5 }; // the same area of interest the pantographs look for their wire in + + for( auto const &cell : m_cells ) { + // we reject early cells which aren't within our area of interest + if( glm::length2( cell.area().center - Point ) < sq( cell.area().radius + radius ) + && cell.wire_over( Point, Front, Up, Left, Halfwidth, Minheight, Maxheight ) ) { + return true; + } + } + return false; +} + // legacy method, polls event launchers within radius around specified point void basic_section::update_events( glm::dvec3 const &Location, float const Radius ) { @@ -857,7 +952,7 @@ basic_section::deserialize( std::istream &Input ) { m_area.deserialize( Input ); // section shapes: shape count followed by shape data auto shapecount { sn_utils::ld_uint32( Input ) }; - while( shapecount-- ) { + while( ( shapecount-- ) && ( true == Input.good() ) ) { m_shapes.emplace_back( shape_node().deserialize( Input ) ); } // partitioned data @@ -866,6 +961,19 @@ basic_section::deserialize( std::istream &Input ) { } } +// takes over the content restored from a file into another section, as deserialize() would have added it to this one +void +basic_section::merge( basic_section &&Other ) { + + m_area.center = Other.m_area.center; + m_area.radius = std::max( m_area.radius, Other.m_area.radius ); + m_shapes.insert( m_shapes.end(), std::make_move_iterator( Other.m_shapes.begin() ), std::make_move_iterator( Other.m_shapes.end() ) ); + Other.m_shapes.clear(); + for( std::size_t index { 0 }; index < m_cells.size(); ++index ) { + m_cells[ index ].merge( std::move( Other.m_cells[ index ] ) ); + } +} + // sends content of the class in legacy (text) format to provided stream void basic_section::export_as_text( std::ostream &Output ) const { @@ -1165,30 +1273,44 @@ basic_region::update_traction( TDynamicObject *Vehicle, int const Pantographinde } } +// checks whether there's a contact wire over specified point, within reach of a pantograph there +bool +basic_region::wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, double const Halfwidth, double const Minheight, double const Maxheight ) const { + + // the vertical up and the horizontal left of the heading. the tilt of the track in curves is left out + auto const up { glm::dvec3 { 0.0, 1.0, 0.0 } }; + auto const left { glm::cross( up, Front ) }; + auto const leftlength { glm::length( left ) }; + if( leftlength <= 0.0 ) { + // no heading along the ground + return false; + } + // a list of its own, not the shared scratchpad of the region + std::vector sectionlist; + sections( Point, EU07_CELLSIZE * 0.5, sectionlist ); + for( auto const *section : sectionlist ) { + if( section->wire_over( Point, Front, up, left / leftlength, Halfwidth, Minheight, Maxheight ) ) { + return true; + } + } + return false; +} + // checks whether specified file is a valid region data file bool basic_region::is_scene( std::string const &Scenariofile ) const { - auto filename { Scenariofile }; - while( filename[ 0 ] == '$' ) { - // trim leading $ char rainsted utility may add to the base name for modified .scn files - filename.erase( 0, 1 ); - } - erase_extension( filename ); - filename = Global.asCurrentSceneryPath + filename; - filename += EU07_FILEEXTENSION_REGION; + auto const filename { region_file_name( Scenariofile ) }; if( false == FileExists( filename ) ) { return false; } - // file type and version check + // file type and version check, and whether the sections add up to the whole file. a file cut short (by a write + // interrupted with an older version, or a copy) is caught here, while the scenery can still be loaded from the text std::ifstream input( filename, std::ios::binary ); - - uint32_t headermain{ sn_utils::ld_uint32( input ) }; - uint32_t headertype{ sn_utils::ld_uint32( input ) }; - - if( headermain != EU07_FILEHEADER || headertype != EU07_FILEVERSION_REGION ) { - // wrong file type + if( auto const layout { region_file::check_layout( input, EU07_FILEHEADER, EU07_FILEVERSION_REGION, static_cast( m_sections.size() ) ) }; + false == layout.empty() ) { + WriteLog( "Bad file: \"" + filename + "\" " + layout + ", ignored" ); return false; } @@ -1199,38 +1321,35 @@ basic_region::is_scene( std::string const &Scenariofile ) const { void basic_region::serialize( std::string const &Scenariofile ) const { - auto filename { Scenariofile }; - while( filename[ 0 ] == '$' ) { - // trim leading $ char rainsted utility may add to the base name for modified .scn files - filename.erase( 0, 1 ); - } - erase_extension( filename ); - filename = Global.asCurrentSceneryPath + filename; - filename += EU07_FILEEXTENSION_REGION; + auto const filename { region_file_name( Scenariofile ) }; - std::ofstream output { filename, std::ios::binary }; - - // region file version 1 - // header: EU07SBT + version (0-255) - sn_utils::ls_uint32( output, EU07_FILEHEADER ); - sn_utils::ls_uint32( output, EU07_FILEVERSION_REGION ); - // sections - // TBD, TODO: build table of sections and file offsets, if we postpone section loading until they're within range - std::uint32_t sectioncount { 0 }; - for( auto *section : m_sections ) { - if( section != nullptr ) { - ++sectioncount; + // the file is written under a temporary name and takes the final one only when complete, so a write cut short + // (a crash, the process killed) leaves no partial file to be read on the next start + auto const error { region_file::write_through_temporary( filename, [ this ]( std::ostream &output ) { + // region file version 1 + // header: EU07SBT + version (0-255) + sn_utils::ls_uint32( output, EU07_FILEHEADER ); + sn_utils::ls_uint32( output, EU07_FILEVERSION_REGION ); + // sections + // TBD, TODO: build table of sections and file offsets, if we postpone section loading until they're within range + std::uint32_t sectioncount { 0 }; + for( auto *section : m_sections ) { + if( section != nullptr ) { + ++sectioncount; + } } - } - // section count, followed by section data - sn_utils::ls_uint32( output, sectioncount ); - std::uint32_t sectionindex { 0 }; - for( auto *section : m_sections ) { - // section data: section index, followed by length of section data, followed by section data - if( section != nullptr ) { - sn_utils::ls_uint32( output, sectionindex ); - section->serialize( output ); } - ++sectionindex; + // section count, followed by section data + sn_utils::ls_uint32( output, sectioncount ); + std::uint32_t sectionindex { 0 }; + for( auto *section : m_sections ) { + // section data: section index, followed by length of section data, followed by section data + if( section != nullptr ) { + sn_utils::ls_uint32( output, sectionindex ); + section->serialize( output ); } + ++sectionindex; + } } ) }; + if( false == error.empty() ) { + ErrorLog( "Bad file: binary version of the scenery wasn't written, " + error ); } } @@ -1238,48 +1357,69 @@ basic_region::serialize( std::string const &Scenariofile ) const { bool basic_region::deserialize( std::string const &Scenariofile ) { - auto filename { Scenariofile }; - while( filename[ 0 ] == '$' ) { - // trim leading $ char rainsted utility may add to the base name for modified .scn files - filename.erase( 0, 1 ); - } - erase_extension( filename ); - filename = Global.asCurrentSceneryPath + filename; - filename += EU07_FILEEXTENSION_REGION; + auto const filename { region_file_name( Scenariofile ) }; if( false == FileExists( filename ) ) { Global.file_binary_terrain_state = false; return false; } // region file version 1 - // file type and version check + // file type and version check, and whether the sections add up to the whole file std::ifstream input( filename, std::ios::binary ); - - uint32_t headermain { sn_utils::ld_uint32( input ) }; - uint32_t headertype { sn_utils::ld_uint32( input ) }; - - if( headermain != EU07_FILEHEADER || headertype != EU07_FILEVERSION_REGION ) { - // wrong file type - WriteLog( "Bad file: \"" + filename + "\" is of either unrecognized type or version" ); + auto const sectionlimit { static_cast( m_sections.size() ) }; + auto error { region_file::check_layout( input, EU07_FILEHEADER, EU07_FILEVERSION_REGION, sectionlimit ) }; + if( false == error.empty() ) { + ErrorLog( "Bad file: \"" + filename + "\" " + error + ", the geometry it holds is missing" ); return false; } // sections // TBD, TODO: build table of sections and file offsets, if we postpone section loading until they're within range - // section count - auto sectioncount { sn_utils::ld_uint32( input ) }; - while( sectioncount-- ) { - // section index, followed by section data size, followed by section data - auto const sectionindex { sn_utils::ld_uint32( input ) }; - auto const sectionsize { sn_utils::ld_uint32( input ) }; - if( m_sections[ sectionindex ] == nullptr ) { - m_sections[ sectionindex ] = new basic_section(); + // the sections are restored apart from the region, which takes them over only once the whole file was read + // without a fault: a damaged file leaves nothing of itself behind + std::vector>> sections; + try { + input.clear(); + input.seekg( 2 * sizeof( std::uint32_t ), std::ios::beg ); + // section count + auto sectioncount { sn_utils::ld_uint32( input ) }; + sections.reserve( sectioncount ); + while( ( sectioncount-- ) && ( true == error.empty() ) ) { + error = read_region_section( input, sectionlimit, sections ); + } + } + catch( std::exception const &Exception ) { + error = std::string( "can't be read, " ) + Exception.what(); + } + if( false == error.empty() ) { + ErrorLog( "Bad file: \"" + filename + "\" " + error + ", the geometry it holds is missing" ); + return false; + } + for( auto &[ sectionindex, section ] : sections ) { + if( m_sections[ sectionindex ] == nullptr ) { + m_sections[ sectionindex ] = section.release(); + } + else { + m_sections[ sectionindex ]->merge( std::move( *section ) ); } - m_sections[ sectionindex ]->deserialize( input ); } return true; } +// removes the region file of specified scenario file, which turned out to be damaged, so the next start writes it anew +void +basic_region::discard_scene( std::string const &Scenariofile ) const { + + auto const filename { region_file_name( Scenariofile ) }; + std::error_code error; + if( true == std::filesystem::remove( filename, error ) ) { + WriteLog( "Bad file: \"" + filename + "\" removed, it will be made anew from the scenery on the next start" ); + } + else if( error ) { + ErrorLog( "Bad file: \"" + filename + "\" can't be removed, " + error.message() + ". Remove it to have it made anew from the scenery" ); + } +} + // sends content of the class in legacy (text) format to provided stream void basic_region::export_as_text( std::ostream &Output ) const { diff --git a/scene/scene.h b/scene/scene.h index 5560171bb..e92b11988 100644 --- a/scene/scene.h +++ b/scene/scene.h @@ -107,6 +107,10 @@ public: // legacy method, finds and assigns traction piece to specified pantograph of provided vehicle void update_traction( TDynamicObject *Vehicle, int const Pantographindex ); + // checks whether a wire, not broken, is within reach of a pantograph at specified point: the plane of the pantograph's + // movement, normal to Front, crosses it over the slide of half width Halfwidth, between Minheight and Maxheight along Up + bool + wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double const Halfwidth, double const Minheight, double const Maxheight ) const; // legacy method, polls event launchers within radius around specified point void update_events(); @@ -132,6 +136,9 @@ public: // restores content of the class from provided stream void deserialize( std::istream &Input ); + // takes over the content restored from a file into another cell, as deserialize() would have added it to this one + void + merge( basic_cell &&Other ); // sends content of the class in legacy (text) format to provided stream void export_as_text( std::ostream &Output ) const; @@ -347,6 +354,10 @@ public: // legacy method, finds and assigns traction piece to specified pantograph of provided vehicle void update_traction( TDynamicObject *Vehicle, int const Pantographindex ); + // checks whether a wire, not broken, is within reach of a pantograph at specified point: the plane of the pantograph's + // movement, normal to Front, crosses it over the slide of half width Halfwidth, between Minheight and Maxheight along Up + bool + wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double const Halfwidth, double const Minheight, double const Maxheight ) const; // legacy method, updates sounds and polls event launchers within radius around specified point void update_events( glm::dvec3 const &Location, float const Radius ); @@ -362,6 +373,9 @@ public: // restores content of the class from provided stream void deserialize( std::istream &Input ); + // takes over the content restored from a file into another section, as deserialize() would have added it to this one + void + merge( basic_section &&Other ); // sends content of the class in legacy (text) format to provided stream void export_as_text( std::ostream &Output ) const; @@ -476,6 +490,11 @@ public: // legacy method, finds and assigns traction piece to specified pantograph of provided vehicle void update_traction( TDynamicObject *Vehicle, int const Pantographindex ); + // checks whether there's a contact wire, not broken, over specified point of a track with heading Front, within reach of + // a pantograph there: over its slide of half width Halfwidth, between Minheight and Maxheight above the point. the + // geometry is the one the pantographs find their wire with (ai_wire::span_contact), with the vertical up + bool + wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, double const Halfwidth, double const Minheight, double const Maxheight ) const; // legacy method, polls event launchers around camera void update_events(); @@ -491,6 +510,9 @@ public: // restores content of the class from file with specified name. returns: true on success, false otherwise bool deserialize( std::string const &Scenariofile ); + // removes the region file of specified scenario file, which turned out to be damaged, so the next start writes it anew + void + discard_scene( std::string const &Scenariofile ) const; // sends content of the class in legacy (text) format to provided stream void export_as_text( std::ostream &Output ) const; diff --git a/scene/scenelayerssave.cpp b/scene/scenelayerssave.cpp index 37983e147..5d52689e9 100644 --- a/scene/scenelayerssave.cpp +++ b/scene/scenelayerssave.cpp @@ -27,6 +27,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/translation.h" #include "editor/editorFormat.hpp" +#include #include #include #include @@ -1768,8 +1769,8 @@ save_result node_layers::save(std::vector const &Rootstatements, st // without the copy nothing is replaced { auto const now{std::time(nullptr)}; - char stamp[32]; - std::strftime(stamp, sizeof(stamp), "%Y%m%d-%H%M%S", std::localtime(&now)); + std::tm const local{local_tm(now)}; + auto const stamp{std::format("{:04}{:02}{:02}-{:02}{:02}{:02}", local.tm_year + 1900, local.tm_mon + 1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec)}; for (auto const output : written) { auto const filepath{path(output)}; diff --git a/scene/scenenode.cpp b/scene/scenenode.cpp index 426f0e077..afe87cf83 100644 --- a/scene/scenenode.cpp +++ b/scene/scenenode.cpp @@ -108,7 +108,13 @@ shape_node::shapenode_data::deserialize( std::istream &Input ) { origin = sn_utils::d_dvec3( Input ); // NOTE: geometry handle is acquired during geometry creation // vertex data - vertices.resize( sn_utils::ld_uint32( Input ) ); + auto const vertexcount { sn_utils::ld_uint32( Input ) }; + if( vertexcount > sn_utils::remaining( Input ) / ( 8 * sizeof( float ) ) ) { + // each vertex takes 8 floats of the data at least: a count the rest of it can't hold comes from a damaged file + Input.setstate( std::ios::failbit ); + return; + } + vertices.resize( vertexcount ); if(has_userdata) userdata.resize(vertices.size()); gfx::basic_vertex localvertex; @@ -143,7 +149,7 @@ shape_node::deserialize( std::istream &Input ) { // restores content of the node from provided input stream shape_node & -shape_node::import( cParser &Input, scene::node_data const &Nodedata ) { +shape_node::import_from( cParser &Input, scene::node_data const &Nodedata ) { // import common data m_name = Nodedata.name; @@ -527,7 +533,13 @@ lines_node::linesnode_data::deserialize( std::istream &Input ) { origin = sn_utils::d_dvec3( Input ); // NOTE: geometry handle is acquired during geometry creation // vertex data - vertices.resize( sn_utils::ld_uint32( Input ) ); + auto const vertexcount { sn_utils::ld_uint32( Input ) }; + if( vertexcount > sn_utils::remaining( Input ) / ( 8 * sizeof( float ) ) ) { + // each vertex takes 8 floats of the data at least: a count the rest of it can't hold comes from a damaged file + Input.setstate( std::ios::failbit ); + return; + } + vertices.resize( vertexcount ); gfx::basic_vertex localvertex; for( auto &vertex : vertices ) { localvertex.deserialize( Input ); @@ -561,7 +573,7 @@ lines_node::deserialize( std::istream &Input ) { // restores content of the node from provded input stream lines_node & -lines_node::import( cParser &Input, scene::node_data const &Nodedata ) { +lines_node::import_from( cParser &Input, scene::node_data const &Nodedata ) { // import common data m_name = Nodedata.name; diff --git a/scene/scenenode.h b/scene/scenenode.h index f10ac0d16..d0246adc1 100644 --- a/scene/scenenode.h +++ b/scene/scenenode.h @@ -122,7 +122,7 @@ public: deserialize( std::istream &Input ); // restores content of the node from provided input stream shape_node & - import( cParser &Input, scene::node_data const &Nodedata ); + import_from( cParser &Input, scene::node_data const &Nodedata ); // imports data from provided submodel shape_node & convert( TSubModel const *Submodel ); @@ -254,7 +254,7 @@ public: deserialize( std::istream &Input ); // restores content of the node from provided input stream lines_node & - import( cParser &Input, scene::node_data const &Nodedata ); + import_from( cParser &Input, scene::node_data const &Nodedata ); // adds content of provided node to already enclosed geometry. returns: true if merge could be performed bool merge( lines_node &Lines ); diff --git a/scene/scenenodegroups.cpp b/scene/scenenodegroups.cpp index 781287806..e3d1bc463 100644 --- a/scene/scenenodegroups.cpp +++ b/scene/scenenodegroups.cpp @@ -207,12 +207,12 @@ node_groups::update_map() continue; last_switch->track[lastc - 'a'] = track; - for (auto trk : last_switch->track) - if (!trk) - goto skip_e; + // all four tracks of the cross switch have to be known before it's assigned + if (!std::ranges::all_of(last_switch->track, [](TTrack const *Track) { return Track != nullptr; })) + continue; if (!assign_cross_switch(*last_switch, sw_name, "ac", 0)) - skip_e: continue; + continue; if (!assign_cross_switch(*last_switch, sw_name, "ad", 1)) continue; if (!assign_cross_switch(*last_switch, sw_name, "bc", 2)) diff --git a/scene/sceneterrain.cpp b/scene/sceneterrain.cpp index d0453f2b3..585912a2b 100644 --- a/scene/sceneterrain.cpp +++ b/scene/sceneterrain.cpp @@ -455,7 +455,7 @@ bool terrain_file::write(std::string const &Text, std::string const &Binaryfile, Message = "node of type \"" + nodedata.type + "\" (line " + std::to_string(input.Line()) + ") can't be a part of binary terrain"; return false; } - auto shape{shape_node().import(input, nodedata)}; + auto shape{shape_node().import_from(input, nodedata)}; // the shapes are all sent to the section cells, which groups them the way it'd be done for translucent geometry. // whether they can be merged into section-wide pieces instead is decided when the file is loaded, see the layout notes shape.m_data.translucent = true; @@ -799,7 +799,7 @@ bool read_text_triangles(std::string const &Text, terrain_reference const &Refer input >> nodedata.range_max >> nodedata.range_min >> nodedata.name >> nodedata.type; if (nodedata.type == "triangles" || nodedata.type == "triangle_strip" || nodedata.type == "triangle_fan") { - auto const shape{shape_node().import(input, nodedata)}; + auto const shape{shape_node().import_from(input, nodedata)}; auto const &data{shape.data()}; auto const *material{GfxRenderer->Material(data.material)}; auto const name{material != nullptr ? material->GetName() : std::string{}}; diff --git a/scene/sn_utils.cpp b/scene/sn_utils.cpp index b6a3f7c32..fbdbcb7f0 100644 --- a/scene/sn_utils.cpp +++ b/scene/sn_utils.cpp @@ -93,14 +93,26 @@ std::string sn_utils::d_str(std::istream &s) char c{}; while (true) { - s.read(&c, 1); - if (c == 0) + // a string cut short by the end of the data ends there too + if (!s.read(&c, 1) || c == 0) break; r.push_back(c); } return r; } +// number of bytes left to read in the stream, 0 if it failed or can't tell +std::uint64_t sn_utils::remaining(std::istream &s) +{ + auto const position{s.tellg()}; + if (position < 0) + return 0; + s.seekg(0, std::ios::end); + auto const end{s.tellg()}; + s.seekg(position); + return end > position ? static_cast(end - position) : 0; +} + bool sn_utils::d_bool(std::istream& s) { return ld_uint16(s) == 1; diff --git a/scene/sn_utils.h b/scene/sn_utils.h index 4212ac29a..87da22d93 100644 --- a/scene/sn_utils.h +++ b/scene/sn_utils.h @@ -20,6 +20,8 @@ public: static glm::dvec3 d_dvec3(std::istream&); static glm::vec3 d_vec3(std::istream&); static glm::vec4 d_vec4(std::istream&); + // number of bytes left to read in the stream, 0 if it failed or can't tell + static std::uint64_t remaining(std::istream&); static void ls_uint16(std::ostream&, uint16_t); static void ls_uint32(std::ostream&, uint32_t); diff --git a/script_screens_doc.md b/script_screens_doc.md index 52ccc9ced..3e9248d11 100644 --- a/script_screens_doc.md +++ b/script_screens_doc.md @@ -137,6 +137,48 @@ used: - on the cpu, in the screens' worker, when the renderer can't do it on the gpu (the NVRHI renderer, OpenGL ES, a shader that failed to load) or `screens.gpupost` is 0. A shader that fails is logged once, and the cpu takes over. +### Limits of a Lua script + +Besides the 200 million instructions of a call, a Lua screen is held to what runs in C, where the count doesn't reach: + +- memory: a screen holds at most 128 MB: its Lua heap and the pixels of its images, fonts and sprites (4 bytes a pixel + of an image, 1 of a font or a sprite). An object that would take the screen over is refused (`memory limit + exceeded`), and a screen found holding more stops with that error. Garbage doesn't count: the check collects it + first, every thousand instructions and before the calls below. Between the checks the screen's heap goes through a + counter of the game's, in front of LuaJIT's own allocator, which refuses a block that would take the screen over + twice the limit as it is asked for (`not enough memory`, an error the script may catch). So what one instruction + makes is held as well: a loop doubling a string (`for i = 1, 11 do s = s .. s end` on a 1 MB `s`) stops at the + concatenation that would go over 256 MB, not at LuaJIT's own heap limit of about 2 GB; +- `string.rep` makes no string over 1 MB; `string.format`, `table.concat` and `string.gsub` (with a string or a table to + replace with) refuse a result that may be over the memory of a screen, counted from the lengths of what they are + given; +- the pattern functions (`string.find`, `match`, `gmatch`, `gsub`) backtrack, and some patterns take hours on a long + subject (`("a"):rep(1e6):find(".-b")`). A call is refused (`the pattern may take too long`) when the steps it may + take at worst are over 100 million, about a tenth of a second at worst: the length of the subject (plus one), times the + length of the pattern, times the subject again for each repetition (`*`, `+`, `-`, `%b`, a back reference `%1`) but + one followed by what always matches (nothing, as in a repetition that ends the pattern, or `(.-)%s*$`), times 2 for + each `?`, and taken once rather than from every position for a pattern anchored with `^` (not in `gmatch`). A + repetition of a character or a `%` class right before the final `$` (`%s*$`) counts the longest run of it in the + subject rather than the whole subject. A plain search (`find` with `plain`, or a pattern of no special characters) is + the subject times the pattern. So a pattern ending in its only repetition (`"[^\n]+"`, `"%d+"`) works on any subject, + one more repetition (`"(%w+)=(%w+)"`) on some 3 000 to 5 000 bytes, and each further one divides that a lot. The + usual trim, `s:match("^%s*(.-)%s*$")`, costs the line times its longest run of spaces: a line of words, even a + megabyte long, is fine, but a long run of spaces inside it is refused, since the trim really takes the square of that. + A trim that stays linear on any string: + + ```lua + local function trim(s) + local first = s:find("%S") + if not first then return "" end + return s:sub(first, #s - s:reverse():find("%S") + 1) + end + ``` +- `xpcall` is made of `pcall`: the handler gets the error once it has left the function, and a coroutine may yield + inside either. There is no `newproxy`, so no finalizer (`__gc`) of the script's own: LuaJIT runs those without the + instruction count; +- the game reads `render` and `init` of the script's table in protected mode, so a metatable of the script's + (`__index`) may provide them; one that fails or runs over switches the screen off. + ## WebAssembly modules A module exports: @@ -208,3 +250,64 @@ clang --target=wasm32 -O2 -nostdlib -Wl,--no-entry -o ekran.wasm ekran.c Any language that compiles to WebAssembly works the same way (Rust `wasm32-unknown-unknown`, Zig, AssemblyScript), as long as the module imports nothing but the `eu07` functions above. + +## Scenery scripts + +A scenery runs a Lua script with `lua ` in its `.scn`, while the scenery loads. The script registers events +and works with memcells, tracks and vehicles through the table `eu07.events` (`event_create`, `event_dispatch`, +`memcell_update`, `writelog` and the rest, see `scripting/lua.cpp`). It shares the sandbox of the Lua screens: + +- the file is a path relative to the scenery folder (`scenery/`), and stays inside it: no `..`, no drive, no leading + `/`. `/` and `\` both separate folders, on Linux too. It is text, of at most 16 MB; precompiled code is not loaded; +- the script gets the base library, `table`, `string`, `math` and `bit`, and of `os` only the clock: `os.time`, + `os.clock`, `os.difftime` and `os.date` (with the C89 conversions only, `%Y`, `%d`, `%H` and so on). It gets no + `io`, the rest of `os`, `ffi`, `debug`, `jit`, `package`, `require`, `dofile`, `load`, `loadfile` or `loadstring`; +- a script that fails stops there, the error goes to the log with the file name and line, and the scenery goes on + loading. An event handler that fails is logged with the name of the event, and the simulation goes on; +- the events, tracks, isolated circuits, memcells and vehicles the functions give (`event_find`, `track_find`, + `memcell_find`, the event and the vehicle an event handler gets...) are handles of their kind: equal for the same + object, usable as keys of a table, and taken only where that kind goes. Another kind, or any other value, is an + error (`bad argument #1 to 'memcell_update' (eu07.memcell expected, got userdata)`); `nil`, which the find + functions give for a missing object, is taken as no object, as before. An event run without a vehicle gives its + handler `nil` for the vehicle. + +Instead of `io`, a scenery script reads and writes files through `eu07`, as the Lua screens read theirs: + +| function | meaning | +|----------------------------------|------------------------------------------------------------------------------------------| +| `eu07.read_file(path)` | the contents of a file of the scenery folder (`scenery/`), or `nil`: a regular file of at most 16 MB, the path as for `lua ` | +| `eu07.write_file(path, text)` | writes `text` (any bytes) to a file of the scenery's data folder, replacing what was there, and makes the folders of `path`; returns `true`, or `nil` and the reason | +| `eu07.read_data_file(path)` | the contents of a file of the scenery's data folder, or `nil`: what `write_file` wrote there | + +The data folder is the scenery's own, in the player's folder of the game: `%APPDATA%\MaSzyna\scenery_data\\` +on Windows, `~/.config/MaSzyna/scenery_data//` on Linux (`~/Library/Application Support/MaSzyna/...` on a +Mac), `` being the `.scn` file without `.scn` (`td.scn`: `scenery_data/td/`). The game writes nowhere else +for a script, and never into its own folder; the log says where the folder is when the scenery loads its first +script. What is written there stays for the next run of the scenery, and the player may delete it. + +A path to write to is relative, with `/` or `\` between the folders, at most 8 folders deep and 200 bytes long, and +each name in it portable: no `..`, no `.`, no empty name, no drive, no `:` `<` `>` `"` `|` `?` `*` or control +characters, no `.` or space at the end, and none of the names Windows keeps for its devices (`con`, `nul`, `com1`, +`lpt1`... with or without an extension). A file is at most 1 MB (1048576 bytes), and the data folder of a scenery holds at most 256 +files and 16 MB together; a write over these limits is refused, and leaves the file as it was. + +```lua +local saved = eu07.read_data_file("state.txt") +local runs = tonumber(saved or "0") + 1 +local ok, reason = eu07.write_file("state.txt", tostring(runs)) +if not ok then eu07.events.writelog("state not saved: " .. reason) end +``` + +A script written for the earlier full libraries stops at the first call to one of them (`attempt to index global +'io' (a nil value)` in the log). For a scenery you trust, `eu07.ini` can give the scripts all of LuaJIT's libraries +again: + +| key | default | meaning | +|---------------------|---------|------------------------------------------------------------------------------------------| +| `lua.fulllibraries` | no | yes: the scenery scripts get all of LuaJIT's libraries (`io`, `os`, `ffi`, `require`...), and with them the files and programs of the computer. The Lua screens stay sandboxed | + +Only `eu07.ini` turns it on: a `config` block of a scenery doesn't (the log says the key was ignored). Nor does it set +the other keys that would take a scenery out of its sandbox or reach the computer: `execonexit`, `extcam.cmd`, +`extcam.rec`, `screenshotsdir`, `network.server`, `network.client`, `zmq.address`, `motiontelemetry`, `uart`, +`feedbackmode`, `feedbackport`, nor does it switch on `python.enabled`, `luascreens.enabled` or `wasm.enabled` when +`eu07.ini` has them off. A scenery may still switch those three off, or `lua.fulllibraries` off, as it always could. diff --git a/scripting/lua.cpp b/scripting/lua.cpp index 14ecbb75d..2011413b5 100644 --- a/scripting/lua.cpp +++ b/scripting/lua.cpp @@ -5,6 +5,8 @@ #include "world/MemCell.h" #include "vehicle/Driver.h" #include "simulation/simulation.h" +#include "scripting/luasandbox.h" +#include "utilities/utilities.h" lua::lua() { @@ -12,7 +14,13 @@ lua::lua() if (!state) throw std::runtime_error("cannot create lua state"); lua_atpanic(state, atpanic); - luaL_openlibs(state); + // sandboxed as the script screens are: no io, ffi, debug, require or load*, and of os only the clock. + // lua.fulllibraries in eu07.ini opens the rest when the scenery loads its first script (interpret()) + lua_sandbox::open_safe_libraries(state); + lua_sandbox::open_clock_library(state); + // the events, tracks, isolated circuits, vehicles and memcells a script holds: a userdata of a metatable of each + // kind, which the functions check + lua_sandbox::open_handles(state); static constexpr luaL_Reg api[] = { @@ -41,6 +49,9 @@ lua::lua() {nullptr, nullptr} }; luaL_register(state, "eu07.events", api); + lua_pop(state, 1); + // eu07.read_file, eu07.write_file and eu07.read_data_file, the files of the scenery in place of io + lua_sandbox::open_file_library(state, &files); } lua::~lua() @@ -51,21 +62,38 @@ lua::~lua() std::string lua::get_error() const { - return lua_tostring(state, -1); + auto const *error = lua_tostring(state, -1); + return error ? error : "unknown error"; } -void lua::interpret(const std::string& file) const +void lua::interpret(const std::string &folder, const std::string &file) { - if (luaL_dofile(state, file.c_str())) { - std::string str = lua_tostring(state, -1); - ErrorLog("lua: Runtime error: " + str, logtype::lua); + if (Global.lua_fulllibraries && !full_libraries) { + // all of LuaJIT's libraries, as before the sandbox: the scripts may then reach files, programs and ffi + luaL_openlibs(state); + full_libraries = true; + WriteLog("lua: lua.fulllibraries is on, the scenery scripts run with all libraries (io, os, ffi, require...)", logtype::lua); + } + // the scripts read the files of the scenery folder, and write theirs into a folder of the scenery among the + // player's files (%APPDATA%/MaSzyna, ~/.config/MaSzyna), never into the game + files.scenery = folder; + if (auto data = lua_sandbox::scenery_data_folder(user_config_path("scenery_data"), Global.SceneryFile); data != files.data) { + files.data = std::move(data); + auto const name = files.data.u8string(); + if (!name.empty()) + WriteLog("lua: the scenery scripts write their files (eu07.write_file) to \"" + std::string(name.begin(), name.end()) + "\"", logtype::lua); + } + // a relative path inside the scenery folder, a file of text, run in protected mode: a script that fails stops + // there, and the scenery goes on loading + if (auto const error = lua_sandbox::run_script_file(state, folder, file)) { + ErrorLog("lua: " + *error, logtype::lua); } } int lua::atpanic(lua_State *s) { - std::string err = lua_tostring(s, -1); - ErrorLog("lua: Runtime error: " + err, logtype::lua); + auto const *err = lua_tostring(s, -1); + ErrorLog(std::string("lua: Runtime error: ") + (err ? err : "unknown error"), logtype::lua); return 0; } @@ -75,13 +103,37 @@ void lua::unref(lua_State *L, const int ref) luaL_unref(L, LUA_REGISTRYINDEX, ref); } +namespace { + +struct event_call { + int handler; + basic_event *event; + TDynamicObject *activator; +}; + +// calls the handler of the event (event_call) with the handles of the event and its activator (nil when there is none) +int call_handler(lua_State *L) +{ + auto const &call = *static_cast(lua_touserdata(L, 1)); + lua_rawgeti(L, LUA_REGISTRYINDEX, call.handler); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::event, call.event); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::vehicle, call.activator); + lua_call(L, 2, 0); + return 0; +} + +} // namespace + /// Executes the callback function of an event created with `scriptapi_event_create`. void lua::dispatch_event(lua_State *L, const int handler, basic_event *event, const TDynamicObject *activator) { - lua_rawgeti(L, LUA_REGISTRYINDEX, handler); - lua_pushlightuserdata(L, event); - lua_pushlightuserdata(L, const_cast(activator)); - lua_call(L, 2, 0); + event_call call{handler, event, const_cast(activator)}; + // in protected mode, the handles made as well: a handler that fails is logged, and the simulation goes on + if (lua_cpcall(L, call_handler, &call) != 0) { + auto const *error = lua_tostring(L, -1); + ErrorLog("lua: event " + (event ? event->m_name : std::string("?")) + ": " + (error ? error : "unknown error"), logtype::lua); + lua_pop(L, 1); + } } void lua::push_memcell_values(lua_State *L, const TMemCell *mc) @@ -103,11 +155,17 @@ memcell_values lua::get_memcell_values(lua_State *L, int idx) // For negative indices, we need to account for the extra item that is the key name/value extracted from the table. if (idx < 0) idx--; - memcell_values mc{nullptr, 0.0, 0.0}; + luaL_checktype(L, idx, LUA_TTABLE); + // no text in the table is an empty one: the memcell and the vehicle take the text as a string. copied: the text of + // a number is made on the stack, and gone with it + memcell_values mc{"", 0.0, 0.0}; lua_pushstring(L, "str"); lua_gettable(L, idx); - if (lua_isstring(L, -1)) - mc.str = lua_tostring(L, -1); + if (lua_isstring(L, -1)) { + std::size_t length = 0; + auto const *text = lua_tolstring(L, -1, &length); + mc.str.assign(text, length); + } lua_pop(L, 1); lua_pushstring(L, "num1"); lua_gettable(L, idx); @@ -124,7 +182,7 @@ memcell_values lua::get_memcell_values(lua_State *L, int idx) int lua::scriptapi_event_create(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); double delay = lua_tonumber(L, 2); double randomdelay = lua_tonumber(L, 3); lua_pushvalue(L, 4); @@ -136,7 +194,7 @@ int lua::scriptapi_event_create(lua_State *L) event->m_delayrandom = randomdelay; if (simulation::Events.insert(event)) { - lua_pushlightuserdata(L, event); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::event, event); return 1; } return 0; @@ -144,11 +202,11 @@ int lua::scriptapi_event_create(lua_State *L) int lua::scriptapi_event_find(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); basic_event *foundevent = simulation::Events.FindEvent(name); if (foundevent) { - lua_pushlightuserdata(L, foundevent); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::event, foundevent); return 1; } ErrorLog("lua: missing event: " + name); @@ -157,7 +215,7 @@ int lua::scriptapi_event_find(lua_State *L) int lua::scriptapi_event_exists(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); basic_event *foundevent = simulation::Events.FindEvent(name); lua_pushboolean(L, foundevent != nullptr); return 1; @@ -165,7 +223,7 @@ int lua::scriptapi_event_exists(lua_State *L) int lua::scriptapi_event_getname(lua_State *L) { - auto *event = static_cast(lua_touserdata(L, 1)); + auto *event = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::event); if (event) { lua_pushstring(L, event->m_name.c_str()); @@ -176,8 +234,8 @@ int lua::scriptapi_event_getname(lua_State *L) int lua::scriptapi_event_dispatch(lua_State *L) { - auto *event = static_cast(lua_touserdata(L, 1)); - auto *activator = static_cast(lua_touserdata(L, 2)); + auto *event = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::event); + auto *activator = lua_sandbox::check_handle(L, 2, lua_sandbox::handle_kind::vehicle); double delay = lua_tonumber(L, 3); if (event) simulation::Events.AddToQuery(event, activator, delay); @@ -186,8 +244,8 @@ int lua::scriptapi_event_dispatch(lua_State *L) int lua::scriptapi_event_dispatch_n(lua_State *L) { - std::string name = lua_tostring(L, 1); - auto *activator = static_cast(lua_touserdata(L, 2)); + std::string name = luaL_checkstring(L, 1); + auto *activator = lua_sandbox::check_handle(L, 2, lua_sandbox::handle_kind::vehicle); double delay = lua_tonumber(L, 3); basic_event *foundevent = simulation::Events.FindEvent(name); if (foundevent) @@ -199,11 +257,11 @@ int lua::scriptapi_event_dispatch_n(lua_State *L) int lua::scriptapi_track_find(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); TTrack *track = simulation::Paths.find(name); if (track) { - lua_pushlightuserdata(L, track); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::track, track); return 1; } ErrorLog("lua: missing track: " + name); @@ -212,7 +270,7 @@ int lua::scriptapi_track_find(lua_State *L) int lua::scriptapi_track_isoccupied(lua_State *L) { - auto *track = static_cast(lua_touserdata(L, 1)); + auto *track = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::track); if (track) { lua_pushboolean(L, !track->IsEmpty()); @@ -223,7 +281,7 @@ int lua::scriptapi_track_isoccupied(lua_State *L) int lua::scriptapi_track_isoccupied_n(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); TTrack *track = simulation::Paths.find(name); if (track) { @@ -236,11 +294,11 @@ int lua::scriptapi_track_isoccupied_n(lua_State *L) int lua::scriptapi_isolated_find(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); TIsolated *isolated = TIsolated::Find(name); if (isolated) { - lua_pushlightuserdata(L, isolated); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::isolated, isolated); return 1; } ErrorLog("lua: missing isolated: " + name); @@ -249,7 +307,7 @@ int lua::scriptapi_isolated_find(lua_State *L) int lua::scriptapi_isolated_isoccupied(lua_State *L) { - auto *isolated = static_cast(lua_touserdata(L, 1)); + auto *isolated = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::isolated); if (isolated) { lua_pushboolean(L, isolated->Busy()); @@ -260,7 +318,7 @@ int lua::scriptapi_isolated_isoccupied(lua_State *L) int lua::scriptapi_isolated_isoccupied_n(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); TIsolated *isolated = TIsolated::Find(name); if (isolated) { @@ -273,7 +331,7 @@ int lua::scriptapi_isolated_isoccupied_n(lua_State *L) int lua::scriptapi_train_getname(lua_State *L) { - auto *dyn = static_cast(lua_touserdata(L, 1)); + auto *dyn = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::vehicle); if (dyn && dyn->Mechanik) { lua_pushstring(L, dyn->Mechanik->TrainName().c_str()); @@ -284,7 +342,7 @@ int lua::scriptapi_train_getname(lua_State *L) int lua::scriptapi_dynobj_putvalues(lua_State *L) { - auto *dyn = static_cast(lua_touserdata(L, 1)); + auto *dyn = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::vehicle); auto [str, num1, num2] = get_memcell_values(L, 2); if (!dyn) return 0; @@ -298,11 +356,11 @@ int lua::scriptapi_dynobj_putvalues(lua_State *L) int lua::scriptapi_memcell_find(lua_State *L) { - std::string str = lua_tostring(L, 1); + std::string str = luaL_checkstring(L, 1); TMemCell *mc = simulation::Memory.find(str); if (mc) { - lua_pushlightuserdata(L, mc); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::memcell, mc); return 1; } ErrorLog("lua: missing memcell: " + str); @@ -311,14 +369,14 @@ int lua::scriptapi_memcell_find(lua_State *L) int lua::scriptapi_memcell_read(lua_State *L) { - auto *mc = static_cast(lua_touserdata(L, 1)); + auto *mc = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::memcell); push_memcell_values(L, mc); return 1; } int lua::scriptapi_memcell_read_n(lua_State *L) { - std::string str = lua_tostring(L, 1); + std::string str = luaL_checkstring(L, 1); TMemCell *mc = simulation::Memory.find(str); push_memcell_values(L, mc); if (!mc) @@ -328,7 +386,7 @@ int lua::scriptapi_memcell_read_n(lua_State *L) int lua::scriptapi_memcell_update(lua_State *L) { - auto *mc = static_cast(lua_touserdata(L, 1)); + auto *mc = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::memcell); auto [str, num1, num2] = get_memcell_values(L, 2); if (mc) mc->UpdateValues(str, num1, num2, @@ -338,7 +396,7 @@ int lua::scriptapi_memcell_update(lua_State *L) int lua::scriptapi_memcell_update_n(lua_State *L) { - std::string mstr = lua_tostring(L, 1); + std::string mstr = luaL_checkstring(L, 1); auto [str, num1, num2] = get_memcell_values(L, 2); TMemCell *mc = simulation::Memory.find(mstr); if (mc) @@ -359,14 +417,14 @@ int lua::scriptapi_random(lua_State *L) int lua::scriptapi_writelog(lua_State *L) { - std::string txt = lua_tostring(L, 1); + std::string txt = luaL_checkstring(L, 1); WriteLog("lua: log: " + txt, logtype::lua); return 0; } int lua::scriptapi_writeerrorlog(lua_State *L) { - std::string txt = lua_tostring(L, 1); + std::string txt = luaL_checkstring(L, 1); ErrorLog("lua: log: " + txt, logtype::lua); return 0; } diff --git a/scripting/lua.h b/scripting/lua.h index 07d729264..dc28a01e4 100644 --- a/scripting/lua.h +++ b/scripting/lua.h @@ -1,15 +1,22 @@ #pragma once #include #include +#include "scripting/luasandbox.h" + +#include class basic_event; class TMemCell; class TDynamicObject; -struct memcell_values { const char *str; double num1; double num2; }; +struct memcell_values { std::string str; double num1; double num2; }; class lua { lua_State *state; + bool full_libraries = false; // lua.fulllibraries: all of LuaJIT's libraries opened + // what eu07.read_file reads (the scenery folder) and eu07.write_file writes (the scenery's data folder), known + // when the scenery loads its scripts (interpret()) + lua_sandbox::file_folders files; static int atpanic(lua_State *s); @@ -41,7 +48,9 @@ public: ~lua(); std::string get_error() const; - void interpret(const std::string& file) const; + // runs the script file, a relative path inside folder (the scenery folder), sandboxed (scripting/luasandbox.h). + // a script that can't be read or fails is logged + void interpret(const std::string &folder, const std::string &file); static void unref(lua_State *L, int ref); static void dispatch_event(lua_State *L, int handler, basic_event *event, const TDynamicObject *activator); static void push_memcell_values(lua_State *L, const TMemCell *mc); diff --git a/scripting/luaprogram.cpp b/scripting/luaprogram.cpp index 36d95d271..a79018a3d 100644 --- a/scripting/luaprogram.cpp +++ b/scripting/luaprogram.cpp @@ -8,14 +8,19 @@ http://mozilla.org/MPL/2.0/. */ // the Lua screens: scripts run by LuaJIT, each screen in a state of its own, with the eu07 table of -// script_screens_doc.md. the state has no io, os, ffi, debug or require, reads files only through eu07 and below the -// script's folder, takes no precompiled code, and runs without the JIT compiler, so that the instruction count hook -// can stop a script stuck in a loop (LuaJIT calls no hooks in compiled code) +// script_screens_doc.md. the state has no io, os, ffi, debug, require or newproxy, reads files only through eu07 and +// below the script's folder, takes no precompiled code, and runs without the JIT compiler, so that the instruction +// count hook can stop a script stuck in a loop (LuaJIT calls no hooks in compiled code). what runs in C without the +// hook is held to limits of its own: the pattern functions to the steps they may take, what makes large strings and +// images to the memory of the screen. the game reads the script's table in protected mode, as its metamethods may +// fail #include "stdafx.h" #include "scripting/scriptscreenprogram.h" #include "scripting/scriptscreendrawing.h" #include "scripting/scriptscreenkernels.h" +#include "scripting/scriptscreenrules.h" +#include "scripting/luasandbox.h" #include "utilities/Logs.h" #include "utilities/dictionary.h" @@ -27,11 +32,11 @@ http://mozilla.org/MPL/2.0/. #include #include +#include #include #include -#include -#include #include +#include #include #include #include @@ -43,20 +48,109 @@ namespace { constexpr int hook_interval{1000}; -constexpr char const *image_metatable{"eu07.image"}; -constexpr char const *font_metatable{"eu07.font"}; -constexpr char const *sprite_metatable{"eu07.sprite"}; +// the longest string string.rep makes +constexpr double max_repeat{1024 * 1024}; +// arrays, to be arguments of collect<> +constexpr char image_metatable[]{"eu07.image"}; +constexpr char font_metatable[]{"eu07.font"}; +constexpr char sprite_metatable[]{"eu07.sprite"}; // the address is the key of the program in the registry of its state constexpr char program_key{0}; +// what set_lua_screen_memory_limit() set +std::atomic &memory_limit_setting() +{ + static std::atomic setting{max_screen_memory}; + return setting; +} + +// what lua_screen_memory_peak() gives +std::atomic &memory_peak() +{ + static std::atomic peak{0}; + return peak; +} + +// the memory of a screen: what its Lua heap holds and the pixels of its images, fonts and sprites, which the objects +// keep outside the heap +struct screen_memory +{ + std::size_t limit{max_screen_memory}; // what the screen may hold, read when its state is made + std::size_t heap{0}; + std::size_t objects{0}; + std::size_t peak{0}; // the most the screen held + bool enforced{false}; // a call into the script is in progress: the allocator refuses what goes over the limit + // what the screen holds when it is checked next (lua_program::over_memory) with a full collection + std::size_t collect_at{max_screen_memory}; + // LuaJIT's own allocator of the state, which limited_alloc gives the blocks to + lua_Alloc base{nullptr}; + void *base_data{nullptr}; +}; + +// keeps the most the screen held +void note_peak(screen_memory &Memory) +{ + auto const held{Memory.heap + Memory.objects}; + if (held <= Memory.peak) + { + return; + } + Memory.peak = held; + auto &peak{memory_peak()}; + auto seen{peak.load()}; + while (held > seen && false == peak.compare_exchange_weak(seen, held)) + { + // a failed exchange put the value another screen stored in seen; try again while held is still more + } +} + +// the allocator of a screen's state, put in front of LuaJIT's own (lua_setallocf) once the state is made: LuaJIT 2.0 +// on x64 (the game's on Windows) and 2.1 on x64 without GC64 make no state with an allocator of the game's +// (lua_newstate gives nullptr), as their heap has to stay in the low addresses only their own allocator keeps to. so +// LuaJIT's allocator still makes every block; this one counts them, and refuses a block that would take the screen over +// twice its limit (what it holds, and its garbage between the collections) while a call into the script is in +// progress: LuaJIT raises "not enough memory" there, in the protected call, before the block is made. that holds what +// one instruction makes, which the instruction hook sees only once it is made (a concatenation, a .. b). the game's own +// work between the calls isn't refused, as it isn't protected +void *limited_alloc(void *Data, void *Block, std::size_t Old, std::size_t New) +{ + auto &memory{*static_cast(Data)}; + if (Block == nullptr) + { + Old = 0; + } + if (New > Old && memory.enforced && memory.heap - std::min(Old, memory.heap) + New + memory.objects > 2 * memory.limit) + { + return nullptr; + } + auto *result{memory.base(memory.base_data, Block, Old, New)}; + if (New == 0 || result != nullptr) + { + memory.heap = memory.heap - std::min(Old, memory.heap) + New; + note_peak(memory); + } + return result; +} + class lua_program final : public program { public: - lua_program(std::string const &Script, script_screen_kind const Kind) : kind{Kind}, script{Script}, folder{substr_path(Script)} {} + lua_program(std::string const &Script, script_screen_kind const Kind) + : kind{Kind}, script{Script}, folder{substr_path(Script)}, output{std::format("Lua screen \"{}\"", Script)} + { + } ~lua_program() override { if (m_state != nullptr) { + // the finalizers lua_close runs aren't counted: the budget of the last call may be spent + lua_sethook(m_state, nullptr, 0, 0); + // LuaJIT's own allocator back: lua_close frees the whole heap of its allocator only when the state has it, + // and otherwise leaves the heap's own bookkeeping behind + if (memory.base != nullptr) + { + lua_setallocf(m_state, memory.base, memory.base_data); + } lua_close(m_state); } } @@ -71,7 +165,15 @@ class lua_program final : public program std::string const folder; render_call *call{nullptr}; // the refresh in progress bool commands_ignored{false}; // a screen outside the cab tried to send a command, and it was logged + output_limits output; std::int64_t budget{0}; // instructions left to the call in progress + char const *stopped{nullptr}; // why the call in progress is being stopped: the hook raises it at every instruction + screen_memory memory; + + // true when the screen would hold more than its limit with Adding bytes more. checked with a full collection + // once it has made a quarter of the limit since the last one, so a screen near its limit isn't collected over and + // over + bool over_memory(lua_State *L, std::size_t Adding); private: // calls what's on the stack, with the instruction limit. logs a failure @@ -92,6 +194,19 @@ lua_program *program_of(lua_State *L) return self; } +bool lua_program::over_memory(lua_State *L, std::size_t const Adding) +{ + if (memory.heap + memory.objects + Adding <= memory.collect_at) + { + return false; + } + // what is garbage doesn't count + lua_gc(L, LUA_GCCOLLECT, 0); + auto const held{memory.heap + memory.objects}; + memory.collect_at = std::max(memory.limit, held + memory.limit / 4); + return held + Adding > memory.limit; +} + void count_hook(lua_State *L, lua_Debug * /*Debug*/) { auto *self{program_of(L)}; @@ -99,33 +214,71 @@ void count_hook(lua_State *L, lua_Debug * /*Debug*/) { return; } - self->budget -= hook_interval; - if (self->budget < 0) + if (self->stopped == nullptr) { - luaL_error(L, "instruction limit exceeded"); + self->budget -= hook_interval; + if (self->budget < 0) + { + self->stopped = "instruction limit exceeded"; + } + else if (self->over_memory(L, 0)) + { + // what the allocator lets through, up to twice the limit with the garbage, is caught here + self->stopped = "memory limit exceeded"; + } } + if (self->stopped != nullptr) + { + // from now on the hook runs at every instruction, and raises the error again. a script that catches it (pcall, + // xpcall, coroutine.resume) gets it again at its next instruction, so the error comes out of every level of the + // script in turn, and the call ends. run() sets the interval back for the next call. the hook is the state's, + // shared by its coroutines + lua_sethook(L, count_hook, LUA_MASKCOUNT, 1); + luaL_error(L, "%s", self->stopped); + } +} + +// raises a Lua error when the screen can't take Bytes more: called before an object of the api is made +void reserve_memory(lua_State *L, std::size_t const Bytes) +{ + if (auto *self{program_of(L)}; self != nullptr && self->over_memory(L, Bytes)) + { + luaL_error(L, "memory limit exceeded (%d MB)", static_cast(self->memory.limit / (1024 * 1024))); + } +} + +// the memory the screen of the state may hold +std::size_t memory_limit(lua_State *L) +{ + auto const *self{program_of(L)}; + return self != nullptr ? self->memory.limit : max_screen_memory; } // objects of the api ------------------------------------------------------------------------------------------------- +// where the userdata of an object keeps the bytes it counts in the screen's memory, after the object +template constexpr std::size_t charge_offset{(sizeof(Type_) + alignof(std::size_t) - 1) / alignof(std::size_t) * alignof(std::size_t)}; + // puts the object in a new userdata with the metatable, left on the stack: an rvalue is moved in, an lvalue copied. -// what's stored is the plain type (no reference, no const), the one collect<> and check_object<> are given -template std::remove_cvref_t *push_object(lua_State *L, Type_ &&Object, char const *Metatable) +// what's stored is the plain type (no reference, no const), the one collect<> and check_object<> are given. Bytes: what +// the object holds outside the heap (its pixels), counted in the screen's memory until it is collected, and checked +// with reserve_memory() before the object was made +template std::remove_cvref_t *push_object(lua_State *L, Type_ &&Object, char const *Metatable, std::size_t const Bytes) { using object_type = std::remove_cvref_t; - auto *memory{lua_newuserdata(L, sizeof(object_type))}; + auto *memory{static_cast(lua_newuserdata(L, charge_offset + sizeof(std::size_t)))}; auto *object{new (memory) object_type(std::forward(Object))}; + std::memcpy(memory + charge_offset, &Bytes, sizeof(Bytes)); + if (auto *self{program_of(L)}; self != nullptr) + { + self->memory.objects += Bytes; + note_peak(self->memory); + } luaL_getmetatable(L, Metatable); lua_setmetatable(L, -2); return object; } -template int collect(lua_State *L) -{ - static_cast(lua_touserdata(L, 1))->~Type_(); - return 0; -} - // the object at the index when it has the metatable, otherwise nullptr template Type_ *test_object(lua_State *L, int const Index, char const *Metatable) { @@ -140,6 +293,25 @@ template Type_ *test_object(lua_State *L, int const Index, char return matches ? static_cast(object) : nullptr; } +// __gc. the metatables are locked (make_metatable), so only the collector calls it; all the same it destroys only an +// object of its own type, and once: the object loses its metatable, which its methods check for +template int collect(lua_State *L) +{ + if (auto *object{test_object(L, 1, Metatable_)}; object != nullptr) + { + std::size_t bytes{0}; + std::memcpy(&bytes, reinterpret_cast(object) + charge_offset, sizeof(bytes)); + object->~Type_(); + lua_pushnil(L); + lua_setmetatable(L, 1); + if (auto *self{program_of(L)}; self != nullptr) + { + self->memory.objects -= std::min(bytes, self->memory.objects); + } + } + return 0; +} + template Type_ &check_object(lua_State *L, int const Index, char const *Metatable) { auto *object{test_object(L, Index, Metatable)}; @@ -198,6 +370,28 @@ struct lua_image } }; +// the pixels an image holds: as drawn, and as its post-processing leaves it +std::size_t image_bytes(int const Width, int const Height, int const Finalwidth, int const Finalheight) +{ + auto const drawn{static_cast(Width) * static_cast(Height)}; + auto const done{Width == Finalwidth && Height == Finalheight ? 0 : static_cast(Finalwidth) * static_cast(Finalheight)}; + return (drawn + done) * 4; +} + +std::size_t image_bytes(lua_image const &Image) +{ + return image_bytes(Image.drawn.width(), Image.drawn.height(), Image.width(), Image.height()); +} + +// a new image, Image a step further, counted in the screen's memory +void push_image_then(lua_State *L, lua_image const &Image, post_step const &Step) +{ + reserve_memory(L, image_bytes(Image.drawn.width(), Image.drawn.height(), width_after(Step, Image.width()), height_after(Step, Image.height()))); + auto next{Image.then(Step)}; + auto const bytes{image_bytes(next)}; + push_object(L, std::move(next), image_metatable, bytes); +} + lua_image &check_lua_image(lua_State *L, int const Index) { return check_object(L, Index, image_metatable); @@ -262,6 +456,12 @@ std::optional read_png(std::string const &Folder, std::string_vie int width{0}; int height{0}; int channels{0}; + // the size first: a small file may declare an image of gigabytes + if (0 == stbi_info_from_memory(reinterpret_cast(file->data()), static_cast(file->size()), &width, &height, &channels) || + false == valid_image_side(width) || false == valid_image_side(height)) + { + return std::nullopt; + } // the texture loader turns every image bottom row first, for all threads (model/Texture.cpp): fonts and sprites are // read top row first, as led_util reads them stbi_set_flip_vertically_on_load_thread(0); @@ -285,7 +485,9 @@ int api_image(lua_State *L) luaL_argcheck(L, valid_image_side(width), 1, "between 1 and 4096"); luaL_argcheck(L, valid_image_side(height), 2, "between 1 and 4096"); auto const color{lua_isnoneornil(L, 3) ? rgb{0, 0, 0} : check_color(L, 3)}; - push_object(L, lua_image{canvas{width, height, color}, {}}, image_metatable); + auto const bytes{image_bytes(width, height, width, height)}; + reserve_memory(L, bytes); + push_object(L, lua_image{canvas{width, height, color}, {}}, image_metatable, bytes); return 1; } @@ -300,9 +502,12 @@ int api_font(lua_State *L) auto const description{read_screen_file(self->folder, std::string{path} + ".txt")}; if (image.has_value() && description.has_value()) { + // the glyphs keep a bit of each pixel; a byte is counted + auto const bytes{static_cast(image->width) * static_cast(image->height)}; + reserve_memory(L, bytes); if (auto font{bitmap_font::parse(image->pixels, image->width, image->height, *description)}; font.has_value()) { - push_object(L, std::move(*font), font_metatable); + push_object(L, std::move(*font), font_metatable, bytes); loaded = true; } } @@ -323,7 +528,9 @@ int api_sprite(lua_State *L) { if (auto const image{read_png(self->folder, std::string{path} + ".png")}; image.has_value()) { - push_object(L, bitmap_font::sprite(image->pixels, image->width, image->height), sprite_metatable); + auto const bytes{static_cast(image->width) * static_cast(image->height)}; + reserve_memory(L, bytes); + push_object(L, bitmap_font::sprite(image->pixels, image->width, image->height), sprite_metatable, bytes); loaded = true; } } @@ -362,9 +569,13 @@ int api_log(lua_State *L) { lua_concat(L, count * 2 - 1); } - auto const *self{program_of(L)}; - auto const *text{lua_tostring(L, -1)}; - WriteLog(std::format("Lua screen \"{}\": {}", self->script, text != nullptr ? text : "")); + auto *self{program_of(L)}; + std::size_t length{0}; + auto const *text{lua_tolstring(L, -1, &length)}; + if (auto const line{self->output.take_log(text != nullptr ? std::string_view{text, length} : std::string_view{})}; line.has_value()) + { + WriteLog(*line); + } return 0; } @@ -388,7 +599,10 @@ int api_command(lua_State *L) } return 0; } - self->call->commands.emplace_back(std::string{name}, param1, param2, self->call->vehicle); + if (self->output.take_command(*self->call, name)) + { + self->call->commands.emplace_back(std::string{name}, param1, param2, self->call->vehicle); + } return 0; } @@ -411,12 +625,7 @@ int api_read_file(lua_State *L) // loads a script as text: precompiled code is refused. leaves the chunk, or an error message, on the stack bool load_chunk(lua_State *L, std::string_view const Code, std::string const &Name) { - if (false == Code.empty() && Code.front() == '\x1b') - { - lua_pushfstring(L, "%s: precompiled scripts aren't loaded", Name.c_str()); - return false; - } - return 0 == luaL_loadbufferx(L, Code.data(), Code.size(), ("@" + Name).c_str(), "t"); + return lua_sandbox::load_text_chunk(L, Code, Name); } // eu07.include(path): runs another script below the script's folder and returns what it returns @@ -566,7 +775,7 @@ int image_led_post(lua_State *L) post_step step; step.type = post_step::kind::led; step.bloom = bloom; - push_object(L, image.then(step), image_metatable); + push_image_then(L, image, step); return 1; } @@ -582,14 +791,16 @@ int image_resize(lua_State *L) step.type = post_step::kind::resize; step.width = width; step.height = height; - push_object(L, image.then(step), image_metatable); + push_image_then(L, image, step); return 1; } int image_copy(lua_State *L) { auto const &image{check_lua_image(L, 1)}; - push_object(L, lua_image{image}, image_metatable); + auto const bytes{image_bytes(image)}; + reserve_memory(L, bytes); + push_object(L, lua_image{image}, image_metatable, bytes); return 1; } @@ -663,6 +874,227 @@ constexpr std::array api_functions{ luaL_Reg{nullptr, nullptr}, }; +// string.rep, which makes no string longer than max_repeat. a separator (a third argument, where LuaJIT takes one) +// is counted as well +int api_repeat(lua_State *L) +{ + std::size_t length{0}; + luaL_checklstring(L, 1, &length); + auto const count{luaL_checknumber(L, 2)}; + std::size_t separator{0}; + luaL_optlstring(L, 3, "", &separator); + // as a double: no overflow for any count, and a count of NaN fails both comparisons + if (false == (count <= 0) && false == (static_cast(length) * count + static_cast(separator) * (count - 1) <= max_repeat)) + { + return luaL_error(L, "string.rep: the result would be over %d bytes", static_cast(max_repeat)); + } + lua_pushvalue(L, lua_upvalueindex(1)); + lua_insert(L, 1); + lua_call(L, lua_gettop(L) - 1, 1); + return 1; +} + +// the functions of the libraries that make a string in one call, around the library's own (the upvalue): refused when +// the result may be over the memory of a screen. what they make otherwise is counted with the rest of the heap +int too_large(lua_State *L, char const *Function) +{ + return luaL_error(L, "%s: the result may be over the memory of a screen (%d MB)", Function, static_cast(memory_limit(L) / (1024 * 1024))); +} + +// calls the library's own function, the upvalue, with the arguments, and returns what it returns +int call_library(lua_State *L) +{ + lua_pushvalue(L, lua_upvalueindex(1)); + lua_insert(L, 1); + lua_call(L, lua_gettop(L) - 1, LUA_MULTRET); + return lua_gettop(L); +} + +// string.format: no longer than the format and its arguments, each string as %q writes it (a character as up to 4, +// "\0" as "\000"), anything else in at most 512 characters +int api_format(lua_State *L) +{ + std::size_t length{0}; + luaL_checklstring(L, 1, &length); + auto total{static_cast(length)}; + for (int idx = 2; idx <= lua_gettop(L); ++idx) + { + total += lua_type(L, idx) == LUA_TSTRING ? 4.0 * static_cast(lua_objlen(L, idx)) : 512.0; + } + if (total > static_cast(memory_limit(L))) + { + return too_large(L, "string.format"); + } + return call_library(L); +} + +// table.concat: the items and the separators between them. the items are read as the library reads them, up to the +// first one that isn't a string or a number, on which the library raises its error +int api_concat(lua_State *L) +{ + luaL_checktype(L, 1, LUA_TTABLE); + std::size_t separator{0}; + luaL_optlstring(L, 2, "", &separator); + auto const first{luaL_optinteger(L, 3, 1)}; + auto const last{lua_isnoneornil(L, 4) ? static_cast(lua_objlen(L, 1)) : luaL_checkinteger(L, 4)}; + auto const limit{static_cast(memory_limit(L))}; + auto total{0.0}; + for (auto idx = first; idx <= last; ++idx) + { + lua_rawgeti(L, 1, static_cast(idx)); + auto const type{lua_type(L, -1)}; + // a number in at most 32 characters + total += (type == LUA_TSTRING ? static_cast(lua_objlen(L, -1)) : 32.0) + (idx > first ? static_cast(separator) : 0.0); + lua_pop(L, 1); + if (type != LUA_TSTRING && type != LUA_TNUMBER) + { + break; + } + if (total > limit) + { + return too_large(L, "table.concat"); + } + } + return call_library(L); +} + +// the pattern functions, upvalue 2 telling which +enum class pattern_function +{ + find, + match, + gmatch, + gsub +}; + +constexpr std::array pattern_function_names{"string.find", "string.match", "string.gmatch", "string.gsub"}; + +// the longest text a replacement of gsub puts in place of the matches: a string (or a number) as it is, with each %0-%9 +// as long as a match, a table by its longest value. nothing when it can't be told (a function, a table with a +// metatable): what those give is made in Lua, under the hook +std::optional replacement_length(lua_State *L, int const Index, double const Subject, double const Matches) +{ + if (lua_type(L, Index) == LUA_TSTRING || lua_type(L, Index) == LUA_TNUMBER) + { + std::size_t length{0}; + auto const *text{lua_tolstring(L, Index, &length)}; + auto const captures{static_cast(std::count(text, text + length, '%'))}; + // the matches don't overlap: a capture of each takes at most the subject; a position capture is a number + return Matches * static_cast(length) + captures * (Subject + 24.0 * Matches); + } + if (lua_type(L, Index) == LUA_TTABLE) + { + if (lua_getmetatable(L, Index) != 0) + { + // pushed: off the stack again, or the library gets it as the 4th argument + lua_pop(L, 1); + return std::nullopt; + } + auto longest{0.0}; + lua_pushnil(L); + while (lua_next(L, Index) != 0) + { + longest = std::max(longest, lua_type(L, -1) == LUA_TSTRING ? static_cast(lua_objlen(L, -1)) : 32.0); + lua_pop(L, 1); + } + return Matches * longest; + } + return std::nullopt; +} + +// string.find, match, gmatch and gsub, refused for a pattern that may take too long on the subject: they run in C, +// without the instruction hook (see lua_pattern_cost() and max_pattern_cost). gsub with a string or a table is refused +// as well when its result may be over the memory of a screen +int api_pattern(lua_State *L) +{ + auto const function{static_cast(lua_tointeger(L, lua_upvalueindex(2)))}; + auto const *name{pattern_function_names[static_cast(function)]}; + std::size_t subject{0}; + auto const *text{luaL_checklstring(L, 1, &subject)}; + std::size_t length{0}; + auto const *pattern{luaL_checklstring(L, 2, &length)}; + auto const plain{function == pattern_function::find && lua_toboolean(L, 4) != 0}; + if (lua_pattern_cost(std::string_view{pattern, length}, std::string_view{text, subject}, plain, function != pattern_function::gmatch) > max_pattern_cost) + { + return luaL_error(L, "%s: the pattern may take too long on a subject of %d bytes", name, static_cast(subject)); + } + if (function == pattern_function::gsub) + { + auto const size{static_cast(subject)}; + auto const matches{lua_isnumber(L, 4) ? std::clamp(static_cast(lua_tonumber(L, 4)), 0.0, size + 1.0) : size + 1.0}; + if (auto const replaced{replacement_length(L, 3, size, matches)}; replaced.has_value() && size + *replaced > static_cast(memory_limit(L))) + { + return too_large(L, name); + } + } + return call_library(L); +} + +// xpcall(f, handler, ...), in Lua on top of pcall: LuaJIT calls the handler of its own xpcall where the error was +// raised, before the stack unwinds, which for the error of the instruction hook is while the hook still runs, when no +// hook is called, so a handler that loops would never be stopped. here the handler is called once the error has left +// f, under pcall as well, and a script has no debug library to look at the stack with. made in Lua, a coroutine yields +// across it as across pcall +constexpr std::string_view xpcall_source{R"lua( +local pcall, select, error = pcall, select, error +local function finish(handler, ok, ...) + if ok then + return true, ... + end + local _, handled = pcall(handler, (...)) + return false, handled +end +return function(...) + if select("#", ...) < 2 then + error("bad argument #2 to 'xpcall' (value expected)", 2) + end + local f, handler = ... + return finish(handler, pcall(f, select(3, ...))) +end +)lua"}; + +// what the screens get of the libraries in place of the library's own functions, which run in C without the hook: +// string.rep, string.format and table.concat with a cap on the length of the result, the pattern functions with a cap +// on the steps they take, and xpcall made of pcall. strings share the string table as their methods +void limit_libraries(lua_State *L) +{ + lua_getglobal(L, LUA_STRLIBNAME); + lua_getfield(L, -1, "rep"); + lua_pushcclosure(L, api_repeat, 1); + lua_setfield(L, -2, "rep"); + lua_getfield(L, -1, "format"); + lua_pushcclosure(L, api_format, 1); + lua_setfield(L, -2, "format"); + for (std::size_t idx = 0; idx < pattern_function_names.size(); ++idx) + { + // "string.find": the name in the table is past the dot + auto const *name{pattern_function_names[idx] + sizeof("string.") - 1}; + lua_getfield(L, -1, name); + lua_pushinteger(L, static_cast(idx)); + lua_pushcclosure(L, api_pattern, 2); + lua_setfield(L, -2, name); + } + lua_pop(L, 1); + + lua_getglobal(L, LUA_TABLIBNAME); + lua_getfield(L, -1, "concat"); + lua_pushcclosure(L, api_concat, 1); + lua_setfield(L, -2, "concat"); + lua_pop(L, 1); + + if (0 == luaL_loadbuffer(L, xpcall_source.data(), xpcall_source.size(), "=xpcall") && 0 == lua_pcall(L, 0, 1, 0)) + { + lua_setglobal(L, "xpcall"); + } + else + { + // a script then gets no xpcall rather than the one the hook doesn't reach + lua_pop(L, 1); + lua_pushnil(L); + lua_setglobal(L, "xpcall"); + } +} + template void make_metatable(lua_State *L, char const *Name, std::array const &Methods, lua_CFunction Collect) { luaL_newmetatable(L, Name); @@ -679,6 +1111,9 @@ template void make_metatable(lua_State *L, char const *Name, lua_setfield(L, -2, "__index"); lua_pushcfunction(L, Collect); lua_setfield(L, -2, "__gc"); + // getmetatable() of an object gives this instead of the table + lua_pushboolean(L, 0); + lua_setfield(L, -2, "__metatable"); lua_pop(L, 1); } @@ -724,30 +1159,12 @@ void push_state(lua_State *L, dictionary_source const &Input) } } -void open_library(lua_State *L, lua_CFunction Open, char const *Name) -{ - lua_pushcfunction(L, Open); - lua_pushstring(L, Name); - lua_call(L, 1, 0); -} - void lua_program::open_libraries() { - open_library(m_state, luaopen_base, ""); - open_library(m_state, luaopen_table, LUA_TABLIBNAME); - open_library(m_state, luaopen_string, LUA_STRLIBNAME); - open_library(m_state, luaopen_math, LUA_MATHLIBNAME); - open_library(m_state, luaopen_bit, LUA_BITLIBNAME); - // what reaches files or loads code - for (auto const *name : {"dofile", "loadfile", "load", "loadstring", "module", "require"}) - { - lua_pushnil(m_state); - lua_setglobal(m_state, name); - } - lua_getglobal(m_state, LUA_STRLIBNAME); - lua_pushnil(m_state); - lua_setfield(m_state, -2, "dump"); - lua_pop(m_state, 1); + // base, table, string, math and bit, without what reaches files or loads code + lua_sandbox::open_safe_libraries(m_state); + // what runs in C without the hook is held to limits of its own + limit_libraries(m_state); } void lua_program::register_api() @@ -757,9 +1174,9 @@ void lua_program::register_api() lua_pushlightuserdata(L, this); lua_rawset(L, LUA_REGISTRYINDEX); - make_metatable(L, image_metatable, image_methods, collect); - make_metatable(L, font_metatable, font_methods, collect); - make_metatable(L, sprite_metatable, sprite_methods, collect); + make_metatable(L, image_metatable, image_methods, collect); + make_metatable(L, font_metatable, font_methods, collect); + make_metatable(L, sprite_metatable, sprite_methods, collect); lua_newtable(L); for (auto const &function : api_functions) @@ -780,16 +1197,48 @@ void lua_program::register_api() bool lua_program::run(int const Arguments, int const Results, std::string_view const What) { budget = instruction_limit; - if (0 == lua_pcall(m_state, Arguments, Results, 0)) + stopped = nullptr; + // the interval, which the hook shortens once the budget of a call is spent + lua_sethook(m_state, count_hook, LUA_MASKCOUNT, hook_interval); + output.start_call(); + memory.enforced = true; + auto const status{lua_pcall(m_state, Arguments, Results, 0)}; + memory.enforced = false; + if (0 == status) { return true; } auto const *message{lua_tostring(m_state, -1)}; ErrorLog(std::format("Lua screen \"{}\": {} failed: {}", script, What, message != nullptr ? message : "unknown error")); lua_pop(m_state, 1); + // what the call left behind, a heap run over the limit + lua_gc(m_state, LUA_GCCOLLECT, 0); return false; } +// render and init of the table the script returned (the argument), read in protected mode: the table may have a +// metatable of the script's, whose __index runs the script and may fail +int screen_functions(lua_State *L) +{ + lua_getfield(L, 1, "render"); + lua_getfield(L, 1, "init"); + return 2; +} + +// a refresh: render of the screen's table (its reference, the second argument) called with the state of the refresh +// (the dictionary_source, the first). in protected mode, the reading of render and the making of the state as well +int call_render(lua_State *L) +{ + auto const &input{*static_cast(lua_touserdata(L, 1))}; + auto const screen{static_cast(lua_tointeger(L, 2))}; + lua_settop(L, 0); + lua_rawgeti(L, LUA_REGISTRYINDEX, screen); + lua_getfield(L, 1, "render"); + push_state(L, input); + lua_call(L, 1, 1); + return 1; +} + bool lua_program::start() { m_state = luaL_newstate(); @@ -798,20 +1247,25 @@ bool lua_program::start() ErrorLog(std::format("Lua screen \"{}\": failed to create the state", script)); return false; } + // the screen's allocator in front of LuaJIT's own, counting from what the state holds already + memory.limit = memory_limit_setting().load(); + memory.collect_at = memory.limit; + memory.heap = static_cast(lua_gc(m_state, LUA_GCCOUNT, 0)) * 1024 + static_cast(lua_gc(m_state, LUA_GCCOUNTB, 0)); + memory.base = lua_getallocf(m_state, &memory.base_data); + lua_setallocf(m_state, limited_alloc, &memory); // no compiled code: LuaJIT calls no hooks in it, and the hook is what stops a script stuck in a loop luaJIT_setmode(m_state, 0, LUAJIT_MODE_ENGINE | LUAJIT_MODE_OFF); open_libraries(); register_api(); lua_sethook(m_state, count_hook, LUA_MASKCOUNT, hook_interval); - std::ifstream file{script, std::ios::binary}; - if (false == file.is_open()) + auto const code{read_regular_file(script)}; + if (false == code.has_value()) { - ErrorLog(std::format("Lua screen \"{}\": file not found", script)); + ErrorLog(std::format("Lua screen \"{}\": file not found, or larger than {} bytes", script, max_screen_file)); return false; } - std::string const code{std::istreambuf_iterator{file}, std::istreambuf_iterator{}}; - if (false == load_chunk(m_state, code, script)) + if (false == load_chunk(m_state, *code, script)) { ErrorLog(std::format("Lua screen \"{}\": {}", script, lua_tostring(m_state, -1))); return false; @@ -825,19 +1279,22 @@ bool lua_program::start() ErrorLog(std::format("Lua screen \"{}\": the script has to return a table with a render function", script)); return false; } - lua_getfield(m_state, -1, "render"); - auto const renders{lua_isfunction(m_state, -1)}; - lua_pop(m_state, 1); - if (false == renders) + lua_pushcfunction(m_state, screen_functions); + lua_pushvalue(m_state, -2); + if (false == run(1, 2, "reading render and init")) + { + return false; + } + // the table, render, init + if (false == lua_isfunction(m_state, -2)) { ErrorLog(std::format("Lua screen \"{}\": the script has to return a table with a render function", script)); return false; } - m_screen = luaL_ref(m_state, LUA_REGISTRYINDEX); - - lua_rawgeti(m_state, LUA_REGISTRYINDEX, m_screen); - lua_getfield(m_state, -1, "init"); lua_remove(m_state, -2); + lua_insert(m_state, -2); + // init, the table + m_screen = luaL_ref(m_state, LUA_REGISTRYINDEX); if (lua_isfunction(m_state, -1)) { if (false == run(0, 0, "init")) @@ -856,11 +1313,10 @@ bool lua_program::start() bool lua_program::render(render_call &Call) { call = &Call; - lua_rawgeti(m_state, LUA_REGISTRYINDEX, m_screen); - lua_getfield(m_state, -1, "render"); - lua_remove(m_state, -2); - push_state(m_state, Call.input); - auto const rendered{run(1, 1, "render")}; + lua_pushcfunction(m_state, call_render); + lua_pushlightuserdata(m_state, const_cast(&Call.input)); + lua_pushinteger(m_state, m_screen); + auto const rendered{run(2, 1, "render")}; call = nullptr; if (false == rendered) { @@ -902,6 +1358,17 @@ class lua_runtime_host final : public runtime } // namespace +void set_lua_screen_memory_limit(std::size_t const Bytes) +{ + memory_limit_setting().store(Bytes); + memory_peak().store(0); +} + +std::size_t lua_screen_memory_peak() +{ + return memory_peak().load(); +} + std::unique_ptr make_lua_runtime() { return std::make_unique(); diff --git a/scripting/luasandbox.cpp b/scripting/luasandbox.cpp new file mode 100644 index 000000000..16e7f70ba --- /dev/null +++ b/scripting/luasandbox.cpp @@ -0,0 +1,522 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "scripting/luasandbox.h" + +#include "scripting/scriptscreenrules.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace lua_sandbox +{ + +namespace +{ + +void open_library(lua_State *L, lua_CFunction Open, char const *Name) +{ + lua_pushcfunction(L, Open); + lua_pushstring(L, Name); + lua_call(L, 1, 0); +} + +// the conversions of strftime in C89, which every C library knows. LuaJIT hands each one to strftime on its own +constexpr std::string_view date_conversions{"aAbBcdHIjmMpSUwWxXyYZ%"}; + +// os.date(format, time), the library's own (the upvalue) for a format of known conversions only: the Microsoft +// C library ends the program on one it doesn't know ("%Q", "%#") +int api_date(lua_State *L) +{ + std::size_t length{0}; + auto const *format{luaL_optlstring(L, 1, "%c", &length)}; + std::string_view const text{format, length}; + for (std::size_t idx = 0; idx + 1 < text.size(); ++idx) + { + if (text[idx] != '%') + { + continue; + } + ++idx; + if (date_conversions.find(text[idx]) == std::string_view::npos) + { + return luaL_error(L, "os.date: unknown conversion '%%%c'", text[idx]); + } + } + lua_pushvalue(L, lua_upvalueindex(1)); + lua_insert(L, 1); + lua_call(L, lua_gettop(L) - 1, LUA_MULTRET); + return lua_gettop(L); +} + +} // namespace + +std::string with_forward_slashes(std::string_view const Path) +{ + std::string result{Path}; + std::ranges::replace(result, '\\', '/'); + return result; +} + +void open_safe_libraries(lua_State *L) +{ + open_library(L, luaopen_base, ""); + open_library(L, luaopen_table, LUA_TABLIBNAME); + open_library(L, luaopen_string, LUA_STRLIBNAME); + open_library(L, luaopen_math, LUA_MATHLIBNAME); + open_library(L, luaopen_bit, LUA_BITLIBNAME); + // what reaches files or loads code, and newproxy: a userdata of a metatable of the script's own, whose __gc LuaJIT + // runs without the hooks (the instruction limit of the Lua screens), at any allocation and in lua_close + for (auto const *name : {"dofile", "loadfile", "load", "loadstring", "module", "require", "newproxy"}) + { + lua_pushnil(L); + lua_setglobal(L, name); + } + lua_getglobal(L, LUA_STRLIBNAME); + lua_pushnil(L); + lua_setfield(L, -2, "dump"); + lua_pop(L, 1); +} + +void open_clock_library(lua_State *L) +{ + // the whole library, of which a new table takes what only reads the clock + open_library(L, luaopen_os, LUA_OSLIBNAME); + lua_getglobal(L, LUA_OSLIBNAME); + lua_newtable(L); + for (auto const *name : {"time", "clock", "difftime"}) + { + lua_getfield(L, -2, name); + lua_setfield(L, -2, name); + } + lua_getfield(L, -2, "date"); + lua_pushcclosure(L, api_date, 1); + lua_setfield(L, -2, "date"); + // the new table in place of the library: the global, and the one the libraries know as loaded, which + // luaL_openlibs fills up again rather than make a new global + lua_pushvalue(L, -1); + lua_setglobal(L, LUA_OSLIBNAME); + lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); + lua_pushvalue(L, -2); + lua_setfield(L, -2, LUA_OSLIBNAME); + // _LOADED, the new table, the library + lua_pop(L, 3); +} + +bool load_text_chunk(lua_State *L, std::string_view const Code, std::string const &Name) +{ + if (false == Code.empty() && Code.front() == '\x1b') + { + lua_pushfstring(L, "%s: precompiled scripts aren't loaded", Name.c_str()); + return false; + } + return 0 == luaL_loadbufferx(L, Code.data(), Code.size(), ("@" + Name).c_str(), "t"); +} + +std::optional read_file(std::filesystem::path const &Folder, std::string_view const Path, std::uintmax_t const Limit) +{ + // a NUL would end the name the system sees + if (false == script_screens::is_safe_relative_path(Path) || Path.find('\0') != std::string_view::npos) + { + return std::nullopt; + } + // a folder or a device (CON, NUL, COM1...) isn't a regular file. in the code page of the system, as the game opens + // its files + auto const path{Folder / with_forward_slashes(Path)}; + std::error_code error; + if (false == std::filesystem::is_regular_file(path, error)) + { + return std::nullopt; + } + auto const size{std::filesystem::file_size(path, error)}; + if (error || size > Limit) + { + return std::nullopt; + } + std::ifstream file{path, std::ios::binary}; + if (false == file.is_open()) + { + return std::nullopt; + } + std::string contents(static_cast(size), '\0'); + file.read(contents.data(), static_cast(contents.size())); + // what was read, should the file have shrunk meanwhile + contents.resize(static_cast(file.gcount())); + return contents; +} + +std::optional read_script_file(std::string const &Folder, std::string_view const Path) +{ + return read_file(std::filesystem::path{Folder}, Path, max_script_file); +} + +std::optional run_script_file(lua_State *L, std::string const &Folder, std::string_view const Path) +{ + auto const name{Folder + std::string{Path}}; + auto const code{read_script_file(Folder, Path)}; + if (false == code.has_value()) + { + return name + ": not found, not a file, larger than " + std::to_string(max_script_file) + + " bytes, or outside the folder (an absolute path, a drive or '..')"; + } + if (false == load_text_chunk(L, *code, name) || 0 != lua_pcall(L, 0, 0, 0)) + { + std::size_t length{0}; + auto const *message{lua_tolstring(L, -1, &length)}; + std::string result{message != nullptr ? std::string{message, length} : name + ": unknown error"}; + lua_pop(L, 1); + return result; + } + return std::nullopt; +} + +namespace +{ + +char lower_case(char const Character) +{ + return Character >= 'A' && Character <= 'Z' ? static_cast(Character - 'A' + 'a') : Character; +} + +// the names Windows opens as its devices, whatever the extension +bool is_device_name(std::string_view Name) +{ + // the extension, and the spaces before it, don't count ("nul.txt", "con .log") + Name = Name.substr(0, Name.find('.')); + while (false == Name.empty() && Name.back() == ' ') + { + Name.remove_suffix(1); + } + std::string name; + std::ranges::transform(Name, std::back_inserter(name), lower_case); + if (name == "con" || name == "prn" || name == "aux" || name == "nul" || name == "conin$" || name == "conout$") + { + return true; + } + return name.size() == 4 && (name.starts_with("com") || name.starts_with("lpt")) && name[3] >= '0' && name[3] <= '9'; +} + +// a name of a file or a folder that every system takes as it is +bool is_portable_name(std::string_view const Name) +{ + if (Name.empty() || Name == "." || Name == ".." || Name.back() == '.' || Name.back() == ' ') + { + return false; + } + for (auto const character : Name) + { + if (static_cast(character) < 0x20 || character == 0x7f || + std::string_view{"<>:\"|?*"}.find(character) != std::string_view::npos) + { + return false; + } + } + return false == is_device_name(Name); +} + +// true when Path, a canonical path, is Folder, a canonical path, or inside it +bool is_inside(std::filesystem::path const &Path, std::filesystem::path const &Folder) +{ + return std::mismatch(Folder.begin(), Folder.end(), Path.begin(), Path.end()).first == Folder.end(); +} + +file_folders const &folders_of(lua_State *L) +{ + return *static_cast(lua_touserdata(L, lua_upvalueindex(1))); +} + +std::string_view check_text(lua_State *L, int const Index) +{ + std::size_t length{0}; + auto const *text{luaL_checklstring(L, Index, &length)}; + return {text, length}; +} + +void push_contents(lua_State *L, std::optional const &Contents) +{ + if (Contents.has_value()) + { + lua_pushlstring(L, Contents->data(), Contents->size()); + } + else + { + lua_pushnil(L); + } +} + +// eu07.read_file(path): the contents of a file of the scenery folder, or nil +int api_read_file(lua_State *L) +{ + auto const path{check_text(L, 1)}; + auto const &folders{folders_of(L)}; + push_contents(L, folders.scenery.empty() ? std::nullopt : read_file(folders.scenery, path, max_script_file)); + return 1; +} + +// eu07.read_data_file(path): the contents of a file of the scenery's data folder, or nil +int api_read_data_file(lua_State *L) +{ + auto const path{check_text(L, 1)}; + auto const &folders{folders_of(L)}; + push_contents(L, folders.data.empty() ? std::nullopt : read_file(folders.data, path, max_data_file)); + return 1; +} + +// eu07.write_file(path, text): writes the file of the scenery's data folder. true, or nil and why not +int api_write_file(lua_State *L) +{ + auto const path{check_text(L, 1)}; + auto const contents{check_text(L, 2)}; + if (auto const error{write_data_file(folders_of(L).data, path, contents)}; error.has_value()) + { + lua_pushnil(L); + lua_pushlstring(L, error->data(), error->size()); + return 2; + } + lua_pushboolean(L, 1); + return 1; +} + +} // namespace + +bool is_safe_write_path(std::string_view const Path) +{ + if (Path.size() > max_data_path || false == script_screens::is_safe_relative_path(Path)) + { + return false; + } + std::size_t names{0}; + std::size_t start{0}; + while (start <= Path.size()) + { + auto const end{std::min(Path.find_first_of("/\\", start), Path.size())}; + if (false == is_portable_name(Path.substr(start, end - start))) + { + return false; + } + ++names; + start = end + 1; + } + // the folders, and the file in them + return names <= max_data_depth + 1; +} + +std::optional write_data_file(std::filesystem::path const &Folder, std::string_view const Path, std::string_view const Contents) +{ + namespace fs = std::filesystem; + std::string const name{Path}; + if (Folder.empty()) + { + return name + ": no folder to write to (the game knows no folder of the player)"; + } + if (false == is_safe_write_path(Path)) + { + return name + ": not a path to write to (a relative path of portable names, at most " + std::to_string(max_data_path) + + " bytes and " + std::to_string(max_data_depth) + " folders deep, without '..')"; + } + if (Contents.size() > max_data_file) + { + return name + ": larger than " + std::to_string(max_data_file) + " bytes"; + } + auto const target{Folder / with_forward_slashes(Path)}; + std::error_code error; + // a link, a folder or anything else that isn't a file stays as it is + auto const status{fs::symlink_status(target, error)}; + auto const exists{status.type() != fs::file_type::not_found}; + if (exists && status.type() != fs::file_type::regular) + { + return name + ": not a file"; + } + std::uintmax_t replaced{0}; + if (exists) + { + replaced = fs::file_size(target, error); + if (error) + { + return name + ": can't be replaced"; + } + } + // what the folder holds, and will hold with the file in place of what was there + std::uintmax_t held{0}; + std::size_t files{0}; + if (fs::is_directory(Folder, error)) + { + for (fs::recursive_directory_iterator entry{Folder, error}, end; !error && entry != end; entry.increment(error)) + { + std::error_code entryerror; + if (entry->symlink_status(entryerror).type() == fs::file_type::regular) + { + auto const size{entry->file_size(entryerror)}; + held += entryerror ? 0 : size; + ++files; + } + } + if (error) + { + return name + ": the data folder can't be read"; + } + } + if (files + (exists ? 0 : 1) > max_data_files) + { + return name + ": the data folder holds " + std::to_string(max_data_files) + " files already"; + } + if (held - std::min(replaced, held) + Contents.size() > max_data_folder) + { + return name + ": the data folder would hold more than " + std::to_string(max_data_folder) + " bytes"; + } + fs::create_directories(target.parent_path(), error); + if (error) + { + return name + ": its folder can't be made"; + } + // still inside the data folder, should a link in it lead elsewhere + auto const root{fs::canonical(Folder, error)}; + auto const parent{error ? fs::path{} : fs::canonical(target.parent_path(), error)}; + if (error || false == is_inside(parent, root)) + { + return name + ": outside the data folder"; + } + std::ofstream file{parent / target.filename(), std::ios::binary | std::ios::trunc}; + if (false == file.is_open()) + { + return name + ": can't be opened to write"; + } + file.write(Contents.data(), static_cast(Contents.size())); + file.close(); + if (file.fail()) + { + return name + ": couldn't be written whole"; + } + return std::nullopt; +} + +std::filesystem::path scenery_data_folder(std::filesystem::path const &Root, std::string_view const Scenery) +{ + auto name{with_forward_slashes(Scenery)}; + if (name.size() >= 4) + { + std::string extension; + std::ranges::transform(std::string_view{name}.substr(name.size() - 4), std::back_inserter(extension), lower_case); + if (extension == ".scn") + { + name.resize(name.size() - 4); + } + } + if (Root.empty() || false == is_safe_write_path(name)) + { + return {}; + } + return Root / name; +} + +void open_file_library(lua_State *L, file_folders const *Folders) +{ + // eu07, which the scenery scripts have for eu07.events, made when there is none + lua_getglobal(L, "eu07"); + if (false == lua_istable(L, -1)) + { + lua_pop(L, 1); + lua_newtable(L); + lua_pushvalue(L, -1); + lua_setglobal(L, "eu07"); + } + // luaL_Reg, not std::pair: GCC deduces std::pair{"read_file", api_read_file} as a pair of an array and a function + static constexpr luaL_Reg functions[]{{"read_file", api_read_file}, {"write_file", api_write_file}, {"read_data_file", api_read_data_file}}; + for (auto const &[name, function] : functions) + { + lua_pushlightuserdata(L, const_cast(Folders)); + lua_pushcclosure(L, function, 1); + lua_setfield(L, -2, name); + } + lua_pop(L, 1); +} + +namespace +{ + +constexpr std::array handle_names{"eu07.event", "eu07.track", "eu07.isolated", "eu07.vehicle", "eu07.memcell"}; +// the addresses are the keys of the handles of each kind in the registry: the objects, to their userdata +constexpr std::array handle_cache_keys{}; + +void *cache_key(handle_kind const Kind) +{ + return const_cast(&handle_cache_keys[static_cast(Kind)]); // NOSONAR: the address is only a key +} + +} // namespace + +char const *handle_name(handle_kind const Kind) +{ + return handle_names[static_cast(Kind)]; +} + +void open_handles(lua_State *L) +{ + for (std::size_t idx = 0; idx < handle_names.size(); ++idx) + { + auto const kind{static_cast(idx)}; + luaL_newmetatable(L, handle_name(kind)); + // getmetatable() of a handle gives this instead of the table + lua_pushboolean(L, 0); + lua_setfield(L, -2, "__metatable"); + lua_pop(L, 1); + // the handles made, weak: a handle the script dropped is collected, and made again when asked for + lua_pushlightuserdata(L, cache_key(kind)); + lua_newtable(L); + lua_createtable(L, 0, 1); + lua_pushliteral(L, "v"); + lua_setfield(L, -2, "__mode"); + lua_setmetatable(L, -2); + lua_rawset(L, LUA_REGISTRYINDEX); + } +} + +void push_handle(lua_State *L, handle_kind const Kind, void *Object) +{ + if (Object == nullptr) + { + lua_pushnil(L); + return; + } + lua_pushlightuserdata(L, cache_key(Kind)); + lua_rawget(L, LUA_REGISTRYINDEX); + lua_pushlightuserdata(L, Object); + lua_rawget(L, -2); + if (false == lua_isnil(L, -1)) + { + // the cache, the handle + lua_remove(L, -2); + return; + } + lua_pop(L, 1); + *static_cast(lua_newuserdata(L, sizeof(void *))) = Object; + luaL_getmetatable(L, handle_name(Kind)); + lua_setmetatable(L, -2); + lua_pushlightuserdata(L, Object); + lua_pushvalue(L, -2); + lua_rawset(L, -4); + lua_remove(L, -2); +} + +void *check_handle(lua_State *L, int const Index, handle_kind const Kind) +{ + if (lua_isnoneornil(L, Index)) + { + return nullptr; + } + return *static_cast(luaL_checkudata(L, Index, handle_name(Kind))); +} + +} // namespace lua_sandbox diff --git a/scripting/luasandbox.h b/scripting/luasandbox.h new file mode 100644 index 000000000..dfb1cd024 --- /dev/null +++ b/scripting/luasandbox.h @@ -0,0 +1,134 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +// what the Lua states of the game share to run scripts sandboxed: the scenery scripts (scripting/lua.cpp, lua in the +// .scn) and the script screens (scripting/luaprogram.cpp). a sandboxed script reaches no files, no other programs, no +// ffi and no debug library, and loads no code of its own: no require, dofile, load or precompiled chunks + +#include + +#include +#include +#include +#include +#include +#include + +namespace lua_sandbox +{ + +// the largest script file a scenery loads +constexpr std::uintmax_t max_script_file{16 * 1024 * 1024}; + +// the libraries a sandboxed script gets: base, table, string, math and bit, without dofile, loadfile, load, +// loadstring, module, require and string.dump +void open_safe_libraries(lua_State *L); + +// the os table with only what reads the clock: os.time, os.clock, os.difftime and os.date, the last refusing the +// conversions the C library doesn't know (the Microsoft one ends the program on them) +void open_clock_library(lua_State *L); + +// loads Code as text, under the name Name: precompiled code is refused. leaves the chunk, or an error message, on the +// stack +bool load_text_chunk(lua_State *L, std::string_view Code, std::string const &Name); + +// Path with each '\' turned into '/', as the game reads the paths in its data (replace_slashes): a scenery made on +// Windows may name its folders either way, and on Linux only '/' separates them +std::string with_forward_slashes(std::string_view Path); + +// the file Path of Folder, when Path is a relative path inside Folder (no '..', no drive, no leading separator) and +// names a regular file of at most max_script_file bytes. nothing otherwise. '\' separates folders in Path as '/' does, +// on every system +std::optional read_script_file(std::string const &Folder, std::string_view Path); + +// reads the script Path of Folder (as read_script_file), loads it as text and runs it in protected mode. nothing when +// it ran, otherwise why it didn't +std::optional run_script_file(lua_State *L, std::string const &Folder, std::string_view Path); + +// the files a scenery script reads and writes itself (eu07.read_file, eu07.write_file, eu07.read_data_file): it reads +// the files of the scenery folder, and writes only into a data folder of its scenery, outside the game + +// the largest file a script writes, all the files of a data folder together, and how many files a data folder holds +constexpr std::uintmax_t max_data_file{1024 * 1024}; +constexpr std::uintmax_t max_data_folder{16 * 1024 * 1024}; +constexpr std::size_t max_data_files{256}; +// the longest path a script writes to, and how many folders deep it goes +constexpr std::size_t max_data_path{200}; +constexpr std::size_t max_data_depth{8}; + +// the file Path of Folder, when Path is a relative path inside Folder (as read_script_file) and names a regular file of +// at most Limit bytes. nothing otherwise +std::optional read_file(std::filesystem::path const &Folder, std::string_view Path, std::uintmax_t Limit); + +// true for a path a script may write to: a relative path inside the folder (is_safe_relative_path), '/' or '\' between +// the folders, at most max_data_path bytes and max_data_depth folders deep, each name portable: not empty, not '.' or +// '..', none of the characters Windows refuses (: < > " | ? * and the control characters), no '.' or ' ' at the end, +// and not a device of Windows (con, prn, aux, nul, com0-9, lpt0-9, conin$, conout$, with an extension or without) +bool is_safe_write_path(std::string_view Path); + +// writes Contents to the file Path of Folder (a data folder), replacing what was there, and makes Folder and the folders +// of Path. refused for a path that isn't safe (is_safe_write_path), for more than max_data_file bytes, when Folder would +// hold more than max_data_files files or max_data_folder bytes, when Path names something else than a file, and when it +// leads out of Folder through a link. nothing when written, otherwise why not +std::optional write_data_file(std::filesystem::path const &Folder, std::string_view Path, std::string_view Contents); + +// the data folder of the scenery Scenery (its .scn file, relative to the scenery folder) in Root: Root and the file +// without ".scn" (td.scn: Root/td). empty when Root is, or the name isn't a safe path (is_safe_write_path) +std::filesystem::path scenery_data_folder(std::filesystem::path const &Root, std::string_view Scenery); + +// where the file functions of a scenery script read and write +struct file_folders +{ + // the scenery folder, which eu07.read_file reads, ending with a separator. empty: nothing is read + std::string scenery; + // the data folder of the scenery, which eu07.write_file writes and eu07.read_data_file reads. empty: nothing is + // written there or read from it + std::filesystem::path data; +}; + +// adds eu07.read_file(path), eu07.write_file(path, text) and eu07.read_data_file(path) to the state, on the folders of +// Folders, read on every call: Folders is to outlive the state +void open_file_library(lua_State *L, file_folders const *Folders); + +// the objects of the simulation a scenery script holds (eu07.events): each kind is a userdata of a metatable of its +// own, so a function given the handle of another kind, a light userdata or anything else raises a Lua error, and never +// takes one object for another. the objects outlive the state (the scenery's events, tracks, memcells and isolated +// track circuits, and its vehicles, which the game takes off the tracks but doesn't delete) +enum class handle_kind +{ + event, + track, + isolated, + vehicle, + memcell +}; + +// the name of the metatable of the kind, as the errors give it ("eu07.memcell expected, got userdata") +char const *handle_name(handle_kind Kind); + +// makes the metatables of the handles; once, before the first handle. a script can't reach them (getmetatable gives +// false) +void open_handles(lua_State *L); + +// pushes the handle of Object, of the kind, or nil for nullptr. one object has one handle while the script holds it: +// the handles of an object found twice are equal, and the same key of a table +void push_handle(lua_State *L, handle_kind Kind, void *Object); + +// the object of the handle at Index: nullptr for nil or nothing (what the find functions give for a missing object), +// a Lua error (bad argument) for anything else than a handle of the kind +void *check_handle(lua_State *L, int Index, handle_kind Kind); + +template Type_ *check_handle(lua_State *L, int const Index, handle_kind const Kind) +{ + return static_cast(check_handle(L, Index, Kind)); +} + +} // namespace lua_sandbox diff --git a/scripting/scriptscreendrawing.cpp b/scripting/scriptscreendrawing.cpp index f738d9292..870b5b8a3 100644 --- a/scripting/scriptscreendrawing.cpp +++ b/scripting/scriptscreendrawing.cpp @@ -64,13 +64,11 @@ bool lit_pixel(std::span const Rgba, int const Width, int co glyph cut_glyph(std::span const Rgba, int const Width, int const Height, int const First, int const Count) { std::vector lit(static_cast(Count) * Height, false); - for (auto column = 0; column < Count; ++column) + // only the columns inside the image are read + auto const last{static_cast(std::min(static_cast(First) + Count, Width))}; + for (auto x = std::max(First, 0); x < last; ++x) { - auto const x{First + column}; - if (x < 0 || x >= Width) - { - continue; - } + auto const column{x - First}; for (auto y = 0; y < Height; ++y) { lit[static_cast(column) * Height + y] = lit_pixel(Rgba, Width, x, y); @@ -128,14 +126,15 @@ std::u32string decode_utf8(std::string_view const Text) std::optional bitmap_font::parse(std::span const Rgba, int const Width, int const Height, std::string_view const Description) { - if (Width <= 0 || Height <= 0 || Rgba.size() < static_cast(Width) * Height * 4) + if (Width <= 0 || Height <= 0 || Width > max_font_image_side || Height > max_font_image_side || Rgba.size() < static_cast(Width) * Height * 4) { return std::nullopt; } bitmap_font font; font.m_height = Height; auto const all{lines(Description)}; - auto x{0}; + auto x{0}; // where the glyph starts: at most max_font_columns + auto glyphs{0}; // the first line is a comment for (std::size_t line = 1; line < all.size(); ++line) { @@ -157,10 +156,14 @@ std::optional bitmap_font::parse(std::span cons digits.remove_suffix(1); } auto width{0}; - if (std::from_chars(digits.data(), digits.data() + digits.size(), width).ec != std::errc{} || width < 0) + if (std::from_chars(digits.data(), digits.data() + digits.size(), width).ec != std::errc{} || width < 0 || width > max_font_image_side) { continue; } + if (++glyphs > max_font_glyphs || x + width > max_font_columns) + { + return std::nullopt; + } auto cut{cut_glyph(Rgba, Width, Height, x, width)}; if (font.m_glyphs.empty()) { diff --git a/scripting/scriptscreendrawing.h b/scripting/scriptscreendrawing.h index 215f2bf73..5b8166efa 100644 --- a/scripting/scriptscreendrawing.h +++ b/scripting/scriptscreendrawing.h @@ -57,12 +57,19 @@ class glyph std::vector m_lit; }; +// what a font may be: an image no larger than a screen image, a glyph no wider; no more glyphs, nor columns of them +// side by side, than a font can use. a glyph past the image's edge is unlit there, as with led_util +constexpr int max_font_image_side{4096}; +constexpr int max_font_glyphs{4096}; +constexpr int max_font_columns{2 * max_font_image_side}; + class bitmap_font { public: // a font as led_util.load_font() reads it: Rgba (Width x Height) has the glyphs side by side, a column apart; // Description has a comment line, then a line per glyph: the character and its width. a pixel is lit unless it is - // opaque white. nothing for a description without glyphs + // opaque white. a glyph wider than max_font_image_side is skipped. nothing for a description without glyphs, or + // beyond the limits above static std::optional parse(std::span Rgba, int Width, int Height, std::string_view Description); // a sprite as led_util.load_spr() reads it: the whole image as one glyph static glyph sprite(std::span Rgba, int Width, int Height); diff --git a/scripting/scriptscreenprogram.h b/scripting/scriptscreenprogram.h index 6b0d1b70b..10bed2124 100644 --- a/scripting/scriptscreenprogram.h +++ b/scripting/scriptscreenprogram.h @@ -14,11 +14,13 @@ http://mozilla.org/MPL/2.0/. #include "scripting/scriptscreens.h" +#include #include #include #include #include #include +#include #include namespace script_screens @@ -28,6 +30,23 @@ namespace script_screens constexpr int max_image_side{4096}; // the most instructions one call into a screen may run, so that a script stuck in a loop can't hang the worker constexpr std::int64_t instruction_limit{200'000'000}; +// what one call into a screen may send and log; the rest is dropped, which the log tells once per screen. the longest +// name of a command the engine knows is under 40 characters +constexpr std::size_t max_commands_per_call{64}; +constexpr std::size_t max_command_name{64}; +constexpr int max_log_lines_per_call{32}; +constexpr std::size_t max_log_line{1024}; // bytes of the text, a longer one is cut +// the largest file a screen reads: its script or module, a file below its folder +constexpr std::uintmax_t max_screen_file{16 * 1024 * 1024}; +// the memory a Lua screen may hold: its Lua heap, and the pixels of its images, fonts and sprites. checked with a full +// collection, so its garbage doesn't count; between the collections it may take the screen up to twice this, which +// the screen's allocator refuses to go over as each block is asked for +constexpr std::size_t max_screen_memory{128 * 1024 * 1024}; + +// for the unit tests, which fill the memory of a screen and stay small: the memory a Lua screen made from now on may +// hold in place of max_screen_memory, and the most any Lua screen held since it was set (its heap and its objects) +void set_lua_screen_memory_limit(std::size_t Bytes); +std::size_t lua_screen_memory_peak(); struct pending_command { @@ -86,6 +105,31 @@ std::unique_ptr make_wasm_runtime(); std::string utf8_text(std::string const &Text); // a file of the screen's folder or below; nothing for a path leading outside, or no such file std::optional read_screen_file(std::string const &Folder, std::string_view Path); +// the file, when it is a regular file of at most max_screen_file bytes: not a folder, a device or anything larger +std::optional read_regular_file(std::string const &Path); + +// what a screen sends and logs, held to the limits of one call. Name: how the log names the screen +class output_limits +{ + public: + explicit output_limits(std::string Name) : m_name{std::move(Name)} {} + + // a new call into the screen + void start_call() + { + m_log_lines = 0; + } + // true when the command may go with the call; a command over the limits is dropped + bool take_command(render_call const &Call, std::string_view Name); + // the line to log, cut to max_log_line; nothing when the call logged enough + std::optional take_log(std::string_view Text); + + private: + std::string m_name; + int m_log_lines{0}; + bool m_commands_dropped{false}; // logged once + bool m_logs_dropped{false}; // logged once +}; // seconds of a steady clock, the same for every screen, for animations that don't depend on how often the screen is // refreshed double screen_time(); diff --git a/scripting/scriptscreenrules.cpp b/scripting/scriptscreenrules.cpp index 58c69efde..5aa71cdd4 100644 --- a/scripting/scriptscreenrules.cpp +++ b/scripting/scriptscreenrules.cpp @@ -13,6 +13,9 @@ http://mozilla.org/MPL/2.0/. #include "utilities/parser.h" #include +#include +#include +#include namespace script_screens { @@ -123,4 +126,322 @@ bool is_safe_relative_path(std::string_view const Path) return true; } +std::optional screen_script_path(std::string const &Folder, std::string const &Script) +{ + // as substr_path() tells a folder + auto path{Script.find('/') == std::string::npos ? Folder + Script : Script}; + if (false == is_safe_relative_path(path)) + { + return std::nullopt; + } + return path; +} + +namespace +{ + +// the end of the set that starts at Start ('['), past its ']'; Pattern.size() for a set that doesn't end. as Lua's +// classEnd: a ']' right after '[' or '[^' is in the set, and '%' escapes the character after it +std::size_t set_end(std::string_view const Pattern, std::size_t Start) +{ + auto idx{Start + 1}; + if (idx < Pattern.size() && Pattern[idx] == '^') + { + ++idx; + } + do + { + if (idx >= Pattern.size()) + { + return Pattern.size(); + } + if (Pattern[idx++] == '%') + { + ++idx; + } + } while (idx >= Pattern.size() || Pattern[idx] != ']'); + return idx + 1; +} + +// one item of a pattern, as Lua's matcher takes them +struct pattern_item +{ + enum class kind + { + single, // a character, '.', a %class or a [set], with its quantifier if any + paren, // '(' or ')': a capture costs nothing + scan, // %bxy or a back reference %1-%9: goes along the subject + frontier, // %f[set]: a test of one position + end_anchor // '$' that ends the pattern + }; + kind type{kind::single}; + std::size_t begin{0}; // of a single, without its quantifier + std::size_t end{0}; + char quantifier{0}; // '*', '+', '-', '?' or none +}; + +std::vector pattern_items(std::string_view const Pattern, std::size_t idx) +{ + std::vector items; + while (idx < Pattern.size()) + { + auto const character{Pattern[idx]}; + if (character == '(' || character == ')') + { + items.push_back({pattern_item::kind::paren, idx, idx + 1}); + ++idx; + continue; + } + if (character == '$' && idx + 1 == Pattern.size()) + { + items.push_back({pattern_item::kind::end_anchor, idx, idx + 1}); + break; + } + std::size_t end{idx + 1}; + if (character == '%' && idx + 1 < Pattern.size()) + { + auto const next{Pattern[idx + 1]}; + if (next == 'b') + { + items.push_back({pattern_item::kind::scan, idx, idx + 4}); + idx += 4; + continue; + } + if (next == 'f') + { + auto const after{idx + 2 < Pattern.size() && Pattern[idx + 2] == '[' ? set_end(Pattern, idx + 2) : idx + 2}; + items.push_back({pattern_item::kind::frontier, idx, after}); + idx = after; + continue; + } + if (next >= '0' && next <= '9') + { + items.push_back({pattern_item::kind::scan, idx, idx + 2}); + idx += 2; + continue; + } + end = idx + 2; + } + else if (character == '[') + { + end = set_end(Pattern, idx); + } + pattern_item item{pattern_item::kind::single, idx, end}; + if (end < Pattern.size() && (Pattern[end] == '*' || Pattern[end] == '+' || Pattern[end] == '-' || Pattern[end] == '?')) + { + item.quantifier = Pattern[end]; + ++end; + } + items.push_back(item); + idx = end; + } + return items; +} + +// when the rest of a pattern matches, once the matcher gets to it +enum class rest_match +{ + always, // from any position: whatever comes before it is tried once + at_end, // at least at the end of the subject + maybe +}; + +rest_match match_with(std::string_view const Pattern, pattern_item const &Item, rest_match const Rest) +{ + switch (Item.type) + { + case pattern_item::kind::paren: + return Rest; + case pattern_item::kind::end_anchor: + return rest_match::at_end; + case pattern_item::kind::single: + if (Item.quantifier == '*' || Item.quantifier == '-' || Item.quantifier == '?') + { + // matches nothing as well; '.' repeated goes on to the end of the subject + auto const dot{Item.quantifier != '?' && Item.end - Item.begin == 1 && Pattern[Item.begin] == '.'}; + return dot && Rest == rest_match::at_end ? rest_match::always : Rest; + } + return rest_match::maybe; + default: + return rest_match::maybe; + } +} + +// whether Character is in the %class Class, as Lua's match_class +bool in_class(unsigned char const Character, unsigned char const Class) +{ + bool in{false}; + switch (std::tolower(Class)) + { + case 'a': in = std::isalpha(Character) != 0; break; + case 'c': in = std::iscntrl(Character) != 0; break; + case 'd': in = std::isdigit(Character) != 0; break; + case 'l': in = std::islower(Character) != 0; break; + case 'p': in = std::ispunct(Character) != 0; break; + case 's': in = std::isspace(Character) != 0; break; + case 'u': in = std::isupper(Character) != 0; break; + case 'w': in = std::isalnum(Character) != 0; break; + case 'x': in = std::isxdigit(Character) != 0; break; + case 'z': in = Character == 0; break; + default: return Class == Character; + } + return std::isupper(Class) != 0 ? !in : in; +} + +// the longest run of the subject that the single item (a character, '.' or a %class) matches; the whole subject for a +// set, which isn't gone through here +std::size_t longest_run(std::string_view const Pattern, pattern_item const &Item, std::string_view const Subject) +{ + auto const single{Pattern.substr(Item.begin, Item.end - Item.begin)}; + if (single == "." || single.front() == '[') + { + return Subject.size(); + } + std::size_t longest{0}; + std::size_t run{0}; + for (auto const character : Subject) + { + auto const c{static_cast(character)}; + auto const in{single.size() == 2 ? in_class(c, static_cast(single[1])) : c == static_cast(single[0])}; + run = in ? run + 1 : 0; + longest = std::max(longest, run); + } + return longest; +} + +// the characters Lua's matchbalance goes along for a %bxy tried in the subject: from each opening character to the one +// that closes it, or to the end of the subject when nothing does +struct balance_walks +{ + double longest{0.0}; // of one try + double total{0.0}; // of a try at every opening character +}; + +// the openings held while their closing characters are looked for; a subject nested deeper counts as never closed +constexpr std::size_t max_balance_depth{65536}; + +balance_walks balance_walks_of(char const Open, char const Close, std::string_view const Subject) +{ + balance_walks walks; + auto const size{Subject.size()}; + auto const add{[&walks](std::size_t const Walk) { + walks.longest = std::max(walks.longest, static_cast(Walk)); + walks.total += static_cast(Walk); + }}; + if (Open == Close) + { + // the next one closes it, and opens the try that starts there + auto previous{Subject.find(Open)}; + while (previous != std::string_view::npos) + { + auto const next{Subject.find(Open, previous + 1)}; + add((next != std::string_view::npos ? next : size) - previous); + previous = next; + } + return walks; + } + std::vector open; + for (std::size_t idx{0}; idx < size; ++idx) + { + if (Subject[idx] == Close) + { + if (false == open.empty()) + { + add(idx - open.back()); + open.pop_back(); + } + } + else if (Subject[idx] == Open) + { + if (open.size() >= max_balance_depth) + { + auto const openings{static_cast(std::count(Subject.begin(), Subject.end(), Open))}; + return {static_cast(size), openings * static_cast(size)}; + } + open.push_back(idx); + } + } + for (auto const idx : open) + { + add(size - idx); + } + return walks; +} + +// how many times over a %bxy counts: it goes along the subject on its own, whatever follows it, so it counts where it +// ends the pattern as well. without the subject, as many times as the subject has positions. with it: the longest walk +// of one try (plus one); or, when nothing but captures is before it in a pattern tried from every position, each +// opening character is tried once, and it's the walks of all of them over the positions (plus one) +double balance_cost(std::string_view const Pattern, pattern_item const &Item, std::string_view const *Subject, double const Positions, bool const Once) +{ + if (Subject == nullptr) + { + return Positions; + } + if (Item.begin + 3 >= Pattern.size()) + { + // malformed: the function raises its error + return 1.0; + } + auto const walks{balance_walks_of(Pattern[Item.begin + 2], Pattern[Item.begin + 3], *Subject)}; + return Once ? 1.0 + walks.total / Positions : 1.0 + walks.longest; +} + +double pattern_cost(std::string_view const Pattern, std::size_t const Size, std::string_view const *Subject, bool const Plain, bool const Anchorable) +{ + auto const length{static_cast(std::max(Pattern.size(), 1))}; + auto const positions{static_cast(Size) + 1.0}; + // LuaJIT searches plainly for a pattern without the special characters as well + if (Plain || Pattern.find_first_of("^$*+?.([%-") == std::string_view::npos) + { + return positions * length; + } + auto const anchored{Anchorable && Pattern.front() == '^'}; + auto const items{pattern_items(Pattern, anchored ? 1U : 0U)}; + auto cost{anchored ? 1.0 : positions}; + // from the end: what follows each item, and whether that's only the end of the subject + auto rest{rest_match::always}; + auto only_end{true}; + // the first item that isn't a capture: a %bxy there is tried once from each position + auto const first{std::find_if(items.begin(), items.end(), [](pattern_item const &Item) { return Item.type != pattern_item::kind::paren; })}; + for (auto item{items.rbegin()}; item != items.rend(); ++item) + { + if (item->type == pattern_item::kind::single && item->quantifier == '?') + { + cost *= 2.0; + } + if (item->type == pattern_item::kind::scan && Pattern[item->begin + 1] == 'b') + { + cost *= balance_cost(Pattern, *item, Subject, positions, false == anchored && first != items.end() && &*item == &*first); + only_end = false; + rest = rest_match::maybe; + continue; + } + auto const repeated{item->type == pattern_item::kind::scan + || (item->type == pattern_item::kind::single && item->quantifier != 0 && item->quantifier != '?')}; + // a repetition followed by what always matches is tried once (as one that ends the pattern): past it the match + // is over. otherwise the rest is tried at each length it takes, as many as the subject has positions; before + // '$' alone, as many as its longest run in the subject, past which it stops + if (repeated && rest != rest_match::always) + { + auto const before_end{only_end && rest == rest_match::at_end && item->type == pattern_item::kind::single}; + cost *= before_end && Subject != nullptr ? static_cast(longest_run(Pattern, *item, *Subject)) + 1.0 : positions; + } + only_end = only_end && (item->type == pattern_item::kind::paren || item->type == pattern_item::kind::end_anchor); + rest = match_with(Pattern, *item, rest); + } + return cost * length; +} + +} // namespace + +double lua_pattern_cost(std::string_view const Pattern, std::size_t const Subject, bool const Plain, bool const Anchorable) +{ + return pattern_cost(Pattern, Subject, nullptr, Plain, Anchorable); +} + +double lua_pattern_cost(std::string_view const Pattern, std::string_view const Subject, bool const Plain, bool const Anchorable) +{ + return pattern_cost(Pattern, Subject.size(), &Subject, Plain, Anchorable); +} } // namespace script_screens diff --git a/scripting/scriptscreenrules.h b/scripting/scriptscreenrules.h index d7d753841..bd751e50b 100644 --- a/scripting/scriptscreenrules.h +++ b/scripting/scriptscreenrules.h @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #pragma once #include +#include #include #include @@ -72,4 +73,36 @@ class frame_schedule // drive or a leading separator bool is_safe_relative_path(std::string_view Path); +// the path the game opens the script of a screen by: a name without a folder is in the vehicle's folder (Folder), a +// path is from the game's folder. nothing for a path that leads outside the game's folder (as for the files a screen +// reads: absolute, with a drive, or with ".."), since the script's folder is the one the screen then reads files from +std::optional screen_script_path(std::string const &Folder, std::string const &Script); + +// the Lua pattern functions (string.find, match, gmatch, gsub) run in C, where the instruction limit doesn't reach, and +// backtrack: ("a"):rep(1e6):find(".-b") would take hours. a call is refused when the steps it may take at worst, by +// lua_pattern_cost(), are over this: LuaJIT 2.0 goes through the worst patterns that cost as much (a):rep(5770) and +// .-b) in about a tenth of a second +constexpr double max_pattern_cost{1e8}; + +// the steps a Lua pattern function may take at worst on a subject of Subject bytes, Pattern being m bytes long: +// - a plain search (string.find with plain set, or a pattern without special characters): Subject x m; +// - a pattern: tried from every position of the subject (Subject + 1), or from the first only when Anchored (it starts +// with '^', and the function anchors: find, match, gsub, not gmatch), times (Subject + 1) for each repetition ('*', +// '+', '-', %b, a back reference %1-%9) but one followed by what always matches (nothing, ')', a repetition with '*' +// or '-' or a '?' of what always matches, '.*' / '.-' before '$'), where the match is over: so neither the last +// repetition nor the first %s* of "^%s*(.-)%s*$" multiplies. times 2 for each '?', times m for the work of each step +// (a set is gone through item by item) +// - a %bxy goes along the subject on its own, whatever follows it, so it counts where it ends the pattern as well: +// ("("):rep(1e6):find("%b()") walks to the end of the subject from each of its characters +// a malformed pattern costs nothing here: the function raises its error itself +double lua_pattern_cost(std::string_view Pattern, std::size_t Subject, bool Plain, bool Anchorable); +// as above, on the subject itself: a repetition of a character or a %class right before the final '$' ("%s*$") counts +// as many times as the longest run of it in the subject (plus one), not the whole subject: past that run it fails or +// gets to the end, so the trim "^%s*(.-)%s*$" costs about the subject times its longest run of spaces +// a %bxy counts as many times as the longest way from an opening character to the one that closes it (to the end of +// the subject when nothing does), plus one; when only captures are before it in a pattern tried from every position, +// each opening character is tried once, and it's the ways from all of them over the positions of the subject. so +// "%b()" on a long text of short balanced pairs is cheap, and on one that doesn't balance it's the subject squared +double lua_pattern_cost(std::string_view Pattern, std::string_view Subject, bool Plain, bool Anchorable); + } // namespace script_screens diff --git a/scripting/scriptscreens.cpp b/scripting/scriptscreens.cpp index 08314932e..224a2f27e 100644 --- a/scripting/scriptscreens.cpp +++ b/scripting/scriptscreens.cpp @@ -26,6 +26,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include #include @@ -34,6 +35,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include #include @@ -99,12 +101,73 @@ std::optional read_screen_file(std::string const &Folder, std::stri { return std::nullopt; } - std::ifstream file{Folder + std::string{Path}, std::ios::binary}; + return read_regular_file(Folder + std::string{Path}); +} + +std::optional read_regular_file(std::string const &Path) +{ + // a folder or a device (CON, NUL, COM1...) isn't a regular file + std::error_code error; + // in the code page of the system, as the game opens its files + std::filesystem::path const path{Path}; + if (false == std::filesystem::is_regular_file(path, error)) + { + return std::nullopt; + } + auto const size{std::filesystem::file_size(path, error)}; + if (error || size > max_screen_file) + { + return std::nullopt; + } + std::ifstream file{path, std::ios::binary}; if (false == file.is_open()) { return std::nullopt; } - return std::string{std::istreambuf_iterator{file}, std::istreambuf_iterator{}}; + std::string contents(static_cast(size), '\0'); + file.read(contents.data(), static_cast(contents.size())); + // what was read, should the file have shrunk meanwhile + contents.resize(static_cast(file.gcount())); + return contents; +} + +bool output_limits::take_command(render_call const &Call, std::string_view const Name) +{ + if (Call.commands.size() < max_commands_per_call && Name.size() <= max_command_name) + { + return true; + } + if (false == m_commands_dropped) + { + m_commands_dropped = true; + ErrorLog(std::format("{}: commands over {} in a refresh, or with names over {} characters, are dropped", m_name, max_commands_per_call, max_command_name)); + } + return false; +} + +std::optional output_limits::take_log(std::string_view Text) +{ + if (m_log_lines >= max_log_lines_per_call) + { + if (false == m_logs_dropped) + { + m_logs_dropped = true; + ErrorLog(std::format("{}: log lines over {} in a call are dropped", m_name, max_log_lines_per_call)); + } + return std::nullopt; + } + ++m_log_lines; + if (Text.size() <= max_log_line) + { + return std::format("{}: {}", m_name, Text); + } + // cut on the start of a UTF-8 character + auto end{max_log_line}; + while (end > 0 && (static_cast(Text[end]) & 0xC0) == 0x80) + { + --end; + } + return std::format("{}: {} [cut at {} of {} bytes]", m_name, Text.substr(0, end), end, Text.size()); } double screen_time() diff --git a/scripting/wasmprogram.cpp b/scripting/wasmprogram.cpp index d2f914cf0..1a1751732 100644 --- a/scripting/wasmprogram.cpp +++ b/scripting/wasmprogram.cpp @@ -25,8 +25,6 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include -#include #include #include #include @@ -117,7 +115,10 @@ std::int32_t to_int32(std::size_t const Value) class wasm_program final : public program { public: - wasm_program(std::string const &Script, script_screen_kind const Kind) : kind{Kind}, script{Script}, folder{substr_path(Script)} {} + wasm_program(std::string const &Script, script_screen_kind const Kind) + : kind{Kind}, script{Script}, folder{substr_path(Script)}, output{std::format("WASM screen \"{}\"", Script)} + { + } ~wasm_program() override { if (exec_env != nullptr) @@ -142,6 +143,7 @@ class wasm_program final : public program input_view const *input{nullptr}; render_call *call{nullptr}; bool commands_ignored{false}; // a screen outside the cab tried to send a command, and it was logged + output_limits output; private: bool call_i32(wasm_function_inst_t Function, std::string_view Name, std::int32_t &Result); @@ -300,17 +302,23 @@ void native_command(wasm_exec_env_t Env, char const *Name, std::uint32_t const L } return; } - screen->call->commands.emplace_back(std::string{Name, Length}, Param1, Param2, screen->call->vehicle); + if (screen->output.take_command(*screen->call, std::string_view{Name, Length})) + { + screen->call->commands.emplace_back(std::string{Name, Length}, Param1, Param2, screen->call->vehicle); + } } void native_log(wasm_exec_env_t Env, char const *Text, std::uint32_t const Length) { - auto const *screen{program_of(Env)}; + auto *screen{program_of(Env)}; if (screen == nullptr || Text == nullptr) { return; } - WriteLog(std::format("WASM screen \"{}\": {}", screen->script, std::string_view{Text, Length})); + if (auto const line{screen->output.take_log(std::string_view{Text, Length})}; line.has_value()) + { + WriteLog(*line); + } } // reads a file from the screen's folder into the buffer. returns the size of the whole file, which may be more @@ -436,6 +444,7 @@ bool wasm_program::instantiate(wasm_module_t const Module) bool wasm_program::call_i32(wasm_function_inst_t Function, std::string_view const Name, std::int32_t &Result) { wasm_runtime_set_instruction_count_limit(exec_env, static_cast(instruction_limit)); + output.start_call(); std::array cells{}; if (false == wasm_runtime_call_wasm(exec_env, Function, 0, cells.data())) { @@ -514,9 +523,9 @@ class wasm_runtime_host final : public runtime { for (auto const &[script, entry] : m_modules) { - if (entry.module != nullptr) + if (entry.wasm_module != nullptr) { - wasm_runtime_unload(entry.module); + wasm_runtime_unload(entry.wasm_module); } } if (m_started) @@ -542,7 +551,7 @@ class wasm_runtime_host final : public runtime struct module_entry { std::vector bytes; // the runtime reads the module from here as long as it is loaded - wasm_module_t module{nullptr}; + wasm_module_t wasm_module{nullptr}; }; wasm_module_t load_module(std::string const &Script); @@ -575,40 +584,40 @@ wasm_module_t wasm_runtime_host::load_module(std::string const &Script) { if (auto const lookup{m_modules.find(Script)}; lookup != m_modules.end()) { - return lookup->second.module; + return lookup->second.wasm_module; } // a failure is kept as well, so the module isn't tried again for every screen using it auto &entry{m_modules[Script]}; - std::ifstream file{Script, std::ios::binary}; - if (false == file.is_open()) + auto const file{read_regular_file(Script)}; + if (false == file.has_value()) { - ErrorLog(std::format("WASM screen \"{}\": file not found", Script)); + ErrorLog(std::format("WASM screen \"{}\": file not found, or larger than {} bytes", Script, max_screen_file)); return nullptr; } - entry.bytes.assign(std::istreambuf_iterator{file}, std::istreambuf_iterator{}); + entry.bytes.assign(file->begin(), file->end()); if (entry.bytes.empty() || entry.bytes.size() > std::numeric_limits::max()) { ErrorLog(std::format("WASM screen \"{}\": invalid module size", Script)); return nullptr; } std::array error{}; - entry.module = wasm_runtime_load(entry.bytes.data(), static_cast(entry.bytes.size()), error.data(), static_cast(error.size())); - if (entry.module == nullptr) + entry.wasm_module = wasm_runtime_load(entry.bytes.data(), static_cast(entry.bytes.size()), error.data(), static_cast(error.size())); + if (entry.wasm_module == nullptr) { ErrorLog(std::format("WASM screen \"{}\": failed to load the module: {}", Script, error.data())); } - return entry.module; + return entry.wasm_module; } std::unique_ptr wasm_runtime_host::load(std::string const &Script, script_screen_kind const Kind) { - auto *module{load_module(Script)}; - if (module == nullptr) + auto *wasm_module{load_module(Script)}; + if (wasm_module == nullptr) { return nullptr; } auto loaded{std::make_unique(Script, Kind)}; - if (false == loaded->instantiate(module)) + if (false == loaded->instantiate(wasm_module)) { return nullptr; } diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index b30d8a6c7..e4161ce61 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -25,6 +25,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/physicslog.h" #include "utilities/utilities.h" +#include "world/stationnames.h" #include #include @@ -392,8 +393,9 @@ void blackbox_recorder::write_map() { if (values == nullptr) continue; auto const &text{values->input_text()}; + // the name in the form the station records and the rows of the timetable have theirs, as it always was if (text.starts_with(stoppoint)) - m_writer->stop_point(stoppoints++, text_of(std::string_view{text}.substr(stoppoint.size())), values->input_location(), + m_writer->stop_point(stoppoints++, text_of(timetable::station_ascii(text.substr(stoppoint.size()))), values->input_location(), static_cast(values->input_value(1)), static_cast(values->input_value(2)), heading_of(values->input_location())); else if (text == "Warning_signal") m_writer->horn_point(hornpoints++, text_of(values->name()), values->input_location(), static_cast(values->input_value(1)), @@ -542,6 +544,7 @@ void blackbox_recorder::look_around(bool const Keyframe) { look_at_vehicles(Keyframe); auto const vehicles{clock::now()}; look_at_couplers(); + look_at_derailments(); auto const couplers{clock::now()}; look_at_switches(); auto const switches{clock::now()}; @@ -555,6 +558,59 @@ void blackbox_recorder::look_around(bool const Keyframe) { } } +namespace { + +std::uint8_t cause_of(derail_motion::cause const Cause) { + switch (Cause) { + case derail_motion::cause::overturned: + return blackbox::derailment_causes::overturned; + case derail_motion::cause::end_of_track: + return blackbox::derailment_causes::end_of_track; + case derail_motion::cause::pulled_off: + return blackbox::derailment_causes::pulled_off; + case derail_motion::cause::collision: + return blackbox::derailment_causes::collision; + default: + return blackbox::derailment_causes::flange_climbed; + } +} + +} // namespace + +void blackbox_recorder::look_at_derailments() { + for (auto *vehicle : simulation::Vehicles.sequence()) { + if (false == vehicle->bEnabled) + continue; + auto const &motion{vehicle->MoverParameters->OffTrack}; + auto const id{vehicle_id(vehicle)}; + auto &entry{m_vehicles[vehicle]}; + if (false == motion.active()) { + entry.derailment = 0; + continue; + } + auto const phase{motion.at_rest() ? 2 : 1}; + if (entry.derailment >= phase) + continue; + blackbox::derailment_state state; + state.time = m_time; + state.vehicle = id; + state.cause = cause_of(motion.reason()); + state.position = vehicle->GetPosition(); + state.heading = static_cast(std::atan2(vehicle->VectorFront().x, vehicle->VectorFront().z)); + state.speed_kmh = static_cast(vehicle->MoverParameters->V * 3.6); + state.offset = static_cast(vehicle->off_track_offset()); + state.roll = static_cast(motion.roll()); + state.travelled = static_cast(motion.travelled()); + state.lying = motion.lying(); + // seen first at rest, it left the track before + for (auto written = entry.derailment + 1; written <= phase; ++written) { + state.phase = (written == 1 ? blackbox::derailment_phases::left_track : blackbox::derailment_phases::at_rest); + m_writer->derailment(state); + } + entry.derailment = phase; + } +} + void blackbox_recorder::look_at_couplers() { for (auto *vehicle : simulation::Vehicles.sequence()) { if (false == vehicle->bEnabled) @@ -720,8 +776,9 @@ std::uint32_t blackbox_recorder::known_id(TDynamicObject const *Vehicle) { return Vehicle != nullptr && Vehicle->bEnabled ? vehicle_id(Vehicle) : blackbox::no_vehicle; } -std::uint32_t blackbox_recorder::signal_at(glm::dvec3 const &Location) const { - auto const found{std::ranges::find_if(m_signals, [&Location](signal_entry const &Signal) { return glm::distance(Signal.location, Location) < 0.01; })}; +std::uint32_t blackbox_recorder::signal_of(TMemCell const *Cell) const { + // by the memory cell, not by its position: two signals can have their cells at one point + auto const found{std::ranges::find(m_signals, Cell, &signal_entry::cell)}; if (found == m_signals.end()) return blackbox::no_signal; return static_cast(std::distance(m_signals.begin(), found)); @@ -750,7 +807,7 @@ void blackbox_recorder::signal_passed(TDynamicObject const *Vehicle, basic_event if (m_writer == nullptr || Vehicle == nullptr) return; auto const location{Event.input_location()}; - m_writer->signal_passed({m_time, vehicle_id(Vehicle), signal_at(location), text_of(Event.name()), location, static_cast(Speed1), static_cast(Speed2), + m_writer->signal_passed({m_time, vehicle_id(Vehicle), signal_of(Event.input_cell()), text_of(Event.name()), location, static_cast(Speed1), static_cast(Speed2), static_cast(Trainspeed), static_cast(Overrun), Flags}); } diff --git a/simulation/blackboxrecorder.h b/simulation/blackboxrecorder.h index a3aaf5d0f..cdc61da61 100644 --- a/simulation/blackboxrecorder.h +++ b/simulation/blackboxrecorder.h @@ -69,6 +69,8 @@ private: bool listed{false}; std::array couplers; // as seen last bool couplers_known{false}; + // off the track: 0 not, 1 written as leaving it, 2 written as at rest + int derailment{0}; }; struct switch_entry { TTrack *track{nullptr}; @@ -99,6 +101,8 @@ private: void look_at_signals(); // the couplers of every vehicle against the last look: those coupled at the first look, then the changes void look_at_couplers(); + // the vehicles leaving the track and coming to rest off it (physics.derailment new) + void look_at_derailments(); void write_camera(); // the timetable of the train the user is in, written again when it is another one; none isn't written void look_at_timetable(TDynamicObject const &Vehicle, std::uint32_t Id); @@ -106,7 +110,8 @@ private: std::uint32_t vehicle_id(TDynamicObject const *Vehicle); // the number of a vehicle still on the scenery, no_vehicle for none or one taken off it std::uint32_t known_id(TDynamicObject const *Vehicle); - std::uint32_t signal_at(glm::dvec3 const &Location) const; + // the number of the signal whose aspect the memory cell tells, no_signal for one which isn't on the map + std::uint32_t signal_of(TMemCell const *Cell) const; std::mutex m_mutex; std::array m_filebuffer{}; diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp index c6b150cf4..2eb0a3c89 100644 --- a/simulation/simulation.cpp +++ b/simulation/simulation.cpp @@ -148,6 +148,8 @@ state_manager::update( double const Deltatime, int Iterationcount ) { simulation::Roadpoints.update( totaltime ); Timer::subsystem.sim_roads.stop(); simulation::Vehicles.update( Deltatime, Iterationcount ); + // the tracks the heat buckles, by itself or under the trains just moved + TTrack::update_buckling( totaltime ); } void @@ -432,12 +434,10 @@ void state_manager::process_commands() { } while (vehicle) { - vehicle->MoverParameters->DamageFlag = 0; - vehicle->MoverParameters->EngDmgFlag = 0; + // no damage, back on the rails with the state of the derailment cleared + vehicle->MoverParameters->repair_damage(); vehicle->MoverParameters->V = 0.000001; // HACK: force vehicle position re-calculation vehicle->MoverParameters->DistCounter = 0.0; - vehicle->MoverParameters->WheelFlat = 0.0; - vehicle->MoverParameters->AlarmChainFlag = false; vehicle->MoverParameters->OffsetTrackH = 0.0; vehicle->MoverParameters->OffsetTrackV = 0.0; diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index 2d8541d7f..c1fad53ae 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -272,8 +272,8 @@ state_serializer::deserialize_assignment( cParser &Input, scene::scratch_data &S while( false == token.empty() && token != "endassignment" ) { // assignment is expected to come as string pairs: language id and the actual assignment enclosed in quotes to form a single token - auto assignment{ Input.getToken() }; - win1250_to_ascii( assignment ); + // the assignment is only shown to the player, so it's kept with its letters, in utf-8 as the user interface takes it + auto const assignment{ data_text_to_utf8( Input.getToken() ) }; Scratchpad.trainset.assignment.emplace( token, assignment ); token = Input.getToken(); } @@ -384,8 +384,9 @@ state_serializer::deserialize_camera( cParser &Input, scene::scratch_data &Scrat void state_serializer::deserialize_config( cParser &Input, scene::scratch_data &Scratchpad ) { - // config parameters (re)definition - Global.ConfigParse( Input ); + // config parameters (re)definition, but for what only eu07.ini sets: programs to run, connections, the sandbox of + // the scripts (utilities/inionlysettings.h) + Global.ConfigParse( Input, config_source::scenery ); if( Global.test.enabled ) { // a scenery doesn't get to turn on what a test keeps off simulation::apply_test_mode_settings(); @@ -427,7 +428,8 @@ void state_serializer::deserialize_lua( cParser &Input, scene::scratch_data &Scr std::string file; Input >> file; #ifdef WITH_LUA - simulation::Lua.interpret(Global.asCurrentSceneryPath + file); + // the file is relative to the scenery folder, and stays inside it + simulation::Lua.interpret(Global.asCurrentSceneryPath, file); #else ErrorLog(file + ": lua scripts not supported in this build."); #endif @@ -446,7 +448,13 @@ state_serializer::deserialize_firstinit( cParser &Input, scene::scratch_data &Sc // TBD: postpone loading furter and only load required blocks during the simulation? if (false == Scratchpad.binary.terrain_included) { - Region->deserialize(Scratchpad.name); + if (false == Region->deserialize(Scratchpad.name)) + { + // the file looked whole to is_scene() but its content is damaged. the geometry it holds is missing from this + // session, as the text definitions were skipped already. the file is the game's own copy of the text, so it + // goes, and the next start loads the text and writes it anew + Region->discard_scene(Scratchpad.name); + } } else { @@ -467,6 +475,9 @@ state_serializer::deserialize_firstinit( cParser &Input, scene::scratch_data &Sc Scratchpad.binary.terrain_binaryfiles.clear(); simulation::Paths.InitTracks(); + if( Global.track_check ) { + simulation::Paths.CheckTracks(); + } // the roads tie up their own lanes where they gain or lose some, the junctions tie the lanes of the roads together, // what's left loose after that gets closed by the roads simulation::Roads.InitLanes(); @@ -598,7 +609,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch else if( nodedata.type == "road" ) { auto *road { new road_node( nodedata ) }; - road->import( + road->import_from( Input, ( Scratchpad.location.offset.empty() ? glm::dvec3 { 0.0 } : @@ -637,7 +648,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch else if( nodedata.type == "sweep" ) { auto *sweep { new sweep_node( nodedata ) }; - sweep->import( + sweep->import_from( Input, ( Scratchpad.location.offset.empty() ? glm::dvec3 { 0.0 } : @@ -651,7 +662,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch else if( nodedata.type == "junction" ) { auto *junction { new junction_node( nodedata ) }; - junction->import( + junction->import_from( Input, ( Scratchpad.location.offset.empty() ? glm::dvec3 { 0.0 } : @@ -683,7 +694,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch else if( roadpoint_node::is_keyword( nodedata.type ) ) { // level crossing, or a point where road vehicles appear or are taken away auto *point { new roadpoint_node( nodedata ) }; - point->import( + point->import_from( Input, ( Scratchpad.location.offset.empty() ? glm::dvec3 { 0.0 } : @@ -784,7 +795,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch if( false == skip ) { ++Scratchpad.binary.geometry_imported; - auto shape { scene::shape_node().import( Input, nodedata ) }; + auto shape { scene::shape_node().import_from( Input, nodedata ) }; material = shape.data().material; if( true == Global.editor_session ) { shape.source_file( scene::terrain_file::reference_of( Input.Name() ) ); @@ -822,7 +833,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch ++Scratchpad.binary.geometry_imported; simulation::Region->insert( - scene::lines_node().import( + scene::lines_node().import_from( Input, nodedata ), Scratchpad ); } diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp index 1c6c90535..f6e2a4a39 100644 --- a/simulation/simulationtest.cpp +++ b/simulation/simulationtest.cpp @@ -90,8 +90,10 @@ void apply_test_mode_settings() Global.iMultiplayer = 0; Global.exec_on_exit.clear(); // and the same way every time, unless given another seed (-seed, or randomseed in the settings) - if (!Global.random_seed) + if (false == Global.random_seed_given) { Global.random_seed = seed_of("test"); + Global.random_seed_given = true; + } // the real time limit, which the scenery may set too test().watch_wall_clock(wall_clock_limit(Global.test.wall_timeout, Global.test.timeout)); } diff --git a/staticFiles/python/local/abstractscreenrenderer.py b/staticFiles/python/local/abstractscreenrenderer.py index 3ebf20813..59341c045 100644 --- a/staticFiles/python/local/abstractscreenrenderer.py +++ b/staticFiles/python/local/abstractscreenrenderer.py @@ -1,6 +1,73 @@ from PIL import Image, ImageDraw, ImageFont from math import ceil, floor, cos, sin, radians +import builtins import os +import sys +import time + +# Linux tells the case of the letters in a file name apart, Windows doesn't, and the data is made on Windows: a screen asks for +# "WS_on.png" where the disk has "ws_on.png", or names a folder in another case. The simulator opens such files of its own through +# FileOnDisk(); the files a screen opens itself (images, fonts, text) are found here the same way. The name given when it's on the +# disk, otherwise the one differing from it only in case, of the file or of its folders. On Windows nothing changes. +_case_sensitive = not sys.platform.startswith('win') +_cased_listings = {} # folder -> (when listed, {name in lower case: name on the disk}) + +def _cased_name(folder, name): + """the name in the folder differing from the one given only in case, as on the disk; None when there's none""" + listed = _cased_listings.get(folder) + # a name missing gets the folder listed again, at most once a second, as FileCased() does + if listed is None or (name.lower() not in listed[1] and time.monotonic() - listed[0] >= 1.0): + names = {} + try: + for entry in os.listdir(folder or '.'): + names.setdefault(entry.lower(), entry) + except OSError: + pass + listed = (time.monotonic(), names) + _cased_listings[folder] = listed + return listed[1].get(name.lower()) + +def file_on_disk(path): + """the file to open: as it's named on the disk, the path given when there's none (and on Windows, which finds it itself)""" + if not _case_sensitive or not isinstance(path, str) or os.path.exists(path): + return path + text = path.replace('\\', '/') + parts = [part for part in text.split('/') if part] + cased = '/' if text.startswith('/') else '' + for index, part in enumerate(parts): + last = index == len(parts) - 1 + found = part + if part not in ('.', '..') and not os.path.exists(cased + part): + found = _cased_name(cased, part) + if found is None: + if not last: + return path + # a file not there yet goes into its folder as named on the disk: one written for the first time. The folder + # gets listed anew next time, the file being there by then + _cased_listings.pop(cased, None) + return cased + part + cased += found if last else found + '/' + return cased + +def _open_files_on_disk(): + # Image.open() opens the file through builtins.open(); the fonts are opened by FreeType, from the name. What the wrappers + # call is held here, not looked up in __main__, which the screens share and could name the same + on_disk = file_on_disk + open_given = builtins.open + truetype_given = ImageFont.truetype + + def open_on_disk(file, *args, **kwargs): + return open_given(on_disk(file), *args, **kwargs) + + def truetype_on_disk(font=None, *args, **kwargs): + return truetype_given(on_disk(font), *args, **kwargs) + + open_on_disk.file_on_disk = True + builtins.open = open_on_disk + ImageFont.truetype = truetype_on_disk + +if _case_sensitive and not getattr(builtins.open, 'file_on_disk', False): + _open_files_on_disk() # Pillow 10 removed ImageFont.getsize(), ImageDraw.textsize() and Image.ANTIALIAS, which the screen scripts use; for # Python 3.14 only a newer Pillow is available, so they are put back, on top of getbbox() / textbbox() and LANCZOS @@ -30,7 +97,7 @@ class abstractscreenrenderer(): def openimage(self, name): exts = [ ".png", ".tga", ".dds" ] for e in exts: - path = name + e + path = file_on_disk(name + e) if os.path.isfile(path): if e == ".dds": return Image.open(path).transpose(Image.FLIP_TOP_BOTTOM) diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index ea5ebc89b..529fefea6 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -37,8 +37,10 @@ With `--test` the simulator: test mode are applied again after it, - runs the simulation as fast as it can in fixed steps of 0.03 s of simulation time per frame (three 10 ms physics steps), whatever the real time, the time speed or the machine, -- seeds its random numbers with a fixed seed unless `-seed` or `randomseed` gives one, so two - runs of a scenery come out the same (the physicslogs of two runs are byte for byte equal), +- seeds its random numbers with a fixed seed unless `-seed` or `randomseed` gives one, so, + with the fixed step above, two runs of a scenery come out the same (the physicslogs of two + runs are byte for byte equal; a seed without the fixed step isn't enough, see + [A seed alone doesn't make a run repeatable](#a-seed-alone-doesnt-make-a-run-repeatable)), - quits when the test ends, and says how it ended in the exit code and in a `test: ...` line on stdout and in the log. A command line it can't take, a start that fails, or an exception thrown by the simulator (of any type, on Linux too) ends the same way, with the @@ -135,13 +137,46 @@ Python 3.10+, no extra packages. Options: `cmake-build-*/bin/Release/eu07*.exe`. The build needs the `--test` and `-ini` command line options. - name one or more cases to run only those, e.g. `run.py ... eu07_td_timetable`. -- `-j N` runs N cases at once. Each case prints its results when it is done. All 19 cases - take about 30 s with `-j 4`, loading included. +- `-j N` runs N cases at once. Each case prints its results when it is done. The 42 cases + that aren't `slow` take about 30 s with `-j 4` and 2 minutes one at a time, loading included. - `--watch` runs a case the old way, in a visible window in real time (or faster with `--timespeed N`), closed after the case's `duration`; the exit code isn't checked then. For watching what a case does. +- `--slow` runs the cases marked `slow` too. Without it, and with no cases named, they are + skipped (and listed): each is a whole mission on a big scenery and takes many minutes. A + slow case named on the command line always runs. Run them one at a time (`-j 1`): each + simulator loads a whole scenery. A case on a mission of the base scenery with physicslog on + (`vehicle` given) removes every physicslog written in the game dir meanwhile, so with `-j N` + it runs alone, after the others. +- `--seed N` (a number or a word) runs the cases with another seed of the simulator's random + numbers (`randomseed`) than the fixed one of the test mode, for a bug that shows up only + sometimes: run the case with a few seeds. A seed repeats a run only in the test mode, see + below. -Exit code is 0 when every case passed. Logs of each run (`log.txt`, `errors.txt`, +### A seed alone doesn't make a run repeatable + +The same seed gives the same run only when every frame lasts the same simulation time. Each +frame the simulator splits the time since the last one into physics steps of at most 10 ms +(`driver_mode::update()`); outside the test mode that time comes from the wall clock (times +`timespeed`), so the number and the length of the steps follow the frame rate, and with them +the speeds, the pressures and the moments the AI decides things. Two runs of one scenery with +one seed then drift apart, the more so on a busy machine. + +- The test mode (`--test`, what `run.py` runs by default) sets a fixed step itself: 0.03 s of + simulation time per frame, three 10 ms steps, whatever the wall clock + (`Timer::set_fixed_step()` in `driver_mode::enter()`). A case run twice with the same + `--seed`, or with none, comes out the same. This is the way to repeat a run. +- `--watch` doesn't use the test mode: it runs on the wall clock, so a watched run isn't + repeatable, seed or not. Use it to look at a case, not to repeat one. +- Outside the test mode (`--watch`, or the simulator started by hand with `-seed`) the setting + `deltaoverride N` makes every frame last 1/N s of simulation time, whatever the wall clock + and `timespeed` (`Timer::set_delta_override()`). It goes in `eu07.ini`, a `-ini` file or a + case's `ini` list. In the test mode it takes the place of the 0.03 s step. Whether a watched + run with it repeats byte for byte hasn't been checked. + +Exit code is 0 when every case passed, or failed as its `xfail` mark says it does (`XFAIL` in +the summary); a case marked `xfail` that passes (`XPASS`) fails the run, so that the mark gets +removed. Logs of each run (`log.txt`, `errors.txt`, `stdout.txt`, the physicslogs of the vehicle and of other trains of the case, the black box as `autotest_.blackbox`) are moved to `tests/scenarios/out//`. @@ -171,7 +206,17 @@ The lead vehicle is named `autotest_`, so every case has its own physicslo files and cases can run in parallel. The `autotest_*` sceneries (and the simulator's `.sbt` geometry cache of them) stay in the game's `scenery/` dir; the cache is dropped when the base scenery is newer, and after a run cut short (`wall_timeout`, `error`, a crash, or killed by run.py), -which could have been writing it. +which could have been writing it. A case with `file.binary.terrain no` in its `ini` has no cache +written, and one left by an earlier run is removed. + +A case with `vehicle` runs a train of the base scenery under its own name: its physicslog is +`physicslog/.dat` (one of that name already in the game dir is replaced), and with the +physicslogs on, every train of the scenery writes one, over any of the same name; those written +during the run are deleted after it. Don't run such a case along with another one in the same game dir. + +Apart from these the game dir loses its `log.txt` and `errors.txt`, those of the last game +session: the simulator deletes them at every start, before it knows that the run's log goes +to `logs/`. ## Writing a case @@ -180,14 +225,21 @@ which could have been writing it. | key | meaning | | --- | --- | | `base_scenery` | scenery file in the game's `scenery/` dir | -| `strip_trainsets` | drop the base scenery's trainsets (default `true`) | +| `strip_trainsets` | drop the base scenery's trainsets (default `true`); `false` keeps them, for a case on one of the scenery's own missions (below) | +| `vehicle` | the train under test is this vehicle of the base scenery (its node name), instead of the `autotest_` one of the fragment: `test.vehicle`, the physicslog checked and `{{vehicle}}` are this one. With `strip_trainsets` `false` | +| `replace` | literal replacements in the text of the base scenery, a list of `[old, new]`, e.g. to put another locomotive on a mission; an `old` the scenery doesn't have is an error | +| `physicslog` | `false` turns the physicslogs (and the black box) off for the run: on a scenery with dozens of AI trains each of them would write 3-4 kB per second of simulation into the game dir. Such a case has the result of the test mode and the log checks only (default `true`) | +| `slow` | `true` marks a case that takes many minutes: skipped unless named or run with `--slow` | +| `xfail` | marks a case that fails because of a known, reported bug, with the reference and the reason as its text, e.g. `"eu07/maszyna#524: the AI never couples"`. Its failure is reported as `XFAIL` and doesn't fail the run; when it passes (`XPASS`) the run fails until the mark is removed | | `time` | replace the scenery start time, `HH:MM` | | `track_friction` | set the friction of every track of the base scenery (default in the sceneries is 0.15), e.g. for slippery rail | | `track_events` | lines added to tracks of the base scenery, by track name, e.g. `{ "tor1k": "event0 test_pass" }`; only tracks in the scenery file itself, not in its includes | | `test_config` | lines of a `config` block added to the scenery, e.g. `["test.timeout 90"]`; the block always has `test.vehicle` with the case's lead vehicle, so only its train counts for the pass and the standstill | | `ini` | extra `eu07.ini` lines for the run, after the common ones of the runner's `-ini` file, e.g. `["crashdamage yes"]` | -| `fragment` | `.scn` file in `cases/` added to the scenery: trainsets after `FirstInit` (before it they derail on unlinked track), the rest before it (launchers read after it never fire) | +| `fragment` | `.scn` file in `cases/` added to the scenery: trainsets after `FirstInit` (before it they derail on unlinked track), the rest before it (launchers read after it never fire). Optional when the case keeps the scenery's trainsets | | `vars` | values for `{{name}}` in the fragment; a list becomes one line per item | +| `timetable` | a timetable file in `cases/` for a trainset of the fragment, for a train whose timetable no scenery of the game has: copied to the game's `scenery/` dir as `autotest_.txt` for the run and removed after it; the fragment names it `{{timetable}}` | +| `vehicle_variants` | vehicles of the case's own, made from those of the game, e.g. with a `.fiz` key the game's data doesn't have yet: a list of `{ "name": ..., "from": "/", "replace": [[old, new], ...] }`. For the run the vehicle's `.fiz`, with the literal replacements (an `old` it doesn't have is an error), and its `.mmd` are copied beside it in the game's `dynamic/` dir as `autotest__` and removed after it; the fragment names the type `{{variant_}}`, e.g. `dynamic pkp/et42_v2 112e-014-a {{variant_a}} ...`. The copy of the `.mmd` has the name of the vehicle it is made from in place of `(p2)`, the type name the simulator hands it, which some pass on to the include that names the model. An optional `"fiz_from": "/"` copies that file instead of the vehicle's own `.fiz`, named in full, e.g. `pkp/e6act_v2/e6acta.fiz.inc` for a vehicle whose `.fiz` only includes it (`e6actad.fiz`); the `.mmd` still comes from `from`. Keys for a section of the included file can't go after the include on a line of their own: a second `Power:` line loads the power source anew | | `expect` | the result the test mode should end with: `pass`, `fail`, `signal_passed_at_danger`, `timeout`, `standstill` or `error`, or `wall_timeout` for the timeout of the real time watchdog (the timeout code with a verdict saying it was the real time; a case expecting `timeout` fails on it). Default `timeout` for a case with `duration`, else `pass` | | `duration` | seconds of simulation to record: the test timeout of the run (`--test-timeout`) | | `timeout` | wall-clock seconds before giving up, loading included: the simulator's `--test-wall-timeout` (default 600) | @@ -209,6 +261,91 @@ starting at `vars.velocity` km/h; with `track_friction` 0.03 it locks the wheels and slides past the signal, so those cases set `test.fail_if_stop_overran no`. `td_red_signal_pass.scn` adds the `test_pass` event, which `test_mode_pass` puts as `event0` on `tor1k`, the track in front of the signal. +`td_shunt_red_signal.scn` is the same with no timetable, so the AI shunts (Shunt) towards the signal at +stop, starting `vars.offset` m into `tdo_n1734`: `eu07_td_shunt_red_signal` alone and +`eu07_td_shunt_push_red_signal` pushing three coaches, both from 30 km/h, have to stop before the signal, +151 m from the start (the shunting AI used to coast up to it and pass it at about 28 km/h, fixed +by #409). They stop after 145 m and 141 m. + +The `traxx_*` cases run a Traxx (E186, `p160dc`), whose driver's brake handle (MHZ_6P) has a time +chamber, like the MHZ_K5P, M394, Knorr, St113, FVel6 and FVE408 handles, which no other case has: the +AI getting such a locomotive ready has a rule of its own for releasing the train brake (5775493b2, +#444). `traxx_td_timetable` is the timetable run from a trainset ready to depart, +`traxx_td_timetable_cold` the same from a cold start (`td_cold_timetable.scn`, the handle in its +holding position, the brake pipe low), and `traxx_td_crew_add` the locomotive standing ready to depart +with nobody in it, the handle in its holding position and the brake pipe charged, until a driver is +put in (`td_crew.scn`, as `eu07_td_crew_add`). In all three the driver puts the handle to running +within a second of starting and leaves. + +`eu07_td_departure_station_capitals` runs an EU07 from where `td_timetable.scn` puts it, with the W4 of Stacja1 about +35 m ahead, on a timetable of its own (`td_departure_station_capitals.txt`, fragment `td_departure_station.scn`): +its first row, the station of departure, gives no arrival time and is written in capitals (`STACJA1`), the relation +says `Stacja1`, as in some timetables of the game (`Os33733` of linia_107_poludnie.scn starts at `ZAGORZ`). The +train has to stop there and leave at its departure time, 10:35, which the log shows as `as TEST24: at 10:35 next +Przystanek`; taking Stacja1 for a station it passes through, the driver logs `passed STACJA1` at once and leaves as +soon as the route is set at 10:34, and the train manager gives no departure signal. `eu07_td_departure_station` is the +same with the row written as in the relation. `eu07_td_timetable_past_w4` (fragment `td_timetable_past_w4.scn`) puts +the td/rozklad train, an EU07 with three coaches, with its head 80 m past the W4 of Stacja1, on `tor1k`: the W4 stays +under the consist, behind the head, and the driver still counts Stacja1 and leaves at 10:35, since the scan of the +route begins at the last vehicle and keeps a W4 behind the head. + +`eu07_coaches_td_timetable` is the timetable case with the EU07 and three coaches, a train that brakes with the train +brake, beside the light EU07 and the SN61 alone, which brake with the independent brake. The `*_td_downgrade_w4_signal` +cases (fragment `td_downgrade_w4_signal.scn`, timetable `td_downgrade.txt`) run on a line the fragment adds beside the +tracks of td.scn, at x = -3000: 300 m level, then 3000 m down a gradient of 20 per mille, under an overhead wire fed +by a substation of its own (`gr_pwr`; the wire on the section `pwr01` of td.scn gave the EU07 no voltage). The train +starts on the level at the W4 of Gora, stops at the W4 of Dol 1500 m down the gradient, leaves at 10:38 and stops before +`gr_sem`, a signal at stop 1100 m further down (a memory cell with `SetVelocity 0 0` and the event that reads it, no +model), about 1590 m and 2690 m from the start. The three trains are the light EU07, the SN61 alone and the EU07 with +three coaches. + +`e6actad_genset_td_timetable` (fragment `td_timetable_genset.scn`) is the timetable run of a dual-mode vehicle on its +genset (eu07/maszyna#536): an E6ACTad, the Dragon 2 "last mile" with a 520 kW diesel generator set. The game data has no +genset for it yet, so the case makes its own E6ACTad (`vehicle_variants`, `{{variant_g6}}`): the `.mmd` of `e6actad`, and +as its `.fiz` the `e6acta.fiz.inc` that `e6actad.fiz` includes (`fiz_from`), with `GensetStart=Manual` added to the +`Cntrl.` line and `GensetPower=520 GensetVoltage=3000 GensetIdleRPM=700 GensetMaxRPM=1800 GensetStartTime=8 +GensetSpinUpTime=3 GensetPmaxRatio=0.85` to the `Power:` line. `event0` of the start track gives the standing vehicle, once, +`PutValues` `MainSwitch 0`, `TractionMode 1` (the selector on the genset) and `GensetSwitch 1`, a second apart, as the +vehicle holds one command at a time. The AI knows nothing of the genset: it closes the line breaker once the genset runs +and drives the timetable on it, at most 520 kW x 0.85 = 442 kW at the wheels (`traction_power`). +`e6actad_catenary_td_timetable` is the same variant without the events: it stays on the catenary and takes several +times that, which shows the check tells the two apart. + +### Heavy trains + +The heavy train cases (#187, #199, #263, #265) run on lines of their own beside the tracks of td.scn, at x = -3000, as +the `*_td_downgrade_w4_signal` cases of #479 do: 100 m tracks, an overhead wire fed by a substation of its own (none for +the diesel case) and signals at stop that are a memory cell with `SetVelocity 0 0` and the event that reads it, with no +model. Each train starts on a level stretch long enough for the whole consist, with its head 10 m before the W4 of Gora, +which is where the distances in the checks start from. A freight train leaves a station of its timetable as soon as it +stands there (`IsCargoTrain` in `TController`), so the freight trains leave Gora at once, not at 10:35. The checks that +look for a train that comes to a stand use the vehicle speed (`keeps_moving`), as the wheels of a heavy train starting +on poor rails spin while it stands; `starts_again` checks a start from a signal that clears at a given time, and how far +the train rolls back meanwhile. + +| case | fragment | train | what it shows | +| --- | --- | --- | --- | +| `et41_coal_td_downgrade_restriction` | `td_downgrade_restriction.scn`: 600 m level, 3500 m down 20 per mille, 20 km/h from 1500 to 1900 m down, the signal 3000 m down | ET41, 25 coal wagons 412W with 40 t each, G (about 1670 t) | passes: through the restriction at 10.5 km/h at the lowest, stops at the signal (3078 m) | +| `et22_764_td_downgrade_restriction` | the same | ET22, 20 heavy wagons 764 with 84 t each (about 2650 t) | `xfail`: dips to 8.5 km/h in the 20 km/h restriction (below the 10 km/h #263 counts as a defect); it doesn't stop | +| `st43_steel_td_downgrade12_long` | `td_downgrade12_long.scn`: 900 m level, 6500 m down 12 per mille, no wire, the signal 6000 m down | ST43, 45 coil wagons 425S, G | passes: holds 35-37.5 km/h of the 40 all the way down, never below 20 km/h, stops at the signal | +| `et41_coal_td_upgrade_start` | `td_upgrade_signal_start.scn`: 600 m level, 2500 m up 10 per mille, a signal 1000 m up that clears at 10:42, another 2300 m up | the ET41 with 25 coal wagons | passes: stops at the first signal with the whole train on the gradient, moves off 4.7 s after it clears, 10 km/h after 52 s, rolls back 0.04 m | +| `eu07a_coaches_td_upgrade_long` | `td_upgrade_long.scn`: 600 m level, 5500 m up 10 per mille, the signal 5300 m up | EU07A (303E), 8 coaches (about 360 t), passenger timetable at 80 km/h | passes: 80 km/h at 1430 m, never below 73.8 km/h on the climb | +| `et41_coal_td_slippery_start` | `td_level_signal.scn`: 2100 m level, the signal 1000 m ahead | ET41, 25 coal wagons with 60 t each (about 2170 t), `friction 0.3` | passes with the fix of this branch: gets going and stops at the signal (1082 m, at 392 s); before it, 395 slips in 1500 s and 75 m | + +What the AI still does with heavy trains, without a case that fails on it: + +- On a steep descent into a restriction a heavy G train holds the speed by applying and releasing the train brake in + turn. Its brake takes 10-15 s to release, so it falls well below the limit before the brake lets go: 10.5-12 km/h + for the ET41 with coal wagons, 8.5 km/h for the ET22 with the 764 wagons (the `xfail` above), in a 20 km/h + restriction. #263 reported this train stopping before the restriction in 10 of 12 runs; on staging it no longer + does, also with `friction 0.5` and with the wagons fully loaded. +- Starting uphill, a heavy train pulls against its train brake while the brake releases (#265): in + `et41_coal_td_upgrade_start` about 13 s at about 200 kN with the head moving by the slack of the couplers alone. It + starts at full power, without taking up the slack first. +- The AI doesn't know the adhesion of the rails: it plans braking with `Global.FrictionWeatherFactor` alone, and the + result of its running brake test (`adjust_desired_speed_for_braking_test`) is shown in the debug panel only. It sands + ahead of a slip only at a high motor current, and, since the fix of `et41_coal_td_slippery_start`, through the rest of + a start that has slipped (`control_wheelslip()`); not before a hard brake, nor before the first slip of a start. The `test_mode_*` cases show the ends of the test mode: `test_mode_pass` (exit 0, the pass event), `test_mode_signal_passed_at_danger` (exit 11), `test_mode_timeout` (exit 12, from @@ -220,6 +357,13 @@ standstill of 100 s ends the test although the traffic runs on (counting every v into the test timeout). `test_mode_pass_while_moving` reports the pass from `event2` of `tor1k` (the direction the train runs), as the train runs onto it, with `test.no_movement_before_pass no`, so the test ends with the train still moving. +`test_mode_standing_1m_past_signal` and `test_mode_standing_4m_past_signal` (fragment `td_past_red_signal.scn`) set +the td/rozklad train at a stand with its head 1 m and 4 m past the exit signal at stop (the memory cell of the +signal is 51 m into `tor1k`). The driver finds the signal behind the head at its first look ahead, 13.6 s in, and a +standing train passes nothing, so both run into their timeout. When a signal found up to 5 m behind the head +still counted as one the head had ahead, standing or not, both ended as signals passed at danger at 13.6 s (a +train set 6 m or 20 m past didn't). Starting at 0 km/h the driver doesn't wake up within the case, so they start at +0.1 km/h, as `td_red_signal.scn` does. The `en57_2000_automatic_coupler_*` cases (issue #86) share `td_automatic_coupler_hit.scn`: an EN57-2000 unit without a driver runs at `vars.velocity` km/h into a standing one, from @@ -230,18 +374,274 @@ couple and neither shows up: the black box has to have the last car of the stand writes nothing to the log when couplers catch). Nothing reports a result, so both end on the 60 s test timeout. +`et21_td_no_wire_reports` (issue #421, fragment `td_no_wire.scn`) adds a 200 m track of its own, +with no overhead wire, 400 m off the line of td.scn (every track of td.scn is under the wire), with +an ET21 and its AI driver on it. The pantographs go up and find no wire, so the locomotive can't +start: the driver has to say so in the log, once, naming the locomotive and where it stands, and +not mistake it for a wire without voltage. It ends on the standstill. + +The `eu07_td_off_track_*` cases run with `physics.derailment new`, where a derailed vehicle leaves the track and +moves on the ground by itself (`vehicle/derailmotion.h`); they check what the black box records of it with +`leaves_track`, and the log has a line of each vehicle off the track every second (`derailment: ... off the track`). +`td_off_track.scn` keeps an EU07 with an AI driver standing on track 1 of Stacja1 to log its physics, and has the train +of the case, without a driver, run at `vars.velocity` km/h from `vars.offset` m past point 1 of `vars.track`: +`eu07_td_off_track_buckle_fast` (133 km/h, `tdo_n222` buckled 600 mm over 8 m from the start with the `buckle` +keyword of the track) and `eu07_td_off_track_overturn` (190 km/h, over the overturning speed of the R 600 m curve) +from `tdo_n157`, `eu07_td_off_track_end` off the end of a track of its own (`vars.track_nodes`). +`eu07_td_off_track_buckle` is `td_buckle_event.scn` with an EU07 and three coaches on the timetable, at the 46 km/h +of the AI. The `eu07_td_off_track_curve_*` cases have an EU07 overturn at 150 km/h on a track of R 300 m of their own, +on level ground, on an embankment 4 m high and in a cutting, made of triangle strips in the fragment +(`td_off_track_curve_*.scn`, written by `make_off_track_curves.py`: a curve of R 300 m from (-300, 400) about the +centre (-600, 400), the cross section swept along it every 0.03 rad; the banks of the cutting rise 4 m at 1:1.5, then +on at 1:5). + +`eu07_td_cold_connect` (fragment `td_cold_connect.scn`) has an EU07 with a hand brake +(`4E-ZEZ_GREY`; the plain `4e` has none) standing cold on track 1 of Stacja1 (trainset velocity 0, +so it starts with the hand brake on) and two coaches standing 45 m ahead of it. Its driver sleeps +until `event0` of its track gives it, once, `Shunt -1 3`: start the engine, couple to the consist +ahead (Connect, the first order it drives under), go on shunting. It passes when the first coach, +pushed, runs onto `tor1k` (`eventall2`), with the train still moving, and the black box has the +locomotive coupled to the coaches (it couples about 70 s after the start). A driver that leaves its +hand brake on under Connect pulls against it for good and the case ends as a standstill after 300 s. + +The `eu07_td_buckle_*` cases (fragment `td_buckle_event.scn`) run the timetable train of +`td_timetable.scn` and buckle the curve `tdo_n222`, about 950 m ahead of it, with a `trackbuckle` +event of `vars.amplitude` at 10:35. Both have `physics.derailment new` in `ini`: the default, +`monitor`, leaves the decision to the legacy draw and only logs what the criteria would do +(`derailment monitor: ... overturned at 46 km/h on track tdo_n222`), so the train runs on to +Przystanek whatever the buckle. With 600 mm over a main lobe of 8 m the locomotive overturns on +the buckle at 46 km/h, 1036 m from the start (`Bad driving: ... derailed on buckled track`); with +30 mm it keeps on the rails and stops at Przystanek after 1400 m. + +`sm42_td_uncouple_past_signal` (fragment `td_uncouple_past_signal.scn`) is the uncoupling of the SM42 at Debica on +L053 poranek (step 10 of `deb_sm42_stat`) on td.scn. An SM42 with no timetable stands turned at the far end of `tor1k`, +three wagons loaded with gravel (51 m of train) behind it towards the exit signal `stacja1_j`, which stays at stop (no +route). `tdo_n1734`, the track behind `tor1k`, is closed (`trackvel 0`) from the start. `event0` of `tor1k` gives the +driver `Shunt -1 0`: it pulls the wagons back for 47 m and stops in front of the closed track, with the far end of the +last wagon 2 m past the signal's memory cell (the `distance` check keeps it 0-4 m past). The pull leaves the screw +coupler stretched, 0.019 m apart at the buffers, and a screw coupler is let go only with the buffers pressed together +(under 0.01 m). At the first stand `event0` gives `Shunt 0 0`: brake the wagons, change direction, push the buffers in, +uncouple. After the direction change the driver counts `stacja1_j` as passed at its first move, so its speed is capped +at 0. The driver used to work the brake releaser only while it wanted to speed up, so the locomotive stayed braked by +the wagons' brake application and never closed the gap: no `uncoupled` in the log, and the case ran into its timeout. +Now the locomotive is released, eases into the wagons and uncouples within a second. The wagons are loaded so that the +stop leaves the gap above 0.01 m: with a coach and an empty wagon the buffers came to rest 0.009 m apart and the +coupler let go at once. + +The `*_td_crew_*` cases (eu07/maszyna#510, fragment `td_crew.scn`) are about the crew command of a +`putvalues` event, `Crew: `: cab 1 or -1 puts an AI driver in cab A or B of +the vehicle named, 0 takes its AI driver off. The vehicle is named in the text, so the events are +set off by event launchers, at an hour or with a delay; `vars.trainsets` are the vehicles and +`vars.crew` the events of the case: + +- `eu07_td_crew_add`: an EU07 standing cold with nobody in it gets a driver in cab A 20 s after + the start. A driver put in a standing vehicle waits for orders, as the one of a standing + trainset does, so `event0` of its track gives the order to go (`Shunt -1 0`), once: the driver + starts the locomotive and leaves through the exit signal, whose aspect makes it a train run. + `eu07_td_crew_add_rear` is the same with cab B: the locomotive leaves the other way, its rear + end leading (`moves`, from the black box). +- `eu07_td_crew_remove`: the EU07 of `eu07_td_timetable` loses its driver at 10:36, on the run at + 59 km/h. It is left with the power off and the brake valve in the emergency position: it + stands 16 s and 168 m later and doesn't move in the 164 s to the end (`stops_driverless`; the + physicslog ends when the driver goes). `en57_td_crew_remove` (driven from the head car, the + motors in the middle one), `vectron_td_crew_remove` (induction motors and an integrated handle) + and `sm42_td_crew_remove` (diesel) are the same with other vehicles. +- `eu07_td_crew_swap`: the driver waiting at Stacja1 is taken off after 20 s, which leaves the + locomotive braked, and a new one put in 20 s later, who gets the order to go, releases the + brakes and leaves. +- `golf_td_crew_swap`: a car running along the road `d3` at 50 km/h loses its driver, which + leaves it with its own brake applied in full: it stands 3 s and 17 m later. A road vehicle has + no cab to tell by and takes a driver all the same: the new one, put in 40 s later, drives on + along the road, at up to 100 km/h, having no timetable to cap the speed as the first one had + (the trainset's `50`). +- `eu07_td_crew_refused`: the run of `eu07_td_timetable` with crew events which must be refused, + at the start and again on the run: a second driver for the locomotive, a driver for a coach + (no cab), a cab which is none of 1, -1, 0, a driver taken off a coach which has none, and a + vehicle the scenery lacks. Each leaves its line in the log and the train runs its timetable to + the stop at Przystanek as it does without them. +- `en57_td_crew_parted`: an EN57-2000 unit with an AI driver and no timetable stands on track 1, + another one with nobody in it runs into its rear at 100 km/h (`crashdamage yes`). The hit + breaks the coupler between the middle and the rear car (`parts`, at 2 s), which leaves the rear + car with the driver in charge of it. The driver taken off at 10:35 had all three cars in charge, + the parted one too, and none of them keeps it (the log line `the driver was in charge of 3 + vehicles`; the cars still coupled to the head car are two). + +A vehicle with a user in it is left alone by the command, which the test mode can't show: nobody +sits in a vehicle there. + +`eu07_td_hauls_dead_vectron` is the timetable run with a dead locomotive in the train: behind the EU07 a +Vectron with nobody in it, coupled with the hook and the brake hose alone (the EU07's coupling `3`) and +prepared for hauling, the parameter `H` after its own coupling (`0.H`: the pullee mode of +MaSzyna-EU07/maszyna#64). The checks are those of the timetable cases; the train takes 300 s to +Przystanek and on (20 km/h after 79 s, the stop after 220 s and 1405 m). Without the `H` the Vectron, +which applies the emergency brake while none of its cabs is active, empties the brake pipe of the train +in two seconds, both locomotives stand with their brake cylinders full and the train never moves. +`eu07_td_hauls_dead_vectron_cold` (fragment `td_cold_timetable.scn`) is the same train from a cold start: +trainset velocity 0, so both locomotives stand braked (brake pipe at 3.5 bar, batteries off, the spring +brake of the Vectron switched on), and `event0` of the track gives the driver `Obey_train`, once. The EU07 +starts up, charges the brake pipe and leaves on time (the stop after 209 s and 1393 m); without the `H` +the pipe stays below 1 bar and the case ends as a standstill after 300 s. + +`eu07_td_reinspect_brakes_after_coupling` (fragment `td_reinspect_brakes.scn`, eu07/maszyna#350 and #282) is about the +wagon inspector of the AI (`TController::AutoRewident()`) on a train formed by coupling. An EU07 stands cold on the line +from Stacja1 (`koniec`) and a cut stands 45 m ahead of it, braked, with nobody in it: 16 coaches with P alone (BDhpumn) +and next to the locomotive 8 empty wagons with G and P (401W), 541 m of wagons. `event0` of the locomotive's track gives +the driver `Shunt -3 3`, once: couple to the cut with the coupler and the brake hose and run it on as a train +(`Obey_train`), waiting for the way, which `event2` of `tdo_n231`, in front of the cut, gives as a `SetVelocity 40 40` +(no signal of the line is in sight). Over 500 m of wagons make it a train on G (Cw-1 §19.1), where the brake of a wagon +without G is cut out (§19.9). The inspector looks at the train as the AI couples, at 4 km/h (t=69 s), too fast for it to +cut a brake out, and leaves that for the next standstill: `reinspect_brakes()` cuts the 16 coaches out as the train stands +a moment later, its brakes applied by the empty pipe of the cut. Neither the physicslog nor the black box has the brakes +of the wagons, so the case tells by how the train brakes: `event2` of `tdo_n240` takes the driver off at 38 km/h, which +leaves the brake valve in the emergency position, and braked by the locomotive and the 8 wagons alone the train stops 29 s +and 211 m later, a mean deceleration of 0.27 m/s² (`stops_driverless` with `max_deceleration` 0.40). With every brake +working it stops at 0.57 m/s², 99 m: that is `eu07_td_reinspect_brakes_legacy_inspector`, the same run with the inspector +of the earlier releases (`ai.brakesetting.cw1 no`), which cuts no brake out, and also what a build whose +`reinspect_brakes()` does nothing gives for the first case, which then fails. The test passes 150 s after the driver goes. + +The `*_section*` and `*_converter_interlock*` cases are about the line breaker closed ahead of the pantographs +(`PantRequiresMain=Yes` in `Cntrl.`, MaSzyna-EU07/maszyna#272) and the line contactors that wait for the +converter of their own vehicle (`LineContactorsInterlock=Converter`, #276), driven by the AI on the timetable +run of td.scn. The overhead wire of td.scn is changed with `replace`: one span of it, 61 m some 400 m from +the start (`0.7764 5.845 1561.2417` onwards, over the way out of Stacja1, which the train runs under power at +50-55 km/h), gets no supply and 0 V (`traction none 0`), and in `ep05_td_section_insulator` the span before +it is split around a section insulator 1 m long (`traction * 0`, as sceneries hang insulators). The EP05 has +`PantRequiresMain=Yes` in the game's data; the ET42 has no `LineContactorsInterlock` yet (SVN data of #276), +so those cases run variants of the vehicles made for the run (`vehicle_variants`). + +- `ep05_td_timetable`: the EP05 on the plain timetable run, the reference: 20 km/h after 73 s, the stop + after 205 s and 1400 m. +- `ep05_td_dead_section`: the EP05 runs into the span without voltage under power, nothing on the track + telling its driver to coast. The traction force drops to nothing at once and the AI puts the master + controller to 0; the line breaker stays closed (the log + says the vehicle lost power for 4.05 s, which it says only while the line breaker is closed). Behind the + section the AI takes power again (535 m, 36 kN by 595 m) and stops at Przystanek (1399 m). +- `ep05_td_neutral_section`: the same with the track under that span, `koniec`, marked as one to coast + through (`overhead 0`, which `track_events` adds as it adds events): the AI puts the master controller to + 0 as the locomotive runs onto it, 25 m ahead of the dead wire, and takes power again behind it. +- `eu07_td_dead_section`: the old behaviour for reference, an EU07 (pantographs first) into the same span: + its line breaker opens after 0.2 s (`lost power for 0.21 sec`, no longer), and behind the section the AI + closes it again and takes power (493 m). +- `ep05_td_section_insulator`: the EP05 runs under the insulator under power at 50 km/h. The pantograph is + without voltage for some 0.07 s, which the vehicle bridges by holding the last voltage for 0.2 s + (`TDynamicObject::Update`): the traction force stays between 50 and 58 kN past it and nothing is logged. + Without the hold the undervoltage relay of a `PantRequiresMain` vehicle would open the line contactors, + which close again only with the master controller back at its first position. With the insulator 15 m long + instead (a trial run) the vehicle does lose power there (logged, the force drops to 0), which shows the + pantograph runs under the piece of wire. +- `et42_td_converter_interlock_cold`: an ET42 with `LineContactorsInterlock=Converter` in both sections + stands cold (`td_cold_timetable.scn`) and is ordered to run the timetable: the AI starts the converters, + leaves (20 km/h after 74 s) and stops at Przystanek (1393 m). It and `et42_td_converter_interlock`, the + same from the timetable start, check that the AI gets such a train going; a plain ET42 passes them too. +- `et42_td_converter_interlock_slow_converter`: the check that the interlock takes effect. The same cold ET42 + with a converter that starts 60 s after it is switched on (`ConverterStartDelay=60`): the line contactors + wait for it, and the train reaches 20 km/h at 80.0 s; `starts` with `after: 77` fails it earlier. With the + same converter and no interlock it gets there at 73.8 s, as fast as without the slow converter (a copy of + the case without the key, run once, not kept). +- `ep05_td_interlock_dead_section_cold`: #272 and #276 together, an EP05 with `LineContactorsInterlock=Converter` + added, standing cold, with the span without voltage on its way: the pantographs can go up only through the + closed line breaker, so the AI has to close it first, then start the converter; it leaves (20 km/h after + 77 s). Under the dead wire the converter stops with the main circuit, behind it the converter starts again + and the AI takes power (573 m, 4 s later than the EP05 without the interlock) and stops at Przystanek + (1393 m). + +What these can't reach: the local converter switch of the ET42 (`converterlocal_sw:`), which the AI has to put +back on (`LineContactorsHeldByLocalConverterSwitch()`, the part of #276 in `determine_consist_state()` and +the `converteron` hint), is in the cab only: no command of a scenery or of the train's cables sets +`ConverterAllowLocal`, and nobody sits in a cab in the test mode, so the switch is always on in a case. + +The `eu07_td_switch_*` cases (fragment `td_switch_thrown.scn`, the review of #289, point 2b) throw a switch of +Stacja1 by an event under an EU07 with three coaches and check that the train keeps to the rails (`on_track`) and that +the AI keeps to the route it is really on. Both switches of the station have their points towards the line and the +way to track 2 straight (position 0), to track 1 curved (position 1); the ends of the two ways are 1.9 m apart, the +tracks 4.6 m. `zwr01` at the west end is run through facing by a train running into the station, `zwr02` at the east +end trailing by one leaving it. The throw is an event set off once, by the rear axle of the locomotive running onto a +track (`event1`/`event2` of it, which only the vehicle with the driver sets off) or by a launcher 5 s after the start; +a driver that stands cold gets its order (`vars.order`) from `event0` of its track, after the throw where the train +stands over the switch. On track 1 a signal at stop of the case's own stands at z 1100: the train has to stop before +it (`event0` of `tdo_n1725` passes the test, running onto `tdo_n1734` fails it); on track 2 the exit signal `stacja1_k` +at stop. What they showed on `staging` of 2026-11-22 (f15ea405), where an axle on a switch keeps the way it ran onto +(the segment it took when it got onto the switch) but leaves the switch by the way it is set to now, and the AI does +not scan its route again for a switch that changed behind the head of the train: + +| case | throw | result | +| --- | --- | --- | +| `eu07_td_switch_facing_control` | none, set to track 1 from the start | passes: stops before the signal of track 1 | +| `eu07_td_switch_thrown_facing_head` | `zwr01` to track 1 with the locomotive on the switch | `xfail`: the locomotive jumps sideways at the end of the switch (0.78 m off the track in the black box), the whole train goes to track 1, and the AI, still on the route of track 2, runs past the signal of track 1 at 40 km/h | +| `eu07_td_switch_thrown_facing_behind` | `zwr01` to track 1 with the locomotive just past it | `xfail`: the locomotive runs on along track 2 and the coaches coupled to it along track 1, side by side, for 900 m | +| `eu07_td_switch_thrown_standing_facing` | `zwr01` to track 1 under the standing train, which then leaves facing | `xfail`: the second coach runs with a bogie on each track, its body 2.3 m off both; the AI, which scans from the last vehicle, reads the signals of track 1 while it runs on track 2 (a signal passed at danger, `stacja1_j`) | +| `eu07_td_switch_thrown_standing_trailing` | `zwr02` to track 1 under the standing train, which then leaves trailing | passes: the first wheels coming from track 2 push the switch back (as through any switch set against them from the frog end) | +| `eu07_td_switch_thrown_trailing` | `zwr02` to track 2 under the coaches of the timetable train leaving track 1 | passes: the switch is pushed back, the train stops at Przystanek after 1402 m | + +Nothing derails in any of them with `physics.derailment monitor` (the default; the monitor reported nothing either), +and the three `xfail` cases run with `physics.derailment new` came out the same to the metre: the criteria of +derailment look at the curve, the cant and the speed of a vehicle, not at its bogies being on two tracks. Nor does the +coupler between a locomotive and a coach 4.6 m beside it break. + +### Cases on a mission of a scenery + +The cases made from players' reports (eu07/maszyna#421, #506, #524, #525) run a whole mission +of a scenery of the game, among its own traffic: `strip_trainsets` `false`, `vehicle` the +mission's own locomotive or unit, every train driven by AI as always in the test mode. They are +`slow`, have `physicslog` `false` unless a check needs the black box, and `file.binary.terrain no` +in `ini`, so that no geometry cache of the copied scenery (hundreds of MB for these) is written +into the game dir. What they add to the scenery: + +- nothing, when standing too long is the bug: `test.standstill` is set above the longest wait + the mission has, and the run ends with `duration` (`baltyk_skm1_*`), +- `mission_state_probe.scn`: these sceneries steer each station with a state cell per train + (text and two values, e.g. `deb_tme222158_stat` = `a 6 *`: the route of step 6 is set). The + probe is a loop of two events that looks at the cell `vars.cell` every 5 s and reports the + pass once it holds `vars.state` (a `memcompare`: `* 6 *`, `d * *`), with `vars.reason` as the + text. No fail event: a train that never gets there ends the test with the standstill or the + timeout. A periodic event launcher wouldn't do, the simulator polls those near the camera only, +- events named `:event0`, `:event1`, `:event2` or `:eventall1`...: the simulator binds an + event with such a name to the track by itself, so a fragment can hang events on tracks that + live in the scenery's includes, where `track_events` doesn't reach (`wrzosy_pxe336080_couple.scn`). + The name must not be one the scenery has already: a second event of the same name replaces the first. + +A train whose trainset has velocity 0 has a driver that sleeps in `Wait_for_orders` when nobody +is in the cab: the player would drive it, so the fragment has to give the orders the player's +hands stand for, with `PutValues` from an event the vehicle itself sets off (`event0` of the +track it stands on). The first of them may be the one to couple (`Shunt -2 -3`): a driver whose +first order is `Connect` releases the hand brake a cold locomotive starts with +(`eu07_td_cold_connect`). The mission trains of velocity 0.1 wait for their signal and need nothing. + +The cases and what they showed on master of 2026-11-11 (the two L053 poranek rows also on +staging f15ea405 of 2026-11-23): + +| case | report | result | +| --- | --- | --- | +| `wrzosy_pxe336080_couples` | #524 | passes: ordered to, the locomotive couples to the rake (`couples`, 262 s) and takes it out of the depot (696 s). The scenery itself gives no such order | +| `baltyk_skm1_roj55324_shunting_signal` | #525 | passes, with four seeds: the unit on the siding is let into the platforms 4 minutes after the start, once the shunter beside it has done its first moves, and leaves at 10:42 | +| `baltyk_skm1_roj55321_departure` | #525 | passes, with three seeds: the unit in the platform leaves at 10:34 | +| `l053_poranek_tme222158_debica` | #421 | passes: TME222158 gets the exit signal to Sandomierz (step 6 of `deb_tme222158_stat`) after 4086.2 s. On master of 2026-11-11 the station jammed 4 minutes after the start, the AI of EP07-338'16 passed the shunting signal Tm4 at stop at 29 km/h; #409 fixed that. On staging f15ea405 (2026-11-23) the station's SM42-1096 jammed it next: ordered to uncouple at step 10 of `deb_sm42_stat`, with its cut standing across `debica_k_sem_info` at stop, it stayed braked and never got the coupler off (standstill after 4347 s), until the AI kept the locomotive released while it pushes the buffers in to uncouple (`sm42_td_uncouple_past_signal`) | +| `l053_poranek_tme222158_debica_et21` | #421 | passes after 4131.6 s. On master of 2026-11-11, with an ET21 as in the report, the locomotive stopped for good at Debica Towarowa, on the headshunt 20 m past the end of the overhead wire, and its driver never got out of `Prepare_engine`. Since #409 the ET21 gets through Debica Towarowa (steps 1-5 of `dt_tme222158_stat`) to Debica; there it waited for the SM42 as `l053_poranek_tme222158_debica` did, until the same fix | +| `l053_poludnie_roj32134_debica` | #506 | passes: both trains run and the unit ends at Debica after 6134 s; no train in its way | + +In the L053 sceneries the test mode logs a signal passed at danger for several shunting +locomotives within minutes, so these cases have `test.fail_if_stop_overran no`. + +The simulation ran at 15 times real time on Baltyk and at 5-8 times on L053 (with another +build going on on the machine) with the physicslogs off, and at 3-4 times on Wrzosy with them +on (250 drivers, the road vehicles included: 740 MB of physicslogs in 900 s), after 30-150 s of +loading. + Checks (speeds in km/h, times in seconds of physicslog time, distances in metres). Most use the physicslog Velocity column, which is the wheel speed: it stays at 0 while the wheels are locked in a skid. The ones marked *vehicle speed* use the vehicle speed column at the end of the row instead, logged by builds from this branch on. -- `starts` `min_speed`, `within`: reaches `min_speed` within `within` seconds. +- `starts` `min_speed`, `within` (`after`): reaches `min_speed` within `within` seconds (and not before `after` seconds, + when given). - `max_speed` `limit`, `tolerance`: never goes faster than `limit + tolerance`. - `brakes` `min_pressure`: after moving off, brake cylinder pressure reaches `min_pressure` bar (physicslog pressures are in bar whatever its header says; the brake pipe runs at 5.0). -- `stops` `moving_speed`, `stop_speed`, `hold`, optional `min_distance`, `max_distance`: after - reaching `moving_speed`, stays at or below `stop_speed` for `hold` seconds; with the distances, - that stop has to be between them (metres travelled, as in `distance`). +- `stops` `moving_speed`, `stop_speed`, `hold`, optional `min_distance`, `max_distance`, `max_time`, + `nth`: after reaching `moving_speed`, stays at or below `stop_speed` for `hold` seconds; with the + distances, that stop has to be between them (metres travelled, as in `distance`), with `max_time` + it has to begin by then (seconds of the physicslog). `nth` (default 1) takes a later stop: each + stop after the first counts once the train has reached `moving_speed` again. - `stays_stopped` `moving_speed`, `stop_speed`: after moving off and stopping, never goes above `stop_speed` again. - `distance` `min`, `max`: total distance travelled. The physicslog has no position, so the @@ -255,6 +655,16 @@ the row instead, logged by builds from this branch on. after moving off, moves no more than `max_distance` metres, e.g. no creeping on locked wheels. - `ends_moving` `min_speed`: the last row of the physicslog is at `min_speed` or faster, e.g. the test ended without waiting for the train to stop. +- `traction_power` `max_kw`, optional `min_peak_kw` (*vehicle speed*): the power at the wheels, the + traction force times the vehicle speed, never goes above `max_kw` and, given `min_peak_kw`, reaches + it at least once; e.g. a dual-mode vehicle running on the power of its genset. The traction force + column is in N, whatever the header says. +- `keeps_moving` `moving_speed`, `min_speed`, `until_distance`, optional `from_distance` (*vehicle speed*): once at + `moving_speed`, the speed stays at or above `min_speed` between the two distances (metres travelled, from the vehicle + speed), e.g. a heavy train doesn't come to a stand on a descent before a restriction. Reports the lowest speed. +- `starts_again` `after`, `min_speed`, `within`, optional `max_rollback` (*vehicle speed* for the rollback): standing + at the time `after` (a signal that clears then), the train reaches `min_speed` within `within` seconds, and rolls back + no more than `max_rollback` metres meanwhile. - `log_contains` `pattern`: a line of the run's `log.txt` matches the regex, e.g. the `Bad driving: ... collided` message of a collision. - `log_lacks` `pattern`: no line of the run's `log.txt` matches the regex. @@ -264,10 +674,64 @@ the row instead, logged by builds from this branch on. filled in as in the fragment, e.g. `{{vehicle}}_rb`. Fails when the two were coupled from the start, came apart again, or the run left no black box. The black box is looked at once a second, so the time given is that of the first look after the couplers caught. +- `parts` `vehicle`, `other`, optional `before`: the black box has the two vehicles, coupled to + each other, come apart (the coupler itself let go: broken, or uncoupled), by the time `before` + of the recording when given. +- `driver_changes` `vehicle`, `to`, optional `after`, `before`: the black box has the vehicle get + the driver `to` (`none`, `ai` or `user`) at a time of the recording between the two, having had + another one before, and keep it to the end. +- `stops_driverless` `vehicle`, `min_speed`, `within`, optional `stop_speed` (0.5), `max_creep` + (1 m), `hold` (60 s): the black box has the vehicle lose its driver at `min_speed` or faster, + stand `within` seconds later and stay within `max_creep` of where it stopped for the rest of + the recording, or until it gets a driver again, at least `hold` seconds. The physicslog can't + tell: the driver writes it, so it ends when the driver goes. Optional `min_deceleration`, + `max_deceleration` (m/s²): the mean deceleration of that stop, from the speed the driver left at + and the way to the stop (v²/2s), has to be within them, e.g. a train some of whose brakes are + cut out stops slower. +- `moves` `vehicle`, `min_speed`, optional `direction` (`front`, or `rear`): the black box has the + vehicle reach `min_speed` with that end leading (the physicslog speed has no direction). +- `traction` `from_distance`, `to_distance`, and one or more of `reaches`, `at_most`, `at_least`: the + traction force in kN (the physicslog has it in N, whatever its header says) while the vehicle runs between + the two distances (metres travelled, as in `distance`): its highest there reaches `reaches`, e.g. the power + taken again behind a section without voltage; it stays at or below `at_most`, e.g. none under a dead wire; + it stays at or above `at_least`, e.g. no power lost under an insulator. +- `master_controller` `from_distance`, `to_distance`, `at_most`: the master controller stays at or below the + position between the two distances, e.g. at 0 where the scenery tells the driver to coast. +- `leaves_track` `vehicle`, optional `cause` (`flange climbed`, `overturned`, `end of track`, `pulled off`, + `collision`), `min_offset`, `max_offset`, `min_distance`, `max_distance`, `lying`: with + `physics.derailment new` the black box has the vehicle leave the track and come to rest off it; at rest its + distance from the axis of the track (either side) and the distance it went on the ground are within the + bounds, and it lies on its side, or not, as `lying` says. +- `consist_folds` `vehicles` (the names of the train front to back, comma separated), `min_bend`, optional + `min_folds` (1), `alternate`, `both_sides`: with `physics.derailment new` the train came to rest folded up off + the track: at least `min_folds` of the bends between neighbours at rest (the angle between their headings in the + black box, either way along) are `min_bend` degrees or more; with `alternate` neighbouring bends of that size turn + opposite ways (a zigzag), with `both_sides` some of the vehicles rest on either side of the track. A vehicle that + stayed on the rails has no bend with its neighbours. +- `no_overlap` `max_transient`, `max_at_rest` (a check on the log): with `physics.derailment new` the bodies of the + vehicles off the track and of those near them don't go into each other. The simulator logs every second the most + any two of them overlapped by (`derailment: the bodies overlap by up to ... m (which two, how they are related) + over the last second, ... m now`), and once more when all vehicles off the track are at rest (`, all at rest`); the + most on the way is at most `max_transient` m, the overlap at rest at most `max_at_rest` m. + +- `on_track` `vehicles`, optional `max_offset` (0.75 m), `max_detour` (5 m): every vehicle whose name starts with + `vehicles` (e.g. `{{vehicle}}`, the train of the case) keeps to the rails in the black box, in each of its states: + its middle is within `max_offset` of the line of a track (level distance, the map of the tracks of the black box), + and of two vehicles coupled to each other the way along the tracks from one to the other (through the ends of the + tracks that meet) is no more than `max_detour` longer than the straight line between them. A vehicle with its + bogies on two tracks that part, or thrown sideways, is off the line; a coach running on beside the locomotive it is + coupled to, on the next track, has a way to it hundreds of metres long. A coach on a curve of 300 m, through the + S of a switch, was up to 0.38 m off. The middle of a vehicle is the middle of the chord between its pivots, so on + a curve of radius R a vehicle running right is a^2 / 8R off the track, a being the distance of the pivots: a 19.5 m + coach 0.59 m at R 80, 0.79 m at R 60. The default suits curves down to about R 65 for such a coach; a case with + tighter curves sets more. The black box lists a vehicle once a second, so a jump between two lists shows up only + as it is at the next one. New check types go in `CHECKS` in `run.py`; each gets the physicslog rows and the check's parameters and returns `(passed, detail)`. Checks on the log go in `LOG_CHECKS` and get the text of `log.txt` instead of the rows. Checks on the black box (`blackbox_doc.md` in the root of the repo; the simulator writes it along with the physicslogs) go in `BLACKBOX_CHECKS` and get -what `read_blackbox()` read of it: the names of the vehicles and the coupling records. A check +what `read_blackbox()` read of it: the names of the vehicles, the coupling records, and the +states of each vehicle from the `vehicles` records (position, speed, driver; a vehicle is listed +when it moved, changed speed or got another driver, and all of them every 60 s). A check on another kind of record has to add it there. diff --git a/tests/scenarios/cases/baltyk_skm1_roj55321_departure.json b/tests/scenarios/cases/baltyk_skm1_roj55321_departure.json new file mode 100644 index 000000000..98b9c8119 --- /dev/null +++ b/tests/scenarios/cases/baltyk_skm1_roj55321_departure.json @@ -0,0 +1,18 @@ +{ + "description": "eu07/maszyna#525, Baltyk skm1, the mission that starts in the platform of Baltyk Glowny (EN71-014ra, ROJ55321, departure 10:34): the exit signal has to clear and the unit has to leave. Standing for 10 minutes ends the test as standstill.", + "base_scenery": "baltyk_skm1.scn", + "strip_trainsets": false, + "vehicle": "EN71-014ra", + "slow": true, + "physicslog": false, + "ini": [ + "file.binary.terrain no" + ], + "test_config": [ + "test.standstill 600", + "test.fail_if_stop_overran no" + ], + "duration": 900, + "expect": "timeout", + "timeout": 900 +} diff --git a/tests/scenarios/cases/baltyk_skm1_roj55324_shunting_signal.json b/tests/scenarios/cases/baltyk_skm1_roj55324_shunting_signal.json new file mode 100644 index 000000000..a8fa0e7cc --- /dev/null +++ b/tests/scenarios/cases/baltyk_skm1_roj55324_shunting_signal.json @@ -0,0 +1,18 @@ +{ + "description": "eu07/maszyna#525, Baltyk skm1, the mission that starts on the siding of Baltyk Towarowy next to the shunter (EN90-009A, ROJ55324): the station lets the unit into the platforms once its shunter 6Dg-1244, on the track beside it, has done its first moves (4 minutes after the start), and out to Alakowice at 10:42. A shunter that gets stuck leaves the unit at the shunting signal for good: standing for 15 minutes ends the test as standstill.", + "base_scenery": "baltyk_skm1.scn", + "strip_trainsets": false, + "vehicle": "EN90-009A", + "slow": true, + "physicslog": false, + "ini": [ + "file.binary.terrain no" + ], + "test_config": [ + "test.standstill 900", + "test.fail_if_stop_overran no" + ], + "duration": 1800, + "expect": "timeout", + "timeout": 900 +} diff --git a/tests/scenarios/cases/e6actad_catenary_td_timetable.json b/tests/scenarios/cases/e6actad_catenary_td_timetable.json new file mode 100644 index 000000000..9e8ff5f72 --- /dev/null +++ b/tests/scenarios/cases/e6actad_catenary_td_timetable.json @@ -0,0 +1,25 @@ +{ + "description": "GE#536 stage 1, the twin of e6actad_genset_td_timetable without the switching events: the same E6ACTad variant stays on its catenary position and runs the td/rozklad timetable as the plain E6ACT does, on far more than the genset's 442 kW at the wheels, which shows the traction_power check tells the two apart. The same variant g6 as the genset case.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vehicle_variants": [ + { "name": "g6", "from": "pkp/e6act_v2/e6actad", "fiz_from": "pkp/e6act_v2/e6acta.fiz.inc", "replace": [ + ["InactiveCabFlag=15", "InactiveCabFlag=15 GensetStart=Manual"], + ["PhysicalLayout=3", "PhysicalLayout=3 GensetPower=520 GensetVoltage=3000 GensetIdleRPM=700 GensetMaxRPM=1800 GensetStartTime=8 GensetSpinUpTime=3 GensetPmaxRatio=0.85"] + ] } + ], + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\e6act_v2 e6actad-017 {{variant_g6}} 0 headdriver 0 0 enddynamic" + }, + "ini": ["gfxrenderer null"], + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "log_lacks", "pattern": "Genset of" }, + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "traction_power", "max_kw": 6000, "min_peak_kw": 1000 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/scenarios/cases/e6actad_genset_td_timetable.json b/tests/scenarios/cases/e6actad_genset_td_timetable.json new file mode 100644 index 000000000..92338d49d --- /dev/null +++ b/tests/scenarios/cases/e6actad_genset_td_timetable.json @@ -0,0 +1,28 @@ +{ + "description": "GE#536 stage 1: an E6ACTad (Dragon 2 last mile) on the td/rozklad timetable of td.scn, switched to its genset by the scenery before it leaves: PutValues MainSwitch 0, TractionMode 1, GensetSwitch 1 from event0 of its track, 1 s apart. The AI, which knows nothing of the genset, closes the line breaker once the genset runs and drives to Przystanek on at most 442 kW at the wheels (520 kW x 0.85). Makes its own E6ACTad for the run (vehicle_variants g6: e6acta.fiz.inc with the genset keys, the .mmd of e6actad).", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable_genset.scn", + "vehicle_variants": [ + { "name": "g6", "from": "pkp/e6act_v2/e6actad", "fiz_from": "pkp/e6act_v2/e6acta.fiz.inc", "replace": [ + ["InactiveCabFlag=15", "InactiveCabFlag=15 GensetStart=Manual"], + ["PhysicalLayout=3", "PhysicalLayout=3 GensetPower=520 GensetVoltage=3000 GensetIdleRPM=700 GensetMaxRPM=1800 GensetStartTime=8 GensetSpinUpTime=3 GensetPmaxRatio=0.85"] + ] } + ], + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\e6act_v2 e6actad-017 {{variant_g6}} 0 headdriver 0 0 enddynamic" + }, + "ini": ["gfxrenderer null"], + "track_events": { + "tdo_n1734": "event0 autotest_genset" + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Genset of autotest_e6actad_genset_td_timetable: running" }, + { "type": "starts", "min_speed": 20, "within": 180 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "traction_power", "max_kw": 451, "min_peak_kw": 380 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/scenarios/cases/en57_2000_crush_new.json b/tests/scenarios/cases/en57_2000_crush_new.json new file mode 100644 index 000000000..9de8c1688 --- /dev/null +++ b/tests/scenarios/cases/en57_2000_crush_new.json @@ -0,0 +1,17 @@ +{ + "description": "G14 stage 2: an EN57-2000 unit without a driver runs at 20 km/h into a standing one on td.scn, with physics.collisions new. Too fast for the automatic couplers to catch: past the buffers the cab ends crush, a few decimetres, too little for either unit to climb onto the other, so both stay on the rails; the run ends on the 60 s test timeout.", + "base_scenery": "td.scn", + "ini": ["crashdamage yes", "physics.collisions new"], + "fragment": "td_automatic_coupler_hit.scn", + "vars": { + "velocity": "20", + "offset": "0" + }, + "expect": "timeout", + "duration": 60, + "timeout": 300, + "checks": [ + { "type": "log_contains", "pattern": "Bad driving: autotest_\\S+ and autotest_\\S+ collided at \\d+ km/h, the \\w+ end of autotest_\\S+ crushed" }, + { "type": "log_lacks", "pattern": "Bad driving: autotest_\\S+ derailed" } + ] +} diff --git a/tests/scenarios/cases/en57_td_crew_parted.json b/tests/scenarios/cases/en57_td_crew_parted.json new file mode 100644 index 000000000..f75a99179 --- /dev/null +++ b/tests/scenarios/cases/en57_td_crew_parted.json @@ -0,0 +1,34 @@ +{ + "description": "Crew event on a train parted by a broken coupler (eu07/maszyna#510, review of #422): an EN57-2000 unit with an AI driver and no timetable stands on track 1 of Stacja1 on td.scn, and another one with nobody in it runs into its rear at 100 km/h. The hit breaks the coupler between the middle and the rear car of the standing unit (TMoverParameters::damage_coupler()), which parts the unit and leaves the rear car with the driver in charge of it, as uncoupling doesn't. At 10:35 a putvalues event, Crew: 0 0, takes the driver off: all three vehicles of the unit had it in charge, the parted ones too, and none of them keeps it.", + "base_scenery": "td.scn", + "ini": ["crashdamage yes"], + "time": "10:34", + "fragment": "td_crew.scn", + "vars": { + "trainsets": [ + "trainset none tdo_n1734 0.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp\\en57-2000_v1 en57-2040_ra 6ba 0 headdriver 255 0 enddynamic", + "node -1 0 {{vehicle}}_s dynamic pkp\\en57-2000_v1 en57-2040_s 6bs 0 nobody 255 0 enddynamic", + "node -1 0 {{vehicle}}_rb dynamic pkp\\en57-2000_v1 en57-2040_rb 6bb 0 nobody 0 0 enddynamic", + "endtrainset", + "trainset none tdo_n1725 0.0 100", + "node -1 0 {{vehicle}}_hit_ra dynamic pkp\\en57-2000_v1 en57-2040_ra 6ba 0 nobody 255 0 enddynamic", + "node -1 0 {{vehicle}}_hit_s dynamic pkp\\en57-2000_v1 en57-2040_s 6bs 0 nobody 255 0 enddynamic", + "node -1 0 {{vehicle}}_hit_rb dynamic pkp\\en57-2000_v1 en57-2040_rb 6bb 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "crew": [ + "event autotest_crew_off putvalues 0 none 0 0 0 Crew:{{vehicle}} 0 0 endevent", + "node -1 0 autotest_crew_off_launcher eventlauncher 0 0 0 -1 none 1035 autotest_crew_off end" + ] + }, + "duration": 120, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Bad driving: autotest_\\S+ broke a coupler" }, + { "type": "parts", "vehicle": "{{vehicle}}_s", "other": "{{vehicle}}_rb", "before": 30 }, + { "type": "log_contains", "pattern": "Crew: \\[autotest_en57_td_crew_parted\\] the AI driver leaves" }, + { "type": "log_contains", "pattern": "Crew: \\[autotest_en57_td_crew_parted\\] the driver was in charge of 3 vehicles" }, + { "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "none", "after": 50, "before": 70 } + ] +} diff --git a/tests/scenarios/cases/en57_td_crew_remove.json b/tests/scenarios/cases/en57_td_crew_remove.json new file mode 100644 index 000000000..4ca053a47 --- /dev/null +++ b/tests/scenarios/cases/en57_td_crew_remove.json @@ -0,0 +1,29 @@ +{ + "description": "Crew event, the driver disappears (eu07/maszyna#510): as eu07_td_crew_remove, with an EN57 unit of three cars, driven from its head car while the motors are in the middle one, which loses its AI driver on the run at 10:36, stops and stays where it stopped.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_crew.scn", + "vars": { + "trainsets": [ + "trainset td/rozklad tdo_n1734 0.0 0.1", + "node -1 0 {{vehicle}} dynamic pkp\\en57_v2 EN57-1000ra EN57RA_GSO_WKM1_KM_NS_N 0 headdriver 255 0 enddynamic", + "node -1 0 {{vehicle}}_s dynamic pkp\\en57_v2 EN57-1000s EN57S_WKM1_KM_NS_S 0 nobody 255 0 enddynamic", + "node -1 0 {{vehicle}}_rb dynamic pkp\\en57_v2 EN57-1000rb EN57RB_GSO_WKM1_KM_NS 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "crew": [ + "event autotest_crew_off putvalues 0 none 0 0 0 Crew:{{vehicle}} 0 0 endevent", + "node -1 0 autotest_crew_off_launcher eventlauncher 0 0 0 -1 none 1036 autotest_crew_off end" + ] + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "log_contains", "pattern": "Crew: \\[autotest_en57_td_crew_remove\\] the AI driver leaves" }, + { "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "none", "after": 115, "before": 130 }, + { "type": "stops_driverless", "vehicle": "{{vehicle}}", "min_speed": 20, "within": 60, "hold": 100 }, + { "type": "log_lacks", "pattern": "derailed" }, + { "type": "log_lacks", "pattern": "collided" } + ] +} diff --git a/tests/scenarios/cases/ep05_td_dead_section.json b/tests/scenarios/cases/ep05_td_dead_section.json new file mode 100644 index 000000000..d6bfe2c49 --- /dev/null +++ b/tests/scenarios/cases/ep05_td_dead_section.json @@ -0,0 +1,22 @@ +{ + "description": "#272: an EP05 (PantRequiresMain=Yes: its line breaker closes ahead of the pantographs and holds without voltage) runs the td/rozklad timetable of td.scn with one span of the overhead wire on its way, 61 m some 400 m from the start, left without voltage, and nothing on the track to tell the driver to coast. The AI runs into it under power: the line breaker stays closed (the log keeps saying the vehicle lost power, which it says only while the line breaker is closed), the traction force drops to nothing and the AI puts the master controller to 0; behind the section the AI takes power again and stops at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/ep05_v2 ep05-23 ep05 0 headdriver 0 0 enddynamic" + }, + "replace": [ + ["node -1 0 none traction pwr01 3500 4500 0.01 cu 3.0 1\r\n0.7764 5.845 1561.2417", "node -1 0 none traction none 0 4500 0.01 cu 3.0 1\r\n0.7764 5.845 1561.2417"] + ], + "duration": 240, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "traction", "from_distance": 420, "to_distance": 455, "at_most": 1}, + {"type": "traction", "from_distance": 460, "to_distance": 620, "reaches": 25}, + {"type": "log_contains", "pattern": "lost power for [3-9]\\.\\d\\d sec"}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/ep05_td_interlock_dead_section_cold.json b/tests/scenarios/cases/ep05_td_interlock_dead_section_cold.json new file mode 100644 index 000000000..4cccc94f5 --- /dev/null +++ b/tests/scenarios/cases/ep05_td_interlock_dead_section_cold.json @@ -0,0 +1,28 @@ +{ + "description": "#272 with #276: an EP05 whose line breaker closes ahead of the pantographs (PantRequiresMain=Yes) and whose line contactors close only with its own converter running (LineContactorsInterlock=Converter, a variant of the .fiz made for the run) stands cold on track 1 of Stacja1 and gets the order to run the td/rozklad timetable, with the span without voltage of ep05_td_dead_section on its way. The pantographs go up only through the closed line breaker, so the AI has to close it first, then start the converter, and leave; under the dead wire the main circuit, and with it the converter, has no voltage; behind it the AI takes power again and stops at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_cold_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/ep05_v2 ep05-23 {{variant_ep05}} 0 headdriver 0 0 enddynamic" + }, + "vehicle_variants": [ + {"name": "ep05", "from": "pkp/ep05_v2/ep05", "replace": [["Camshaft=Yes PantRequiresMain=Yes", "Camshaft=Yes PantRequiresMain=Yes LineContactorsInterlock=Converter"]]} + ], + "replace": [ + ["node -1 0 none traction pwr01 3500 4500 0.01 cu 3.0 1\r\n0.7764 5.845 1561.2417", "node -1 0 none traction none 0 4500 0.01 cu 3.0 1\r\n0.7764 5.845 1561.2417"] + ], + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "duration": 300, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "traction", "from_distance": 420, "to_distance": 455, "at_most": 1}, + {"type": "traction", "from_distance": 460, "to_distance": 620, "reaches": 25}, + {"type": "log_contains", "pattern": "lost power for [3-9]\\.\\d\\d sec"}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/ep05_td_neutral_section.json b/tests/scenarios/cases/ep05_td_neutral_section.json new file mode 100644 index 000000000..ea261b0b7 --- /dev/null +++ b/tests/scenarios/cases/ep05_td_neutral_section.json @@ -0,0 +1,26 @@ +{ + "description": "#272: as ep05_td_dead_section, with the track under the span without voltage (koniec, 371-466 m) marked as a section to coast through (overhead 0), as a scenery marks a neutral section: the AI puts the master controller to zero when the locomotive runs onto that track, coasts under the dead wire with the line breaker closed, and takes power again behind it.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/ep05_v2 ep05-23 ep05 0 headdriver 0 0 enddynamic" + }, + "replace": [ + ["node -1 0 none traction pwr01 3500 4500 0.01 cu 3.0 1\r\n0.7764 5.845 1561.2417", "node -1 0 none traction none 0 4500 0.01 cu 3.0 1\r\n0.7764 5.845 1561.2417"] + ], + "track_events": { + "koniec": "overhead 0" + }, + "duration": 240, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "master_controller", "from_distance": 395, "to_distance": 455, "at_most": 0}, + {"type": "traction", "from_distance": 415, "to_distance": 455, "at_most": 1}, + {"type": "traction", "from_distance": 470, "to_distance": 640, "reaches": 25}, + {"type": "log_contains", "pattern": "lost power for [3-9]\\.\\d\\d sec"}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/ep05_td_section_insulator.json b/tests/scenarios/cases/ep05_td_section_insulator.json new file mode 100644 index 000000000..2490bcf9b --- /dev/null +++ b/tests/scenarios/cases/ep05_td_section_insulator.json @@ -0,0 +1,21 @@ +{ + "description": "#272: the EP05 of ep05_td_timetable runs under power under a section insulator: a piece of the overhead wire 1 m long with no supply (\"*\", 0 V), some 375 m from the start. The pantograph is without voltage for a few hundredths of a second, which the vehicle bridges by holding the last voltage for 0.2 s (TDynamicObject::Update). Without the hold the undervoltage relay would open the line contactors, which on a PantRequiresMain vehicle close again only with the master controller back at its first position: the traction force stays up all the way past the insulator.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/ep05_v2 ep05-23 ep05 0 headdriver 0 0 enddynamic" + }, + "replace": [ + ["node -1 0 none traction pwr01 3500 4500 0.01 cu 3.0 1\r\n0.687223 5.8 1500.25\r\n0.7764 5.845 1561.2417\r\n0.687223 7.5 1500.25\r\n0.7764 7.545 1561.2417\r\n0.4 4.0 3 0.04 vis\r\nendtraction", "node -1 0 none traction pwr01 3500 4500 0.01 cu 3.0 1\r\n0.687223 5.8 1500.25\r\n0.7457 5.8295 1540.2499\r\n0.687223 7.5 1500.25\r\n0.7457 7.5295 1540.2499\r\n0.4 4.0 3 0.04 vis\r\nendtraction\r\nnode -1 0 none traction * 0 4500 0.01 cu 3.0 1\r\n0.7457 5.8295 1540.2499\r\n0.7472 5.8302 1541.2499\r\n0.7457 7.5295 1540.2499\r\n0.7472 7.5302 1541.2499\r\n0.4 4.0 3 0.04 vis\r\nendtraction\r\nnode -1 0 none traction pwr01 3500 4500 0.01 cu 3.0 1\r\n0.7472 5.8302 1541.2499\r\n0.7764 5.845 1561.2417\r\n0.7472 7.5302 1541.2499\r\n0.7764 7.545 1561.2417\r\n0.4 4.0 3 0.04 vis\r\nendtraction"] + ], + "duration": 240, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "traction", "from_distance": 345, "to_distance": 395, "at_least": 30}, + {"type": "log_lacks", "pattern": "lost power"}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/ep05_td_timetable.json b/tests/scenarios/cases/ep05_td_timetable.json new file mode 100644 index 000000000..4291cdb72 --- /dev/null +++ b/tests/scenarios/cases/ep05_td_timetable.json @@ -0,0 +1,17 @@ +{ + "description": "EP05 (PantRequiresMain=Yes) on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek. The reference run of the ep05_td_*_section cases, with the overhead wire live all the way.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/ep05_v2 ep05-23 ep05 0 headdriver 0 0 enddynamic" + }, + "duration": 240, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "brakes", "min_pressure": 0.5}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/et21_td_no_wire_reports.json b/tests/scenarios/cases/et21_td_no_wire_reports.json new file mode 100644 index 000000000..3aeaeecde --- /dev/null +++ b/tests/scenarios/cases/et21_td_no_wire_reports.json @@ -0,0 +1,27 @@ +{ + "description": "ET21 with an AI driver on a track of td.scn's own with no overhead wire: it raises the pantographs, finds no wire and can't start; the driver tells of it in the log, once, and keeps waiting for the voltage (eu07/maszyna#421). The test ends on the standstill.", + "base_scenery": "td.scn", + "fragment": "td_no_wire.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\et21_v2 ET21-367 3e2 0 headdriver 0 0 enddynamic" + }, + "test_config": [ + "test.standstill 300" + ], + "expect": "standstill", + "timeout": 900, + "checks": [ + { + "type": "log_contains", + "pattern": "AI \\[autotest_et21_td_no_wire_reports\\]: can't start, no overhead wire above its raised pantographs \\(at -?[\\d.]+, -?[\\d.]+, -?[\\d.]+\\)" + }, + { + "type": "log_lacks", + "pattern": "no voltage in the overhead wire at its raised pantographs" + }, + { + "type": "distance", + "max": 1 + } + ] +} diff --git a/tests/scenarios/cases/et22_764_td_downgrade_restriction.json b/tests/scenarios/cases/et22_764_td_downgrade_restriction.json new file mode 100644 index 000000000..b53a23411 --- /dev/null +++ b/tests/scenarios/cases/et22_764_td_downgrade_restriction.json @@ -0,0 +1,62 @@ +{ + "description": "An ET22 with 20 loaded heavy wagons 764 (Uaai, 84 t of machinery each, KE, G; about 2650 t) on the line of et41_coal_td_downgrade_restriction: down 20 per mille into a 20 km/h restriction 400 m long, then to the signal at stop. The train is to keep above 10 km/h through the restriction (#187: it almost stops).", + "xfail": "#187, #263: down 20 per mille the AI holds the 20 km/h restriction by applying and releasing the train brake in turn (handle 0, then 1.25-2.75, then 0 again); the release of this G train takes 10-15 s, so each one comes late and the train dips to 8.5 km/h, below the 10 km/h #263 counts as a defect. It doesn't stop. Known limitation of the AI, not fixed here", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_downgrade_restriction.scn", + "timetable": "td_freight_downgrade.txt", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\et22_v3 201E-1150 201E 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_w01 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w02 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w03 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w04 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w05 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w06 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w07 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w08 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w09 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w10 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w11 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w12 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w13 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w14 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w15 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w16 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w17 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w18 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w19 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w20 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic" + ] + }, + "expect": "standstill", + "duration": 1200, + "timeout": 1500, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 300 + }, + { + "type": "max_speed", + "limit": 60, + "tolerance": 5 + }, + { + "type": "keeps_moving", + "moving_speed": 20, + "min_speed": 10, + "until_distance": 2450 + }, + { + "type": "stops", + "moving_speed": 15, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 2950, + "max_distance": 3110 + } + ] +} diff --git a/tests/scenarios/cases/et41_coal_td_downgrade_restriction.json b/tests/scenarios/cases/et41_coal_td_downgrade_restriction.json new file mode 100644 index 000000000..966c6b0a8 --- /dev/null +++ b/tests/scenarios/cases/et41_coal_td_downgrade_restriction.json @@ -0,0 +1,67 @@ +{ + "description": "An ET41 with 25 loaded coal wagons (412W, 60 t each, cast-iron blocks, G; about 1670 t) on a line of its own beside td.scn: from the level down a gradient of 20 per mille at the 60 km/h of its timetable, into a 20 km/h restriction 400 m long 1500 m down the gradient, then to the signal at stop 3000 m down. The train is to pass through the restriction without coming to a stand, and stop at the signal (#263, #187).", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_downgrade_restriction.scn", + "timetable": "td_freight_downgrade.txt", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\et41_v2 41-045-a 203e-a 0 headdriver 55 0 enddynamic", + "node -1 0 {{vehicle}}_b dynamic pkp\\et41_v2 41-045-b 203e-b 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w01 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w02 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w03 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w04 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w05 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w06 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w07 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w08 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w09 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w10 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w11 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w12 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w13 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w14 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w15 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w16 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w17 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w18 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w19 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w20 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w21 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w22 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w23 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w24 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w25 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic" + ] + }, + "expect": "standstill", + "duration": 1200, + "timeout": 1500, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 300 + }, + { + "type": "max_speed", + "limit": 60, + "tolerance": 5 + }, + { + "type": "keeps_moving", + "moving_speed": 20, + "min_speed": 10, + "until_distance": 2400 + }, + { + "type": "stops", + "moving_speed": 15, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 2950, + "max_distance": 3110 + } + ] +} diff --git a/tests/scenarios/cases/et41_coal_td_slippery_start.json b/tests/scenarios/cases/et41_coal_td_slippery_start.json new file mode 100644 index 000000000..34696d422 --- /dev/null +++ b/tests/scenarios/cases/et41_coal_td_slippery_start.json @@ -0,0 +1,66 @@ +{ + "description": "An ET41 with 25 fully loaded coal wagons (412W, 80 t each, G; about 2170 t) starts on level track with the rail friction at 0.3 of its normal (eu07.ini friction 0.3, as on wet leaves), and runs to the signal at stop 1000 m ahead. The train is to get going, keep moving and stop at the signal (#187: heavy trains slip, grip and snatch over and over and often don't get going).", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_level_signal.scn", + "timetable": "td_freight_downgrade.txt", + "ini": [ + "friction 0.3" + ], + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\et41_v2 41-045-a 203e-a 0 headdriver 55 0 enddynamic", + "node -1 0 {{vehicle}}_b dynamic pkp\\et41_v2 41-045-b 203e-b 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w01 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w02 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w03 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w04 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w05 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w06 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w07 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w08 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w09 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w10 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w11 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w12 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w13 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w14 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w15 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w16 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w17 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w18 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w19 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w20 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w21 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w22 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w23 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w24 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w25 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic" + ] + }, + "expect": "standstill", + "duration": 1500, + "timeout": 1800, + "checks": [ + { + "type": "moves", + "vehicle": "{{vehicle}}", + "min_speed": 10 + }, + { + "type": "keeps_moving", + "moving_speed": 5, + "min_speed": 3, + "from_distance": 100, + "until_distance": 900 + }, + { + "type": "stops", + "moving_speed": 10, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 1040, + "max_distance": 1150 + } + ] +} diff --git a/tests/scenarios/cases/et41_coal_td_upgrade_start.json b/tests/scenarios/cases/et41_coal_td_upgrade_start.json new file mode 100644 index 000000000..05d005919 --- /dev/null +++ b/tests/scenarios/cases/et41_coal_td_upgrade_start.json @@ -0,0 +1,73 @@ +{ + "description": "An ET41 with 25 loaded coal wagons (412W, 60 t each, G; about 1670 t) on a line of its own beside td.scn: up a gradient of 10 per mille to the signal hu_sem1 1000 m up, at stop until 10:42, where it stops with the whole train on the gradient; when the signal clears, it is to start without rolling back and get away, to the signal at stop 2300 m up (#265, #187).", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_upgrade_signal_start.scn", + "timetable": "td_freight_downgrade.txt", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\et41_v2 41-045-a 203e-a 0 headdriver 55 0 enddynamic", + "node -1 0 {{vehicle}}_b dynamic pkp\\et41_v2 41-045-b 203e-b 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w01 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w02 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w03 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w04 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w05 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w06 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w07 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w08 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w09 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w10 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w11 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w12 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w13 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w14 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w15 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w16 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w17 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w18 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w19 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w20 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w21 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w22 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w23 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w24 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w25 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic" + ] + }, + "expect": "standstill", + "duration": 1500, + "timeout": 1800, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 300 + }, + { + "type": "max_speed", + "limit": 60, + "tolerance": 5 + }, + { + "type": "stops", + "moving_speed": 15, + "stop_speed": 1.0, + "hold": 60, + "min_distance": 1040, + "max_distance": 1110 + }, + { + "type": "starts_again", + "after": 480, + "min_speed": 10, + "within": 120, + "max_rollback": 1.0 + }, + { + "type": "distance", + "min": 2340, + "max": 2410 + } + ] +} diff --git a/tests/scenarios/cases/et42_td_converter_interlock.json b/tests/scenarios/cases/et42_td_converter_interlock.json new file mode 100644 index 000000000..35d78a4f4 --- /dev/null +++ b/tests/scenarios/cases/et42_td_converter_interlock.json @@ -0,0 +1,24 @@ +{ + "description": "#276: as et42_td_converter_interlock_cold, from the timetable start (trainset velocity 0.1, the locomotive ready to go).", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp/et42_v2 112e-014-a {{variant_a}} 0 headdriver 255 0 enddynamic", + "node -1 0 {{vehicle}}_b dynamic pkp/et42_v2 112e-014-b {{variant_b}} 0 nobody 3 0 enddynamic" + ] + }, + "vehicle_variants": [ + {"name": "a", "from": "pkp/et42_v2/112e-a", "replace": [["IniCDelay=0.5 SCDelay=0.1", "IniCDelay=0.5 SCDelay=0.1 LineContactorsInterlock=Converter"]]}, + {"name": "b", "from": "pkp/et42_v2/112e-b", "replace": [["IniCDelay=0.5 SCDelay=0.1", "IniCDelay=0.5 SCDelay=0.1 LineContactorsInterlock=Converter"]]} + ], + "duration": 240, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "brakes", "min_pressure": 0.5}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/et42_td_converter_interlock_cold.json b/tests/scenarios/cases/et42_td_converter_interlock_cold.json new file mode 100644 index 000000000..f8dfdff56 --- /dev/null +++ b/tests/scenarios/cases/et42_td_converter_interlock_cold.json @@ -0,0 +1,27 @@ +{ + "description": "#276: an ET42 whose sections take power only with their own converter running (LineContactorsInterlock=Converter in Cntrl., the .fiz key the shipped et42_v2 doesn't have yet: a variant of both sections made for the run) stands cold on track 1 of Stacja1 on td.scn and gets the order to run the td/rozklad timetable. The AI has to start the converters before the line contactors close: it leaves, keeps to the speed limit and stops at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_cold_timetable.scn", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp/et42_v2 112e-014-a {{variant_a}} 0 headdriver 255 0 enddynamic", + "node -1 0 {{vehicle}}_b dynamic pkp/et42_v2 112e-014-b {{variant_b}} 0 nobody 3 0 enddynamic" + ] + }, + "vehicle_variants": [ + {"name": "a", "from": "pkp/et42_v2/112e-a", "replace": [["IniCDelay=0.5 SCDelay=0.1", "IniCDelay=0.5 SCDelay=0.1 LineContactorsInterlock=Converter"]]}, + {"name": "b", "from": "pkp/et42_v2/112e-b", "replace": [["IniCDelay=0.5 SCDelay=0.1", "IniCDelay=0.5 SCDelay=0.1 LineContactorsInterlock=Converter"]]} + ], + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "duration": 300, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "brakes", "min_pressure": 0.5}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/et42_td_converter_interlock_slow_converter.json b/tests/scenarios/cases/et42_td_converter_interlock_slow_converter.json new file mode 100644 index 000000000..d492aa671 --- /dev/null +++ b/tests/scenarios/cases/et42_td_converter_interlock_slow_converter.json @@ -0,0 +1,27 @@ +{ + "description": "#276, the check that the interlock takes effect: the ET42 of et42_td_converter_interlock_cold, with ConverterStartDelay=60 added to both sections, so the converters need a minute to start. With LineContactorsInterlock=Converter the line contactors wait for them and the train leaves later than it does with the same converter delay and no interlock (20 km/h at 80.0 s with it, at 73.8 s without it, measured with this case and a copy without the interlock key). Then it runs the timetable to Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_cold_timetable.scn", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp/et42_v2 112e-014-a {{variant_a}} 0 headdriver 255 0 enddynamic", + "node -1 0 {{vehicle}}_b dynamic pkp/et42_v2 112e-014-b {{variant_b}} 0 nobody 3 0 enddynamic" + ] + }, + "vehicle_variants": [ + {"name": "a", "from": "pkp/et42_v2/112e-a", "replace": [["IniCDelay=0.5 SCDelay=0.1", "IniCDelay=0.5 SCDelay=0.1 LineContactorsInterlock=Converter ConverterStartDelay=60"]]}, + {"name": "b", "from": "pkp/et42_v2/112e-b", "replace": [["IniCDelay=0.5 SCDelay=0.1", "IniCDelay=0.5 SCDelay=0.1 LineContactorsInterlock=Converter ConverterStartDelay=60"]]} + ], + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "duration": 300, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "after": 77, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "brakes", "min_pressure": 0.5}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/eu07_coaches_td_downgrade_w4_signal.json b/tests/scenarios/cases/eu07_coaches_td_downgrade_w4_signal.json new file mode 100644 index 000000000..1faae73ff --- /dev/null +++ b/tests/scenarios/cases/eu07_coaches_td_downgrade_w4_signal.json @@ -0,0 +1,42 @@ +{ + "description": "An EU07 with three coaches on the line of eu07_td_downgrade_w4_signal, down a gradient of 20 per mille: stops at the W4 of Dol, then before the signal at stop. A train braking with the train brake, the control of the light EU07 and SN61 cases.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_downgrade_w4_signal.scn", + "timetable": "td_downgrade.txt", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic" + ] + }, + "duration": 540, + "timeout": 900, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 150 + }, + { + "type": "max_speed", + "limit": 80, + "tolerance": 3 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 1500, + "max_distance": 1700 + }, + { + "type": "distance", + "min": 2550, + "max": 2750 + } + ] +} diff --git a/tests/scenarios/cases/eu07_coaches_td_timetable.json b/tests/scenarios/cases/eu07_coaches_td_timetable.json new file mode 100644 index 000000000..c8621c3b0 --- /dev/null +++ b/tests/scenarios/cases/eu07_coaches_td_timetable.json @@ -0,0 +1,40 @@ +{ + "description": "EU07 with three coaches on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek with the train brake.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic" + ] + }, + "duration": 360, + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 150 + }, + { + "type": "max_speed", + "limit": 90, + "tolerance": 3 + }, + { + "type": "brakes", + "min_pressure": 0.5 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 0, + "min_distance": 1380, + "max_distance": 1420 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_buckle_derails.json b/tests/scenarios/cases/eu07_td_buckle_derails.json new file mode 100644 index 000000000..8506736a5 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_buckle_derails.json @@ -0,0 +1,19 @@ +{ + "description": "EU07 on td.scn on the td/rozklad timetable; at 10:35, as it leaves, the curve tdo_n222 about 950 m ahead buckles hard with a trackbuckle event: 600 mm out of the curve over a main lobe of 8 m (an equivalent radius of 9 m, about 30 m for the body on axles 11 m apart). The AI doesn't see it and runs into it at the 46 km/h it has there: with physics.derailment new (the default, monitor, only logs what the criteria would do and the train runs on) the locomotive leaves the rails on the buckle and stops short of Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_buckle_event.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic", + "amplitude": "600 8" + }, + "ini": ["gfxrenderer null", "physics.derailment new"], + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Track \"tdo_n222\" buckled \\(event autotest_buckle\\): 600 mm to the (left|right) at [0-9.]+ m, main lobe 8.0 m" }, + { "type": "log_contains", "pattern": "Bad driving: autotest_\\S+ derailed on buckled track" }, + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "distance", "max": 1100 } + ] +} diff --git a/tests/scenarios/cases/eu07_td_buckle_event.json b/tests/scenarios/cases/eu07_td_buckle_event.json new file mode 100644 index 000000000..13e0da7bc --- /dev/null +++ b/tests/scenarios/cases/eu07_td_buckle_event.json @@ -0,0 +1,19 @@ +{ + "description": "EU07 on td.scn on the td/rozklad timetable; at 10:35, as it leaves, the curve tdo_n222 about 950 m ahead buckles with a trackbuckle event (30 mm out of the curve, as the heat does: an equivalent radius of 330 m, too little to derail it). The track is laid again during the game and the train keeps on it to Przystanek, with physics.derailment new: the criteria decide, as in eu07_td_buckle_derails.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_buckle_event.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic", + "amplitude": "30" + }, + "ini": ["gfxrenderer null", "physics.derailment new"], + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Track \"tdo_n222\" buckled \\(event autotest_buckle\\): 30 mm to the (left|right)" }, + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 }, + { "type": "log_lacks", "pattern": "Bad driving" } + ] +} diff --git a/tests/scenarios/cases/eu07_td_cold_connect.json b/tests/scenarios/cases/eu07_td_cold_connect.json new file mode 100644 index 000000000..26c975861 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_cold_connect.json @@ -0,0 +1,28 @@ +{ + "description": "EU07 with a hand brake (4E-ZEZ_GREY) on td.scn, standing cold with the hand brake on, gets the order to couple to the two coaches standing 45 m ahead (Shunt -1 3): after starting the engine it has to release its hand brake, run up to the coaches, couple and push them on. Connect is the first order the AI drives under.", + "base_scenery": "td.scn", + "fragment": "td_cold_connect.scn", + "vars": { + "locomotive": "pkp\\4e_v1 4E-ZEZ-234 4E-ZEZ_GREY", + "rake": [ + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 0 0 enddynamic" + ] + }, + "track_events": { + "tdo_n1725": "event0 autotest_wake", + "tor1k": "eventall2 autotest_pass" + }, + "test_config": [ + "test.timeout 900", + "test.standstill 300", + "test.no_movement_before_pass no" + ], + "expect": "pass", + "timeout": 900, + "checks": [ + { "type": "couples", "vehicle": "{{vehicle}}", "other": "{{vehicle}}_c2" }, + { "type": "log_lacks", "pattern": "derailed" }, + { "type": "log_lacks", "pattern": "collided" } + ] +} diff --git a/tests/scenarios/cases/eu07_td_crew_add.json b/tests/scenarios/cases/eu07_td_crew_add.json new file mode 100644 index 000000000..eb3c3637c --- /dev/null +++ b/tests/scenarios/cases/eu07_td_crew_add.json @@ -0,0 +1,31 @@ +{ + "description": "Crew event, a driver appears (eu07/maszyna#510): an EU07 stands cold on track 1 of Stacja1 on td.scn with nobody in it. 20 s after the start a putvalues event, Crew: 1 0, puts an AI driver in its cab A; the scenery then gives the driver the order to go (Shunt -1 0 from event0 of the track), and the driver starts the locomotive and leaves through the exit signal.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_crew.scn", + "vars": { + "trainsets": [ + "trainset none tdo_n1734 0.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "crew": [ + "event autotest_crew_put putvalues 0 none 0 0 0 Crew:{{vehicle}} 1 0 endevent", + "event autotest_crew_on multiple 20 none autotest_crew_put autotest_crew_waits endevent", + "node -1 0 autotest_crew_on_launcher eventlauncher 0 0 0 -1 none 1034 autotest_crew_on end" + ] + }, + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_add\\] an AI driver takes cab A" }, + { "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "ai", "after": 15, "before": 30 }, + { "type": "starts", "min_speed": 20, "within": 240 }, + { "type": "moves", "vehicle": "{{vehicle}}", "direction": "front", "min_speed": 20 }, + { "type": "log_lacks", "pattern": "derailed" }, + { "type": "log_lacks", "pattern": "collided" } + ] +} diff --git a/tests/scenarios/cases/eu07_td_crew_add_rear.json b/tests/scenarios/cases/eu07_td_crew_add_rear.json new file mode 100644 index 000000000..a4a677807 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_crew_add_rear.json @@ -0,0 +1,33 @@ +{ + "description": "Crew event, a driver appears in cab B (eu07/maszyna#510): as eu07_td_crew_add, with Crew: -1 0. The driver takes the rear cab, so the order to go sends the locomotive the other way, its rear end leading.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_crew.scn", + "vars": { + "trainsets": [ + "trainset none tdo_n1734 0.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "crew": [ + "event autotest_crew_put putvalues 0 none 0 0 0 Crew:{{vehicle}} -1 0 endevent", + "event autotest_crew_on multiple 20 none autotest_crew_put autotest_crew_waits endevent", + "node -1 0 autotest_crew_on_launcher eventlauncher 0 0 0 -1 none 1034 autotest_crew_on end" + ] + }, + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "test_config": [ + "test.fail_if_stop_overran no" + ], + "duration": 200, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_add_rear\\] an AI driver takes cab B" }, + { "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "ai", "after": 15, "before": 30 }, + { "type": "moves", "vehicle": "{{vehicle}}", "direction": "rear", "min_speed": 5 }, + { "type": "log_lacks", "pattern": "derailed" }, + { "type": "log_lacks", "pattern": "collided" } + ] +} diff --git a/tests/scenarios/cases/eu07_td_crew_refused.json b/tests/scenarios/cases/eu07_td_crew_refused.json new file mode 100644 index 000000000..4dc273e03 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_crew_refused.json @@ -0,0 +1,40 @@ +{ + "description": "Crew events which must change nothing (eu07/maszyna#510): the run of eu07_td_timetable, with a coach standing on track 2, and crew events set off at the start and again at 10:36, on the run: a second driver for the locomotive (it has one), a driver for the coach (no cab), a cab which is none of 1, -1, 0, a driver taken off the coach (it has none) and a vehicle the scenery lacks. Each is refused in the log and the train runs its timetable to the stop at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_crew.scn", + "vars": { + "trainsets": [ + "trainset td/rozklad tdo_n1734 0.0 0.1", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic", + "endtrainset", + "trainset none tor2k 30.0 0.0", + "node -1 0 {{vehicle}}_coach dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "crew": [ + "event autotest_crew_second putvalues 0 none 0 0 0 Crew:{{vehicle}} 1 0 endevent", + "event autotest_crew_coach putvalues 0 none 0 0 0 Crew:{{vehicle}}_coach 1 0 endevent", + "event autotest_crew_cab putvalues 0 none 0 0 0 Crew:{{vehicle}} 2 0 endevent", + "event autotest_crew_nobody putvalues 0 none 0 0 0 Crew:{{vehicle}}_coach 0 0 endevent", + "event autotest_crew_unknown putvalues 0 none 0 0 0 Crew:autotest_no_such_vehicle 0 0 endevent", + "event autotest_crew_all multiple 0 none autotest_crew_second autotest_crew_coach autotest_crew_cab autotest_crew_nobody autotest_crew_unknown endevent", + "node -1 0 autotest_crew_launcher1 eventlauncher 0 0 0 -1 none 1034 autotest_crew_all end", + "node -1 0 autotest_crew_launcher2 eventlauncher 0 0 0 -1 none 1036 autotest_crew_all end" + ] + }, + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "brakes", "min_pressure": 0.5 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 }, + { "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_refused\\] refused, the vehicle has a driver already" }, + { "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_refused_coach\\] refused, the vehicle has no cab" }, + { "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_refused\\] refused, the cab has to be 1, -1 or 0" }, + { "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_refused_coach\\] no driver to take off" }, + { "type": "log_contains", "pattern": "PutValues - \\[Crew:autotest_no_such_vehicle\\]" }, + { "type": "log_lacks", "pattern": "Crew: .* (takes cab|leaves)" } + ] +} diff --git a/tests/scenarios/cases/eu07_td_crew_remove.json b/tests/scenarios/cases/eu07_td_crew_remove.json new file mode 100644 index 000000000..8f1968eaa --- /dev/null +++ b/tests/scenarios/cases/eu07_td_crew_remove.json @@ -0,0 +1,27 @@ +{ + "description": "Crew event, the driver disappears (eu07/maszyna#510): an EU07 with an AI driver leaves Stacja1 on td.scn on the td/rozklad timetable at 10:35. At 10:36, on the run, a putvalues event, Crew: 0 0, takes the driver off: the locomotive is left with the power off and the brake valve in the emergency position, stops and stays where it stopped.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_crew.scn", + "vars": { + "trainsets": [ + "trainset td/rozklad tdo_n1734 0.0 0.1", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic", + "endtrainset" + ], + "crew": [ + "event autotest_crew_off putvalues 0 none 0 0 0 Crew:{{vehicle}} 0 0 endevent", + "node -1 0 autotest_crew_off_launcher eventlauncher 0 0 0 -1 none 1036 autotest_crew_off end" + ] + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_remove\\] the AI driver leaves" }, + { "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "none", "after": 115, "before": 130 }, + { "type": "stops_driverless", "vehicle": "{{vehicle}}", "min_speed": 20, "within": 60, "hold": 100 }, + { "type": "log_lacks", "pattern": "derailed" }, + { "type": "log_lacks", "pattern": "collided" } + ] +} diff --git a/tests/scenarios/cases/eu07_td_crew_swap.json b/tests/scenarios/cases/eu07_td_crew_swap.json new file mode 100644 index 000000000..4614c4622 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_crew_swap.json @@ -0,0 +1,34 @@ +{ + "description": "Crew events, the driver is replaced (eu07/maszyna#510): an EU07 with an AI driver waits on track 1 of Stacja1 on td.scn. 20 s after the start Crew: 0 0 takes the driver off, which leaves the locomotive braked; 20 s later Crew: 1 0 puts a new one in cab A, who gets the order to go (Shunt -1 0 from event0 of the track), releases the brakes and leaves through the exit signal.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_crew.scn", + "vars": { + "trainsets": [ + "trainset td/rozklad tdo_n1734 0.0 0.1", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic", + "endtrainset" + ], + "crew": [ + "event autotest_crew_off putvalues 20 none 0 0 0 Crew:{{vehicle}} 0 0 endevent", + "node -1 0 autotest_crew_off_launcher eventlauncher 0 0 0 -1 none 1034 autotest_crew_off end", + "event autotest_crew_put putvalues 0 none 0 0 0 Crew:{{vehicle}} 1 0 endevent", + "event autotest_crew_on multiple 40 none autotest_crew_put autotest_crew_waits endevent", + "node -1 0 autotest_crew_on_launcher eventlauncher 0 0 0 -1 none 1034 autotest_crew_on end" + ] + }, + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_swap\\] the AI driver leaves" }, + { "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_swap\\] an AI driver takes cab A" }, + { "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "ai", "after": 35, "before": 50 }, + { "type": "starts", "min_speed": 20, "within": 200 }, + { "type": "moves", "vehicle": "{{vehicle}}", "direction": "front", "min_speed": 20 }, + { "type": "log_lacks", "pattern": "derailed" }, + { "type": "log_lacks", "pattern": "collided" } + ] +} diff --git a/tests/scenarios/cases/eu07_td_dead_section.json b/tests/scenarios/cases/eu07_td_dead_section.json new file mode 100644 index 000000000..44c4c38f5 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_dead_section.json @@ -0,0 +1,22 @@ +{ + "description": "The reference of ep05_td_dead_section: an EU07, whose pantographs come first and whose line breaker opens without voltage (no PantRequiresMain), runs into the same span without voltage under power. Its line breaker opens 0.2 s into the section (the log says it lost power for 0.2x s, no longer: it says so only while the line breaker is closed), and behind it the AI closes the line breaker again, takes power and stops at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "replace": [ + ["node -1 0 none traction pwr01 3500 4500 0.01 cu 3.0 1\r\n0.7764 5.845 1561.2417", "node -1 0 none traction none 0 4500 0.01 cu 3.0 1\r\n0.7764 5.845 1561.2417"] + ], + "duration": 240, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "log_contains", "pattern": "lost power for 0\\.2\\d sec"}, + {"type": "log_lacks", "pattern": "lost power for (0\\.[3-9]|[1-9])"}, + {"type": "traction", "from_distance": 460, "to_distance": 700, "reaches": 25}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/eu07_td_departure_station.json b/tests/scenarios/cases/eu07_td_departure_station.json new file mode 100644 index 000000000..eb97b708c --- /dev/null +++ b/tests/scenarios/cases/eu07_td_departure_station.json @@ -0,0 +1,35 @@ +{ + "description": "Control for eu07_td_departure_station_capitals: the same timetable with the first row written as in the relation (Stacja1). The train stops at Stacja1 and leaves at 10:35.", + "base_scenery": "td.scn", + "time": "10:33", + "fragment": "td_departure_station.scn", + "timetable": "td_departure_station.txt", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 360, + "timeout": 600, + "checks": [ + { + "type": "log_lacks", + "pattern": "as TEST25: at \\d+:\\d+ passed Stacja1" + }, + { + "type": "log_contains", + "pattern": "as TEST25: at 10:35 next Przystanek" + }, + { + "type": "starts", + "min_speed": 20, + "within": 240 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 0, + "min_distance": 1380, + "max_distance": 1420 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_departure_station_capitals.json b/tests/scenarios/cases/eu07_td_departure_station_capitals.json new file mode 100644 index 000000000..cf1cbe2bd --- /dev/null +++ b/tests/scenarios/cases/eu07_td_departure_station_capitals.json @@ -0,0 +1,35 @@ +{ + "description": "EU07 on td.scn on a timetable whose first row, the station of departure, is written in capitals (STACJA1) and gives no arrival time, while the relation says Stacja1. The train is to stop there and wait for its departure at 10:35, not take Stacja1 for a station it passes through and leave as soon as the route is set at 10:34 (linia_107_poludnie.scn, Os33733 at ZAGORZ).", + "base_scenery": "td.scn", + "time": "10:33", + "fragment": "td_departure_station.scn", + "timetable": "td_departure_station_capitals.txt", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 360, + "timeout": 600, + "checks": [ + { + "type": "log_lacks", + "pattern": "as TEST24: at \\d+:\\d+ passed STACJA1" + }, + { + "type": "log_contains", + "pattern": "as TEST24: at 10:35 next Przystanek" + }, + { + "type": "starts", + "min_speed": 20, + "within": 240 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 0, + "min_distance": 1380, + "max_distance": 1420 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_downgrade_w4_signal.json b/tests/scenarios/cases/eu07_td_downgrade_w4_signal.json new file mode 100644 index 000000000..e26f6180d --- /dev/null +++ b/tests/scenarios/cases/eu07_td_downgrade_w4_signal.json @@ -0,0 +1,47 @@ +{ + "description": "A light EU07 on a line of its own beside td.scn, down a gradient of 20 per mille on a timetable: stops at the W4 of Dol 1500 m down the gradient, leaves at 10:38 and stops before the signal gr_sem at stop 1100 m further down. The EU07 alone brakes with its independent brake.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_downgrade_w4_signal.scn", + "timetable": "td_downgrade.txt", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 540, + "timeout": 900, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 150 + }, + { + "type": "max_speed", + "limit": 80, + "tolerance": 3 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 1500, + "max_distance": 1700 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 2550, + "max_distance": 2750, + "max_time": 355, + "nth": 2 + }, + { + "type": "distance", + "min": 2550, + "max": 2750 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_hauls_dead_vectron.json b/tests/scenarios/cases/eu07_td_hauls_dead_vectron.json new file mode 100644 index 000000000..8c06596c8 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_hauls_dead_vectron.json @@ -0,0 +1,20 @@ +{ + "description": "EU07 on td.scn hauls a dead Vectron prepared for hauling (coupling 3, parameter H: the pullee mode of MaSzyna-EU07/maszyna#64), AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek. Without the H the Vectron vents the brake pipe and the train never moves.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp/4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 dead_{{vehicle}} dynamic pkp/vectron_v1 1293-107 wariant_7w 0 nobody 0.H 0 enddynamic" + ] + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "brakes", "min_pressure": 0.5 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/scenarios/cases/eu07_td_hauls_dead_vectron_cold.json b/tests/scenarios/cases/eu07_td_hauls_dead_vectron_cold.json new file mode 100644 index 000000000..ed43f3c98 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_hauls_dead_vectron_cold.json @@ -0,0 +1,23 @@ +{ + "description": "As eu07_td_hauls_dead_vectron, from a cold start: the trainset stands with velocity 0, so both locomotives start braked (brake pipe at 3.5 bar, batteries off, the Vectron's spring brake on). The EU07's driver gets the order to run as a train, starts the engine, charges the brake pipe and hauls the Vectron, prepared for hauling (parameter H), to Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_cold_timetable.scn", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp/4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 dead_{{vehicle}} dynamic pkp/vectron_v1 1293-107 wariant_7w 0 nobody 0.H 0 enddynamic" + ] + }, + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "brakes", "min_pressure": 0.5 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/scenarios/cases/eu07_td_off_track_buckle.json b/tests/scenarios/cases/eu07_td_off_track_buckle.json new file mode 100644 index 000000000..29768b643 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_off_track_buckle.json @@ -0,0 +1,56 @@ +{ + "description": "physics.derailment new: EU07 with three coaches on td.scn on the td/rozklad timetable; at 10:35, as it leaves, the curve tdo_n222 about 950 m ahead buckles hard with a trackbuckle event (600 mm out of the curve over a main lobe of 8 m). The AI runs into it at the 33-35 km/h it has there with the coaches (46 km/h alone): the locomotive overturns on the buckle, goes off the track towards the bulge, falls on its side and stops on the ground some 30 m on; the coupling pulls the first coach off the rails.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_buckle_event.scn", + "vars": { + "amplitude": "600 8", + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_w1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_w2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_w3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic" + ] + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "expect": "timeout", + "duration": 240, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "Track \\\"tdo_n222\\\" buckled \\(event autotest_buckle\\): 600 mm" + }, + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+ leaves the track" + }, + { + "type": "starts", + "min_speed": 20, + "within": 150 + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}", + "min_offset": 3, + "max_distance": 45, + "min_distance": 15, + "lying": true + }, + { + "type": "consist_folds", + "vehicles": "{{vehicle}},{{vehicle}}_w1", + "min_bend": 15 + }, + { + "type": "no_overlap", + "max_transient": 0.2, + "max_at_rest": 0.05 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_off_track_buckle_fast.json b/tests/scenarios/cases/eu07_td_off_track_buckle_fast.json new file mode 100644 index 000000000..6b7154396 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_off_track_buckle_fast.json @@ -0,0 +1,55 @@ +{ + "description": "physics.derailment new: an EU07 with three coaches and no driver runs at 133 km/h into the curve tdo_n222 of td.scn (R 600 m, cant 65 mm), buckled hard 600 mm over a main lobe of 8 m from the start (the buckle keyword of the track). The locomotive overturns on the buckle: it leaves the track, falls on its side within a second and slides on the ground to a stop some 170 m on, 30 m off the track; the coaches behind it go off and over as well, and the train comes to rest folded, the vehicles turned against each other by 10 to 20 degrees.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_off_track.scn", + "vars": { + "track": "tdo_n157", + "offset": "60", + "velocity": "133", + "track_nodes": "", + "consist": [ + "node -1 0 {{vehicle}}_off dynamic pkp\\4e_v1 4e-004 4e 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_off_w1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_off_w2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_off_w3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic" + ] + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "expect": "timeout", + "duration": 60, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+_off leaves the track" + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}_off", + "cause": "overturned", + "min_offset": 20, + "min_distance": 120, + "max_distance": 230, + "lying": true + }, + { + "type": "consist_folds", + "vehicles": "{{vehicle}}_off,{{vehicle}}_off_w1,{{vehicle}}_off_w2,{{vehicle}}_off_w3", + "min_bend": 8, + "min_folds": 2 + }, + { + "type": "no_overlap", + "max_transient": 0.2, + "max_at_rest": 0.05 + } + ], + "track_events": { + "tdo_n222": "buckle 600;8" + } +} diff --git a/tests/scenarios/cases/eu07_td_off_track_curve_cutting.json b/tests/scenarios/cases/eu07_td_off_track_curve_cutting.json new file mode 100644 index 000000000..8b930e541 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_off_track_curve_cutting.json @@ -0,0 +1,36 @@ +{ + "description": "physics.derailment new: an EU07 without a driver runs at 150 km/h into a curve of R 300 m without cant, a track of 150 m laid on its own in the fields of td.scn (autotest_curve), in a cutting with banks of 1:1.5 4 m high, the ground rising on beyond them at 1:5 (triangles of the fragment). Over its overturning speed (about 120 km/h) it overturns out of the curve: it runs into the bank on the outside of the curve, climbs it and stops sooner than on level ground.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_off_track_curve_cutting.scn", + "vars": { + "velocity": "150" + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "expect": "timeout", + "duration": 60, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+_off leaves the track" + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}_off", + "cause": "overturned", + "min_offset": 40, + "min_distance": 150, + "max_distance": 230 + }, + { + "type": "no_overlap", + "max_transient": 0.2, + "max_at_rest": 0.05 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_off_track_curve_embankment.json b/tests/scenarios/cases/eu07_td_off_track_curve_embankment.json new file mode 100644 index 000000000..6db8b4ed8 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_off_track_curve_embankment.json @@ -0,0 +1,37 @@ +{ + "description": "physics.derailment new: an EU07 without a driver runs at 150 km/h into a curve of R 300 m without cant, a track of 150 m laid on its own in the fields of td.scn (autotest_curve), on an embankment 4 m high with slopes of 1:1.5 (triangles of the fragment). Over its overturning speed (about 120 km/h) it overturns out of the curve: it falls on its side over the edge of the embankment, slides down its slope and on over the level ground at its foot, 4 m lower.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_off_track_curve_embankment.scn", + "vars": { + "velocity": "150" + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "expect": "timeout", + "duration": 60, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+_off leaves the track" + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}_off", + "cause": "overturned", + "min_offset": 40, + "min_distance": 150, + "max_distance": 280, + "lying": true + }, + { + "type": "no_overlap", + "max_transient": 0.2, + "max_at_rest": 0.05 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_off_track_curve_flat.json b/tests/scenarios/cases/eu07_td_off_track_curve_flat.json new file mode 100644 index 000000000..df4103e81 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_off_track_curve_flat.json @@ -0,0 +1,37 @@ +{ + "description": "physics.derailment new: an EU07 without a driver runs at 150 km/h into a curve of R 300 m without cant, a track of 150 m laid on its own in the fields of td.scn (autotest_curve), on level ground (the grass of td.scn). Over its overturning speed (about 120 km/h) it overturns out of the curve: it slides on the grass out of the curve, falls on its side and stops.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_off_track_curve_flat.scn", + "vars": { + "velocity": "150" + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "expect": "timeout", + "duration": 60, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+_off leaves the track" + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}_off", + "cause": "overturned", + "min_offset": 40, + "min_distance": 150, + "max_distance": 260, + "lying": true + }, + { + "type": "no_overlap", + "max_transient": 0.2, + "max_at_rest": 0.05 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_off_track_end.json b/tests/scenarios/cases/eu07_td_off_track_end.json new file mode 100644 index 000000000..5a37cb2d0 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_off_track_end.json @@ -0,0 +1,46 @@ +{ + "description": "physics.derailment new: an EU07 with three coaches and no driver runs at 60 km/h off the end of a track of 150 m laid on its own in the fields of td.scn (autotest_stub): it runs straight on, upright, on the ground, and stops some 30 m on (the friction of 0.3 against the 39 km/h left of its 60 km/h as it drops off the end of the rails, the coaches pushing it); the first coach follows it off the end.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_off_track.scn", + "vars": { + "track": "autotest_stub", + "offset": "100", + "velocity": "60", + "track_nodes": "node -1 0 autotest_stub track normal 150.0 1.435 0.15 25.0 20 0 flat vis\n rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1\n-150.0 0.2 600.0 0.0 //point 1\n0.0 0.0 0.0 //control vector 1\n0.0 0.0 0.0 //control vector 2\n-150.0 0.2 750.0 0.0 //point 2\n0\nendtrack", + "consist": [ + "node -1 0 {{vehicle}}_off dynamic pkp\\4e_v1 4e-004 4e 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_off_w1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_off_w2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_off_w3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic" + ] + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "expect": "timeout", + "duration": 60, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+_off leaves the track" + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}_off", + "cause": "end of track", + "max_offset": 0.5, + "min_distance": 5, + "max_distance": 60, + "lying": false + }, + { + "type": "no_overlap", + "max_transient": 0.2, + "max_at_rest": 0.05 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_off_track_overturn.json b/tests/scenarios/cases/eu07_td_off_track_overturn.json new file mode 100644 index 000000000..c1bff7403 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_off_track_overturn.json @@ -0,0 +1,46 @@ +{ + "description": "physics.derailment new: an EU07 with three coaches and no driver runs at 190 km/h into the curve of R 600 m of td.scn (tdo_n213, tdo_n222), cant 65 mm: over the overturning speed (about 165 km/h) it overturns out of the curve, falls on its side and slides off the track to a stop; the coaches go over as well.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_off_track.scn", + "vars": { + "track": "tdo_n157", + "offset": "60", + "velocity": "190", + "track_nodes": "", + "consist": [ + "node -1 0 {{vehicle}}_off dynamic pkp\\4e_v1 4e-004 4e 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_off_w1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_off_w2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_off_w3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic" + ] + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "expect": "timeout", + "duration": 60, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+_off leaves the track" + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}_off", + "cause": "overturned", + "min_offset": 50, + "min_distance": 250, + "max_distance": 420, + "lying": true + }, + { + "type": "no_overlap", + "max_transient": 0.2, + "max_at_rest": 0.05 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_reinspect_brakes_after_coupling.json b/tests/scenarios/cases/eu07_td_reinspect_brakes_after_coupling.json new file mode 100644 index 000000000..be4b96feb --- /dev/null +++ b/tests/scenarios/cases/eu07_td_reinspect_brakes_after_coupling.json @@ -0,0 +1,69 @@ +{ + "description": "eu07/maszyna#350, #282: an EU07 on td.scn couples on the run (Shunt -3 3) to a cut standing on the line, 16 coaches with P alone and 8 empty wagons with G and P, 541 m of wagons, and runs it on as a train (Obey_train): a train on G (Cw-1 19.1), so the brakes of the coaches are to be cut out (19.9). The inspector looks at the train as it couples, at 4 km/h, and leaves the cut-outs for the standstill; reinspect_brakes() makes them as the train stands just after. The driver taken off at 38 km/h leaves the brake valve in the emergency position: braked by the locomotive and the 8 wagons alone the train stops at some 0.27 m/s2, over 210 m (with every brake working, 0.57 m/s2 over 99 m).", + "base_scenery": "td.scn", + "fragment": "td_reinspect_brakes.scn", + "vars": { + "locomotive": "pkp\\4e_v1 4e-004 4e", + "cut": [ + "node -1 0 {{vehicle}}_c01 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c02 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c03 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c04 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c05 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c06 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c07 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c08 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c09 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c10 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c11 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c12 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c13 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c14 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c15 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c16 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w1 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w2 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w3 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w4 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w5 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w6 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w7 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w8 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 0 0 enddynamic" + ] + }, + "track_events": { + "koniec": "event0 autotest_wake", + "tdo_n231": "event2 autotest_way", + "tdo_n240": "event2 autotest_crew_off" + }, + "test_config": [ + "test.timeout 1200", + "test.standstill 600" + ], + "expect": "pass", + "timeout": 600, + "checks": [ + { + "type": "couples", + "vehicle": "{{vehicle}}", + "other": "{{vehicle}}_w8" + }, + { + "type": "stops_driverless", + "vehicle": "{{vehicle}}", + "min_speed": 30, + "within": 90, + "hold": 60, + "min_deceleration": 0.15, + "max_deceleration": 0.4 + }, + { + "type": "log_lacks", + "pattern": "derailed" + }, + { + "type": "log_lacks", + "pattern": "collided" + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_reinspect_brakes_legacy_inspector.json b/tests/scenarios/cases/eu07_td_reinspect_brakes_legacy_inspector.json new file mode 100644 index 000000000..e3a03c2da --- /dev/null +++ b/tests/scenarios/cases/eu07_td_reinspect_brakes_legacy_inspector.json @@ -0,0 +1,71 @@ +{ + "description": "The train of eu07_td_reinspect_brakes_after_coupling with the inspector of the releases before eu07/maszyna#350 (ai.brakesetting.cw1 no), which cuts no brake out: every brake of the train works, and the emergency stop after the driver is taken off at 38 km/h comes at some 0.57 m/s2, over 99 m. It shows what the deceleration check of that case tells apart.", + "base_scenery": "td.scn", + "fragment": "td_reinspect_brakes.scn", + "vars": { + "locomotive": "pkp\\4e_v1 4e-004 4e", + "cut": [ + "node -1 0 {{vehicle}}_c01 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c02 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c03 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c04 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c05 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c06 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c07 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c08 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c09 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c10 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c11 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c12 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c13 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c14 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c15 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c16 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w1 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w2 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w3 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w4 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w5 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w6 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w7 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w8 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 0 0 enddynamic" + ] + }, + "track_events": { + "koniec": "event0 autotest_wake", + "tdo_n231": "event2 autotest_way", + "tdo_n240": "event2 autotest_crew_off" + }, + "test_config": [ + "test.timeout 1200", + "test.standstill 600" + ], + "expect": "pass", + "timeout": 600, + "checks": [ + { + "type": "couples", + "vehicle": "{{vehicle}}", + "other": "{{vehicle}}_w8" + }, + { + "type": "stops_driverless", + "vehicle": "{{vehicle}}", + "min_speed": 30, + "within": 60, + "hold": 60, + "min_deceleration": 0.45 + }, + { + "type": "log_lacks", + "pattern": "derailed" + }, + { + "type": "log_lacks", + "pattern": "collided" + } + ], + "ini": [ + "ai.brakesetting.cw1 no" + ] +} diff --git a/tests/scenarios/cases/eu07_td_shunt_push_red_signal.json b/tests/scenarios/cases/eu07_td_shunt_push_red_signal.json new file mode 100644 index 000000000..243d37641 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_shunt_push_red_signal.json @@ -0,0 +1,24 @@ +{ + "description": "EU07 shunting on td.scn (no timetable, so its AI drives under Shunt), pushing three coaches with no route set, the first coach starting at 30 km/h about 150 m before the exit signal stacja1_j at stop: stops before the signal and stays there.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_shunt_red_signal.scn", + "vars": { + "offset": "0.0", + "velocity": "30", + "consist": [ + "node -1 0 {{vehicle}}_w1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_w2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_w3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + ] + }, + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "max_speed", "limit": 40 }, + { "type": "stops", "moving_speed": 5, "stop_speed": 0.5, "hold": 5 }, + { "type": "stays_stopped", "moving_speed": 5, "stop_speed": 0.5 }, + { "type": "distance", "max": 150 } + ] +} diff --git a/tests/scenarios/cases/eu07_td_shunt_red_signal.json b/tests/scenarios/cases/eu07_td_shunt_red_signal.json new file mode 100644 index 000000000..bc23046cd --- /dev/null +++ b/tests/scenarios/cases/eu07_td_shunt_red_signal.json @@ -0,0 +1,19 @@ +{ + "description": "EU07 shunting on td.scn (no timetable, so its AI drives under Shunt) with no route set, starting at 30 km/h about 150 m before the exit signal stacja1_j at stop: stops before the signal and stays there.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_shunt_red_signal.scn", + "vars": { + "offset": "0.0", + "velocity": "30", + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "max_speed", "limit": 40 }, + { "type": "stops", "moving_speed": 5, "stop_speed": 0.5, "hold": 5 }, + { "type": "stays_stopped", "moving_speed": 5, "stop_speed": 0.5 }, + { "type": "distance", "max": 150 } + ] +} diff --git a/tests/scenarios/cases/eu07_td_switch_facing_control.json b/tests/scenarios/cases/eu07_td_switch_facing_control.json new file mode 100644 index 000000000..e512703d7 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_switch_facing_control.json @@ -0,0 +1,52 @@ +{ + "description": "Switch under a train, the control of the facing cases (#289 review 2b): an EU07 with three coaches runs from the west line into Stacja1 on td.scn, facing through switch zwr01, which is set to track 1 from the start (keyctrl02, with the entry signal at 40). Nothing is thrown. The train has to stop before a signal at stop on track 1 and stay on the rails.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_switch_thrown.scn", + "vars": { + "trainsets": [ + "trainset none start 80.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "route": "node -1 0 autotest_route_launcher eventlauncher 0 0 0 -1 none 1034 keyctrl02 end", + "throw": "zwr01_1", + "trigger": "", + "order": "Shunt -1 0" + }, + "track_events": { + "start": "event0 autotest_wake", + "tdo_n1725": [ + "event2 autotest_signal1_info", + "event0 autotest_pass" + ], + "tdo_n1734": [ + "eventall1 autotest_fail", + "eventall2 autotest_fail" + ] + }, + "test_config": [ + "test.timeout 400", + "test.standstill 120" + ], + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 30, + "within": 200 + }, + { + "type": "on_track", + "vehicles": "{{vehicle}}", + "max_offset": 0.6 + }, + { + "type": "log_lacks", + "pattern": "Bad driving" + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_switch_thrown_facing_behind.json b/tests/scenarios/cases/eu07_td_switch_thrown_facing_behind.json new file mode 100644 index 000000000..7798cef47 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_switch_thrown_facing_behind.json @@ -0,0 +1,50 @@ +{ + "description": "Switch thrown under a train running facing through it (#289 review 2b): as eu07_td_switch_thrown_facing_head, but zwr01 is thrown to track 1 when the locomotive has left the switch for track 2 (event of tor2p, set off by its rear axle), with the coaches still before and on the switch. A train cannot run on two tracks at once: every vehicle has to keep to the line of a track, whatever the throw does to them.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_switch_thrown.scn", + "vars": { + "trainsets": [ + "trainset none start 80.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "route": "node -1 0 autotest_route_launcher eventlauncher 0 0 0 -1 none 1034 keyctrl01 end", + "throw": "zwr01_1 zwr01_V40", + "trigger": "", + "order": "Shunt -1 0" + }, + "track_events": { + "start": "event0 autotest_wake", + "tor2p": [ + "event1 autotest_throw", + "event2 autotest_throw" + ], + "tdo_n109": "event0 autotest_pass" + }, + "test_config": [ + "test.timeout 400", + "test.standstill 120" + ], + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 30, + "within": 200 + }, + { + "type": "on_track", + "vehicles": "{{vehicle}}", + "max_offset": 0.6 + }, + { + "type": "log_lacks", + "pattern": "Bad driving" + } + ], + "xfail": "#289 review 2b, as before the stack (TrkFoll reverted in c268673c): the axles still on the switch leave it by the way it is set to now, those behind it take that way too, so the coaches go to track 1 and the locomotive they are coupled to runs on along track 2, 4.6 m beside them, with nothing derailed or broken" +} diff --git a/tests/scenarios/cases/eu07_td_switch_thrown_facing_head.json b/tests/scenarios/cases/eu07_td_switch_thrown_facing_head.json new file mode 100644 index 000000000..c02cad4d7 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_switch_thrown_facing_head.json @@ -0,0 +1,57 @@ +{ + "description": "Switch thrown under a train running facing through it (#289 review 2b): as eu07_td_switch_facing_control, but the way is set to track 2 (keyctrl01) and zwr01 is thrown to track 1 when the locomotive has run onto the switch with both its bogies (event of the switch track, set off by its rear axle). The locomotive and the train behind it have to go on to track 1 and stay on the rails, and the AI has to stop before the signal at stop on track 1.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_switch_thrown.scn", + "vars": { + "trainsets": [ + "trainset none start 80.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "route": "node -1 0 autotest_route_launcher eventlauncher 0 0 0 -1 none 1034 keyctrl01 end", + "throw": "zwr01_1 zwr01_V40", + "trigger": "", + "order": "Shunt -1 0" + }, + "track_events": { + "start": "event0 autotest_wake", + "zwr01": [ + "event1 autotest_throw", + "event2 autotest_throw" + ], + "tdo_n1725": [ + "event2 autotest_signal1_info", + "event0 autotest_pass" + ], + "tdo_n1734": [ + "eventall1 autotest_fail", + "eventall2 autotest_fail" + ] + }, + "test_config": [ + "test.timeout 400", + "test.standstill 120" + ], + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 30, + "within": 200 + }, + { + "type": "on_track", + "vehicles": "{{vehicle}}", + "max_offset": 0.6 + }, + { + "type": "log_lacks", + "pattern": "Bad driving" + } + ], + "xfail": "#289 review 2b, as before the stack (TrkFoll reverted in c268673c): an axle keeps the way of the switch it ran onto but leaves by the way the switch is set to now, so the locomotive jumps 1.9 m sideways at the end of the switch, an axle at a time; and the AI keeps the route it scanned before the throw (a switch behind the head of the train is not scanned again), so on track 1 it brakes for the exit signal of track 2 and runs past the signal at stop of track 1 at 40 km/h" +} diff --git a/tests/scenarios/cases/eu07_td_switch_thrown_standing_facing.json b/tests/scenarios/cases/eu07_td_switch_thrown_standing_facing.json new file mode 100644 index 000000000..fb3694906 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_switch_thrown_standing_facing.json @@ -0,0 +1,49 @@ +{ + "description": "Switch thrown under a standing train, which then leaves facing through it (#289 review 2b): an EU07 with three coaches stands cold across zwr01 on td.scn, the locomotive on track 2, the last coaches over the switch, which is set to track 2. 5 s after the start the switch is thrown to track 1; then the driver gets the order to go, into the station, facing through the switch. Every vehicle has to keep to the line of a track.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_switch_thrown.scn", + "vars": { + "trainsets": [ + "trainset none tor2p 50.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "route": "", + "throw": "zwr01_1 zwr01_V40", + "trigger": [ + "event autotest_throw_later multiple 5 none autotest_throw endevent", + "node -1 0 autotest_throw_launcher eventlauncher 0 0 0 -1 none 1034 autotest_throw_later end" + ], + "order": "Shunt -1 0" + }, + "track_events": { + "tor2p": "event0 autotest_wake_after_throw", + "tdo_n109": "event0 autotest_pass" + }, + "test_config": [ + "test.timeout 400", + "test.standstill 120" + ], + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 200 + }, + { + "type": "on_track", + "vehicles": "{{vehicle}}", + "max_offset": 0.6 + }, + { + "type": "log_lacks", + "pattern": "Bad driving" + } + ], + "xfail": "#289 review 2b, as before the stack (TrkFoll reverted in c268673c): the axles that stood on the switch leave it by the way it is set to now, so the second coach runs with one bogie on track 2 and the other on track 1, 4.6 m apart, its body 2.3 m off both, with nothing derailed or broken; and the AI scans its route from the last vehicle through the switch as now set, reads the signals of track 1 while it runs on track 2, and its head is counted past the exit signal of track 1 at stop" +} diff --git a/tests/scenarios/cases/eu07_td_switch_thrown_standing_trailing.json b/tests/scenarios/cases/eu07_td_switch_thrown_standing_trailing.json new file mode 100644 index 000000000..321806476 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_switch_thrown_standing_trailing.json @@ -0,0 +1,52 @@ +{ + "description": "Switch thrown under a standing train, which then leaves trailing through it (#289 review 2b): an EU07 with three coaches stands cold across zwr02 on td.scn, the locomotive on the line, the coaches behind it over the switch and on track 2, the switch set to track 2. 5 s after the start it is thrown to track 1; then the driver gets the order to go, out to the line. The wheels coming from track 2 push the switch back over (as through any switch set against them from the frog end); every vehicle has to keep to the line of a track. Passes once the locomotive runs onto tdo_n176, with the train clear of the switch.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_switch_thrown.scn", + "vars": { + "trainsets": [ + "trainset none tdo_n145 40.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "route": "", + "throw": "zwr02_1 zwr02_v40", + "trigger": [ + "event autotest_throw_later multiple 5 none autotest_throw endevent", + "node -1 0 autotest_throw_launcher eventlauncher 0 0 0 -1 none 1034 autotest_throw_later end" + ], + "order": "Obey_train 0 0" + }, + "track_events": { + "tdo_n145": "event0 autotest_wake_after_throw", + "tdo_n176": [ + "event1 autotest_pass_running", + "event2 autotest_pass_running" + ] + }, + "test_config": [ + "test.timeout 400", + "test.standstill 120", + "test.no_movement_before_pass no" + ], + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 10, + "within": 200 + }, + { + "type": "on_track", + "vehicles": "{{vehicle}}", + "max_offset": 0.6 + }, + { + "type": "log_lacks", + "pattern": "Bad driving" + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_switch_thrown_trailing.json b/tests/scenarios/cases/eu07_td_switch_thrown_trailing.json new file mode 100644 index 000000000..21d0d7bac --- /dev/null +++ b/tests/scenarios/cases/eu07_td_switch_thrown_trailing.json @@ -0,0 +1,56 @@ +{ + "description": "Switch thrown under a train running trailing through it (#289 review 2b): the td/rozklad timetable train, an EU07 with three coaches, leaves track 1 of Stacja1 on td.scn through zwr02 from its frog end; when the locomotive has run onto the line (event of tdo_n145, set off by its rear axle) the switch is thrown to track 2 under the coaches. The wheels coming from track 1 push it back over; the train has to stay on the rails and run its timetable to the stop at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_switch_thrown.scn", + "vars": { + "trainsets": [ + "trainset td/rozklad tdo_n1734 0.0 0.1", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "route": "node -1 0 autotest_route_launcher eventlauncher 0 0 0 -1 none 1034 keyctrl04 end", + "throw": "zwr02_0 zwr02_vmax", + "trigger": "", + "order": "Obey_train 0 0" + }, + "track_events": { + "tdo_n145": [ + "event1 autotest_throw", + "event2 autotest_throw" + ] + }, + "duration": 300, + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 240 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 0, + "min_distance": 1380, + "max_distance": 1420 + }, + { + "type": "on_track", + "vehicles": "{{vehicle}}", + "max_offset": 0.6 + }, + { + "type": "log_lacks", + "pattern": "Bad driving" + }, + { + "type": "log_contains", + "pattern": "EVENT LAUNCHED.*: autotest_throw_done$" + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_timetable_past_w4.json b/tests/scenarios/cases/eu07_td_timetable_past_w4.json new file mode 100644 index 000000000..c60effbed --- /dev/null +++ b/tests/scenarios/cases/eu07_td_timetable_past_w4.json @@ -0,0 +1,28 @@ +{ + "description": "EU07 with three coaches on td.scn on the td/rozklad timetable, placed with its head 80 m past the W4 of Stacja1, the first station of the timetable, which stays under the consist. The driver counts Stacja1 as the stop it stands at and leaves at 10:35.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable_past_w4.scn", + "vars": { + "offset": 15, + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic" + ] + }, + "duration": 300, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "as ROJ65113: at 10:35 next Przystanek" + }, + { + "type": "starts", + "min_speed": 20, + "within": 240 + } + ] +} diff --git a/tests/scenarios/cases/eu07a_coaches_td_upgrade_long.json b/tests/scenarios/cases/eu07a_coaches_td_upgrade_long.json new file mode 100644 index 000000000..aa6fb0f86 --- /dev/null +++ b/tests/scenarios/cases/eu07a_coaches_td_upgrade_long.json @@ -0,0 +1,50 @@ +{ + "description": "An EU07A (303E) with 8 coaches (about 360 t) on a line of its own beside td.scn: up a gradient of 10 per mille, 5.5 km long, at the 80 km/h of its timetable, to the signal at stop 5300 m up. The train is to keep above 70 km/h on the climb (#187: an EU07A hung at 55-58 km/h on 10 per mille).", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_upgrade_long.scn", + "timetable": "td_passenger_upgrade.txt", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\303e_v1 303E-336'20 303E 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c4 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c5 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c6 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c7 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c8 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic" + ] + }, + "expect": "standstill", + "duration": 1200, + "timeout": 1500, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 150 + }, + { + "type": "max_speed", + "limit": 80, + "tolerance": 3 + }, + { + "type": "keeps_moving", + "moving_speed": 20, + "min_speed": 70, + "from_distance": 2500, + "until_distance": 4800 + }, + { + "type": "stops", + "moving_speed": 15, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 5330, + "max_distance": 5410 + } + ] +} diff --git a/tests/scenarios/cases/golf_td_crew_swap.json b/tests/scenarios/cases/golf_td_crew_swap.json new file mode 100644 index 000000000..9eca8c05c --- /dev/null +++ b/tests/scenarios/cases/golf_td_crew_swap.json @@ -0,0 +1,30 @@ +{ + "description": "Crew events on a road vehicle (eu07/maszyna#510): a car with an AI driver runs along the road d3 of td.scn, at 50 km/h, the top speed its trainset gives it. 20 s after the start Crew: 0 0 takes the driver off: the car is left with its own brake applied in full, stops and stands. 40 s later Crew: 1 0 puts a driver in again (a road vehicle has no cab to tell by, and takes one all the same), who drives on along the road, with no timetable to cap the speed.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_crew.scn", + "vars": { + "trainsets": [ + "trainset 50 d3 0.0 30", + "node -1 0 {{vehicle}} dynamic road\\golf none golf 0 headdriver 0 0 enddynamic", + "endtrainset" + ], + "crew": [ + "event autotest_crew_off putvalues 20 none 0 0 0 Crew:{{vehicle}} 0 0 endevent", + "node -1 0 autotest_crew_off_launcher eventlauncher 0 0 0 -1 none 1034 autotest_crew_off end", + "event autotest_crew_on putvalues 60 none 0 0 0 Crew:{{vehicle}} 1 0 endevent", + "node -1 0 autotest_crew_on_launcher eventlauncher 0 0 0 -1 none 1034 autotest_crew_on end" + ] + }, + "duration": 120, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Crew: \\[autotest_golf_td_crew_swap\\] the AI driver leaves" }, + { "type": "stops_driverless", "vehicle": "{{vehicle}}", "min_speed": 10, "within": 30, "hold": 30 }, + { "type": "log_contains", "pattern": "Crew: \\[autotest_golf_td_crew_swap\\] an AI driver takes cab A" }, + { "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "ai", "after": 55, "before": 70 }, + { "type": "starts", "min_speed": 20, "within": 60 }, + { "type": "log_lacks", "pattern": "derailed" }, + { "type": "log_lacks", "pattern": "collided" } + ] +} diff --git a/tests/scenarios/cases/l053_poludnie_roj32134_debica.json b/tests/scenarios/cases/l053_poludnie_roj32134_debica.json new file mode 100644 index 000000000..7ed64bf96 --- /dev/null +++ b/tests/scenarios/cases/l053_poludnie_roj32134_debica.json @@ -0,0 +1,24 @@ +{ + "description": "eu07/maszyna#506, L053 poludnie, ROJ23133 Debica - Rudawa and ROJ32134 back (EN57-1797ra): the unit runs both trains among the scenery's traffic and ends at Debica (the station's state cell of ROJ32134 says done).", + "base_scenery": "l053_poludnie.scn", + "strip_trainsets": false, + "vehicle": "EN57-1797ra", + "fragment": "mission_state_probe.scn", + "vars": { + "cell": "deb_roj32134_stat", + "state": "d * *", + "reason": "roj32134_ended_at_debica" + }, + "slow": true, + "physicslog": false, + "ini": [ + "file.binary.terrain no" + ], + "test_config": [ + "test.timeout 7200", + "test.standstill 1500", + "test.fail_if_stop_overran no" + ], + "expect": "pass", + "timeout": 3600 +} diff --git a/tests/scenarios/cases/l053_poranek_tme222158_debica.json b/tests/scenarios/cases/l053_poranek_tme222158_debica.json new file mode 100644 index 000000000..dde90e86a --- /dev/null +++ b/tests/scenarios/cases/l053_poranek_tme222158_debica.json @@ -0,0 +1,30 @@ +{ + "description": "eu07/maszyna#421, L053 poranek, TME222158: the locomotive brings the wagons with steel coils from Debica Towarowa to Debica, uncouples (Shunt 0 0 from the scenery), shunts on the Ms2 signals while the station's SM42 takes the wagons away, couples to its next train and gets the exit signal to Sandomierz (step 6 of the station's state cell).", + "base_scenery": "l053_poranek.scn", + "strip_trainsets": false, + "vehicle": "ET22-654", + "fragment": "mission_state_probe.scn", + "vars": { + "cell": "deb_tme222158_stat", + "state": "* 6 *", + "reason": "tme222158_got_the_exit_signal_at_debica" + }, + "slow": true, + "physicslog": false, + "ini": [ + "file.binary.terrain no" + ], + "test_config": [ + "test.timeout 6000", + "test.standstill 2100", + "test.fail_if_stop_overran no" + ], + "expect": "pass", + "timeout": 3600, + "checks": [ + { + "type": "log_contains", + "pattern": "Uncoupling \\[et22-654\\]: uncoupled" + } + ] +} diff --git a/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json b/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json new file mode 100644 index 000000000..7ad5a1a78 --- /dev/null +++ b/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json @@ -0,0 +1,36 @@ +{ + "description": "eu07/maszyna#421 as reported in 2021, with an ET21 on TME222158 (the scenery has an ET22 there now): the same run as l053_poranek_tme222158_debica, the locomotive of the mission replaced.", + "base_scenery": "l053_poranek.scn", + "strip_trainsets": false, + "replace": [ + [ + "node -1 0 ET22-654 dynamic pkp\\et22_v3 201E-654 201E -1 headdriver 3 0 enddynamic", + "node -1 0 ET21-367 dynamic pkp\\et21_v2 ET21-367 3e2 -1 headdriver 3 0 enddynamic" + ] + ], + "vehicle": "ET21-367", + "fragment": "mission_state_probe.scn", + "vars": { + "cell": "deb_tme222158_stat", + "state": "* 6 *", + "reason": "tme222158_got_the_exit_signal_at_debica" + }, + "slow": true, + "physicslog": false, + "ini": [ + "file.binary.terrain no" + ], + "test_config": [ + "test.timeout 6000", + "test.standstill 2100", + "test.fail_if_stop_overran no" + ], + "expect": "pass", + "timeout": 3600, + "checks": [ + { + "type": "log_contains", + "pattern": "Uncoupling \\[et21-367\\]: uncoupled" + } + ] +} diff --git a/tests/scenarios/cases/mission_state_probe.scn b/tests/scenarios/cases/mission_state_probe.scn new file mode 100644 index 000000000..fd158dab3 --- /dev/null +++ b/tests/scenarios/cases/mission_state_probe.scn @@ -0,0 +1,13 @@ +// added by tests/scenarios/run.py to a scenery that keeps its own trainsets (strip_trainsets false): the +// case tests one of the scenery's missions, with every train driven by AI. +// the sceneries of this kind steer their stations with state cells, one per train (text and two values, +// e.g. "a 6 *": the route of step 6 is set for the train, "d * *": the train is done at this station). +// the probe looks at the cell {{cell}} every 5 s from the start on and reports the pass once it holds +// {{state}}. no fail event: a train that never gets there ends the test with the standstill or the +// timeout of the test mode. +// the two events calling each other are the loop these sceneries use themselves (e.g. bal_obsluga_stacji); +// an event with "onstart" in its name is queued when the scenery starts. +event onstart_autotest_probe multiple 30 none autotest_probe endevent +event autotest_probe multiple 0 {{cell}} autotest_pass else autotest_probe_wait condition memcompare {{state}} endevent +event autotest_probe_wait multiple 5 none autotest_probe endevent +event autotest_pass UpdateValues 0 __test.result {{reason}} 1 * endevent diff --git a/tests/scenarios/cases/sm42_td_crew_remove.json b/tests/scenarios/cases/sm42_td_crew_remove.json new file mode 100644 index 000000000..42e55d9d1 --- /dev/null +++ b/tests/scenarios/cases/sm42_td_crew_remove.json @@ -0,0 +1,27 @@ +{ + "description": "Crew event, the driver disappears (eu07/maszyna#510): as eu07_td_crew_remove, with an SM42 diesel shunter which loses its AI driver on the run at 10:36, stops and stays where it stopped.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_crew.scn", + "vars": { + "trainsets": [ + "trainset td/rozklad tdo_n1734 0.0 0.1", + "node -1 0 {{vehicle}} dynamic pkp\\sm42_v1 6D-468 6D 0 headdriver 0 0 enddynamic", + "endtrainset" + ], + "crew": [ + "event autotest_crew_off putvalues 0 none 0 0 0 Crew:{{vehicle}} 0 0 endevent", + "node -1 0 autotest_crew_off_launcher eventlauncher 0 0 0 -1 none 1036 autotest_crew_off end" + ] + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "log_contains", "pattern": "Crew: \\[autotest_sm42_td_crew_remove\\] the AI driver leaves" }, + { "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "none", "after": 115, "before": 130 }, + { "type": "stops_driverless", "vehicle": "{{vehicle}}", "min_speed": 20, "within": 60, "hold": 100 }, + { "type": "log_lacks", "pattern": "derailed" }, + { "type": "log_lacks", "pattern": "collided" } + ] +} diff --git a/tests/scenarios/cases/sm42_td_uncouple_past_signal.json b/tests/scenarios/cases/sm42_td_uncouple_past_signal.json new file mode 100644 index 000000000..f1ae7b835 --- /dev/null +++ b/tests/scenarios/cases/sm42_td_uncouple_past_signal.json @@ -0,0 +1,25 @@ +{ + "description": "SM42 shunter on td.scn pulls three loaded wagons back along tor1k and stops with the far end of the last one a few metres past the exit signal stacja1_j at stop, then gets Shunt 0 0 (uncouple): after the direction change the signal lies at stop over that wagon, behind the new head, and the AI has to push the buffers in all the same and let the coupler go.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_uncouple_past_signal.scn", + "vars": { + "wagons": [ + "node -1 0 {{vehicle}}_w3 dynamic pkp\\401z_v2 82515940087-8 401zp_2 0 nobody 3 60 gravel enddynamic", + "node -1 0 {{vehicle}}_w2 dynamic pkp\\401z_v2 82515942691-5 401zp_1 0 nobody 3 60 gravel enddynamic", + "node -1 0 {{vehicle}}_w1 dynamic pkp\\401z_v2 82515993043-7 401zl_2 0 nobody 3 60 gravel enddynamic" + ] + }, + "track_events": { + "tor1k": "event0 autotest_wake" + }, + "test_config": [ + "test.fail_if_stop_overran no" + ], + "duration": 180, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Uncoupling \\[autotest_sm42_td_uncouple_past_signal\\]: uncoupled" }, + { "type": "distance", "min": 45, "max": 49 } + ] +} diff --git a/tests/scenarios/cases/sn61_td_downgrade_w4_signal.json b/tests/scenarios/cases/sn61_td_downgrade_w4_signal.json new file mode 100644 index 000000000..033313dc0 --- /dev/null +++ b/tests/scenarios/cases/sn61_td_downgrade_w4_signal.json @@ -0,0 +1,47 @@ +{ + "description": "An SN61 railcar alone on the line of eu07_td_downgrade_w4_signal, down a gradient of 20 per mille: stops at the W4 of Dol, then before the signal at stop. The SN61 alone brakes with its independent brake.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_downgrade_w4_signal.scn", + "timetable": "td_downgrade.txt", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\sn61_v2 SN61-13 SN61_v1 0 headdriver 0 0 enddynamic" + }, + "duration": 540, + "timeout": 900, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 150 + }, + { + "type": "max_speed", + "limit": 80, + "tolerance": 3 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 1500, + "max_distance": 1700 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 2550, + "max_distance": 2750, + "max_time": 366, + "nth": 2 + }, + { + "type": "distance", + "min": 2550, + "max": 2750 + } + ] +} diff --git a/tests/scenarios/cases/st43_steel_td_downgrade12_long.json b/tests/scenarios/cases/st43_steel_td_downgrade12_long.json new file mode 100644 index 000000000..371faa23c --- /dev/null +++ b/tests/scenarios/cases/st43_steel_td_downgrade12_long.json @@ -0,0 +1,86 @@ +{ + "description": "An ST43 with 45 loaded steel coil wagons (425S, G) on a line of its own beside td.scn: from the level down a gradient of 12 per mille, 6 km long, at the 40 km/h of its timetable, to the signal at stop 6000 m down. The train is not to come to a stand on the way down (#199).", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_downgrade12_long.scn", + "timetable": "td_freight_downgrade12.txt", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\st43_v1 st43-195 060Da 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_w01 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w02 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w03 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w04 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w05 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w06 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w07 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w08 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w09 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w10 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w11 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w12 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w13 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w14 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w15 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w16 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w17 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w18 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w19 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w20 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w21 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w22 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w23 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w24 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w25 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w26 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w27 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w28 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w29 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w30 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w31 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w32 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w33 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w34 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w35 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w36 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w37 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w38 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w39 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w40 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w41 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w42 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w43 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w44 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w45 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic" + ] + }, + "expect": "standstill", + "duration": 1500, + "timeout": 1800, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 400 + }, + { + "type": "max_speed", + "limit": 40, + "tolerance": 5 + }, + { + "type": "keeps_moving", + "moving_speed": 20, + "min_speed": 5, + "until_distance": 5800 + }, + { + "type": "stops", + "moving_speed": 15, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 5950, + "max_distance": 6110 + } + ] +} diff --git a/tests/scenarios/cases/td_buckle_event.scn b/tests/scenarios/cases/td_buckle_event.scn new file mode 100644 index 000000000..b9d47d434 --- /dev/null +++ b/tests/scenarios/cases/td_buckle_event.scn @@ -0,0 +1,11 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed: +// td_timetable.scn (the timetable train from track 1 of Stacja1 to Przystanek), and at 10:35, as the train leaves, +// the curve tdo_n222 (R 600 m, about 950 m ahead of it) buckles in the heat out of the curve with the +// trackbuckle event of {{amplitude}} mm (see world/TrackBuckle.h) +trainset td/rozklad tdo_n1734 0.0 0.1 +{{consist}} +endtrainset + +node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end +event autotest_buckle trackbuckle 0 tdo_n222 {{amplitude}} endevent +node -1 0 autotest_buckle_launcher eventlauncher 0 0 0 -1 none 1035 autotest_buckle end diff --git a/tests/scenarios/cases/td_cold_connect.scn b/tests/scenarios/cases/td_cold_connect.scn new file mode 100644 index 000000000..3ea9306c6 --- /dev/null +++ b/tests/scenarios/cases/td_cold_connect.scn @@ -0,0 +1,28 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// on the straight track 1 of Stacja1: a locomotive with an AI driver stands cold (trainset velocity 0, so +// it starts "Braked": hand brake on, battery off, pantographs down) on tdo_n1725, its front 60 m past +// point 1 of the track, facing point 2; the rake (vars.rake) stands, braked as well and with nobody in it, +// on tdo_n1734 ahead of it, its front 60 m past point 1 of that track, some 45 m in front of the +// locomotive (two coaches of 26.4 m). +trainset none tdo_n1725 60.0 0.0 +node -1 0 {{vehicle}} dynamic {{locomotive}} 0 headdriver 0 0 enddynamic +endtrainset + +trainset none tdo_n1734 60.0 0.0 +{{rake}} +endtrainset + +// a driver of a standing trainset sleeps on Wait_for_orders until something wakes it. event0 of the +// locomotive's track (the case's track_events) runs while it stands there and gives it, once (the memory +// cell), the order a scenery gives a shunter to couple: Shunt -1 3, couple to the consist standing ahead +// with the coupler and the brake hose and go on shunting. the engine is cold, so the AI starts it +// first: its orders are Prepare_engine, Connect, Shunt, and Connect is the first one it drives under. +node -1 0 autotest_ordered memcell 0 0 0 ordered 0 0 none endmemcell +event autotest_wake multiple 0 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event autotest_order PutValues 0 none 0 0 0 Shunt -1 3 endevent +event autotest_order_given UpdateValues 0 autotest_ordered * 1 * endevent + +// the rake, pushed by the locomotive, runs onto tor1k (40 m ahead of its first coach) towards its +// point 2: eventall2 of tor1k (the case's track_events) passes the test, which ends there with the train +// still moving (test.no_movement_before_pass no), 100 m short of the exit signal at the end of tor1k. +event autotest_pass UpdateValues 0 __test.result the_rake_was_coupled_and_pushed 1 * endevent diff --git a/tests/scenarios/cases/td_cold_timetable.scn b/tests/scenarios/cases/td_cold_timetable.scn new file mode 100644 index 000000000..b11c4825a --- /dev/null +++ b/tests/scenarios/cases/td_cold_timetable.scn @@ -0,0 +1,19 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed: +// the trainset goes after FirstInit, the launcher and the events before it. +// the case's consist stands cold where td.scn keeps its timetable train (track 1 of Stacja1): trainset +// velocity 0, so every vehicle starts "Braked": brake pipe at 3.5 bar, battery off, hand and spring brakes on. +// it has the same timetable: Stacja1 10:35 -> Przystanek -> Stacja2. +trainset td/rozklad tdo_n1734 0.0 0.0 +{{consist}} +endtrainset + +// the way out of track 1, as in td_timetable.scn +node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end + +// a driver of a standing trainset sleeps on Wait_for_orders until something wakes it. event0 of the train's +// track (the case's track_events) runs while it stands there and gives it, once (the memory cell), the order +// to run as a train: Obey_train. the engine is cold, so the AI starts it first (Prepare_engine). +node -1 0 autotest_ordered memcell 0 0 0 ordered 0 0 none endmemcell +event autotest_wake multiple 0 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event autotest_order PutValues 0 none 0 0 0 Obey_train 0 0 endevent +event autotest_order_given UpdateValues 0 autotest_ordered * 1 * endevent diff --git a/tests/scenarios/cases/td_crew.scn b/tests/scenarios/cases/td_crew.scn new file mode 100644 index 000000000..33def0f24 --- /dev/null +++ b/tests/scenarios/cases/td_crew.scn @@ -0,0 +1,22 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// the vehicles of the case (vars.trainsets), the lead one on track 1 of Stacja1 (tdo_n1734), where td.scn keeps +// its timetable train, and the crew events of the case (vars.crew, eu07/maszyna#510): a putvalues event with +// "Crew: " puts an AI driver in cab A (1) or cab B (-1) of the vehicle named, or takes its +// AI driver off (0). the vehicle is named in the text, so the events run from event launchers, with no vehicle +// setting them off. +{{trainsets}} + +// the way out of track 1, see td_timetable.scn +node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end + +{{crew}} + +// a driver put in a standing vehicle waits for orders, as the driver of a standing trainset does, and the scenery +// has to give them. event0 of the track the locomotive stands on (the track_events of the case) runs while a +// vehicle with a driver in charge stands there; once the cell says a new driver waits (autotest_crew_waits, run +// along with the crew event), it gives the order to go, Shunt -1 0, one time. +node -1 0 autotest_ordered memcell 0 0 0 ordered 0 0 none endmemcell +event autotest_crew_waits UpdateValues 0 autotest_ordered * 1 * endevent +event autotest_wake multiple 0 autotest_ordered autotest_order autotest_order_given condition memcompare * 1 * endevent +event autotest_order PutValues 0 none 0 0 0 Shunt -1 0 endevent +event autotest_order_given UpdateValues 0 autotest_ordered * 2 * endevent diff --git a/tests/scenarios/cases/td_departure_station.scn b/tests/scenarios/cases/td_departure_station.scn new file mode 100644 index 000000000..b005516c4 --- /dev/null +++ b/tests/scenarios/cases/td_departure_station.scn @@ -0,0 +1,9 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// the same start as td_timetable.scn, the W4 of Stacja1 about 35 m ahead of the train, but on the case's own +// timetable: {{timetable}}, a copy of the case's "timetable" file, Stacja1 10:35 -> Przystanek -> Stacja2 whose +// first row gives no arrival time, only the departure. the route out of track 1 is set at 10:34 +trainset {{timetable}} tdo_n1734 0.0 0.1 +{{consist}} +endtrainset + +node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end diff --git a/tests/scenarios/cases/td_departure_station.txt b/tests/scenarios/cases/td_departure_station.txt new file mode 100644 index 000000000..cd4851228 --- /dev/null +++ b/tests/scenarios/cases/td_departure_station.txt @@ -0,0 +1,20 @@ +________________________________________________________________ +[ Rodzaj i numer pociagu | TEST25 ] +[ Kategoria | RO ] +[________________________________________________|______________] +[ | Stacja1 ] +[ Relacja pociagu | Stacja2 ] +[________________________________________________|______________] +[ Wymagany % ciezaru hamujacego | 88% ] +[________________________________________________|______________] +[ Seria i obciazenie lokomotywy | EU07 210 ] +[________________________________________________|______________] +[ | | Stacja1 2 | | ] +[ | 60 | R1,L,H,RT,PP 2 10.35 | ] +[ | |----------------------------------1----------|---] +[ | | Przystanek 1 10.37 | 4 ] +[ |_____| R1,+,L,H,PP,pt 1 10.37.3 | ] +[ | 90 |----------------------------------1----------|---] +[ | | Stacja2 1 10.39 | 1 ] +[ | | R1 1 10.40 | ] +[_______|_____|__________________________________1__________|___] diff --git a/tests/scenarios/cases/td_departure_station_capitals.txt b/tests/scenarios/cases/td_departure_station_capitals.txt new file mode 100644 index 000000000..8d727d5d0 --- /dev/null +++ b/tests/scenarios/cases/td_departure_station_capitals.txt @@ -0,0 +1,20 @@ +________________________________________________________________ +[ Rodzaj i numer pociagu | TEST24 ] +[ Kategoria | RO ] +[________________________________________________|______________] +[ | Stacja1 ] +[ Relacja pociagu | Stacja2 ] +[________________________________________________|______________] +[ Wymagany % ciezaru hamujacego | 88% ] +[________________________________________________|______________] +[ Seria i obciazenie lokomotywy | EU07 210 ] +[________________________________________________|______________] +[ | | STACJA1 2 | | ] +[ | 60 | R1,L,H,RT,PP 2 10.35 | ] +[ | |----------------------------------1----------|---] +[ | | Przystanek 1 10.37 | 4 ] +[ |_____| R1,+,L,H,PP,pt 1 10.37.3 | ] +[ | 90 |----------------------------------1----------|---] +[ | | Stacja2 1 10.39 | 1 ] +[ | | R1 1 10.40 | ] +[_______|_____|__________________________________1__________|___] diff --git a/tests/scenarios/cases/td_downgrade.txt b/tests/scenarios/cases/td_downgrade.txt new file mode 100644 index 000000000..ddc50d031 --- /dev/null +++ b/tests/scenarios/cases/td_downgrade.txt @@ -0,0 +1,20 @@ +________________________________________________________________ +[ Rodzaj i numer pociagu | TEST26 ] +[ Kategoria | RO ] +[________________________________________________|______________] +[ | Gora ] +[ Relacja pociagu | Koniec ] +[________________________________________________|______________] +[ Wymagany % ciezaru hamujacego | 88% ] +[________________________________________________|______________] +[ Seria i obciazenie lokomotywy | EU07 210 ] +[________________________________________________|______________] +[ | | Gora 2 | | ] +[ | 80 | R1,L,H,RT,PP 2 10.35 | ] +[ | |----------------------------------1----------|---] +[ | | Dol 1 10.37 | 4 ] +[ |_____| R1,+,L,H,PP 1 10.38 | ] +[ | 80 |----------------------------------1----------|---] +[ | | Koniec 1 10.45 | 7 ] +[ | | R1 1 10.46 | ] +[_______|_____|__________________________________1__________|___] diff --git a/tests/scenarios/cases/td_downgrade12_long.scn b/tests/scenarios/cases/td_downgrade12_long.scn new file mode 100644 index 000000000..37cf1eff3 --- /dev/null +++ b/tests/scenarios/cases/td_downgrade12_long.scn @@ -0,0 +1,608 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a line of its own, away from the tracks of td.scn: 900 m level, then 6500 m down a gradient of 12 per mille, +// with no overhead wire (diesel trains). the train starts on the level with its head 10 m before the W4 of Gora and runs on +// the timetable {{timetable}} (no stop; a freight train leaves Gora at once) at its line limit, down to the signal hl_sem +// at stop 6000 m down the gradient. the line goes on 500 m past the signal +node -1 0 hl_00 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -800.0 0.0 +0 +endtrack +node -1 0 hl_01 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -700.0 0.0 +0 +endtrack +node -1 0 hl_02 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -600.0 0.0 +0 +endtrack +node -1 0 hl_03 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -500.0 0.0 +0 +endtrack +node -1 0 hl_04 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -400.0 0.0 +0 +endtrack +node -1 0 hl_05 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -300.0 0.0 +0 +endtrack +node -1 0 hl_06 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -200.0 0.0 +0 +endtrack +node -1 0 hl_07 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -100.0 0.0 +0 +endtrack +node -1 0 hl_08 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 0.0 0.0 +0 +event2 gora#1_stopinfo +endtrack +node -1 0 hl_09 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 0.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 58.80 100.0 0.0 +0 +endtrack +node -1 0 hl_10 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 58.80 100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 57.60 200.0 0.0 +0 +endtrack +node -1 0 hl_11 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 57.60 200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 56.40 300.0 0.0 +0 +endtrack +node -1 0 hl_12 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 56.40 300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 55.20 400.0 0.0 +0 +endtrack +node -1 0 hl_13 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 55.20 400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 54.00 500.0 0.0 +0 +endtrack +node -1 0 hl_14 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 54.00 500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 52.80 600.0 0.0 +0 +endtrack +node -1 0 hl_15 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 52.80 600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 51.60 700.0 0.0 +0 +endtrack +node -1 0 hl_16 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 51.60 700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 50.40 800.0 0.0 +0 +endtrack +node -1 0 hl_17 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 50.40 800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 49.20 900.0 0.0 +0 +endtrack +node -1 0 hl_18 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 49.20 900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 48.00 1000.0 0.0 +0 +endtrack +node -1 0 hl_19 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 48.00 1000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 46.80 1100.0 0.0 +0 +endtrack +node -1 0 hl_20 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 46.80 1100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 45.60 1200.0 0.0 +0 +endtrack +node -1 0 hl_21 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 45.60 1200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 44.40 1300.0 0.0 +0 +endtrack +node -1 0 hl_22 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 44.40 1300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 43.20 1400.0 0.0 +0 +endtrack +node -1 0 hl_23 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 43.20 1400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 42.00 1500.0 0.0 +0 +endtrack +node -1 0 hl_24 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 42.00 1500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 40.80 1600.0 0.0 +0 +endtrack +node -1 0 hl_25 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 40.80 1600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 39.60 1700.0 0.0 +0 +endtrack +node -1 0 hl_26 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 39.60 1700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 38.40 1800.0 0.0 +0 +endtrack +node -1 0 hl_27 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 38.40 1800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 37.20 1900.0 0.0 +0 +endtrack +node -1 0 hl_28 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 37.20 1900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 36.00 2000.0 0.0 +0 +endtrack +node -1 0 hl_29 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 36.00 2000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 34.80 2100.0 0.0 +0 +endtrack +node -1 0 hl_30 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 34.80 2100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 33.60 2200.0 0.0 +0 +endtrack +node -1 0 hl_31 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 33.60 2200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 32.40 2300.0 0.0 +0 +endtrack +node -1 0 hl_32 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 32.40 2300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 31.20 2400.0 0.0 +0 +endtrack +node -1 0 hl_33 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 31.20 2400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 30.00 2500.0 0.0 +0 +endtrack +node -1 0 hl_34 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 30.00 2500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 28.80 2600.0 0.0 +0 +endtrack +node -1 0 hl_35 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 28.80 2600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 27.60 2700.0 0.0 +0 +endtrack +node -1 0 hl_36 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 27.60 2700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 26.40 2800.0 0.0 +0 +endtrack +node -1 0 hl_37 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 26.40 2800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 25.20 2900.0 0.0 +0 +endtrack +node -1 0 hl_38 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 25.20 2900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 24.00 3000.0 0.0 +0 +endtrack +node -1 0 hl_39 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 24.00 3000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 22.80 3100.0 0.0 +0 +endtrack +node -1 0 hl_40 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 22.80 3100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 21.60 3200.0 0.0 +0 +endtrack +node -1 0 hl_41 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 21.60 3200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 20.40 3300.0 0.0 +0 +endtrack +node -1 0 hl_42 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 20.40 3300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 19.20 3400.0 0.0 +0 +endtrack +node -1 0 hl_43 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 19.20 3400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 18.00 3500.0 0.0 +0 +endtrack +node -1 0 hl_44 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 18.00 3500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 16.80 3600.0 0.0 +0 +endtrack +node -1 0 hl_45 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 16.80 3600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 15.60 3700.0 0.0 +0 +endtrack +node -1 0 hl_46 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 15.60 3700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 14.40 3800.0 0.0 +0 +endtrack +node -1 0 hl_47 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 14.40 3800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 13.20 3900.0 0.0 +0 +endtrack +node -1 0 hl_48 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 13.20 3900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 12.00 4000.0 0.0 +0 +endtrack +node -1 0 hl_49 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 12.00 4000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 10.80 4100.0 0.0 +0 +endtrack +node -1 0 hl_50 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 10.80 4100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 9.60 4200.0 0.0 +0 +endtrack +node -1 0 hl_51 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 9.60 4200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 8.40 4300.0 0.0 +0 +endtrack +node -1 0 hl_52 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 8.40 4300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 7.20 4400.0 0.0 +0 +endtrack +node -1 0 hl_53 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 7.20 4400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 6.00 4500.0 0.0 +0 +endtrack +node -1 0 hl_54 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 6.00 4500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 4.80 4600.0 0.0 +0 +endtrack +node -1 0 hl_55 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 4.80 4600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 3.60 4700.0 0.0 +0 +endtrack +node -1 0 hl_56 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 3.60 4700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 2.40 4800.0 0.0 +0 +endtrack +node -1 0 hl_57 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 2.40 4800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 1.20 4900.0 0.0 +0 +endtrack +node -1 0 hl_58 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 1.20 4900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -0.00 5000.0 0.0 +0 +endtrack +node -1 0 hl_59 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -0.00 5000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -1.20 5100.0 0.0 +0 +endtrack +node -1 0 hl_60 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -1.20 5100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -2.40 5200.0 0.0 +0 +endtrack +node -1 0 hl_61 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -2.40 5200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -3.60 5300.0 0.0 +0 +endtrack +node -1 0 hl_62 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -3.60 5300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -4.80 5400.0 0.0 +0 +endtrack +node -1 0 hl_63 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -4.80 5400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -6.00 5500.0 0.0 +0 +endtrack +node -1 0 hl_64 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -6.00 5500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -7.20 5600.0 0.0 +0 +endtrack +node -1 0 hl_65 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -7.20 5600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -8.40 5700.0 0.0 +0 +endtrack +node -1 0 hl_66 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -8.40 5700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -9.60 5800.0 0.0 +0 +endtrack +node -1 0 hl_67 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -9.60 5800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -10.80 5900.0 0.0 +0 +endtrack +node -1 0 hl_68 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -10.80 5900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -12.00 6000.0 0.0 +0 +event2 hl_sem_info +endtrack +node -1 0 hl_69 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -12.00 6000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -13.20 6100.0 0.0 +0 +endtrack +node -1 0 hl_70 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -13.20 6100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -14.40 6200.0 0.0 +0 +endtrack +node -1 0 hl_71 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -14.40 6200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -15.60 6300.0 0.0 +0 +endtrack +node -1 0 hl_72 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -15.60 6300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -16.80 6400.0 0.0 +0 +endtrack +node -1 0 hl_73 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -16.80 6400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -18.00 6500.0 0.0 +0 +endtrack +// the W4 of the stations of the timetable +include ip/pkp/w4n.inc gora#1 -2997.3 60.00 -90.0 180 0 0 -10 202 end +// a signal at stop: what the AI reads of one, a memory cell with SetVelocity 0 0 and the event that reads it +node -1 0 hl_sem_mem memcell -2997.3 -4.00 6000.0 SetVelocity 0.0 0.0 none endmemcell +event hl_sem_info getvalues 5.0 hl_sem_mem endevent + +trainset {{timetable}} hl_08 0.0 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_downgrade_restriction.scn b/tests/scenarios/cases/td_downgrade_restriction.scn new file mode 100644 index 000000000..42c7cf775 --- /dev/null +++ b/tests/scenarios/cases/td_downgrade_restriction.scn @@ -0,0 +1,638 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a line of its own, away from the tracks of td.scn: 600 m level, then 3500 m down a gradient of 20 per mille, +// under an overhead wire. the train starts on the level with its head 10 m before the W4 of Gora and runs on the timetable +// {{timetable}} (no stop; a freight train leaves Gora at once): its line limit, a 20 km/h restriction from 1500 to 1900 m +// down the gradient, then the signal hr_sem at stop 3000 m down the gradient. the line goes on 500 m past the signal +node -1 0 hr_00 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -500.0 0.0 +0 +endtrack +node -1 0 hr_01 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -400.0 0.0 +0 +endtrack +node -1 0 hr_02 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -300.0 0.0 +0 +endtrack +node -1 0 hr_03 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -200.0 0.0 +0 +endtrack +node -1 0 hr_04 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -100.0 0.0 +0 +endtrack +node -1 0 hr_05 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 0.0 0.0 +0 +event2 gora#1_stopinfo +endtrack +node -1 0 hr_06 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 0.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 58.00 100.0 0.0 +0 +endtrack +node -1 0 hr_07 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 58.00 100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 56.00 200.0 0.0 +0 +endtrack +node -1 0 hr_08 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 56.00 200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 54.00 300.0 0.0 +0 +endtrack +node -1 0 hr_09 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 54.00 300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 52.00 400.0 0.0 +0 +endtrack +node -1 0 hr_10 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 52.00 400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 50.00 500.0 0.0 +0 +endtrack +node -1 0 hr_11 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 50.00 500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 48.00 600.0 0.0 +0 +endtrack +node -1 0 hr_12 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 48.00 600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 46.00 700.0 0.0 +0 +endtrack +node -1 0 hr_13 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 46.00 700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 44.00 800.0 0.0 +0 +endtrack +node -1 0 hr_14 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 44.00 800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 42.00 900.0 0.0 +0 +endtrack +node -1 0 hr_15 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 42.00 900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 40.00 1000.0 0.0 +0 +endtrack +node -1 0 hr_16 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 40.00 1000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 38.00 1100.0 0.0 +0 +endtrack +node -1 0 hr_17 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 38.00 1100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 36.00 1200.0 0.0 +0 +endtrack +node -1 0 hr_18 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 36.00 1200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 34.00 1300.0 0.0 +0 +endtrack +node -1 0 hr_19 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 34.00 1300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 32.00 1400.0 0.0 +0 +endtrack +node -1 0 hr_20 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 32.00 1400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 30.00 1500.0 0.0 +0 +endtrack +node -1 0 hr_21 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 30.00 1500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 28.00 1600.0 0.0 +0 +velocity 20 +endtrack +node -1 0 hr_22 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 28.00 1600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 26.00 1700.0 0.0 +0 +velocity 20 +endtrack +node -1 0 hr_23 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 26.00 1700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 24.00 1800.0 0.0 +0 +velocity 20 +endtrack +node -1 0 hr_24 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 24.00 1800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 22.00 1900.0 0.0 +0 +velocity 20 +endtrack +node -1 0 hr_25 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 22.00 1900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 20.00 2000.0 0.0 +0 +endtrack +node -1 0 hr_26 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 20.00 2000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 18.00 2100.0 0.0 +0 +endtrack +node -1 0 hr_27 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 18.00 2100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 16.00 2200.0 0.0 +0 +endtrack +node -1 0 hr_28 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 16.00 2200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 14.00 2300.0 0.0 +0 +endtrack +node -1 0 hr_29 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 14.00 2300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 12.00 2400.0 0.0 +0 +endtrack +node -1 0 hr_30 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 12.00 2400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 10.00 2500.0 0.0 +0 +endtrack +node -1 0 hr_31 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 10.00 2500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 8.00 2600.0 0.0 +0 +endtrack +node -1 0 hr_32 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 8.00 2600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 6.00 2700.0 0.0 +0 +endtrack +node -1 0 hr_33 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 6.00 2700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 4.00 2800.0 0.0 +0 +endtrack +node -1 0 hr_34 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 4.00 2800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 2.00 2900.0 0.0 +0 +endtrack +node -1 0 hr_35 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 2.00 2900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 0.00 3000.0 0.0 +0 +event2 hr_sem_info +endtrack +node -1 0 hr_36 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 0.00 3000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -2.00 3100.0 0.0 +0 +endtrack +node -1 0 hr_37 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -2.00 3100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -4.00 3200.0 0.0 +0 +endtrack +node -1 0 hr_38 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -4.00 3200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -6.00 3300.0 0.0 +0 +endtrack +node -1 0 hr_39 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -6.00 3300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -8.00 3400.0 0.0 +0 +endtrack +node -1 0 hr_40 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -8.00 3400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -10.00 3500.0 0.0 +0 +endtrack +// the overhead wire along the whole line, as td.scn has it: 5.6 m above the rail, the carrier 1.7 m higher, fed by +// a substation of its own +node -1 0 hr_pwr tractionpowersource -3000.0 60.00 0.0 3400 0 0.01 2000 1.0 3 60.0 end +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -600.0 +-3000.0 65.60 -500.0 +-3000.0 67.30 -600.0 +-3000.0 67.30 -500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -500.0 +-3000.0 65.60 -400.0 +-3000.0 67.30 -500.0 +-3000.0 67.30 -400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -400.0 +-3000.0 65.60 -300.0 +-3000.0 67.30 -400.0 +-3000.0 67.30 -300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -300.0 +-3000.0 65.60 -200.0 +-3000.0 67.30 -300.0 +-3000.0 67.30 -200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -200.0 +-3000.0 65.60 -100.0 +-3000.0 67.30 -200.0 +-3000.0 67.30 -100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -100.0 +-3000.0 65.60 0.0 +-3000.0 67.30 -100.0 +-3000.0 67.30 0.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 0.0 +-3000.0 63.60 100.0 +-3000.0 67.30 0.0 +-3000.0 65.30 100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 63.60 100.0 +-3000.0 61.60 200.0 +-3000.0 65.30 100.0 +-3000.0 63.30 200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 61.60 200.0 +-3000.0 59.60 300.0 +-3000.0 63.30 200.0 +-3000.0 61.30 300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 59.60 300.0 +-3000.0 57.60 400.0 +-3000.0 61.30 300.0 +-3000.0 59.30 400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 57.60 400.0 +-3000.0 55.60 500.0 +-3000.0 59.30 400.0 +-3000.0 57.30 500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 55.60 500.0 +-3000.0 53.60 600.0 +-3000.0 57.30 500.0 +-3000.0 55.30 600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 53.60 600.0 +-3000.0 51.60 700.0 +-3000.0 55.30 600.0 +-3000.0 53.30 700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 51.60 700.0 +-3000.0 49.60 800.0 +-3000.0 53.30 700.0 +-3000.0 51.30 800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 49.60 800.0 +-3000.0 47.60 900.0 +-3000.0 51.30 800.0 +-3000.0 49.30 900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 47.60 900.0 +-3000.0 45.60 1000.0 +-3000.0 49.30 900.0 +-3000.0 47.30 1000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 45.60 1000.0 +-3000.0 43.60 1100.0 +-3000.0 47.30 1000.0 +-3000.0 45.30 1100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 43.60 1100.0 +-3000.0 41.60 1200.0 +-3000.0 45.30 1100.0 +-3000.0 43.30 1200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 41.60 1200.0 +-3000.0 39.60 1300.0 +-3000.0 43.30 1200.0 +-3000.0 41.30 1300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 39.60 1300.0 +-3000.0 37.60 1400.0 +-3000.0 41.30 1300.0 +-3000.0 39.30 1400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 37.60 1400.0 +-3000.0 35.60 1500.0 +-3000.0 39.30 1400.0 +-3000.0 37.30 1500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 35.60 1500.0 +-3000.0 33.60 1600.0 +-3000.0 37.30 1500.0 +-3000.0 35.30 1600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 33.60 1600.0 +-3000.0 31.60 1700.0 +-3000.0 35.30 1600.0 +-3000.0 33.30 1700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 31.60 1700.0 +-3000.0 29.60 1800.0 +-3000.0 33.30 1700.0 +-3000.0 31.30 1800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 29.60 1800.0 +-3000.0 27.60 1900.0 +-3000.0 31.30 1800.0 +-3000.0 29.30 1900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 27.60 1900.0 +-3000.0 25.60 2000.0 +-3000.0 29.30 1900.0 +-3000.0 27.30 2000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 25.60 2000.0 +-3000.0 23.60 2100.0 +-3000.0 27.30 2000.0 +-3000.0 25.30 2100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 23.60 2100.0 +-3000.0 21.60 2200.0 +-3000.0 25.30 2100.0 +-3000.0 23.30 2200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 21.60 2200.0 +-3000.0 19.60 2300.0 +-3000.0 23.30 2200.0 +-3000.0 21.30 2300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 19.60 2300.0 +-3000.0 17.60 2400.0 +-3000.0 21.30 2300.0 +-3000.0 19.30 2400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 17.60 2400.0 +-3000.0 15.60 2500.0 +-3000.0 19.30 2400.0 +-3000.0 17.30 2500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 15.60 2500.0 +-3000.0 13.60 2600.0 +-3000.0 17.30 2500.0 +-3000.0 15.30 2600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 13.60 2600.0 +-3000.0 11.60 2700.0 +-3000.0 15.30 2600.0 +-3000.0 13.30 2700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 11.60 2700.0 +-3000.0 9.60 2800.0 +-3000.0 13.30 2700.0 +-3000.0 11.30 2800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 9.60 2800.0 +-3000.0 7.60 2900.0 +-3000.0 11.30 2800.0 +-3000.0 9.30 2900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 7.60 2900.0 +-3000.0 5.60 3000.0 +-3000.0 9.30 2900.0 +-3000.0 7.30 3000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 5.60 3000.0 +-3000.0 3.60 3100.0 +-3000.0 7.30 3000.0 +-3000.0 5.30 3100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 3.60 3100.0 +-3000.0 1.60 3200.0 +-3000.0 5.30 3100.0 +-3000.0 3.30 3200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 1.60 3200.0 +-3000.0 -0.40 3300.0 +-3000.0 3.30 3200.0 +-3000.0 1.30 3300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 -0.40 3300.0 +-3000.0 -2.40 3400.0 +-3000.0 1.30 3300.0 +-3000.0 -0.70 3400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 -2.40 3400.0 +-3000.0 -4.40 3500.0 +-3000.0 -0.70 3400.0 +-3000.0 -2.70 3500.0 +0.4 4.0 3 0.04 vis +endtraction +// the W4 of the stations of the timetable +include ip/pkp/w4n.inc gora#1 -2997.3 60.00 -90.0 180 0 0 -10 202 end +// a signal at stop: what the AI reads of one, a memory cell with SetVelocity 0 0 and the event that reads it +node -1 0 hr_sem_mem memcell -2997.3 8.00 3000.0 SetVelocity 0.0 0.0 none endmemcell +event hr_sem_info getvalues 5.0 hr_sem_mem endevent + +trainset {{timetable}} hr_05 0.0 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_downgrade_w4_signal.scn b/tests/scenarios/cases/td_downgrade_w4_signal.scn new file mode 100644 index 000000000..ffa43ecc3 --- /dev/null +++ b/tests/scenarios/cases/td_downgrade_w4_signal.scn @@ -0,0 +1,518 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a line of its own, away from the tracks of td.scn: 300 m level, then 3000 m down a gradient of 20 per mille, +// under an overhead wire. +// the train starts on the level, with the W4 of Gora about 40 m ahead, and runs on the timetable {{timetable}}: +// Gora 10:35 -> Dol, a W4 1500 m down the gradient (stop, leaves at 10:38) -> the signal gr_sem, 1100 m further +// down, which stays at stop. the line goes on 400 m past the signal +node -1 0 gr_00 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -200.0 0.0 +0 +endtrack +node -1 0 gr_01 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -100.0 0.0 +0 +endtrack +node -1 0 gr_02 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 0.0 0.0 +0 +event2 gora#1_stopinfo +endtrack +node -1 0 gr_03 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 0.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 58.00 100.0 0.0 +0 +endtrack +node -1 0 gr_04 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 58.00 100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 56.00 200.0 0.0 +0 +endtrack +node -1 0 gr_05 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 56.00 200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 54.00 300.0 0.0 +0 +endtrack +node -1 0 gr_06 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 54.00 300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 52.00 400.0 0.0 +0 +endtrack +node -1 0 gr_07 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 52.00 400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 50.00 500.0 0.0 +0 +endtrack +node -1 0 gr_08 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 50.00 500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 48.00 600.0 0.0 +0 +endtrack +node -1 0 gr_09 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 48.00 600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 46.00 700.0 0.0 +0 +endtrack +node -1 0 gr_10 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 46.00 700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 44.00 800.0 0.0 +0 +endtrack +node -1 0 gr_11 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 44.00 800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 42.00 900.0 0.0 +0 +endtrack +node -1 0 gr_12 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 42.00 900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 40.00 1000.0 0.0 +0 +endtrack +node -1 0 gr_13 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 40.00 1000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 38.00 1100.0 0.0 +0 +endtrack +node -1 0 gr_14 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 38.00 1100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 36.00 1200.0 0.0 +0 +endtrack +node -1 0 gr_15 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 36.00 1200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 34.00 1300.0 0.0 +0 +endtrack +node -1 0 gr_16 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 34.00 1300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 32.00 1400.0 0.0 +0 +endtrack +node -1 0 gr_17 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 32.00 1400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 30.00 1500.0 0.0 +0 +event2 dol#1_stopinfo +endtrack +node -1 0 gr_18 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 30.00 1500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 28.00 1600.0 0.0 +0 +endtrack +node -1 0 gr_19 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 28.00 1600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 26.00 1700.0 0.0 +0 +endtrack +node -1 0 gr_20 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 26.00 1700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 24.00 1800.0 0.0 +0 +endtrack +node -1 0 gr_21 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 24.00 1800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 22.00 1900.0 0.0 +0 +endtrack +node -1 0 gr_22 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 22.00 1900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 20.00 2000.0 0.0 +0 +endtrack +node -1 0 gr_23 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 20.00 2000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 18.00 2100.0 0.0 +0 +endtrack +node -1 0 gr_24 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 18.00 2100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 16.00 2200.0 0.0 +0 +endtrack +node -1 0 gr_25 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 16.00 2200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 14.00 2300.0 0.0 +0 +endtrack +node -1 0 gr_26 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 14.00 2300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 12.00 2400.0 0.0 +0 +endtrack +node -1 0 gr_27 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 12.00 2400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 10.00 2500.0 0.0 +0 +endtrack +node -1 0 gr_28 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 10.00 2500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 8.00 2600.0 0.0 +0 +event2 gr_sem_info +endtrack +node -1 0 gr_29 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 8.00 2600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 6.00 2700.0 0.0 +0 +endtrack +node -1 0 gr_30 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 6.00 2700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 4.00 2800.0 0.0 +0 +endtrack +node -1 0 gr_31 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 4.00 2800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 2.00 2900.0 0.0 +0 +endtrack +node -1 0 gr_32 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 2.00 2900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 0.00 3000.0 0.0 +0 +endtrack +// the overhead wire along the whole line, as td.scn has it: 5.6 m above the rail, the carrier 1.7 m higher, fed by +// a substation of its own +node -1 0 gr_pwr tractionpowersource -3000.0 60.00 0.0 3400 0 0.01 2000 1.0 3 60.0 end +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -300.0 +-3000.0 65.60 -200.0 +-3000.0 67.30 -300.0 +-3000.0 67.30 -200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -200.0 +-3000.0 65.60 -100.0 +-3000.0 67.30 -200.0 +-3000.0 67.30 -100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -100.0 +-3000.0 65.60 0.0 +-3000.0 67.30 -100.0 +-3000.0 67.30 0.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 0.0 +-3000.0 63.60 100.0 +-3000.0 67.30 0.0 +-3000.0 65.30 100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 63.60 100.0 +-3000.0 61.60 200.0 +-3000.0 65.30 100.0 +-3000.0 63.30 200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 61.60 200.0 +-3000.0 59.60 300.0 +-3000.0 63.30 200.0 +-3000.0 61.30 300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 59.60 300.0 +-3000.0 57.60 400.0 +-3000.0 61.30 300.0 +-3000.0 59.30 400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 57.60 400.0 +-3000.0 55.60 500.0 +-3000.0 59.30 400.0 +-3000.0 57.30 500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 55.60 500.0 +-3000.0 53.60 600.0 +-3000.0 57.30 500.0 +-3000.0 55.30 600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 53.60 600.0 +-3000.0 51.60 700.0 +-3000.0 55.30 600.0 +-3000.0 53.30 700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 51.60 700.0 +-3000.0 49.60 800.0 +-3000.0 53.30 700.0 +-3000.0 51.30 800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 49.60 800.0 +-3000.0 47.60 900.0 +-3000.0 51.30 800.0 +-3000.0 49.30 900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 47.60 900.0 +-3000.0 45.60 1000.0 +-3000.0 49.30 900.0 +-3000.0 47.30 1000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 45.60 1000.0 +-3000.0 43.60 1100.0 +-3000.0 47.30 1000.0 +-3000.0 45.30 1100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 43.60 1100.0 +-3000.0 41.60 1200.0 +-3000.0 45.30 1100.0 +-3000.0 43.30 1200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 41.60 1200.0 +-3000.0 39.60 1300.0 +-3000.0 43.30 1200.0 +-3000.0 41.30 1300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 39.60 1300.0 +-3000.0 37.60 1400.0 +-3000.0 41.30 1300.0 +-3000.0 39.30 1400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 37.60 1400.0 +-3000.0 35.60 1500.0 +-3000.0 39.30 1400.0 +-3000.0 37.30 1500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 35.60 1500.0 +-3000.0 33.60 1600.0 +-3000.0 37.30 1500.0 +-3000.0 35.30 1600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 33.60 1600.0 +-3000.0 31.60 1700.0 +-3000.0 35.30 1600.0 +-3000.0 33.30 1700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 31.60 1700.0 +-3000.0 29.60 1800.0 +-3000.0 33.30 1700.0 +-3000.0 31.30 1800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 29.60 1800.0 +-3000.0 27.60 1900.0 +-3000.0 31.30 1800.0 +-3000.0 29.30 1900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 27.60 1900.0 +-3000.0 25.60 2000.0 +-3000.0 29.30 1900.0 +-3000.0 27.30 2000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 25.60 2000.0 +-3000.0 23.60 2100.0 +-3000.0 27.30 2000.0 +-3000.0 25.30 2100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 23.60 2100.0 +-3000.0 21.60 2200.0 +-3000.0 25.30 2100.0 +-3000.0 23.30 2200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 21.60 2200.0 +-3000.0 19.60 2300.0 +-3000.0 23.30 2200.0 +-3000.0 21.30 2300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 19.60 2300.0 +-3000.0 17.60 2400.0 +-3000.0 21.30 2300.0 +-3000.0 19.30 2400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 17.60 2400.0 +-3000.0 15.60 2500.0 +-3000.0 19.30 2400.0 +-3000.0 17.30 2500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 15.60 2500.0 +-3000.0 13.60 2600.0 +-3000.0 17.30 2500.0 +-3000.0 15.30 2600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 13.60 2600.0 +-3000.0 11.60 2700.0 +-3000.0 15.30 2600.0 +-3000.0 13.30 2700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 11.60 2700.0 +-3000.0 9.60 2800.0 +-3000.0 13.30 2700.0 +-3000.0 11.30 2800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 9.60 2800.0 +-3000.0 7.60 2900.0 +-3000.0 11.30 2800.0 +-3000.0 9.30 2900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 7.60 2900.0 +-3000.0 5.60 3000.0 +-3000.0 9.30 2900.0 +-3000.0 7.30 3000.0 +0.4 4.0 3 0.04 vis +endtraction + +// the W4 of the two stations of the timetable; the middle of the consist 2 m before it, leaves on time +include ip/pkp/w4n.inc gora#1 -2997.3 60.00 -60.0 180 0 0 2 202 end +include ip/pkp/w4n.inc dol#1 -2997.3 30.00 1500.0 180 0 0 2 202 end +// a signal at stop: what the AI reads of one, a memory cell with SetVelocity 0 0 and the event that reads it +node -1 0 gr_sem_mem memcell -2997.3 8.00 2600.0 SetVelocity 0.0 0.0 none endmemcell +event gr_sem_info getvalues 5.0 gr_sem_mem endevent + +trainset {{timetable}} gr_02 0.0 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_freight_downgrade.txt b/tests/scenarios/cases/td_freight_downgrade.txt new file mode 100644 index 000000000..1fd01f911 --- /dev/null +++ b/tests/scenarios/cases/td_freight_downgrade.txt @@ -0,0 +1,17 @@ +________________________________________________________________ +[ Rodzaj i numer pociagu | TEST44 ] +[ Kategoria | TME ] +[________________________________________________|______________] +[ | Gora ] +[ Relacja pociagu | Koniec ] +[________________________________________________|______________] +[ Wymagany % ciezaru hamujacego | 50% ] +[________________________________________________|______________] +[ Seria i obciazenie lokomotywy | ET41 1700 ] +[________________________________________________|______________] +[ | | Gora 2 | | ] +[ | 60 | R1,L,H,RT,PP 2 10.35 | ] +[ | |----------------------------------1----------|---] +[ | | Koniec 1 10.55 | 20] +[ | | R1 1 10.56 | ] +[_______|_____|__________________________________1__________|___] diff --git a/tests/scenarios/cases/td_freight_downgrade12.txt b/tests/scenarios/cases/td_freight_downgrade12.txt new file mode 100644 index 000000000..1fc503342 --- /dev/null +++ b/tests/scenarios/cases/td_freight_downgrade12.txt @@ -0,0 +1,17 @@ +________________________________________________________________ +[ Rodzaj i numer pociagu | TEST45 ] +[ Kategoria | TME ] +[________________________________________________|______________] +[ | Gora ] +[ Relacja pociagu | Koniec ] +[________________________________________________|______________] +[ Wymagany % ciezaru hamujacego | 50% ] +[________________________________________________|______________] +[ Seria i obciazenie lokomotywy | ST43 3000 ] +[________________________________________________|______________] +[ | | Gora 2 | | ] +[ | 40 | R1,L,H,RT,PP 2 10.35 | ] +[ | |----------------------------------1----------|---] +[ | | Koniec 1 11.10 | 35] +[ | | R1 1 11.11 | ] +[_______|_____|__________________________________1__________|___] diff --git a/tests/scenarios/cases/td_level_signal.scn b/tests/scenarios/cases/td_level_signal.scn new file mode 100644 index 000000000..c3d13eb87 --- /dev/null +++ b/tests/scenarios/cases/td_level_signal.scn @@ -0,0 +1,333 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a line of its own, away from the tracks of td.scn: 2100 m level, under an overhead wire. the train starts with +// its head 10 m before the W4 of Gora and runs on the timetable {{timetable}} (no stop; a freight train leaves Gora at once) to the signal +// lv_sem at stop 1000 m ahead. the line goes on 500 m past it +node -1 0 lv_00 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -500.0 0.0 +0 +endtrack +node -1 0 lv_01 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -400.0 0.0 +0 +endtrack +node -1 0 lv_02 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -300.0 0.0 +0 +endtrack +node -1 0 lv_03 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -200.0 0.0 +0 +endtrack +node -1 0 lv_04 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -100.0 0.0 +0 +endtrack +node -1 0 lv_05 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 0.0 0.0 +0 +event2 gora#1_stopinfo +endtrack +node -1 0 lv_06 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 0.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 100.0 0.0 +0 +endtrack +node -1 0 lv_07 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 200.0 0.0 +0 +endtrack +node -1 0 lv_08 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 300.0 0.0 +0 +endtrack +node -1 0 lv_09 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 400.0 0.0 +0 +endtrack +node -1 0 lv_10 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 500.0 0.0 +0 +endtrack +node -1 0 lv_11 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 600.0 0.0 +0 +endtrack +node -1 0 lv_12 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 700.0 0.0 +0 +endtrack +node -1 0 lv_13 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 800.0 0.0 +0 +endtrack +node -1 0 lv_14 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 900.0 0.0 +0 +endtrack +node -1 0 lv_15 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 1000.0 0.0 +0 +event2 lv_sem_info +endtrack +node -1 0 lv_16 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 1000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 1100.0 0.0 +0 +endtrack +node -1 0 lv_17 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 1100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 1200.0 0.0 +0 +endtrack +node -1 0 lv_18 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 1200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 1300.0 0.0 +0 +endtrack +node -1 0 lv_19 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 1300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 1400.0 0.0 +0 +endtrack +node -1 0 lv_20 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 1400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 1500.0 0.0 +0 +endtrack +// the overhead wire along the whole line, as td.scn has it: 5.6 m above the rail, the carrier 1.7 m higher, fed by +// a substation of its own +node -1 0 lv_pwr tractionpowersource -3000.0 60.00 0.0 3400 0 0.01 2000 1.0 3 60.0 end +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -600.0 +-3000.0 65.60 -500.0 +-3000.0 67.30 -600.0 +-3000.0 67.30 -500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -500.0 +-3000.0 65.60 -400.0 +-3000.0 67.30 -500.0 +-3000.0 67.30 -400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -400.0 +-3000.0 65.60 -300.0 +-3000.0 67.30 -400.0 +-3000.0 67.30 -300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -300.0 +-3000.0 65.60 -200.0 +-3000.0 67.30 -300.0 +-3000.0 67.30 -200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -200.0 +-3000.0 65.60 -100.0 +-3000.0 67.30 -200.0 +-3000.0 67.30 -100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -100.0 +-3000.0 65.60 0.0 +-3000.0 67.30 -100.0 +-3000.0 67.30 0.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 0.0 +-3000.0 65.60 100.0 +-3000.0 67.30 0.0 +-3000.0 67.30 100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 100.0 +-3000.0 65.60 200.0 +-3000.0 67.30 100.0 +-3000.0 67.30 200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 200.0 +-3000.0 65.60 300.0 +-3000.0 67.30 200.0 +-3000.0 67.30 300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 300.0 +-3000.0 65.60 400.0 +-3000.0 67.30 300.0 +-3000.0 67.30 400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 400.0 +-3000.0 65.60 500.0 +-3000.0 67.30 400.0 +-3000.0 67.30 500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 500.0 +-3000.0 65.60 600.0 +-3000.0 67.30 500.0 +-3000.0 67.30 600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 600.0 +-3000.0 65.60 700.0 +-3000.0 67.30 600.0 +-3000.0 67.30 700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 700.0 +-3000.0 65.60 800.0 +-3000.0 67.30 700.0 +-3000.0 67.30 800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 800.0 +-3000.0 65.60 900.0 +-3000.0 67.30 800.0 +-3000.0 67.30 900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 900.0 +-3000.0 65.60 1000.0 +-3000.0 67.30 900.0 +-3000.0 67.30 1000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 1000.0 +-3000.0 65.60 1100.0 +-3000.0 67.30 1000.0 +-3000.0 67.30 1100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 1100.0 +-3000.0 65.60 1200.0 +-3000.0 67.30 1100.0 +-3000.0 67.30 1200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 1200.0 +-3000.0 65.60 1300.0 +-3000.0 67.30 1200.0 +-3000.0 67.30 1300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 1300.0 +-3000.0 65.60 1400.0 +-3000.0 67.30 1300.0 +-3000.0 67.30 1400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 1400.0 +-3000.0 65.60 1500.0 +-3000.0 67.30 1400.0 +-3000.0 67.30 1500.0 +0.4 4.0 3 0.04 vis +endtraction +// the W4 of the stations of the timetable +include ip/pkp/w4n.inc gora#1 -2997.3 60.00 -90.0 180 0 0 -10 202 end +// a signal at stop: what the AI reads of one, a memory cell with SetVelocity 0 0 and the event that reads it +node -1 0 lv_sem_mem memcell -2997.3 68.00 1000.0 SetVelocity 0.0 0.0 none endmemcell +event lv_sem_info getvalues 5.0 lv_sem_mem endevent + +trainset {{timetable}} lv_05 0.0 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_no_wire.scn b/tests/scenarios/cases/td_no_wire.scn new file mode 100644 index 000000000..edca73c0b --- /dev/null +++ b/tests/scenarios/cases/td_no_wire.scn @@ -0,0 +1,18 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a piece of track of its own, 200 m long and with no overhead wire above it, 400 m off the line of td.scn +// (all of whose tracks are under the wire), and an electric locomotive with an AI driver standing on it. +// the driver raises the pantographs, which find no wire, and waits in Prepare_engine for the voltage for good +// (eu07/maszyna#421); it tells of it in the log once. +node -1 0 autotest_no_wire track normal 200.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-400.0 0.2 0.0 0.0 //point 1 +0.0 0.0 0.0 //control vector 1 +0.0 0.0 0.0 //control vector 2 +-400.0 0.2 200.0 0.0 //point 2 +0 +endtrack + +// no timetable: the driver goes shunting; 0.01 km/h has it prepare the vehicle and wait for a signal (at 0 it sleeps) +trainset none autotest_no_wire 100.0 0.01 +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_off_track.scn b/tests/scenarios/cases/td_off_track.scn new file mode 100644 index 000000000..0318e961d --- /dev/null +++ b/tests/scenarios/cases/td_off_track.scn @@ -0,0 +1,14 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed (physics.derailment new, the vehicles +// off the track moving on the ground, vehicle/derailmotion.h): +// an EU07 with an AI driver and no timetable stands on track 1 of Stacja1, where td.scn keeps its timetable train, +// so it stays put and logs its physics; the train of the case has no driver and runs at {{velocity}} km/h from +// {{offset}} m past point 1 of {{track}} towards its point 2. on the line of td.scn, from tdo_n157 on, that is the +// curve of R 600 m (tdo_n213, tdo_n222, tdo_n231), cant 65 mm +{{track_nodes}} +trainset none tdo_n1734 0.0 0.0 +node -1 0 {{vehicle}} dynamic pkp\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic +endtrainset + +trainset none {{track}} {{offset}} {{velocity}} +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_off_track_curve_cutting.scn b/tests/scenarios/cases/td_off_track_curve_cutting.scn new file mode 100644 index 000000000..2c32a3f50 --- /dev/null +++ b/tests/scenarios/cases/td_off_track_curve_cutting.scn @@ -0,0 +1,441 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed (physics.derailment new, the vehicles +// off the track moving on the ground, vehicle/derailmotion.h): a track of R 300 m without cant laid on its own in the +// fields of td.scn (autotest_curve), in a cutting with banks of 1:1.5 4 m high, the ground rising on beyond them at 1:5; written by a script, see the README. +// an EU07 with an AI driver and no timetable stands on track 1 of Stacja1, where td.scn keeps its timetable train, so +// it stays put and logs its physics; the EU07 of the case has no driver and runs at {{velocity}} km/h from 20 m past +// point 1 of the curve towards its point 2 +node -1 0 none triangle_strip grass +-456.70 32.10 355.67 0 1 0 0 0 end +-322.47 4.00 314.15 0 1 0 0 0 end +-455.43 32.10 359.99 0 1 0 0 0 end +-320.02 4.00 322.51 0 1 0 0 0 end +-454.30 32.10 364.34 0 1 0 0 0 end +-317.83 4.00 330.95 0 1 0 0 0 end +-453.30 32.10 368.73 0 1 0 0 0 end +-315.88 4.00 339.44 0 1 0 0 0 end +-452.42 32.10 373.15 0 1 0 0 0 end +-314.19 4.00 347.99 0 1 0 0 0 end +-451.68 32.10 377.58 0 1 0 0 0 end +-312.76 4.00 356.59 0 1 0 0 0 end +-451.08 32.10 382.04 0 1 0 0 0 end +-311.59 4.00 365.22 0 1 0 0 0 end +-450.61 32.10 386.52 0 1 0 0 0 end +-310.68 4.00 373.89 0 1 0 0 0 end +-450.27 32.10 391.01 0 1 0 0 0 end +-310.02 4.00 382.58 0 1 0 0 0 end +-450.07 32.10 395.50 0 1 0 0 0 end +-309.63 4.00 391.29 0 1 0 0 0 end +-450.00 32.10 400.00 0 1 0 0 0 end +-309.50 4.00 400.00 0 1 0 0 0 end +-450.07 32.10 404.50 0 1 0 0 0 end +-309.63 4.00 408.71 0 1 0 0 0 end +-450.27 32.10 408.99 0 1 0 0 0 end +-310.02 4.00 417.42 0 1 0 0 0 end +-450.61 32.10 413.48 0 1 0 0 0 end +-310.68 4.00 426.11 0 1 0 0 0 end +-451.08 32.10 417.96 0 1 0 0 0 end +-311.59 4.00 434.78 0 1 0 0 0 end +-451.68 32.10 422.42 0 1 0 0 0 end +-312.76 4.00 443.41 0 1 0 0 0 end +-452.42 32.10 426.85 0 1 0 0 0 end +-314.19 4.00 452.01 0 1 0 0 0 end +-453.30 32.10 431.27 0 1 0 0 0 end +-315.88 4.00 460.56 0 1 0 0 0 end +-454.30 32.10 435.66 0 1 0 0 0 end +-317.83 4.00 469.05 0 1 0 0 0 end +-455.43 32.10 440.01 0 1 0 0 0 end +-320.02 4.00 477.49 0 1 0 0 0 end +-456.70 32.10 444.33 0 1 0 0 0 end +-322.47 4.00 485.85 0 1 0 0 0 end +-458.09 32.10 448.61 0 1 0 0 0 end +-325.17 4.00 494.13 0 1 0 0 0 end +-459.62 32.10 452.84 0 1 0 0 0 end +-328.12 4.00 502.34 0 1 0 0 0 end +-461.26 32.10 457.03 0 1 0 0 0 end +-331.31 4.00 510.44 0 1 0 0 0 end +-463.04 32.10 461.16 0 1 0 0 0 end +-334.75 4.00 518.45 0 1 0 0 0 end +-464.93 32.10 465.24 0 1 0 0 0 end +-338.42 4.00 526.36 0 1 0 0 0 end +-466.95 32.10 469.27 0 1 0 0 0 end +-342.33 4.00 534.15 0 1 0 0 0 end +-469.09 32.10 473.23 0 1 0 0 0 end +-346.47 4.00 541.82 0 1 0 0 0 end +-471.34 32.10 477.12 0 1 0 0 0 end +-350.84 4.00 549.36 0 1 0 0 0 end +-473.71 32.10 480.94 0 1 0 0 0 end +-355.43 4.00 556.76 0 1 0 0 0 end +-476.20 32.10 484.70 0 1 0 0 0 end +-360.24 4.00 564.03 0 1 0 0 0 end +-478.80 32.10 488.37 0 1 0 0 0 end +-365.27 4.00 571.15 0 1 0 0 0 end +-481.50 32.10 491.97 0 1 0 0 0 end +-370.51 4.00 578.11 0 1 0 0 0 end +-484.31 32.10 495.48 0 1 0 0 0 end +-375.95 4.00 584.91 0 1 0 0 0 end +-487.23 32.10 498.91 0 1 0 0 0 end +-381.60 4.00 591.55 0 1 0 0 0 end +-490.25 32.10 502.25 0 1 0 0 0 end +-387.44 4.00 598.02 0 1 0 0 0 end +-493.36 32.10 505.49 0 1 0 0 0 end +-393.48 4.00 604.30 0 1 0 0 0 end +-496.58 32.10 508.64 0 1 0 0 0 end +-399.70 4.00 610.41 0 1 0 0 0 end +-499.88 32.10 511.70 0 1 0 0 0 end +-406.10 4.00 616.32 0 1 0 0 0 end +-503.28 32.10 514.65 0 1 0 0 0 end +-412.68 4.00 622.04 0 1 0 0 0 end +-506.76 32.10 517.50 0 1 0 0 0 end +-419.42 4.00 627.56 0 1 0 0 0 +endtri +node -1 0 none triangle_strip grass +-322.47 4.00 314.15 0 1 0 0 0 end +-316.74 0.00 312.38 0 1 0 0 0 end +-320.02 4.00 322.51 0 1 0 0 0 end +-314.24 0.00 320.91 0 1 0 0 0 end +-317.83 4.00 330.95 0 1 0 0 0 end +-312.00 0.00 329.52 0 1 0 0 0 end +-315.88 4.00 339.44 0 1 0 0 0 end +-310.01 0.00 338.19 0 1 0 0 0 end +-314.19 4.00 347.99 0 1 0 0 0 end +-308.29 0.00 346.92 0 1 0 0 0 end +-312.76 4.00 356.59 0 1 0 0 0 end +-306.83 0.00 355.69 0 1 0 0 0 end +-311.59 4.00 365.22 0 1 0 0 0 end +-305.63 0.00 364.51 0 1 0 0 0 end +-310.68 4.00 373.89 0 1 0 0 0 end +-304.70 0.00 373.35 0 1 0 0 0 end +-310.02 4.00 382.58 0 1 0 0 0 end +-304.03 0.00 382.22 0 1 0 0 0 end +-309.63 4.00 391.29 0 1 0 0 0 end +-303.63 0.00 391.11 0 1 0 0 0 end +-309.50 4.00 400.00 0 1 0 0 0 end +-303.50 0.00 400.00 0 1 0 0 0 end +-309.63 4.00 408.71 0 1 0 0 0 end +-303.63 0.00 408.89 0 1 0 0 0 end +-310.02 4.00 417.42 0 1 0 0 0 end +-304.03 0.00 417.78 0 1 0 0 0 end +-310.68 4.00 426.11 0 1 0 0 0 end +-304.70 0.00 426.65 0 1 0 0 0 end +-311.59 4.00 434.78 0 1 0 0 0 end +-305.63 0.00 435.49 0 1 0 0 0 end +-312.76 4.00 443.41 0 1 0 0 0 end +-306.83 0.00 444.31 0 1 0 0 0 end +-314.19 4.00 452.01 0 1 0 0 0 end +-308.29 0.00 453.08 0 1 0 0 0 end +-315.88 4.00 460.56 0 1 0 0 0 end +-310.01 0.00 461.81 0 1 0 0 0 end +-317.83 4.00 469.05 0 1 0 0 0 end +-312.00 0.00 470.48 0 1 0 0 0 end +-320.02 4.00 477.49 0 1 0 0 0 end +-314.24 0.00 479.09 0 1 0 0 0 end +-322.47 4.00 485.85 0 1 0 0 0 end +-316.74 0.00 487.62 0 1 0 0 0 end +-325.17 4.00 494.13 0 1 0 0 0 end +-319.50 0.00 496.08 0 1 0 0 0 end +-328.12 4.00 502.34 0 1 0 0 0 end +-322.51 0.00 504.45 0 1 0 0 0 end +-331.31 4.00 510.44 0 1 0 0 0 end +-325.76 0.00 512.73 0 1 0 0 0 end +-334.75 4.00 518.45 0 1 0 0 0 end +-329.27 0.00 520.90 0 1 0 0 0 end +-338.42 4.00 526.36 0 1 0 0 0 end +-333.02 0.00 528.97 0 1 0 0 0 end +-342.33 4.00 534.15 0 1 0 0 0 end +-337.01 0.00 536.92 0 1 0 0 0 end +-346.47 4.00 541.82 0 1 0 0 0 end +-341.23 0.00 544.74 0 1 0 0 0 end +-350.84 4.00 549.36 0 1 0 0 0 end +-345.69 0.00 552.44 0 1 0 0 0 end +-355.43 4.00 556.76 0 1 0 0 0 end +-350.38 0.00 560.00 0 1 0 0 0 end +-360.24 4.00 564.03 0 1 0 0 0 end +-355.29 0.00 567.42 0 1 0 0 0 end +-365.27 4.00 571.15 0 1 0 0 0 end +-360.42 0.00 574.68 0 1 0 0 0 end +-370.51 4.00 578.11 0 1 0 0 0 end +-365.77 0.00 581.79 0 1 0 0 0 end +-375.95 4.00 584.91 0 1 0 0 0 end +-371.33 0.00 588.73 0 1 0 0 0 end +-381.60 4.00 591.55 0 1 0 0 0 end +-377.09 0.00 595.51 0 1 0 0 0 end +-387.44 4.00 598.02 0 1 0 0 0 end +-383.05 0.00 602.11 0 1 0 0 0 end +-393.48 4.00 604.30 0 1 0 0 0 end +-389.21 0.00 608.52 0 1 0 0 0 end +-399.70 4.00 610.41 0 1 0 0 0 end +-395.56 0.00 614.75 0 1 0 0 0 end +-406.10 4.00 616.32 0 1 0 0 0 end +-402.10 0.00 620.79 0 1 0 0 0 end +-412.68 4.00 622.04 0 1 0 0 0 end +-408.81 0.00 626.62 0 1 0 0 0 end +-419.42 4.00 627.56 0 1 0 0 0 end +-415.69 0.00 632.26 0 1 0 0 0 +endtri +node -1 0 none triangle_strip grass +-316.74 0.00 312.38 0 1 0 0 0 end +-310.06 0.00 310.31 0 1 0 0 0 end +-314.24 0.00 320.91 0 1 0 0 0 end +-307.50 0.00 319.05 0 1 0 0 0 end +-312.00 0.00 329.52 0 1 0 0 0 end +-305.20 0.00 327.86 0 1 0 0 0 end +-310.01 0.00 338.19 0 1 0 0 0 end +-303.17 0.00 336.73 0 1 0 0 0 end +-308.29 0.00 346.92 0 1 0 0 0 end +-301.40 0.00 345.66 0 1 0 0 0 end +-306.83 0.00 355.69 0 1 0 0 0 end +-299.91 0.00 354.65 0 1 0 0 0 end +-305.63 0.00 364.51 0 1 0 0 0 end +-298.68 0.00 363.67 0 1 0 0 0 end +-304.70 0.00 373.35 0 1 0 0 0 end +-297.73 0.00 372.72 0 1 0 0 0 end +-304.03 0.00 382.22 0 1 0 0 0 end +-297.05 0.00 381.80 0 1 0 0 0 end +-303.63 0.00 391.11 0 1 0 0 0 end +-296.64 0.00 390.90 0 1 0 0 0 end +-303.50 0.00 400.00 0 1 0 0 0 end +-296.50 0.00 400.00 0 1 0 0 0 end +-303.63 0.00 408.89 0 1 0 0 0 end +-296.64 0.00 409.10 0 1 0 0 0 end +-304.03 0.00 417.78 0 1 0 0 0 end +-297.05 0.00 418.20 0 1 0 0 0 end +-304.70 0.00 426.65 0 1 0 0 0 end +-297.73 0.00 427.28 0 1 0 0 0 end +-305.63 0.00 435.49 0 1 0 0 0 end +-298.68 0.00 436.33 0 1 0 0 0 end +-306.83 0.00 444.31 0 1 0 0 0 end +-299.91 0.00 445.35 0 1 0 0 0 end +-308.29 0.00 453.08 0 1 0 0 0 end +-301.40 0.00 454.34 0 1 0 0 0 end +-310.01 0.00 461.81 0 1 0 0 0 end +-303.17 0.00 463.27 0 1 0 0 0 end +-312.00 0.00 470.48 0 1 0 0 0 end +-305.20 0.00 472.14 0 1 0 0 0 end +-314.24 0.00 479.09 0 1 0 0 0 end +-307.50 0.00 480.95 0 1 0 0 0 end +-316.74 0.00 487.62 0 1 0 0 0 end +-310.06 0.00 489.69 0 1 0 0 0 end +-319.50 0.00 496.08 0 1 0 0 0 end +-312.88 0.00 498.35 0 1 0 0 0 end +-322.51 0.00 504.45 0 1 0 0 0 end +-315.96 0.00 506.92 0 1 0 0 0 end +-325.76 0.00 512.73 0 1 0 0 0 end +-319.29 0.00 515.39 0 1 0 0 0 end +-329.27 0.00 520.90 0 1 0 0 0 end +-322.88 0.00 523.76 0 1 0 0 0 end +-333.02 0.00 528.97 0 1 0 0 0 end +-326.71 0.00 532.01 0 1 0 0 0 end +-337.01 0.00 536.92 0 1 0 0 0 end +-330.80 0.00 540.15 0 1 0 0 0 end +-341.23 0.00 544.74 0 1 0 0 0 end +-335.12 0.00 548.16 0 1 0 0 0 end +-345.69 0.00 552.44 0 1 0 0 0 end +-339.69 0.00 556.04 0 1 0 0 0 end +-350.38 0.00 560.00 0 1 0 0 0 end +-344.48 0.00 563.78 0 1 0 0 0 end +-355.29 0.00 567.42 0 1 0 0 0 end +-349.51 0.00 571.37 0 1 0 0 0 end +-360.42 0.00 574.68 0 1 0 0 0 end +-354.76 0.00 578.81 0 1 0 0 0 end +-365.77 0.00 581.79 0 1 0 0 0 end +-360.24 0.00 586.08 0 1 0 0 0 end +-371.33 0.00 588.73 0 1 0 0 0 end +-365.93 0.00 593.19 0 1 0 0 0 end +-377.09 0.00 595.51 0 1 0 0 0 end +-371.83 0.00 600.12 0 1 0 0 0 end +-383.05 0.00 602.11 0 1 0 0 0 end +-377.93 0.00 606.88 0 1 0 0 0 end +-389.21 0.00 608.52 0 1 0 0 0 end +-384.24 0.00 613.45 0 1 0 0 0 end +-395.56 0.00 614.75 0 1 0 0 0 end +-390.74 0.00 619.82 0 1 0 0 0 end +-402.10 0.00 620.79 0 1 0 0 0 end +-397.43 0.00 626.00 0 1 0 0 0 end +-408.81 0.00 626.62 0 1 0 0 0 end +-404.30 0.00 631.97 0 1 0 0 0 end +-415.69 0.00 632.26 0 1 0 0 0 end +-411.34 0.00 637.74 0 1 0 0 0 +endtri +node -1 0 none triangle_strip grass +-310.06 0.00 310.31 0 1 0 0 0 end +-304.32 4.00 308.54 0 1 0 0 0 end +-307.50 0.00 319.05 0 1 0 0 0 end +-301.71 4.00 317.45 0 1 0 0 0 end +-305.20 0.00 327.86 0 1 0 0 0 end +-299.37 4.00 326.43 0 1 0 0 0 end +-303.17 0.00 336.73 0 1 0 0 0 end +-297.30 4.00 335.48 0 1 0 0 0 end +-301.40 0.00 345.66 0 1 0 0 0 end +-295.50 4.00 344.59 0 1 0 0 0 end +-299.91 0.00 354.65 0 1 0 0 0 end +-293.98 4.00 353.75 0 1 0 0 0 end +-298.68 0.00 363.67 0 1 0 0 0 end +-292.73 4.00 362.95 0 1 0 0 0 end +-297.73 0.00 372.72 0 1 0 0 0 end +-291.75 4.00 372.18 0 1 0 0 0 end +-297.05 0.00 381.80 0 1 0 0 0 end +-291.06 4.00 381.44 0 1 0 0 0 end +-296.64 0.00 390.90 0 1 0 0 0 end +-290.64 4.00 390.72 0 1 0 0 0 end +-296.50 0.00 400.00 0 1 0 0 0 end +-290.50 4.00 400.00 0 1 0 0 0 end +-296.64 0.00 409.10 0 1 0 0 0 end +-290.64 4.00 409.28 0 1 0 0 0 end +-297.05 0.00 418.20 0 1 0 0 0 end +-291.06 4.00 418.56 0 1 0 0 0 end +-297.73 0.00 427.28 0 1 0 0 0 end +-291.75 4.00 427.82 0 1 0 0 0 end +-298.68 0.00 436.33 0 1 0 0 0 end +-292.73 4.00 437.05 0 1 0 0 0 end +-299.91 0.00 445.35 0 1 0 0 0 end +-293.98 4.00 446.25 0 1 0 0 0 end +-301.40 0.00 454.34 0 1 0 0 0 end +-295.50 4.00 455.41 0 1 0 0 0 end +-303.17 0.00 463.27 0 1 0 0 0 end +-297.30 4.00 464.52 0 1 0 0 0 end +-305.20 0.00 472.14 0 1 0 0 0 end +-299.37 4.00 473.57 0 1 0 0 0 end +-307.50 0.00 480.95 0 1 0 0 0 end +-301.71 4.00 482.55 0 1 0 0 0 end +-310.06 0.00 489.69 0 1 0 0 0 end +-304.32 4.00 491.46 0 1 0 0 0 end +-312.88 0.00 498.35 0 1 0 0 0 end +-307.20 4.00 500.29 0 1 0 0 0 end +-315.96 0.00 506.92 0 1 0 0 0 end +-310.34 4.00 509.03 0 1 0 0 0 end +-319.29 0.00 515.39 0 1 0 0 0 end +-313.74 4.00 517.67 0 1 0 0 0 end +-322.88 0.00 523.76 0 1 0 0 0 end +-317.40 4.00 526.20 0 1 0 0 0 end +-326.71 0.00 532.01 0 1 0 0 0 end +-321.31 4.00 534.62 0 1 0 0 0 end +-330.80 0.00 540.15 0 1 0 0 0 end +-325.48 4.00 542.92 0 1 0 0 0 end +-335.12 0.00 548.16 0 1 0 0 0 end +-329.89 4.00 551.09 0 1 0 0 0 end +-339.69 0.00 556.04 0 1 0 0 0 end +-334.54 4.00 559.13 0 1 0 0 0 end +-344.48 0.00 563.78 0 1 0 0 0 end +-339.43 4.00 567.02 0 1 0 0 0 end +-349.51 0.00 571.37 0 1 0 0 0 end +-344.56 4.00 574.76 0 1 0 0 0 end +-354.76 0.00 578.81 0 1 0 0 0 end +-349.92 4.00 582.34 0 1 0 0 0 end +-360.24 0.00 586.08 0 1 0 0 0 end +-355.50 4.00 589.76 0 1 0 0 0 end +-365.93 0.00 593.19 0 1 0 0 0 end +-361.30 4.00 597.01 0 1 0 0 0 end +-371.83 0.00 600.12 0 1 0 0 0 end +-367.32 4.00 604.08 0 1 0 0 0 end +-377.93 0.00 606.88 0 1 0 0 0 end +-373.54 4.00 610.97 0 1 0 0 0 end +-384.24 0.00 613.45 0 1 0 0 0 end +-379.97 4.00 617.66 0 1 0 0 0 end +-390.74 0.00 619.82 0 1 0 0 0 end +-386.60 4.00 624.17 0 1 0 0 0 end +-397.43 0.00 626.00 0 1 0 0 0 end +-393.42 4.00 630.47 0 1 0 0 0 end +-404.30 0.00 631.97 0 1 0 0 0 end +-400.43 4.00 636.56 0 1 0 0 0 end +-411.34 0.00 637.74 0 1 0 0 0 end +-407.61 4.00 642.44 0 1 0 0 0 +endtri +node -1 0 none triangle_strip grass +-304.32 4.00 308.54 0 1 0 0 0 end +-170.10 32.10 267.02 0 1 0 0 0 end +-301.71 4.00 317.45 0 1 0 0 0 end +-166.30 32.10 279.97 0 1 0 0 0 end +-299.37 4.00 326.43 0 1 0 0 0 end +-162.90 32.10 293.03 0 1 0 0 0 end +-297.30 4.00 335.48 0 1 0 0 0 end +-159.89 32.10 306.19 0 1 0 0 0 end +-295.50 4.00 344.59 0 1 0 0 0 end +-157.27 32.10 319.44 0 1 0 0 0 end +-293.98 4.00 353.75 0 1 0 0 0 end +-155.05 32.10 332.75 0 1 0 0 0 end +-292.73 4.00 362.95 0 1 0 0 0 end +-153.24 32.10 346.13 0 1 0 0 0 end +-291.75 4.00 372.18 0 1 0 0 0 end +-151.82 32.10 359.55 0 1 0 0 0 end +-291.06 4.00 381.44 0 1 0 0 0 end +-150.81 32.10 373.02 0 1 0 0 0 end +-290.64 4.00 390.72 0 1 0 0 0 end +-150.20 32.10 386.50 0 1 0 0 0 end +-290.50 4.00 400.00 0 1 0 0 0 end +-150.00 32.10 400.00 0 1 0 0 0 end +-290.64 4.00 409.28 0 1 0 0 0 end +-150.20 32.10 413.50 0 1 0 0 0 end +-291.06 4.00 418.56 0 1 0 0 0 end +-150.81 32.10 426.98 0 1 0 0 0 end +-291.75 4.00 427.82 0 1 0 0 0 end +-151.82 32.10 440.45 0 1 0 0 0 end +-292.73 4.00 437.05 0 1 0 0 0 end +-153.24 32.10 453.87 0 1 0 0 0 end +-293.98 4.00 446.25 0 1 0 0 0 end +-155.05 32.10 467.25 0 1 0 0 0 end +-295.50 4.00 455.41 0 1 0 0 0 end +-157.27 32.10 480.56 0 1 0 0 0 end +-297.30 4.00 464.52 0 1 0 0 0 end +-159.89 32.10 493.81 0 1 0 0 0 end +-299.37 4.00 473.57 0 1 0 0 0 end +-162.90 32.10 506.97 0 1 0 0 0 end +-301.71 4.00 482.55 0 1 0 0 0 end +-166.30 32.10 520.03 0 1 0 0 0 end +-304.32 4.00 491.46 0 1 0 0 0 end +-170.10 32.10 532.98 0 1 0 0 0 end +-307.20 4.00 500.29 0 1 0 0 0 end +-174.28 32.10 545.82 0 1 0 0 0 end +-310.34 4.00 509.03 0 1 0 0 0 end +-178.85 32.10 558.52 0 1 0 0 0 end +-313.74 4.00 517.67 0 1 0 0 0 end +-183.79 32.10 571.08 0 1 0 0 0 end +-317.40 4.00 526.20 0 1 0 0 0 end +-189.11 32.10 583.49 0 1 0 0 0 end +-321.31 4.00 534.62 0 1 0 0 0 end +-194.80 32.10 595.73 0 1 0 0 0 end +-325.48 4.00 542.92 0 1 0 0 0 end +-200.85 32.10 607.80 0 1 0 0 0 end +-329.89 4.00 551.09 0 1 0 0 0 end +-207.26 32.10 619.68 0 1 0 0 0 end +-334.54 4.00 559.13 0 1 0 0 0 end +-214.03 32.10 631.36 0 1 0 0 0 end +-339.43 4.00 567.02 0 1 0 0 0 end +-221.14 32.10 642.83 0 1 0 0 0 end +-344.56 4.00 574.76 0 1 0 0 0 end +-228.60 32.10 654.09 0 1 0 0 0 end +-349.92 4.00 582.34 0 1 0 0 0 end +-236.39 32.10 665.12 0 1 0 0 0 end +-355.50 4.00 589.76 0 1 0 0 0 end +-244.50 32.10 675.90 0 1 0 0 0 end +-361.30 4.00 597.01 0 1 0 0 0 end +-252.94 32.10 686.44 0 1 0 0 0 end +-367.32 4.00 604.08 0 1 0 0 0 end +-261.69 32.10 696.72 0 1 0 0 0 end +-373.54 4.00 610.97 0 1 0 0 0 end +-270.74 32.10 706.74 0 1 0 0 0 end +-379.97 4.00 617.66 0 1 0 0 0 end +-280.09 32.10 716.48 0 1 0 0 0 end +-386.60 4.00 624.17 0 1 0 0 0 end +-289.73 32.10 725.93 0 1 0 0 0 end +-393.42 4.00 630.47 0 1 0 0 0 end +-299.64 32.10 735.09 0 1 0 0 0 end +-400.43 4.00 636.56 0 1 0 0 0 end +-309.83 32.10 743.95 0 1 0 0 0 end +-407.61 4.00 642.44 0 1 0 0 0 end +-320.28 32.10 752.50 0 1 0 0 0 +endtri +node -1 0 autotest_curve track normal 150.0000 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-300.0000 0.2 400.0000 0.0 //point 1 +-0.0000 0.0 50.2621 //control vector 1 +24.0969 0.0 -44.1091 //control vector 2 +-336.7252 0.2 543.8277 0.0 //point 2 +300.0 +endtrack +trainset none tdo_n1734 0.0 0.0 +node -1 0 {{vehicle}} dynamic pkp\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic +endtrainset + +trainset none autotest_curve 20.0 {{velocity}} +node -1 0 {{vehicle}}_off dynamic pkp\4e_v1 4e-004 4e 0 nobody 0 0 enddynamic +endtrainset diff --git a/tests/scenarios/cases/td_off_track_curve_embankment.scn b/tests/scenarios/cases/td_off_track_curve_embankment.scn new file mode 100644 index 000000000..4f9d6c7c8 --- /dev/null +++ b/tests/scenarios/cases/td_off_track_curve_embankment.scn @@ -0,0 +1,273 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed (physics.derailment new, the vehicles +// off the track moving on the ground, vehicle/derailmotion.h): a track of R 300 m without cant laid on its own in the +// fields of td.scn (autotest_curve), on an embankment 4 m high with slopes of 1:1.5; written by a script, see the README. +// an EU07 with an AI driver and no timetable stands on track 1 of Stacja1, where td.scn keeps its timetable train, so +// it stays put and logs its physics; the EU07 of the case has no driver and runs at {{velocity}} km/h from 20 m past +// point 1 of the curve towards its point 2 +node -1 0 none triangle_strip grass +-322.47 0.00 314.15 0 1 0 0 0 end +-316.74 4.00 312.38 0 1 0 0 0 end +-320.02 0.00 322.51 0 1 0 0 0 end +-314.24 4.00 320.91 0 1 0 0 0 end +-317.83 0.00 330.95 0 1 0 0 0 end +-312.00 4.00 329.52 0 1 0 0 0 end +-315.88 0.00 339.44 0 1 0 0 0 end +-310.01 4.00 338.19 0 1 0 0 0 end +-314.19 0.00 347.99 0 1 0 0 0 end +-308.29 4.00 346.92 0 1 0 0 0 end +-312.76 0.00 356.59 0 1 0 0 0 end +-306.83 4.00 355.69 0 1 0 0 0 end +-311.59 0.00 365.22 0 1 0 0 0 end +-305.63 4.00 364.51 0 1 0 0 0 end +-310.68 0.00 373.89 0 1 0 0 0 end +-304.70 4.00 373.35 0 1 0 0 0 end +-310.02 0.00 382.58 0 1 0 0 0 end +-304.03 4.00 382.22 0 1 0 0 0 end +-309.63 0.00 391.29 0 1 0 0 0 end +-303.63 4.00 391.11 0 1 0 0 0 end +-309.50 0.00 400.00 0 1 0 0 0 end +-303.50 4.00 400.00 0 1 0 0 0 end +-309.63 0.00 408.71 0 1 0 0 0 end +-303.63 4.00 408.89 0 1 0 0 0 end +-310.02 0.00 417.42 0 1 0 0 0 end +-304.03 4.00 417.78 0 1 0 0 0 end +-310.68 0.00 426.11 0 1 0 0 0 end +-304.70 4.00 426.65 0 1 0 0 0 end +-311.59 0.00 434.78 0 1 0 0 0 end +-305.63 4.00 435.49 0 1 0 0 0 end +-312.76 0.00 443.41 0 1 0 0 0 end +-306.83 4.00 444.31 0 1 0 0 0 end +-314.19 0.00 452.01 0 1 0 0 0 end +-308.29 4.00 453.08 0 1 0 0 0 end +-315.88 0.00 460.56 0 1 0 0 0 end +-310.01 4.00 461.81 0 1 0 0 0 end +-317.83 0.00 469.05 0 1 0 0 0 end +-312.00 4.00 470.48 0 1 0 0 0 end +-320.02 0.00 477.49 0 1 0 0 0 end +-314.24 4.00 479.09 0 1 0 0 0 end +-322.47 0.00 485.85 0 1 0 0 0 end +-316.74 4.00 487.62 0 1 0 0 0 end +-325.17 0.00 494.13 0 1 0 0 0 end +-319.50 4.00 496.08 0 1 0 0 0 end +-328.12 0.00 502.34 0 1 0 0 0 end +-322.51 4.00 504.45 0 1 0 0 0 end +-331.31 0.00 510.44 0 1 0 0 0 end +-325.76 4.00 512.73 0 1 0 0 0 end +-334.75 0.00 518.45 0 1 0 0 0 end +-329.27 4.00 520.90 0 1 0 0 0 end +-338.42 0.00 526.36 0 1 0 0 0 end +-333.02 4.00 528.97 0 1 0 0 0 end +-342.33 0.00 534.15 0 1 0 0 0 end +-337.01 4.00 536.92 0 1 0 0 0 end +-346.47 0.00 541.82 0 1 0 0 0 end +-341.23 4.00 544.74 0 1 0 0 0 end +-350.84 0.00 549.36 0 1 0 0 0 end +-345.69 4.00 552.44 0 1 0 0 0 end +-355.43 0.00 556.76 0 1 0 0 0 end +-350.38 4.00 560.00 0 1 0 0 0 end +-360.24 0.00 564.03 0 1 0 0 0 end +-355.29 4.00 567.42 0 1 0 0 0 end +-365.27 0.00 571.15 0 1 0 0 0 end +-360.42 4.00 574.68 0 1 0 0 0 end +-370.51 0.00 578.11 0 1 0 0 0 end +-365.77 4.00 581.79 0 1 0 0 0 end +-375.95 0.00 584.91 0 1 0 0 0 end +-371.33 4.00 588.73 0 1 0 0 0 end +-381.60 0.00 591.55 0 1 0 0 0 end +-377.09 4.00 595.51 0 1 0 0 0 end +-387.44 0.00 598.02 0 1 0 0 0 end +-383.05 4.00 602.11 0 1 0 0 0 end +-393.48 0.00 604.30 0 1 0 0 0 end +-389.21 4.00 608.52 0 1 0 0 0 end +-399.70 0.00 610.41 0 1 0 0 0 end +-395.56 4.00 614.75 0 1 0 0 0 end +-406.10 0.00 616.32 0 1 0 0 0 end +-402.10 4.00 620.79 0 1 0 0 0 end +-412.68 0.00 622.04 0 1 0 0 0 end +-408.81 4.00 626.62 0 1 0 0 0 end +-419.42 0.00 627.56 0 1 0 0 0 end +-415.69 4.00 632.26 0 1 0 0 0 +endtri +node -1 0 none triangle_strip grass +-316.74 4.00 312.38 0 1 0 0 0 end +-310.06 4.00 310.31 0 1 0 0 0 end +-314.24 4.00 320.91 0 1 0 0 0 end +-307.50 4.00 319.05 0 1 0 0 0 end +-312.00 4.00 329.52 0 1 0 0 0 end +-305.20 4.00 327.86 0 1 0 0 0 end +-310.01 4.00 338.19 0 1 0 0 0 end +-303.17 4.00 336.73 0 1 0 0 0 end +-308.29 4.00 346.92 0 1 0 0 0 end +-301.40 4.00 345.66 0 1 0 0 0 end +-306.83 4.00 355.69 0 1 0 0 0 end +-299.91 4.00 354.65 0 1 0 0 0 end +-305.63 4.00 364.51 0 1 0 0 0 end +-298.68 4.00 363.67 0 1 0 0 0 end +-304.70 4.00 373.35 0 1 0 0 0 end +-297.73 4.00 372.72 0 1 0 0 0 end +-304.03 4.00 382.22 0 1 0 0 0 end +-297.05 4.00 381.80 0 1 0 0 0 end +-303.63 4.00 391.11 0 1 0 0 0 end +-296.64 4.00 390.90 0 1 0 0 0 end +-303.50 4.00 400.00 0 1 0 0 0 end +-296.50 4.00 400.00 0 1 0 0 0 end +-303.63 4.00 408.89 0 1 0 0 0 end +-296.64 4.00 409.10 0 1 0 0 0 end +-304.03 4.00 417.78 0 1 0 0 0 end +-297.05 4.00 418.20 0 1 0 0 0 end +-304.70 4.00 426.65 0 1 0 0 0 end +-297.73 4.00 427.28 0 1 0 0 0 end +-305.63 4.00 435.49 0 1 0 0 0 end +-298.68 4.00 436.33 0 1 0 0 0 end +-306.83 4.00 444.31 0 1 0 0 0 end +-299.91 4.00 445.35 0 1 0 0 0 end +-308.29 4.00 453.08 0 1 0 0 0 end +-301.40 4.00 454.34 0 1 0 0 0 end +-310.01 4.00 461.81 0 1 0 0 0 end +-303.17 4.00 463.27 0 1 0 0 0 end +-312.00 4.00 470.48 0 1 0 0 0 end +-305.20 4.00 472.14 0 1 0 0 0 end +-314.24 4.00 479.09 0 1 0 0 0 end +-307.50 4.00 480.95 0 1 0 0 0 end +-316.74 4.00 487.62 0 1 0 0 0 end +-310.06 4.00 489.69 0 1 0 0 0 end +-319.50 4.00 496.08 0 1 0 0 0 end +-312.88 4.00 498.35 0 1 0 0 0 end +-322.51 4.00 504.45 0 1 0 0 0 end +-315.96 4.00 506.92 0 1 0 0 0 end +-325.76 4.00 512.73 0 1 0 0 0 end +-319.29 4.00 515.39 0 1 0 0 0 end +-329.27 4.00 520.90 0 1 0 0 0 end +-322.88 4.00 523.76 0 1 0 0 0 end +-333.02 4.00 528.97 0 1 0 0 0 end +-326.71 4.00 532.01 0 1 0 0 0 end +-337.01 4.00 536.92 0 1 0 0 0 end +-330.80 4.00 540.15 0 1 0 0 0 end +-341.23 4.00 544.74 0 1 0 0 0 end +-335.12 4.00 548.16 0 1 0 0 0 end +-345.69 4.00 552.44 0 1 0 0 0 end +-339.69 4.00 556.04 0 1 0 0 0 end +-350.38 4.00 560.00 0 1 0 0 0 end +-344.48 4.00 563.78 0 1 0 0 0 end +-355.29 4.00 567.42 0 1 0 0 0 end +-349.51 4.00 571.37 0 1 0 0 0 end +-360.42 4.00 574.68 0 1 0 0 0 end +-354.76 4.00 578.81 0 1 0 0 0 end +-365.77 4.00 581.79 0 1 0 0 0 end +-360.24 4.00 586.08 0 1 0 0 0 end +-371.33 4.00 588.73 0 1 0 0 0 end +-365.93 4.00 593.19 0 1 0 0 0 end +-377.09 4.00 595.51 0 1 0 0 0 end +-371.83 4.00 600.12 0 1 0 0 0 end +-383.05 4.00 602.11 0 1 0 0 0 end +-377.93 4.00 606.88 0 1 0 0 0 end +-389.21 4.00 608.52 0 1 0 0 0 end +-384.24 4.00 613.45 0 1 0 0 0 end +-395.56 4.00 614.75 0 1 0 0 0 end +-390.74 4.00 619.82 0 1 0 0 0 end +-402.10 4.00 620.79 0 1 0 0 0 end +-397.43 4.00 626.00 0 1 0 0 0 end +-408.81 4.00 626.62 0 1 0 0 0 end +-404.30 4.00 631.97 0 1 0 0 0 end +-415.69 4.00 632.26 0 1 0 0 0 end +-411.34 4.00 637.74 0 1 0 0 0 +endtri +node -1 0 none triangle_strip grass +-310.06 4.00 310.31 0 1 0 0 0 end +-304.32 0.00 308.54 0 1 0 0 0 end +-307.50 4.00 319.05 0 1 0 0 0 end +-301.71 0.00 317.45 0 1 0 0 0 end +-305.20 4.00 327.86 0 1 0 0 0 end +-299.37 0.00 326.43 0 1 0 0 0 end +-303.17 4.00 336.73 0 1 0 0 0 end +-297.30 0.00 335.48 0 1 0 0 0 end +-301.40 4.00 345.66 0 1 0 0 0 end +-295.50 0.00 344.59 0 1 0 0 0 end +-299.91 4.00 354.65 0 1 0 0 0 end +-293.98 0.00 353.75 0 1 0 0 0 end +-298.68 4.00 363.67 0 1 0 0 0 end +-292.73 0.00 362.95 0 1 0 0 0 end +-297.73 4.00 372.72 0 1 0 0 0 end +-291.75 0.00 372.18 0 1 0 0 0 end +-297.05 4.00 381.80 0 1 0 0 0 end +-291.06 0.00 381.44 0 1 0 0 0 end +-296.64 4.00 390.90 0 1 0 0 0 end +-290.64 0.00 390.72 0 1 0 0 0 end +-296.50 4.00 400.00 0 1 0 0 0 end +-290.50 0.00 400.00 0 1 0 0 0 end +-296.64 4.00 409.10 0 1 0 0 0 end +-290.64 0.00 409.28 0 1 0 0 0 end +-297.05 4.00 418.20 0 1 0 0 0 end +-291.06 0.00 418.56 0 1 0 0 0 end +-297.73 4.00 427.28 0 1 0 0 0 end +-291.75 0.00 427.82 0 1 0 0 0 end +-298.68 4.00 436.33 0 1 0 0 0 end +-292.73 0.00 437.05 0 1 0 0 0 end +-299.91 4.00 445.35 0 1 0 0 0 end +-293.98 0.00 446.25 0 1 0 0 0 end +-301.40 4.00 454.34 0 1 0 0 0 end +-295.50 0.00 455.41 0 1 0 0 0 end +-303.17 4.00 463.27 0 1 0 0 0 end +-297.30 0.00 464.52 0 1 0 0 0 end +-305.20 4.00 472.14 0 1 0 0 0 end +-299.37 0.00 473.57 0 1 0 0 0 end +-307.50 4.00 480.95 0 1 0 0 0 end +-301.71 0.00 482.55 0 1 0 0 0 end +-310.06 4.00 489.69 0 1 0 0 0 end +-304.32 0.00 491.46 0 1 0 0 0 end +-312.88 4.00 498.35 0 1 0 0 0 end +-307.20 0.00 500.29 0 1 0 0 0 end +-315.96 4.00 506.92 0 1 0 0 0 end +-310.34 0.00 509.03 0 1 0 0 0 end +-319.29 4.00 515.39 0 1 0 0 0 end +-313.74 0.00 517.67 0 1 0 0 0 end +-322.88 4.00 523.76 0 1 0 0 0 end +-317.40 0.00 526.20 0 1 0 0 0 end +-326.71 4.00 532.01 0 1 0 0 0 end +-321.31 0.00 534.62 0 1 0 0 0 end +-330.80 4.00 540.15 0 1 0 0 0 end +-325.48 0.00 542.92 0 1 0 0 0 end +-335.12 4.00 548.16 0 1 0 0 0 end +-329.89 0.00 551.09 0 1 0 0 0 end +-339.69 4.00 556.04 0 1 0 0 0 end +-334.54 0.00 559.13 0 1 0 0 0 end +-344.48 4.00 563.78 0 1 0 0 0 end +-339.43 0.00 567.02 0 1 0 0 0 end +-349.51 4.00 571.37 0 1 0 0 0 end +-344.56 0.00 574.76 0 1 0 0 0 end +-354.76 4.00 578.81 0 1 0 0 0 end +-349.92 0.00 582.34 0 1 0 0 0 end +-360.24 4.00 586.08 0 1 0 0 0 end +-355.50 0.00 589.76 0 1 0 0 0 end +-365.93 4.00 593.19 0 1 0 0 0 end +-361.30 0.00 597.01 0 1 0 0 0 end +-371.83 4.00 600.12 0 1 0 0 0 end +-367.32 0.00 604.08 0 1 0 0 0 end +-377.93 4.00 606.88 0 1 0 0 0 end +-373.54 0.00 610.97 0 1 0 0 0 end +-384.24 4.00 613.45 0 1 0 0 0 end +-379.97 0.00 617.66 0 1 0 0 0 end +-390.74 4.00 619.82 0 1 0 0 0 end +-386.60 0.00 624.17 0 1 0 0 0 end +-397.43 4.00 626.00 0 1 0 0 0 end +-393.42 0.00 630.47 0 1 0 0 0 end +-404.30 4.00 631.97 0 1 0 0 0 end +-400.43 0.00 636.56 0 1 0 0 0 end +-411.34 4.00 637.74 0 1 0 0 0 end +-407.61 0.00 642.44 0 1 0 0 0 +endtri +node -1 0 autotest_curve track normal 150.0000 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-300.0000 4.2 400.0000 0.0 //point 1 +-0.0000 0.0 50.2621 //control vector 1 +24.0969 0.0 -44.1091 //control vector 2 +-336.7252 4.2 543.8277 0.0 //point 2 +300.0 +endtrack +trainset none tdo_n1734 0.0 0.0 +node -1 0 {{vehicle}} dynamic pkp\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic +endtrainset + +trainset none autotest_curve 20.0 {{velocity}} +node -1 0 {{vehicle}}_off dynamic pkp\4e_v1 4e-004 4e 0 nobody 0 0 enddynamic +endtrainset diff --git a/tests/scenarios/cases/td_off_track_curve_flat.scn b/tests/scenarios/cases/td_off_track_curve_flat.scn new file mode 100644 index 000000000..ddaf4f287 --- /dev/null +++ b/tests/scenarios/cases/td_off_track_curve_flat.scn @@ -0,0 +1,21 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed (physics.derailment new, the vehicles +// off the track moving on the ground, vehicle/derailmotion.h): a track of R 300 m without cant laid on its own in the +// fields of td.scn (autotest_curve), on level ground; written by a script, see the README. +// an EU07 with an AI driver and no timetable stands on track 1 of Stacja1, where td.scn keeps its timetable train, so +// it stays put and logs its physics; the EU07 of the case has no driver and runs at {{velocity}} km/h from 20 m past +// point 1 of the curve towards its point 2 +node -1 0 autotest_curve track normal 150.0000 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-300.0000 0.2 400.0000 0.0 //point 1 +-0.0000 0.0 50.2621 //control vector 1 +24.0969 0.0 -44.1091 //control vector 2 +-336.7252 0.2 543.8277 0.0 //point 2 +300.0 +endtrack +trainset none tdo_n1734 0.0 0.0 +node -1 0 {{vehicle}} dynamic pkp\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic +endtrainset + +trainset none autotest_curve 20.0 {{velocity}} +node -1 0 {{vehicle}}_off dynamic pkp\4e_v1 4e-004 4e 0 nobody 0 0 enddynamic +endtrainset diff --git a/tests/scenarios/cases/td_passenger_upgrade.txt b/tests/scenarios/cases/td_passenger_upgrade.txt new file mode 100644 index 000000000..bc8e12087 --- /dev/null +++ b/tests/scenarios/cases/td_passenger_upgrade.txt @@ -0,0 +1,17 @@ +________________________________________________________________ +[ Rodzaj i numer pociagu | TEST28 ] +[ Kategoria | RO ] +[________________________________________________|______________] +[ | Gora ] +[ Relacja pociagu | Koniec ] +[________________________________________________|______________] +[ Wymagany % ciezaru hamujacego | 88% ] +[________________________________________________|______________] +[ Seria i obciazenie lokomotywy | EU07 400 ] +[________________________________________________|______________] +[ | | Gora 2 | | ] +[ | 80 | R1,L,H,RT,PP 2 10.35 | ] +[ | |----------------------------------1----------|---] +[ | | Koniec 1 10.45 | 10] +[ | | R1 1 10.46 | ] +[_______|_____|__________________________________1__________|___] diff --git a/tests/scenarios/cases/td_past_red_signal.scn b/tests/scenarios/cases/td_past_red_signal.scn new file mode 100644 index 000000000..e5e68da5f --- /dev/null +++ b/tests/scenarios/cases/td_past_red_signal.scn @@ -0,0 +1,7 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// the timetable train of td.scn (td/rozklad) set at a stand past the exit signal stacja1_j, which stays at stop +// (no route): the head {{offset}} m into tor1k, whose memory cell of the signal is 51 m into the track. the train +// starts at 0.1 km/h, as in td_red_signal.scn: set at 0 its AI driver doesn't wake up within the case +trainset td/rozklad tor1k {{offset}} 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_reinspect_brakes.scn b/tests/scenarios/cases/td_reinspect_brakes.scn new file mode 100644 index 000000000..37c76550a --- /dev/null +++ b/tests/scenarios/cases/td_reinspect_brakes.scn @@ -0,0 +1,33 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// on the line from Stacja1 to Stacja2 (flat, curves of 600 m): a locomotive with an AI driver stands cold +// (trainset velocity 0) on koniec, its front 35 m past point 1 of the track, facing point 2, towards Stacja2; +// a cut of wagons (vars.cut) stands, braked as well and with nobody in it, ahead of it, its front 56 m past +// point 1 of tdo_n222, some 45 m in front of the locomotive. +trainset none koniec 35.0 0.0 +node -1 0 {{vehicle}} dynamic {{locomotive}} 0 headdriver 0 0 enddynamic +endtrainset + +trainset none tdo_n222 56.0 0.0 +{{cut}} +endtrainset + +// event0 of the locomotive's track (the case's track_events) runs while the locomotive stands there. it wakes +// the driver and gives it, once, the order to couple to the cut ahead and run it on as a train: Shunt -3 3, +// Connect (with the coupler and the brake hose) then Obey_train, which waits for the way to be given. the AI +// couples on the run, at some 4 km/h, and the wagon inspector of the train run looks at the new train then, +// before it stands. +node -1 0 autotest_ordered memcell 0 0 0 ordered 0 0 none endmemcell +event autotest_wake multiple 0 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event autotest_order PutValues 0 none 0 0 0 Shunt -3 3 endevent +event autotest_order_given UpdateValues 0 autotest_ordered * 1 * endevent + +// the way: no signal of the line is in sight, so event2 of tdo_n231 (the case's track_events), 40 m in front of +// the cut, gives the speed a signal at proceed would, 40 km/h, which the AI reads as it scans the track ahead +event autotest_way PutValues 0 none 0 0 0 SetVelocity 40 40 endevent + +// event2 of tdo_n240 (the case's track_events), some 700 m on, as the locomotive runs over it pushing the train: +// the driver is taken off (Crew: 0 0), which leaves the brake valve in the emergency position, so the +// train stops on the brakes it has. the pass comes 150 s later, with the train standing. +event autotest_crew_off multiple 0 none autotest_driver_off autotest_pass endevent +event autotest_driver_off putvalues 0 none 0 0 0 Crew:{{vehicle}} 0 0 endevent +event autotest_pass UpdateValues 150 __test.result the_train_was_stopped_with_the_brakes_it_has 1 * endevent diff --git a/tests/scenarios/cases/td_shunt_red_signal.scn b/tests/scenarios/cases/td_shunt_red_signal.scn new file mode 100644 index 000000000..649427247 --- /dev/null +++ b/tests/scenarios/cases/td_shunt_red_signal.scn @@ -0,0 +1,7 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// like td_red_signal_moving.scn (no route, the exit signal stacja1_j about 150 m ahead of the start of +// tdo_n1734 stays at stop), but the train has no timetable, so its AI driver shunts (Shunt), and it +// starts {{offset}} m into tdo_n1734, already moving at {{velocity}} km/h. +trainset none tdo_n1734 {{offset}} {{velocity}} +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_switch_thrown.scn b/tests/scenarios/cases/td_switch_thrown.scn new file mode 100644 index 000000000..b7706034b --- /dev/null +++ b/tests/scenarios/cases/td_switch_thrown.scn @@ -0,0 +1,45 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a switch of Stacja1 thrown by an event while a train stands or runs over it (the review of MaSzyna-EU07/maszyna#289, +// point 2b). Both switches of the station have their points (point 1) towards the line and two ways from there to +// the station: position 0 straight to track 2 (x 0.4), position 1 curved to track 1 (x 2.3 at the end of the switch, +// x 5.0 further on). The events of zwrp34r300.inc / zwrl34r300.inc: + sets position 0, - position 1 +// (and the speed of the switch: none on the straight, 40 on the curve). +// - zwr01, west end: points at z 336, the ways end at z 370 (tor2p, track 2; tdo_n1641, track 1). A train running +// towards z 2000 (into the station) goes through it facing, from the points. +// - zwr02, east end: points at z 1436 (tdo_n145, the line), the ways end at z 1402 (tor2k, track 2; tdo_n1744, +// track 1). A train running towards z 2000 (out of the station) goes through it trailing, from the frog end. +// A trainset faces point 2 of its track (towards z 2000 on all these tracks): the first vehicle has its front as many +// metres past point 1 as the trainset says, the others stand behind it. +{{trainsets}} + +// the way set at the start, if any (a launcher with a positive time fires once at that hour, the scenery starts +// at 10:34) +{{route}} + +// the throw (vars.throw), once: whichever of the events hung on the tracks of the case (track_events) or the +// launcher (vars.trigger) sets it off first, the memory cell keeps the others from doing it again +node -1 0 autotest_thrown memcell 0 0 0 thrown 0 0 none endmemcell +event autotest_throw multiple 0 autotest_thrown {{throw}} autotest_throw_done condition memcompare * 0 * endevent +event autotest_throw_done UpdateValues 0 autotest_thrown * 1 * endevent +{{trigger}} + +// a driver of a trainset of velocity 0 sleeps until it gets an order. event0 of the track its vehicle stands on +// (track_events) gives it, once: vars.order, e.g. Shunt -1 0 (go on shunting with the whole train; a proceed aspect +// of a main signal ahead turns that into a train run) or Obey_train 0 0. autotest_wake gives it at once, +// autotest_wake_after_throw only once the switch has been thrown (for a train standing over the switch) +node -1 0 autotest_ordered memcell 0 0 0 ordered 0 0 none endmemcell +event autotest_wake_after_throw multiple 0 autotest_thrown autotest_wake condition memcompare * 1 * endevent +event autotest_wake multiple 0 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event autotest_order PutValues 0 none 0 0 0 {{order}} endevent +event autotest_order_given UpdateValues 0 autotest_ordered * 1 * endevent + +// a signal at stop on track 1 for a train running towards z 2000: the memory cell stands beside the track at z 1100 +// and event2 of tdo_n1725 (z 1065-1165, track_events) reads it. A train on track 1 has to stop before it, with its head +// on tdo_n1725, where event0 passes the test; running onto tdo_n1734 (z 1165-1265) beyond the signal fails it. On +// track 2 the train stops before the exit signal stacja1_k (z 1316, at stop all the time), with its head on tdo_n109 +// (z 1236-1336) +node -1 0 autotest_signal1 memcell 5.04488 0.2 1100.0 SetVelocity 0 0 none endmemcell +event autotest_signal1_info getvalues 0 autotest_signal1 endevent +event autotest_pass UpdateValues 0 __test.result stopped_before_the_signal 1 * endevent +event autotest_fail UpdateValues 0 __test.result ran_past_the_signal_of_track_1 0 * endevent +event autotest_pass_running UpdateValues 0 __test.result ran_clear_of_the_switch 1 * endevent diff --git a/tests/scenarios/cases/td_timetable_genset.scn b/tests/scenarios/cases/td_timetable_genset.scn new file mode 100644 index 000000000..0918dc1bc --- /dev/null +++ b/tests/scenarios/cases/td_timetable_genset.scn @@ -0,0 +1,18 @@ +// td_timetable.scn (the timetable train on track 1 of Stacja1, route out at 10:34) with the train switched to its +// genset by the scenery before it leaves (eu07/maszyna#536, a dual-mode vehicle): event0 of the start track (the +// track_events of the case) runs while the vehicle with a driver stands there and gives it, once, PutValues +// MainSwitch 0, TractionMode 1 and GensetSwitch 1, a second apart, as the vehicle holds one command at a time. +// the AI knows nothing of the genset: it closes the line breaker once the genset runs and drives on its power +trainset td/rozklad tdo_n1734 0.0 0.1 +{{consist}} +endtrainset + +// the way out of track 1, see td_timetable.scn +node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end + +node -1 0 autotest_genset_done memcell 0 0 0 done 0 0 none endmemcell +event autotest_genset multiple 0 autotest_genset_done autotest_genset_ws autotest_genset_mode autotest_genset_on autotest_genset_mark condition memcompare * 0 * endevent +event autotest_genset_ws PutValues 0 none 0 0 0 MainSwitch 0 0 endevent +event autotest_genset_mode PutValues 1 none 0 0 0 TractionMode 1 0 endevent +event autotest_genset_on PutValues 2 none 0 0 0 GensetSwitch 1 0 endevent +event autotest_genset_mark UpdateValues 0 autotest_genset_done * 1 * endevent diff --git a/tests/scenarios/cases/td_timetable_past_w4.scn b/tests/scenarios/cases/td_timetable_past_w4.scn new file mode 100644 index 000000000..e7e83d51b --- /dev/null +++ b/tests/scenarios/cases/td_timetable_past_w4.scn @@ -0,0 +1,9 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// the timetable train of td.scn (td/rozklad, Stacja1 10:35 -> Przystanek -> Stacja2) placed past the W4 of +// Stacja1 instead of before it: the head {{offset}} m into tor1k, the track after the one with the W4, which is +// left under the consist, behind the head. the route out of track 1 is set at 10:34 +trainset td/rozklad tor1k {{offset}} 0.1 +{{consist}} +endtrainset + +node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end diff --git a/tests/scenarios/cases/td_uncouple_past_signal.scn b/tests/scenarios/cases/td_uncouple_past_signal.scn new file mode 100644 index 000000000..98ab9033e --- /dev/null +++ b/tests/scenarios/cases/td_uncouple_past_signal.scn @@ -0,0 +1,31 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a shunter with no timetable stands at the far end of tor1k (point 2), turned (offset -1) to face back towards +// track 1 of Stacja1, with its wagons (vars.wagons) behind it, towards the exit signal stacja1_j (at stop, no route; +// its memory cell is 51 m into tor1k). the trainset's velocity is negative, so its driver takes the direction of the +// locomotive's cab and pulls. tdo_n1734, the track behind tor1k, is closed (speed 0) from the start, so the shunter +// pulls the wagons back along tor1k and stops in front of it, with the far end of the last wagon a few metres past +// the signal: the signal stands at stop over that wagon for the direction the shunter pushes in when it uncouples. +// the pull leaves the screw coupler stretched, as at a real stop. +trainset none tor1k 100.0 -0.1 +{{wagons}} +node -1 0 {{vehicle}} dynamic pkp\sm42_v1 6DA-1096 6da -1 headdriver 0 0 enddynamic +endtrainset + +node -1 0 autotest_closed eventlauncher 0 0 0 -1 none 1034 autotest_close end +event autotest_close trackvel 0 tdo_n1734 0 endevent + +// a standing shunter waits for the scenery's orders. event0 of tor1k (the case's track_events) runs while it stands +// there. the first time it gives the order to go (Shunt -1 0). 25 s later the shunter is on its way, and the first +// time it stands again, in front of tdo_n1734, it gets the order a scenery gives to leave the wagons: Shunt 0 0, +// uncouple everything behind the locomotive and stay. it brakes the wagons, changes direction, pushes the buffers in +// and lets the coupler go. the order comes at once: standing for long, the wagons' brakes release and the coupler +// draws the buffers together, which leaves nothing to push +node -1 0 autotest_ordered memcell 0 0 0 ordered 0 0 none endmemcell +event autotest_wake multiple 0 none autotest_go autotest_uncouple endevent +event autotest_go multiple 0 autotest_ordered autotest_go_order autotest_go_given autotest_go_done condition memcompare * 0 * endevent +event autotest_go_order PutValues 0 none 0 0 0 Shunt -1 0 endevent +event autotest_go_given UpdateValues 0 autotest_ordered * 1 * endevent +event autotest_go_done UpdateValues 25 autotest_ordered * 2 * endevent +event autotest_uncouple multiple 0 autotest_ordered autotest_uncouple_order autotest_uncouple_given condition memcompare * 2 * endevent +event autotest_uncouple_order PutValues 0 none 0 0 0 Shunt 0 0 endevent +event autotest_uncouple_given UpdateValues 0 autotest_ordered * 3 * endevent diff --git a/tests/scenarios/cases/td_upgrade_long.scn b/tests/scenarios/cases/td_upgrade_long.scn new file mode 100644 index 000000000..12ff5c713 --- /dev/null +++ b/tests/scenarios/cases/td_upgrade_long.scn @@ -0,0 +1,934 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a line of its own, away from the tracks of td.scn: 600 m level, then 5500 m up a gradient of 10 per mille, +// under an overhead wire. the train starts on the level with its head 10 m before the W4 of Gora and runs on the +// timetable {{timetable}} (leaves Gora at 10:35, no other stop) at the line limit of the timetable, up to the signal ul_sem +// at stop 5300 m up the gradient. the line goes on 200 m past it +node -1 0 ul_00 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -500.0 0.0 +0 +endtrack +node -1 0 ul_01 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -400.0 0.0 +0 +endtrack +node -1 0 ul_02 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -300.0 0.0 +0 +endtrack +node -1 0 ul_03 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -200.0 0.0 +0 +endtrack +node -1 0 ul_04 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -100.0 0.0 +0 +endtrack +node -1 0 ul_05 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 0.0 0.0 +0 +event2 gora#1_stopinfo +endtrack +node -1 0 ul_06 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 0.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 61.00 100.0 0.0 +0 +endtrack +node -1 0 ul_07 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 61.00 100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 62.00 200.0 0.0 +0 +endtrack +node -1 0 ul_08 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 62.00 200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 63.00 300.0 0.0 +0 +endtrack +node -1 0 ul_09 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 63.00 300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 64.00 400.0 0.0 +0 +endtrack +node -1 0 ul_10 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 64.00 400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 65.00 500.0 0.0 +0 +endtrack +node -1 0 ul_11 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 65.00 500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 66.00 600.0 0.0 +0 +endtrack +node -1 0 ul_12 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 66.00 600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 67.00 700.0 0.0 +0 +endtrack +node -1 0 ul_13 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 67.00 700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 68.00 800.0 0.0 +0 +endtrack +node -1 0 ul_14 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 68.00 800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 69.00 900.0 0.0 +0 +endtrack +node -1 0 ul_15 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 69.00 900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 70.00 1000.0 0.0 +0 +endtrack +node -1 0 ul_16 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 70.00 1000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 71.00 1100.0 0.0 +0 +endtrack +node -1 0 ul_17 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 71.00 1100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 72.00 1200.0 0.0 +0 +endtrack +node -1 0 ul_18 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 72.00 1200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 73.00 1300.0 0.0 +0 +endtrack +node -1 0 ul_19 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 73.00 1300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 74.00 1400.0 0.0 +0 +endtrack +node -1 0 ul_20 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 74.00 1400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 75.00 1500.0 0.0 +0 +endtrack +node -1 0 ul_21 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 75.00 1500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 76.00 1600.0 0.0 +0 +endtrack +node -1 0 ul_22 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 76.00 1600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 77.00 1700.0 0.0 +0 +endtrack +node -1 0 ul_23 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 77.00 1700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 78.00 1800.0 0.0 +0 +endtrack +node -1 0 ul_24 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 78.00 1800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 79.00 1900.0 0.0 +0 +endtrack +node -1 0 ul_25 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 79.00 1900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 80.00 2000.0 0.0 +0 +endtrack +node -1 0 ul_26 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 80.00 2000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 81.00 2100.0 0.0 +0 +endtrack +node -1 0 ul_27 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 81.00 2100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 82.00 2200.0 0.0 +0 +endtrack +node -1 0 ul_28 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 82.00 2200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 83.00 2300.0 0.0 +0 +endtrack +node -1 0 ul_29 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 83.00 2300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 84.00 2400.0 0.0 +0 +endtrack +node -1 0 ul_30 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 84.00 2400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 85.00 2500.0 0.0 +0 +endtrack +node -1 0 ul_31 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 85.00 2500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 86.00 2600.0 0.0 +0 +endtrack +node -1 0 ul_32 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 86.00 2600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 87.00 2700.0 0.0 +0 +endtrack +node -1 0 ul_33 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 87.00 2700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 88.00 2800.0 0.0 +0 +endtrack +node -1 0 ul_34 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 88.00 2800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 89.00 2900.0 0.0 +0 +endtrack +node -1 0 ul_35 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 89.00 2900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 90.00 3000.0 0.0 +0 +endtrack +node -1 0 ul_36 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 90.00 3000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 91.00 3100.0 0.0 +0 +endtrack +node -1 0 ul_37 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 91.00 3100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 92.00 3200.0 0.0 +0 +endtrack +node -1 0 ul_38 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 92.00 3200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 93.00 3300.0 0.0 +0 +endtrack +node -1 0 ul_39 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 93.00 3300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 94.00 3400.0 0.0 +0 +endtrack +node -1 0 ul_40 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 94.00 3400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 95.00 3500.0 0.0 +0 +endtrack +node -1 0 ul_41 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 95.00 3500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 96.00 3600.0 0.0 +0 +endtrack +node -1 0 ul_42 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 96.00 3600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 97.00 3700.0 0.0 +0 +endtrack +node -1 0 ul_43 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 97.00 3700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 98.00 3800.0 0.0 +0 +endtrack +node -1 0 ul_44 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 98.00 3800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 99.00 3900.0 0.0 +0 +endtrack +node -1 0 ul_45 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 99.00 3900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 100.00 4000.0 0.0 +0 +endtrack +node -1 0 ul_46 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 100.00 4000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 101.00 4100.0 0.0 +0 +endtrack +node -1 0 ul_47 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 101.00 4100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 102.00 4200.0 0.0 +0 +endtrack +node -1 0 ul_48 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 102.00 4200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 103.00 4300.0 0.0 +0 +endtrack +node -1 0 ul_49 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 103.00 4300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 104.00 4400.0 0.0 +0 +endtrack +node -1 0 ul_50 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 104.00 4400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 105.00 4500.0 0.0 +0 +endtrack +node -1 0 ul_51 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 105.00 4500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 106.00 4600.0 0.0 +0 +endtrack +node -1 0 ul_52 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 106.00 4600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 107.00 4700.0 0.0 +0 +endtrack +node -1 0 ul_53 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 107.00 4700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 108.00 4800.0 0.0 +0 +endtrack +node -1 0 ul_54 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 108.00 4800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 109.00 4900.0 0.0 +0 +endtrack +node -1 0 ul_55 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 109.00 4900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 110.00 5000.0 0.0 +0 +endtrack +node -1 0 ul_56 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 110.00 5000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 111.00 5100.0 0.0 +0 +endtrack +node -1 0 ul_57 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 111.00 5100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 112.00 5200.0 0.0 +0 +endtrack +node -1 0 ul_58 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 112.00 5200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 113.00 5300.0 0.0 +0 +event2 ul_sem_info +endtrack +node -1 0 ul_59 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 113.00 5300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 114.00 5400.0 0.0 +0 +endtrack +node -1 0 ul_60 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 114.00 5400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 115.00 5500.0 0.0 +0 +endtrack +// the overhead wire along the whole line, as td.scn has it: 5.6 m above the rail, the carrier 1.7 m higher, fed by +// a substation of its own +node -1 0 ul_pwr tractionpowersource -3000.0 60.00 0.0 3400 0 0.01 2000 1.0 3 60.0 end +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -600.0 +-3000.0 65.60 -500.0 +-3000.0 67.30 -600.0 +-3000.0 67.30 -500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -500.0 +-3000.0 65.60 -400.0 +-3000.0 67.30 -500.0 +-3000.0 67.30 -400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -400.0 +-3000.0 65.60 -300.0 +-3000.0 67.30 -400.0 +-3000.0 67.30 -300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -300.0 +-3000.0 65.60 -200.0 +-3000.0 67.30 -300.0 +-3000.0 67.30 -200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -200.0 +-3000.0 65.60 -100.0 +-3000.0 67.30 -200.0 +-3000.0 67.30 -100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -100.0 +-3000.0 65.60 0.0 +-3000.0 67.30 -100.0 +-3000.0 67.30 0.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 0.0 +-3000.0 66.60 100.0 +-3000.0 67.30 0.0 +-3000.0 68.30 100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 66.60 100.0 +-3000.0 67.60 200.0 +-3000.0 68.30 100.0 +-3000.0 69.30 200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 67.60 200.0 +-3000.0 68.60 300.0 +-3000.0 69.30 200.0 +-3000.0 70.30 300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 68.60 300.0 +-3000.0 69.60 400.0 +-3000.0 70.30 300.0 +-3000.0 71.30 400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 69.60 400.0 +-3000.0 70.60 500.0 +-3000.0 71.30 400.0 +-3000.0 72.30 500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 70.60 500.0 +-3000.0 71.60 600.0 +-3000.0 72.30 500.0 +-3000.0 73.30 600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 71.60 600.0 +-3000.0 72.60 700.0 +-3000.0 73.30 600.0 +-3000.0 74.30 700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 72.60 700.0 +-3000.0 73.60 800.0 +-3000.0 74.30 700.0 +-3000.0 75.30 800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 73.60 800.0 +-3000.0 74.60 900.0 +-3000.0 75.30 800.0 +-3000.0 76.30 900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 74.60 900.0 +-3000.0 75.60 1000.0 +-3000.0 76.30 900.0 +-3000.0 77.30 1000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 75.60 1000.0 +-3000.0 76.60 1100.0 +-3000.0 77.30 1000.0 +-3000.0 78.30 1100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 76.60 1100.0 +-3000.0 77.60 1200.0 +-3000.0 78.30 1100.0 +-3000.0 79.30 1200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 77.60 1200.0 +-3000.0 78.60 1300.0 +-3000.0 79.30 1200.0 +-3000.0 80.30 1300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 78.60 1300.0 +-3000.0 79.60 1400.0 +-3000.0 80.30 1300.0 +-3000.0 81.30 1400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 79.60 1400.0 +-3000.0 80.60 1500.0 +-3000.0 81.30 1400.0 +-3000.0 82.30 1500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 80.60 1500.0 +-3000.0 81.60 1600.0 +-3000.0 82.30 1500.0 +-3000.0 83.30 1600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 81.60 1600.0 +-3000.0 82.60 1700.0 +-3000.0 83.30 1600.0 +-3000.0 84.30 1700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 82.60 1700.0 +-3000.0 83.60 1800.0 +-3000.0 84.30 1700.0 +-3000.0 85.30 1800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 83.60 1800.0 +-3000.0 84.60 1900.0 +-3000.0 85.30 1800.0 +-3000.0 86.30 1900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 84.60 1900.0 +-3000.0 85.60 2000.0 +-3000.0 86.30 1900.0 +-3000.0 87.30 2000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 85.60 2000.0 +-3000.0 86.60 2100.0 +-3000.0 87.30 2000.0 +-3000.0 88.30 2100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 86.60 2100.0 +-3000.0 87.60 2200.0 +-3000.0 88.30 2100.0 +-3000.0 89.30 2200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 87.60 2200.0 +-3000.0 88.60 2300.0 +-3000.0 89.30 2200.0 +-3000.0 90.30 2300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 88.60 2300.0 +-3000.0 89.60 2400.0 +-3000.0 90.30 2300.0 +-3000.0 91.30 2400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 89.60 2400.0 +-3000.0 90.60 2500.0 +-3000.0 91.30 2400.0 +-3000.0 92.30 2500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 90.60 2500.0 +-3000.0 91.60 2600.0 +-3000.0 92.30 2500.0 +-3000.0 93.30 2600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 91.60 2600.0 +-3000.0 92.60 2700.0 +-3000.0 93.30 2600.0 +-3000.0 94.30 2700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 92.60 2700.0 +-3000.0 93.60 2800.0 +-3000.0 94.30 2700.0 +-3000.0 95.30 2800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 93.60 2800.0 +-3000.0 94.60 2900.0 +-3000.0 95.30 2800.0 +-3000.0 96.30 2900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 94.60 2900.0 +-3000.0 95.60 3000.0 +-3000.0 96.30 2900.0 +-3000.0 97.30 3000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 95.60 3000.0 +-3000.0 96.60 3100.0 +-3000.0 97.30 3000.0 +-3000.0 98.30 3100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 96.60 3100.0 +-3000.0 97.60 3200.0 +-3000.0 98.30 3100.0 +-3000.0 99.30 3200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 97.60 3200.0 +-3000.0 98.60 3300.0 +-3000.0 99.30 3200.0 +-3000.0 100.30 3300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 98.60 3300.0 +-3000.0 99.60 3400.0 +-3000.0 100.30 3300.0 +-3000.0 101.30 3400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 99.60 3400.0 +-3000.0 100.60 3500.0 +-3000.0 101.30 3400.0 +-3000.0 102.30 3500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 100.60 3500.0 +-3000.0 101.60 3600.0 +-3000.0 102.30 3500.0 +-3000.0 103.30 3600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 101.60 3600.0 +-3000.0 102.60 3700.0 +-3000.0 103.30 3600.0 +-3000.0 104.30 3700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 102.60 3700.0 +-3000.0 103.60 3800.0 +-3000.0 104.30 3700.0 +-3000.0 105.30 3800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 103.60 3800.0 +-3000.0 104.60 3900.0 +-3000.0 105.30 3800.0 +-3000.0 106.30 3900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 104.60 3900.0 +-3000.0 105.60 4000.0 +-3000.0 106.30 3900.0 +-3000.0 107.30 4000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 105.60 4000.0 +-3000.0 106.60 4100.0 +-3000.0 107.30 4000.0 +-3000.0 108.30 4100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 106.60 4100.0 +-3000.0 107.60 4200.0 +-3000.0 108.30 4100.0 +-3000.0 109.30 4200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 107.60 4200.0 +-3000.0 108.60 4300.0 +-3000.0 109.30 4200.0 +-3000.0 110.30 4300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 108.60 4300.0 +-3000.0 109.60 4400.0 +-3000.0 110.30 4300.0 +-3000.0 111.30 4400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 109.60 4400.0 +-3000.0 110.60 4500.0 +-3000.0 111.30 4400.0 +-3000.0 112.30 4500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 110.60 4500.0 +-3000.0 111.60 4600.0 +-3000.0 112.30 4500.0 +-3000.0 113.30 4600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 111.60 4600.0 +-3000.0 112.60 4700.0 +-3000.0 113.30 4600.0 +-3000.0 114.30 4700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 112.60 4700.0 +-3000.0 113.60 4800.0 +-3000.0 114.30 4700.0 +-3000.0 115.30 4800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 113.60 4800.0 +-3000.0 114.60 4900.0 +-3000.0 115.30 4800.0 +-3000.0 116.30 4900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 114.60 4900.0 +-3000.0 115.60 5000.0 +-3000.0 116.30 4900.0 +-3000.0 117.30 5000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 115.60 5000.0 +-3000.0 116.60 5100.0 +-3000.0 117.30 5000.0 +-3000.0 118.30 5100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 116.60 5100.0 +-3000.0 117.60 5200.0 +-3000.0 118.30 5100.0 +-3000.0 119.30 5200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 117.60 5200.0 +-3000.0 118.60 5300.0 +-3000.0 119.30 5200.0 +-3000.0 120.30 5300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 118.60 5300.0 +-3000.0 119.60 5400.0 +-3000.0 120.30 5300.0 +-3000.0 121.30 5400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 119.60 5400.0 +-3000.0 120.60 5500.0 +-3000.0 121.30 5400.0 +-3000.0 122.30 5500.0 +0.4 4.0 3 0.04 vis +endtraction +// the W4 of the stations of the timetable +include ip/pkp/w4n.inc gora#1 -2997.3 60.00 -90.0 180 0 0 -10 202 end +// a signal at stop: what the AI reads of one, a memory cell with SetVelocity 0 0 and the event that reads it +node -1 0 ul_sem_mem memcell -2997.3 121.00 5300.0 SetVelocity 0.0 0.0 none endmemcell +event ul_sem_info getvalues 5.0 ul_sem_mem endevent + +trainset {{timetable}} ul_05 0.0 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_upgrade_signal_start.scn b/tests/scenarios/cases/td_upgrade_signal_start.scn new file mode 100644 index 000000000..3995d3a96 --- /dev/null +++ b/tests/scenarios/cases/td_upgrade_signal_start.scn @@ -0,0 +1,492 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a line of its own, away from the tracks of td.scn: 600 m level, then 2500 m up a gradient of 10 per mille, +// under an overhead wire. the train starts on the level with its head 10 m before the W4 of Gora and runs on the +// timetable {{timetable}} (no stop; a freight train leaves Gora at once) up to the signal hu_sem1 1000 m up the gradient, at stop until 10:42, +// where it stops with the whole train on the gradient, then on to the signal hu_sem2 at stop 2300 m up the +// gradient. the line goes on 200 m past it +node -1 0 hu_00 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -500.0 0.0 +0 +endtrack +node -1 0 hu_01 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -400.0 0.0 +0 +endtrack +node -1 0 hu_02 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -300.0 0.0 +0 +endtrack +node -1 0 hu_03 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -200.0 0.0 +0 +endtrack +node -1 0 hu_04 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -100.0 0.0 +0 +endtrack +node -1 0 hu_05 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 0.0 0.0 +0 +event2 gora#1_stopinfo +endtrack +node -1 0 hu_06 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 0.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 61.00 100.0 0.0 +0 +endtrack +node -1 0 hu_07 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 61.00 100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 62.00 200.0 0.0 +0 +endtrack +node -1 0 hu_08 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 62.00 200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 63.00 300.0 0.0 +0 +endtrack +node -1 0 hu_09 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 63.00 300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 64.00 400.0 0.0 +0 +endtrack +node -1 0 hu_10 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 64.00 400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 65.00 500.0 0.0 +0 +endtrack +node -1 0 hu_11 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 65.00 500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 66.00 600.0 0.0 +0 +endtrack +node -1 0 hu_12 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 66.00 600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 67.00 700.0 0.0 +0 +endtrack +node -1 0 hu_13 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 67.00 700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 68.00 800.0 0.0 +0 +endtrack +node -1 0 hu_14 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 68.00 800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 69.00 900.0 0.0 +0 +endtrack +node -1 0 hu_15 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 69.00 900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 70.00 1000.0 0.0 +0 +event2 hu_sem1_info +endtrack +node -1 0 hu_16 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 70.00 1000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 71.00 1100.0 0.0 +0 +endtrack +node -1 0 hu_17 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 71.00 1100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 72.00 1200.0 0.0 +0 +endtrack +node -1 0 hu_18 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 72.00 1200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 73.00 1300.0 0.0 +0 +endtrack +node -1 0 hu_19 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 73.00 1300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 74.00 1400.0 0.0 +0 +endtrack +node -1 0 hu_20 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 74.00 1400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 75.00 1500.0 0.0 +0 +endtrack +node -1 0 hu_21 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 75.00 1500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 76.00 1600.0 0.0 +0 +endtrack +node -1 0 hu_22 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 76.00 1600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 77.00 1700.0 0.0 +0 +endtrack +node -1 0 hu_23 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 77.00 1700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 78.00 1800.0 0.0 +0 +endtrack +node -1 0 hu_24 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 78.00 1800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 79.00 1900.0 0.0 +0 +endtrack +node -1 0 hu_25 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 79.00 1900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 80.00 2000.0 0.0 +0 +endtrack +node -1 0 hu_26 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 80.00 2000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 81.00 2100.0 0.0 +0 +endtrack +node -1 0 hu_27 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 81.00 2100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 82.00 2200.0 0.0 +0 +endtrack +node -1 0 hu_28 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 82.00 2200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 83.00 2300.0 0.0 +0 +event2 hu_sem2_info +endtrack +node -1 0 hu_29 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 83.00 2300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 84.00 2400.0 0.0 +0 +endtrack +node -1 0 hu_30 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 84.00 2400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 85.00 2500.0 0.0 +0 +endtrack +// the overhead wire along the whole line, as td.scn has it: 5.6 m above the rail, the carrier 1.7 m higher, fed by +// a substation of its own +node -1 0 hu_pwr tractionpowersource -3000.0 60.00 0.0 3400 0 0.01 2000 1.0 3 60.0 end +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -600.0 +-3000.0 65.60 -500.0 +-3000.0 67.30 -600.0 +-3000.0 67.30 -500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -500.0 +-3000.0 65.60 -400.0 +-3000.0 67.30 -500.0 +-3000.0 67.30 -400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -400.0 +-3000.0 65.60 -300.0 +-3000.0 67.30 -400.0 +-3000.0 67.30 -300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -300.0 +-3000.0 65.60 -200.0 +-3000.0 67.30 -300.0 +-3000.0 67.30 -200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -200.0 +-3000.0 65.60 -100.0 +-3000.0 67.30 -200.0 +-3000.0 67.30 -100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -100.0 +-3000.0 65.60 0.0 +-3000.0 67.30 -100.0 +-3000.0 67.30 0.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 0.0 +-3000.0 66.60 100.0 +-3000.0 67.30 0.0 +-3000.0 68.30 100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 66.60 100.0 +-3000.0 67.60 200.0 +-3000.0 68.30 100.0 +-3000.0 69.30 200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 67.60 200.0 +-3000.0 68.60 300.0 +-3000.0 69.30 200.0 +-3000.0 70.30 300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 68.60 300.0 +-3000.0 69.60 400.0 +-3000.0 70.30 300.0 +-3000.0 71.30 400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 69.60 400.0 +-3000.0 70.60 500.0 +-3000.0 71.30 400.0 +-3000.0 72.30 500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 70.60 500.0 +-3000.0 71.60 600.0 +-3000.0 72.30 500.0 +-3000.0 73.30 600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 71.60 600.0 +-3000.0 72.60 700.0 +-3000.0 73.30 600.0 +-3000.0 74.30 700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 72.60 700.0 +-3000.0 73.60 800.0 +-3000.0 74.30 700.0 +-3000.0 75.30 800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 73.60 800.0 +-3000.0 74.60 900.0 +-3000.0 75.30 800.0 +-3000.0 76.30 900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 74.60 900.0 +-3000.0 75.60 1000.0 +-3000.0 76.30 900.0 +-3000.0 77.30 1000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 75.60 1000.0 +-3000.0 76.60 1100.0 +-3000.0 77.30 1000.0 +-3000.0 78.30 1100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 76.60 1100.0 +-3000.0 77.60 1200.0 +-3000.0 78.30 1100.0 +-3000.0 79.30 1200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 77.60 1200.0 +-3000.0 78.60 1300.0 +-3000.0 79.30 1200.0 +-3000.0 80.30 1300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 78.60 1300.0 +-3000.0 79.60 1400.0 +-3000.0 80.30 1300.0 +-3000.0 81.30 1400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 79.60 1400.0 +-3000.0 80.60 1500.0 +-3000.0 81.30 1400.0 +-3000.0 82.30 1500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 80.60 1500.0 +-3000.0 81.60 1600.0 +-3000.0 82.30 1500.0 +-3000.0 83.30 1600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 81.60 1600.0 +-3000.0 82.60 1700.0 +-3000.0 83.30 1600.0 +-3000.0 84.30 1700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 82.60 1700.0 +-3000.0 83.60 1800.0 +-3000.0 84.30 1700.0 +-3000.0 85.30 1800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 83.60 1800.0 +-3000.0 84.60 1900.0 +-3000.0 85.30 1800.0 +-3000.0 86.30 1900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 84.60 1900.0 +-3000.0 85.60 2000.0 +-3000.0 86.30 1900.0 +-3000.0 87.30 2000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 85.60 2000.0 +-3000.0 86.60 2100.0 +-3000.0 87.30 2000.0 +-3000.0 88.30 2100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 86.60 2100.0 +-3000.0 87.60 2200.0 +-3000.0 88.30 2100.0 +-3000.0 89.30 2200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 87.60 2200.0 +-3000.0 88.60 2300.0 +-3000.0 89.30 2200.0 +-3000.0 90.30 2300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 88.60 2300.0 +-3000.0 89.60 2400.0 +-3000.0 90.30 2300.0 +-3000.0 91.30 2400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 89.60 2400.0 +-3000.0 90.60 2500.0 +-3000.0 91.30 2400.0 +-3000.0 92.30 2500.0 +0.4 4.0 3 0.04 vis +endtraction +// the W4 of the stations of the timetable +include ip/pkp/w4n.inc gora#1 -2997.3 60.00 -90.0 180 0 0 -10 202 end +// a signal at stop: what the AI reads of one, a memory cell with SetVelocity 0 0 and the event that reads it +node -1 0 hu_sem1_mem memcell -2997.3 78.00 1000.0 SetVelocity 0.0 0.0 none endmemcell +event hu_sem1_info getvalues 5.0 hu_sem1_mem endevent +// cleared at 10:42: the memory cell lets the train go at the line speed +event hu_sem1_go updatevalues 0.0 hu_sem1_mem SetVelocity 100 100 endevent +node -1 0 hu_sem1_launcher eventlauncher 0 0 0 -1 none 1042 hu_sem1_go end +// a signal at stop: what the AI reads of one, a memory cell with SetVelocity 0 0 and the event that reads it +node -1 0 hu_sem2_mem memcell -2997.3 91.00 2300.0 SetVelocity 0.0 0.0 none endmemcell +event hu_sem2_info getvalues 5.0 hu_sem2_mem endevent + +trainset {{timetable}} hu_05 0.0 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/test_mode_standing_1m_past_signal.json b/tests/scenarios/cases/test_mode_standing_1m_past_signal.json new file mode 100644 index 000000000..4157dc52d --- /dev/null +++ b/tests/scenarios/cases/test_mode_standing_1m_past_signal.json @@ -0,0 +1,16 @@ +{ + "description": "Test mode, no signal passed at danger for a train set past a signal: EU07 on td.scn standing with its head 1 m past the exit signal stacja1_j at stop (no route). Its driver finds the signal behind the head at its first look ahead, about 13 s in; a standing train passes nothing, so it isn't a signal passed at danger, and the case runs into its timeout.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_past_red_signal.scn", + "vars": { + "offset": "52.0", + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 60, + "timeout": 600, + "checks": [ + { "type": "max_speed", "limit": 1 }, + { "type": "distance", "max": 1 } + ] +} diff --git a/tests/scenarios/cases/test_mode_standing_4m_past_signal.json b/tests/scenarios/cases/test_mode_standing_4m_past_signal.json new file mode 100644 index 000000000..b0b668873 --- /dev/null +++ b/tests/scenarios/cases/test_mode_standing_4m_past_signal.json @@ -0,0 +1,16 @@ +{ + "description": "Test mode, no signal passed at danger for a train set past a signal: EU07 on td.scn standing with its head 4 m past the exit signal stacja1_j at stop (no route). Its driver finds the signal behind the head at its first look ahead, about 13 s in; a standing train passes nothing, so it isn't a signal passed at danger, and the case runs into its timeout.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_past_red_signal.scn", + "vars": { + "offset": "55.0", + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 60, + "timeout": 600, + "checks": [ + { "type": "max_speed", "limit": 1 }, + { "type": "distance", "max": 1 } + ] +} diff --git a/tests/scenarios/cases/traxx_td_crew_add.json b/tests/scenarios/cases/traxx_td_crew_add.json new file mode 100644 index 000000000..9d6200a1b --- /dev/null +++ b/tests/scenarios/cases/traxx_td_crew_add.json @@ -0,0 +1,31 @@ +{ + "description": "As eu07_td_crew_add, with a Traxx (E186, p160dc) standing ready to depart (trainset velocity 0.1) with nobody in it: its brake handle, one with a time chamber (MHZ_6P), in the holding position and the brake pipe and the control reservoir at running pressure. The AI driver put in cab A 20 s after the start gets the locomotive ready, puts the handle to running and leaves through the exit signal.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_crew.scn", + "vars": { + "trainsets": [ + "trainset none tdo_n1734 0.0 0.1", + "node -1 0 {{vehicle}} dynamic pkp/e186_v2 146_226-6 p160dc 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "crew": [ + "event autotest_crew_put putvalues 0 none 0 0 0 Crew:{{vehicle}} 1 0 endevent", + "event autotest_crew_on multiple 20 none autotest_crew_put autotest_crew_waits endevent", + "node -1 0 autotest_crew_on_launcher eventlauncher 0 0 0 -1 none 1034 autotest_crew_on end" + ] + }, + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Crew: \\[autotest_traxx_td_crew_add\\] an AI driver takes cab A" }, + { "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "ai", "after": 15, "before": 30 }, + { "type": "starts", "min_speed": 20, "within": 240 }, + { "type": "moves", "vehicle": "{{vehicle}}", "direction": "front", "min_speed": 20 }, + { "type": "log_lacks", "pattern": "derailed" }, + { "type": "log_lacks", "pattern": "collided" } + ] +} diff --git a/tests/scenarios/cases/traxx_td_timetable.json b/tests/scenarios/cases/traxx_td_timetable.json new file mode 100644 index 000000000..51d84860b --- /dev/null +++ b/tests/scenarios/cases/traxx_td_timetable.json @@ -0,0 +1,17 @@ +{ + "description": "Traxx (E186, p160dc) on td.scn, AI driver on the td/rozklad timetable: a driver's brake handle with a time chamber (MHZ_6P), for which the AI getting the locomotive ready has a rule of its own for releasing the train brake (5775493b2, #444). Starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/e186_v2 146_226-6 p160dc 0 headdriver 0 0 enddynamic" + }, + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "brakes", "min_pressure": 0.5 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/scenarios/cases/traxx_td_timetable_cold.json b/tests/scenarios/cases/traxx_td_timetable_cold.json new file mode 100644 index 000000000..bfdb833a2 --- /dev/null +++ b/tests/scenarios/cases/traxx_td_timetable_cold.json @@ -0,0 +1,20 @@ +{ + "description": "As traxx_td_timetable, from a cold start: the trainset stands with velocity 0, so the locomotive starts braked, its brake handle (MHZ_6P, with a time chamber) in the holding position and the brake pipe below running pressure. The driver gets the order to run as a train, starts the locomotive, puts the handle to running, charges the brake pipe and leaves on time.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_cold_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/e186_v2 146_226-6 p160dc 0 headdriver 0 0 enddynamic" + }, + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "brakes", "min_pressure": 0.5 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/scenarios/cases/vectron_td_crew_remove.json b/tests/scenarios/cases/vectron_td_crew_remove.json new file mode 100644 index 000000000..e677b8a3a --- /dev/null +++ b/tests/scenarios/cases/vectron_td_crew_remove.json @@ -0,0 +1,27 @@ +{ + "description": "Crew event, the driver disappears (eu07/maszyna#510): as eu07_td_crew_remove, with a Vectron (induction motors, an integrated power and brake handle) which loses its AI driver on the run at 10:36, stops and stays where it stopped.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_crew.scn", + "vars": { + "trainsets": [ + "trainset td/rozklad tdo_n1734 0.0 0.1", + "node -1 0 {{vehicle}} dynamic pkp\\vectron_v1 1293-107 wariant_7w 0 headdriver 0 0 enddynamic", + "endtrainset" + ], + "crew": [ + "event autotest_crew_off putvalues 0 none 0 0 0 Crew:{{vehicle}} 0 0 endevent", + "node -1 0 autotest_crew_off_launcher eventlauncher 0 0 0 -1 none 1036 autotest_crew_off end" + ] + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "log_contains", "pattern": "Crew: \\[autotest_vectron_td_crew_remove\\] the AI driver leaves" }, + { "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "none", "after": 115, "before": 130 }, + { "type": "stops_driverless", "vehicle": "{{vehicle}}", "min_speed": 20, "within": 60, "hold": 100 }, + { "type": "log_lacks", "pattern": "derailed" }, + { "type": "log_lacks", "pattern": "collided" } + ] +} diff --git a/tests/scenarios/cases/wrzosy_pxe336080_couple.scn b/tests/scenarios/cases/wrzosy_pxe336080_couple.scn new file mode 100644 index 000000000..c0d504d57 --- /dev/null +++ b/tests/scenarios/cases/wrzosy_pxe336080_couple.scn @@ -0,0 +1,39 @@ +// added by tests/scenarios/run.py to wrzosy_pxe336080.scn, which keeps its own trainsets: the mission of +// eu07/maszyna#524. EU07-234 runs light from final_2t839 through the Wolica depot to the rake of 12 coaches +// pxe_1 .. pxe_12 (linia053_wrzosy/pxe336080_dekoracje.scm, "trainset none woa_odst009 304 0"), has to +// couple to it and take it out of the depot. +// +// the scenery gives the locomotive no order at all: its trainset has velocity 0, so with nobody in the cab +// its driver sleeps in Wait_for_orders, and nothing in the scenery tells it to couple, the player does that +// by hand. the two orders the player's hands stand for are given here. +// +// 1. a minute after the start (the scenery sets the way and the shunting signals at 50-55 s): shunt, as +// the signals say (Shunt -1 0). PutValues goes to the vehicle that set the event off, so it hangs on +// event0 of the track the locomotive stands on (the three its 16 m may reach); event0 comes again and +// again while it stands there, the cell lets the order through once. +// the first order is not the one to couple, on purpose: a driver whose first order is Connect never +// releases the hand brake the locomotive starts with, and pulls against it for good (CheckVehicles() +// leaves AutoRewident() out for Connect). +node -1 0 autotest_ordered memcell 0 0 0 ordered 0 0 none endmemcell +event final_2t838:event0 multiple 60 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event final_2t839:event0 multiple 60 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event final_2t840:event0 multiple 60 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event autotest_order PutValues 0 none 0 0 0 Shunt -1 0 endevent +event autotest_order_given UpdateValues 0 autotest_ordered * 1 * endevent + +// 2. on the last track before the rake, in the direction the locomotive comes from (event2 of +// woa_lokom007, some 35-45 m short of the first coach): couple to the consist standing ahead with the +// coupler and the brake hose (3), turn round and wait for the shunting signal. it is the order these +// sceneries give their AI shunters (dos_sm42_przypnij). +event woa_lokom007:event2 PutValues 0 none 0 0 0 Shunt -2 -3 endevent + +// 330 s after the locomotive ran over lok_woa005 towards the rake the scenery sets the way out +// (lok_woa005:event2 -> PXE_gotowy -> pxe_manewry_ruszaj), coupled or not. it leads back over lok_woa005, +// towards its point 1. every vehicle going that way is counted (eventall1); the locomotive alone makes 1, +// so the second vehicle is a coach of the rake, coupled and pulled. the test ends there, with the train +// still moving (test.no_movement_before_pass no). +node -1 0 autotest_left memcell 0 0 0 left 0 0 none endmemcell +event lok_woa005:eventall1 multiple 0 none autotest_count autotest_judge endevent +event autotest_count AddValues 0 autotest_left * 1 0 endevent +event autotest_judge multiple 0 autotest_left autotest_pass condition memcompare * 2 * endevent +event autotest_pass UpdateValues 0 __test.result the_rake_left_the_depot_behind_the_locomotive 1 * endevent diff --git a/tests/scenarios/cases/wrzosy_pxe336080_couples.json b/tests/scenarios/cases/wrzosy_pxe336080_couples.json new file mode 100644 index 000000000..11d385871 --- /dev/null +++ b/tests/scenarios/cases/wrzosy_pxe336080_couples.json @@ -0,0 +1,26 @@ +{ + "description": "eu07/maszyna#524, Wrzosy PXE336080: EU07-234 runs light to the rake of 12 coaches in the Wolica depot, gets the order to couple (the player's hand, the scenery gives none), has to couple to the first coach and leave the depot with the rake behind it.", + "base_scenery": "wrzosy_pxe336080.scn", + "strip_trainsets": false, + "vehicle": "EU07-234", + "fragment": "wrzosy_pxe336080_couple.scn", + "slow": true, + "ini": [ + "file.binary.terrain no" + ], + "test_config": [ + "test.timeout 1800", + "test.standstill 900", + "test.fail_if_stop_overran no", + "test.no_movement_before_pass no" + ], + "expect": "pass", + "timeout": 1200, + "checks": [ + { + "type": "couples", + "vehicle": "EU07-234", + "other": "pxe_1" + } + ] +} diff --git a/tests/scenarios/make_off_track_curves.py b/tests/scenarios/make_off_track_curves.py new file mode 100644 index 000000000..447d8ddb1 --- /dev/null +++ b/tests/scenarios/make_off_track_curves.py @@ -0,0 +1,118 @@ +"""Writes the eu07_td_off_track_curve_* cases and their fragments (cases/td_off_track_curve_*.scn): a track of R 300 m +laid on its own in the fields of td.scn, on level ground, on an embankment 4 m high and in a cutting whose banks rise +4 m at 1:1.5 and on at 1:5, with an EU07 without a driver overturning on it (physics.derailment new). + + python tests/scenarios/make_off_track_curves.py +""" +import json +import math +from pathlib import Path + +CASES = str(Path(__file__).resolve().parent / "cases") + "/" +R = 300.0 +CENTRE = (-600.0, 400.0) # x, z +THETA = 0.5 # rad of the track, 150 m +RAIL = {'flat': 0.2, 'embankment': 4.2, 'cutting': 0.2} +# the cross section of the ground: (offset from the axis, height), outwards from the centre of the curve positive; +# the grass of td.scn lies at 0 around it +SECTIONS = { + 'embankment': [(-9.5, 0.0), (-3.5, 4.0), (3.5, 4.0), (9.5, 0.0)], + 'cutting': [(-150.0, 32.1), (-9.5, 4.0), (-3.5, 0.0), (3.5, 0.0), (9.5, 4.0), (150.0, 32.1)], +} +BACKSLASH = chr(92) +NEWLINE = chr(10) + + +def point(phi, offset, height): + # outwards: away from the centre of the curve + r = R + offset + return (CENTRE[0] + r * math.cos(phi), height, CENTRE[1] + r * math.sin(phi)) + + +def triangles(kind): + # a triangle strip for each band of the cross section, along the curve every 0.03 rad (9 m) + nodes = [] + section = SECTIONS[kind] + phis = [-0.3 + 0.03 * i for i in range(41)] # 90 m before the track to 120 m past it + for (o1, h1), (o2, h2) in zip(section, section[1:]): + lines = [] + for phi in phis: + for offset, height in ((o1, h1), (o2, h2)): + x, y, z = point(phi, offset, height) + lines.append(f"{x:.2f} {y:.2f} {z:.2f} 0 1 0 0 0") + nodes.append("node -1 0 none triangle_strip grass" + NEWLINE + (" end" + NEWLINE).join(lines) + NEWLINE + "endtri") + return nodes + + +def track(kind): + y = RAIL[kind] + p1 = point(0.0, 0.0, y) + p2 = point(THETA, 0.0, y) + k = 4.0 / 3.0 * math.tan(THETA / 4.0) * R + t1 = (-math.sin(0.0), math.cos(0.0)) + t2 = (-math.sin(THETA), math.cos(THETA)) + return NEWLINE.join([ + f"node -1 0 autotest_curve track normal {R * THETA:.4f} 1.435 0.15 25.0 20 0 flat vis", + " rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1", + f"{p1[0]:.4f} {y} {p1[2]:.4f} 0.0 //point 1", + f"{t1[0] * k:.4f} 0.0 {t1[1] * k:.4f} //control vector 1", + f"{-t2[0] * k:.4f} 0.0 {-t2[1] * k:.4f} //control vector 2", + f"{p2[0]:.4f} {y} {p2[2]:.4f} 0.0 //point 2", + f"{R}", + "endtrack"]) + + +WORDS = { + 'flat': ("on level ground", "the grass of td.scn", + "it slides on the grass out of the curve, falls on its side and stops"), + 'embankment': ("on an embankment 4 m high with slopes of 1:1.5", "triangles of the fragment", + "it falls on its side over the edge of the embankment, slides down its slope and on over the level ground at its foot, 4 m lower"), + 'cutting': ("in a cutting with banks of 1:1.5 4 m high, the ground rising on beyond them at 1:5", "triangles of the fragment", + "it runs into the bank on the outside of the curve, climbs it and stops sooner than on level ground"), +} +CHECKS = { + 'flat': {"min_offset": 3, "min_distance": 50, "max_distance": 250, "lying": True}, + 'embankment': {"min_offset": 5, "min_distance": 30, "max_distance": 300, "lying": True}, + 'cutting': {"min_offset": 3, "min_distance": 20, "max_distance": 230}, +} +HEADER = [ + "// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed (physics.derailment new, the vehicles", + "// off the track moving on the ground, vehicle/derailmotion.h): a track of R 300 m without cant laid on its own in the", + "// fields of td.scn (autotest_curve), {where}; written by a script, see the README.", + "// an EU07 with an AI driver and no timetable stands on track 1 of Stacja1, where td.scn keeps its timetable train, so", + "// it stays put and logs its physics; the EU07 of the case has no driver and runs at {{velocity}} km/h from 20 m past", + "// point 1 of the curve towards its point 2", +] +TRAINS = [ + "trainset none tdo_n1734 0.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp" + BACKSLASH + "4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic", + "endtrainset", + "", + "trainset none autotest_curve 20.0 {{velocity}}", + "node -1 0 {{vehicle}}_off dynamic pkp" + BACKSLASH + "4e_v1 4e-004 4e 0 nobody 0 0 enddynamic", + "endtrainset", +] +for kind in ('flat', 'embankment', 'cutting'): + nodes = ([] if kind == 'flat' else triangles(kind)) + [track(kind)] + where, source, what = WORDS[kind] + lines = [line.replace("{where}", where) for line in HEADER] + nodes + TRAINS + with open(CASES + f"td_off_track_curve_{kind}.scn", "w", encoding="utf-8", newline=NEWLINE) as out: + out.write(NEWLINE.join(lines) + NEWLINE) + case = { + "description": f"physics.derailment new: an EU07 without a driver runs at 150 km/h into a curve of R 300 m without cant, a track of 150 m laid on its own in the fields of td.scn (autotest_curve), {where} ({source}). Over its overturning speed (about 120 km/h) it overturns out of the curve: {what}.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": f"td_off_track_curve_{kind}.scn", + "vars": {"velocity": "150"}, + "ini": ["gfxrenderer null", "physics.derailment new", "couplerphysics all"], + "expect": "timeout", + "duration": 60, + "timeout": 600, + "checks": [ + {"type": "log_contains", "pattern": "derailment: autotest_" + BACKSLASH + "S+_off leaves the track"}, + dict({"type": "leaves_track", "vehicle": "{{vehicle}}_off", "cause": "overturned"}, **CHECKS[kind]), + ], + } + with open(CASES + f"eu07_td_off_track_curve_{kind}.json", "w", encoding="utf-8", newline=NEWLINE) as out: + out.write(json.dumps(case, indent=2, ensure_ascii=False) + NEWLINE) +print("written") diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py index 51fdc3c66..ad7ac5bcb 100644 --- a/tests/scenarios/run.py +++ b/tests/scenarios/run.py @@ -27,7 +27,9 @@ Usage: from __future__ import annotations import argparse +import heapq import json +import math import os import re import shutil @@ -48,7 +50,9 @@ OUT_DIR = HERE / "out" # Velocity is in km/h and pressures in bar, despite the header saying m/s and MPa. COL_TIME = 0 COL_VELOCITY = 1 # wheel speed: stays at 0 while the wheels are locked in a skid +COL_TRACTION_FORCE = 5 # N, despite the header saying kN COL_BRAKE_PRESS = 8 +COL_MASTER_CONTROLLER = 11 # the position of the master controller COL_COMMAND = 16 # text, read as None COL_WHEELSLIP = 20 COL_VEHICLE_VELOCITY = 25 # signed vehicle speed, km/h; only in builds which log it @@ -77,12 +81,14 @@ width 1280 height 720 inactivepause no soundenabled no -physicslog yes +convertmodels 0 +physicslog {physicslog} multiplelogs yes timespeed {timespeed} """ # multiplelogs: log and errors go to logs/log () .txt instead of the shared # log.txt, so runs of different cases can go in parallel +# convertmodels 0: a test run writes no converted models (.e3d) into the game dir # ---------------------------------------------------------------- scenery @@ -143,6 +149,60 @@ def scenery_cache(game_dir: Path, case_name: str) -> Path: return game_dir / "scenery" / f"autotest_{case_name}.sbt" +def timetable_name(case_name: str) -> str: + """The case's own timetable as a trainset names it: {{timetable}} in the fragment.""" + return f"autotest_{case_name}" + + +def timetable_path(game_dir: Path, case_name: str) -> Path: + return game_dir / "scenery" / f"{timetable_name(case_name)}.txt" + + +def variant_name(case_name: str, name: str) -> str: + """A vehicle variant of the case as a trainset names it: {{variant_}} in the fragment.""" + return f"autotest_{case_name}_{name}" + + +def variant_paths(game_dir: Path, case_name: str, variant: dict) -> list[Path]: + """The .fiz and .mmd of a vehicle variant of the case, beside those of the vehicle it is made from.""" + folder = (game_dir / "dynamic" / variant["from"]).parent + return [folder / f"{variant_name(case_name, variant['name'])}{suffix}" for suffix in (".fiz", ".mmd")] + + +def write_vehicle_variants(case: dict, game_dir: Path, case_name: str) -> None: + """Writes the case's vehicle variants into the game's dynamic/ dir: a copy of a vehicle's .fiz with the + case's replacements, e.g. a .fiz key the shipped data doesn't have yet, and a copy of its .mmd. The + simulator hands the .mmd its type name as (p2), which some pass on to the include that names the + model (et42_v2: `include 112e-a.mmd.inc (p2) end`, `models: (p1).t3d`), so the copy has the name of + the vehicle it is made from in place of (p2) and looks and loads as that one does.""" + files = {} + for variant in case.get("vehicle_variants", []): + source = game_dir / "dynamic" / variant["from"] + # the .fiz to copy: the vehicle's own, or another file named in full (fiz_from), e.g. the .fiz.inc a + # vehicle's .fiz only includes, as keys added after the include on a second line of the same section + # would load that section again + fiz_source = game_dir / "dynamic" / variant["fiz_from"] if "fiz_from" in variant else source.with_name(source.name + ".fiz") + fiz_name = variant.get("fiz_from", f"{variant['from']}.fiz") + # .fiz files are cp1250 like the sceneries; latin-1 round-trips every byte + fiz = fiz_source.read_bytes().decode("latin-1") + for old, new in variant.get("replace", []): + if old not in fiz: + sys.exit(f"vehicle_variants: {fiz_name} has no {old!r}") + fiz = fiz.replace(old, new) + mmd = source.with_name(source.name + ".mmd").read_bytes().decode("latin-1").replace("(p2)", source.name) + fiz_path, mmd_path = variant_paths(game_dir, case_name, variant) + files[fiz_path], files[mmd_path] = fiz, mmd + # written once every variant is made, so a case with a wrong replacement leaves nothing in the game dir + for path, text in files.items(): + path.write_bytes(text.encode("latin-1")) + + +def remove_vehicle_variants(case: dict, game_dir: Path, case_name: str) -> None: + for variant in case.get("vehicle_variants", []): + for path in variant_paths(game_dir, case_name, variant): + path.unlink(missing_ok=True) + + def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> str: """Writes the case scenery into the game's scenery dir and returns its file name.""" scenery_dir = game_dir / "scenery" @@ -156,10 +216,16 @@ def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> s text = set_track_friction(text, case["track_friction"]) if "track_events" in case: text = add_track_events(text, case["track_events"]) - fragment = (CASES_DIR / case["fragment"]).read_bytes().decode("latin-1") - # vars first: {{vehicle}} inside a var's value gets filled in the second pass - fragment = fill_vars(fragment, case.get("vars", {}), keep={"vehicle"}) - fragment = fill_vars(fragment, {"vehicle": vehicle}) + for old, new in case.get("replace", []): + if old not in text: + sys.exit(f"replace: the base scenery has no {old!r}") + text = text.replace(old, new) + # a case on a mission of the base scenery may have nothing to add but its test_config + fragment = (CASES_DIR / case["fragment"]).read_bytes().decode("latin-1") if "fragment" in case else "" + # vars first: {{vehicle}} and {{timetable}} inside a var's value get filled in the second pass + variants = {f"variant_{v['name']}": variant_name(case_name, v["name"]) for v in case.get("vehicle_variants", [])} + fragment = fill_vars(fragment, case.get("vars", {}), keep={"vehicle", "timetable", *variants}) + fragment = fill_vars(fragment, {"vehicle": vehicle, "timetable": timetable_name(case_name), **variants}) # FirstInit binds event launchers to their events and links the tracks. so launchers and # events of the case go in before it (read after it they never fire), trainsets after it # (placed before it they stand on unlinked track and derail at once) @@ -175,13 +241,19 @@ def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> s else: text += header + before + "\n" text += header + trainsets + "\n" + # vehicles of the case's own, made from those of the game + write_vehicle_variants(case, game_dir, case_name) name = f"autotest_{case_name}.scn" (scenery_dir / name).write_bytes(text.encode("latin-1")) + # a timetable of the case's own, for a train whose timetable the sceneries of the game have none like + if "timetable" in case: + shutil.copyfile(CASES_DIR / case["timetable"], timetable_path(game_dir, case_name)) # the simulator caches the scenery's static geometry in .sbt and reads it instead of # the terrain in the .scn (tracks, events and trainsets always come from the .scn), so - # drop the cache once the base scenery has changed + # drop the cache once the base scenery, or the fragment of the case (its own terrain), has changed cache = scenery_cache(game_dir, case_name) - if cache.exists() and cache.stat().st_mtime < (scenery_dir / case["base_scenery"]).stat().st_mtime: + sources = [scenery_dir / case["base_scenery"]] + ([CASES_DIR / case["fragment"]] if "fragment" in case else []) + if cache.exists() and cache.stat().st_mtime < max(source.stat().st_mtime for source in sources): cache.unlink() return name @@ -235,9 +307,14 @@ def read_text(path: Path | None) -> str: # physicslog/_.blackbox. A header, then records: a byte of the kind, the length, the content BLACKBOX_MAGIC = b"EU07BBX\0" BLACKBOX_HEADER = 12 # the magic, the version of the format, two bytes reserved +BLACKBOX_TRACK = 0x10 # the map: a rail track, or one way of a switch, as points along it BLACKBOX_VEHICLE = 0x12 # a vehicle: its number and its name +BLACKBOX_VEHICLES = 0x21 # once a second: the vehicles which moved, changed speed or got another driver BLACKBOX_COUPLING = 0x37 # a coupler of a vehicle coupled, uncoupled, or its hoses and cables changed +BLACKBOX_DERAILMENT = 0x38 # a vehicle left the track, or came to rest off it (physics.derailment new) +DERAILMENT_CAUSES = {1: "flange climbed", 2: "overturned", 3: "end of track", 4: "pulled off", 5: "collision"} COUPLING_COUPLER = 0x01 # of the bits telling what is coupled: the coupler itself +BLACKBOX_DRIVERS = {"none": 0, "user": 1, "ai": 2} # the driver byte of a vehicle state @dataclass @@ -253,10 +330,49 @@ class Coupling: previous_other: int +@dataclass +class VehicleState: + """A vehicle in a `vehicles` record: where it is and who drives it from `time` on, until its next one.""" + time: float + position: tuple[float, float, float] + speed: float # km/h, positive along its front + driver: int # 0 none, 1 a user, 2 the AI + + +@dataclass +class Derailment: + """A derailment record: a vehicle off the track as it left it (phase 0) or came to rest (phase 1).""" + time: float + vehicle: int + phase: int + cause: int # DERAILMENT_CAUSES + position: tuple[float, float, float] + heading: float # rad + speed: float # km/h + offset: float # m from the axis of the track, to the left of its front positive + roll: float # rad, to the left positive + travelled: float # m on the ground since it left the rails + lying: bool + + +@dataclass +class Track: + """A `track` record: a plain track, or one way of a switch (several records under the number of the switch).""" + number: int + name: str + kind: int # 0 a plain track, 1 a way of a switch + branch: int # the switch position this way is taken in + points: list[tuple[float, float, float]] + + @dataclass class Blackbox: vehicles: dict[int, str] = field(default_factory=dict) # names by number + tracks: list[Track] = field(default_factory=list) # the map, in the order written couplings: list[Coupling] = field(default_factory=list) # in the order written + derailments: list[Derailment] = field(default_factory=list) # in the order written + states: dict[int, list[VehicleState]] = field(default_factory=dict) # of each vehicle by number, in time order + end_time: float = 0.0 # of the last `vehicles` record def find_blackbox(game_dir: Path, scenery: str, since: float) -> Path | None: @@ -269,8 +385,22 @@ def find_blackbox(game_dir: Path, scenery: str, since: float) -> Path | None: return max(files, key=lambda p: p.stat().st_mtime, default=None) +def _blackbox_text(content: bytes, start: int) -> tuple[str, int]: + """A text of a black box record at `start`, and where the field after it begins.""" + # its length in 7 bit groups, low first, the high bit set on all but the last + size, shift = 0, 0 + while True: + byte = content[start] + start += 1 + size |= (byte & 0x7F) << shift + shift += 7 + if byte < 0x80: + break + return content[start: start + size].decode("utf-8", errors="replace"), start + size + + def read_blackbox(path: Path | None) -> Blackbox | None: - """The vehicles and the coupling records of a black box; None when there is none or it can't be read.""" + """The map, the vehicles and the coupling records of a black box; None when there is none or it can't be read.""" try: data = path.read_bytes() if path else b"" except FileNotFoundError: @@ -288,19 +418,29 @@ def read_blackbox(path: Path | None) -> Blackbox | None: at += 5 + length if kind == BLACKBOX_VEHICLE: number, = struct.unpack_from(" RunResult: + duration: float | None, timeout: float, watch: bool, say, expect_rows: bool = True) -> RunResult: """Runs the simulator on the scenery. In test mode it quits by itself and the exit code is the result; with watch it runs in a window and gets closed after `duration`.""" physicslog.unlink(missing_ok=True) @@ -351,7 +491,9 @@ def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog while True: time.sleep(0.25) # at timespeed 20 that is 5 s of simulation wall = time.monotonic() - started - result.rows = read_physicslog(physicslog) + # the whole file is read each time: in test mode, once there are rows, only for the progress line + if watch or not result.rows or wall - last_report >= 15: + result.rows = read_physicslog(physicslog) sim_t = result.rows[-1][COL_TIME] if result.rows else 0.0 if wall - last_report >= 15: v = result.rows[-1][COL_VELOCITY] if result.rows else 0.0 @@ -366,7 +508,10 @@ def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog if wall > timeout + (0 if watch else KILL_GRACE): result.failure = f"timed out after {wall:.0f}s before {duration}s of simulation" break - if not result.rows: + # not for a case with physicslog off, which has no rows to wait for, nor for one on a mission of the + # base scenery: a big scenery loads for minutes, and a bad vehicle among its decorations isn't the + # case's (a missing test vehicle ends the test mode with `error` by itself) + if expect_rows and not result.rows: result.logs = find_logs(game_dir, scenery, since) fatal = [l.strip() for l in read_text(result.logs.get("errors")).splitlines() if any(k in l for k in FATAL_LOG_LINES)] @@ -397,11 +542,14 @@ def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog # ---------------------------------------------------------------- checks -def check_starts(rows, min_speed, within): +def check_starts(rows, min_speed, within, after=None): for r in rows: if r[COL_TIME] > within: break if r[COL_VELOCITY] >= min_speed: + # a case can also say the train mustn't leave before something it waits for (a converter starting) + if after is not None and r[COL_TIME] < after: + return False, f"reached {min_speed} km/h at t={r[COL_TIME]:.1f}s, before {after}s" return True, f"reached {min_speed} km/h at t={r[COL_TIME]:.1f}s" top = max((r[COL_VELOCITY] for r in rows if r[COL_TIME] <= within), default=0.0) return False, f"top speed in the first {within}s was {top:.1f} km/h, wanted {min_speed}" @@ -437,25 +585,42 @@ def check_brakes(rows, min_pressure, moving_speed=20): return False, f"brake cylinder pressure never reached {min_pressure} bar after moving off" -def check_stops(rows, moving_speed, stop_speed, hold, min_distance=None, max_distance=None): +def check_stops(rows, moving_speed, stop_speed, hold, min_distance=None, max_distance=None, max_time=None, nth=1): + """The nth stop of `hold` seconds after moving off at `moving_speed` (each stop after the first counts once the + train is moving at `moving_speed` again).""" start = _first_moving(rows, moving_speed) if start is None: return False, f"never reached {moving_speed} km/h" dist = _distances(rows) stopped_at = None + held = 0 + moving = True for i in range(start, len(rows)): r = rows[i] + if not moving: + moving = r[COL_VELOCITY] >= moving_speed + continue if r[COL_VELOCITY] <= stop_speed: if stopped_at is None: stopped_at = i if r[COL_TIME] - rows[stopped_at][COL_TIME] >= hold: + held += 1 + if held < nth: + stopped_at = None + moving = False + continue where = dist[stopped_at] - detail = f"came to a stop at t={rows[stopped_at][COL_TIME]:.1f}s after {where:.0f} m" + when = rows[stopped_at][COL_TIME] + detail = f"came to a stop at t={when:.1f}s after {where:.0f} m" if (min_distance is not None and where < min_distance) or (max_distance is not None and where > max_distance): return False, f"{detail}, wanted between {min_distance} and {max_distance} m" + if max_time is not None and when > max_time: + return False, f"{detail}, wanted by t={max_time}s" return True, detail else: stopped_at = None + if held: + return False, f"stopped {held} times for {hold}s after moving off, wanted stop {nth}" return False, f"did not stay below {stop_speed} km/h for {hold}s after moving off" @@ -522,6 +687,58 @@ def check_ends_moving(rows, min_speed): return ok, f"last row t={last[COL_TIME]:.1f}s, v={last[COL_VELOCITY]:.1f} km/h (wanted >= {min_speed})" +def check_keeps_moving(rows, moving_speed, min_speed, until_distance, from_distance=0.0): + """(*vehicle speed*) Once at moving_speed, the speed stays at or above min_speed between the two distances (metres + travelled, from the vehicle speed), e.g. a train doesn't come to a stand on a gradient before a restriction or in + it. The vehicle speed, as wheels slipping at the start would count as moving off.""" + if not rows or len(rows[0]) <= COL_VEHICLE_VELOCITY or rows[0][COL_VEHICLE_VELOCITY] is None: + return False, "the physicslog has no vehicle speed column, the build is too old" + speed = [abs(r[COL_VEHICLE_VELOCITY]) for r in rows] + start = next((i for i, v in enumerate(speed) if v >= moving_speed), None) + if start is None: + return False, f"never reached {moving_speed} km/h" + dist, d = [0.0], 0.0 + for i in range(1, len(rows)): + d += (speed[i - 1] + speed[i]) / 2 / 3.6 * (rows[i][COL_TIME] - rows[i - 1][COL_TIME]) + dist.append(d) + span = [i for i in range(start, len(rows)) if from_distance <= dist[i] <= until_distance] + if not span or dist[-1] < until_distance: + return False, f"travelled {dist[-1]:.0f} m only, wanted {until_distance} m" + low = min(span, key=lambda i: speed[i]) + r = rows[low] + detail = (f"lowest speed {speed[low]:.1f} km/h at t={r[COL_TIME]:.1f}s after {dist[low]:.0f} m " + f"(brake cylinder {r[COL_BRAKE_PRESS]:.2f} bar), wanted >= {min_speed} between {from_distance:.0f} and {until_distance} m") + return speed[low] >= min_speed, detail + + +def check_starts_again(rows, after, min_speed, within, max_rollback=None): + """Standing at the time `after` (e.g. at a signal that clears then), the vehicle reaches min_speed within `within` + seconds; with max_rollback (*vehicle speed*), it rolls back no more than that many metres meanwhile.""" + first = next((i for i, r in enumerate(rows) if r[COL_TIME] >= after), None) + if first is None: + return False, f"the physicslog ends before t={after}s" + if rows[first][COL_VELOCITY] > 1.0: + return False, f"moving at {rows[first][COL_VELOCITY]:.1f} km/h at t={after}s, wanted standing" + moved = next((r[COL_TIME] for r in rows[first:] if r[COL_VELOCITY] > 1.0), None) + reached = next((r[COL_TIME] for r in rows[first:] if r[COL_VELOCITY] >= min_speed), None) + rollback, back = 0.0, 0.0 + if max_rollback is not None: + if len(rows[0]) <= COL_VEHICLE_VELOCITY or rows[0][COL_VEHICLE_VELOCITY] is None: + return False, "the physicslog has no vehicle speed column, the build is too old" + end = reached if reached is not None else after + within + for a, b in zip(rows[first:], rows[first + 1:]): + if b[COL_TIME] > end: + break + back += (a[COL_VEHICLE_VELOCITY] + b[COL_VEHICLE_VELOCITY]) / 2 / 3.6 * (b[COL_TIME] - a[COL_TIME]) + rollback = max(rollback, -back) + detail = (f"moved off (1 km/h) {moved - after:.1f}s after t={after}s" if moved is not None else f"didn't move off after t={after}s") + detail += f", {min_speed} km/h after {reached - after:.1f}s" if reached is not None else f", never reached {min_speed} km/h" + if max_rollback is not None: + detail += f", rolled back {rollback:.2f} m (wanted <= {max_rollback})" + ok = reached is not None and reached - after <= within and (max_rollback is None or rollback <= max_rollback) + return ok, detail + f" (wanted {min_speed} km/h within {within}s)" + + def check_slip_clears(rows, moving_speed, stop_speed, within): """Once the vehicle has stopped after moving off, its wheels stop slipping within `within` seconds (a vehicle left skidding on locked wheels keeps its brakes capped by the sliding adhesion).""" @@ -540,7 +757,68 @@ def check_slip_clears(rows, moving_speed, stop_speed, within): return True, f"stopped at t={rows[stop][COL_TIME]:.1f}s, no slipping after t={deadline:.1f}s" +def check_traction(rows, from_distance, to_distance, reaches=None, at_most=None, at_least=None): + """The traction force of the vehicle in kN (the physicslog has it in N, whatever its header says) while it + runs between two points of its way, in metres travelled as in `distance`: the highest there `reaches` a + force, e.g. the power taken again behind a section without voltage; it stays `at_most` a force, e.g. none + taken where there is no voltage; it stays `at_least` a force, e.g. no power lost under an insulator.""" + dist = _distances(rows) + window = [(d, r) for d, r in zip(dist, rows) if from_distance <= d <= to_distance] + if not window: + return False, f"never got between {from_distance} and {to_distance} m (travelled {dist[-1] if dist else 0:.0f} m)" + + def describe(item): + d, r = item + return f"{r[COL_TRACTION_FORCE] / 1000:.1f} kN at {d:.0f} m, t={r[COL_TIME]:.1f}s, v={r[COL_VELOCITY]:.1f} km/h" + + top = max(window, key=lambda item: item[1][COL_TRACTION_FORCE]) + low = min(window, key=lambda item: item[1][COL_TRACTION_FORCE]) + detail = (f"between {from_distance} and {to_distance} m (t={window[0][1][COL_TIME]:.1f}-{window[-1][1][COL_TIME]:.1f}s) " + f"the traction force was {describe(low)} at its lowest, {describe(top)} at its highest") + if reaches is not None and top[1][COL_TRACTION_FORCE] / 1000 < reaches: + return False, f"{detail}; wanted it to reach {reaches} kN" + if at_most is not None and top[1][COL_TRACTION_FORCE] / 1000 > at_most: + return False, f"{detail}; wanted at most {at_most} kN" + if at_least is not None and low[1][COL_TRACTION_FORCE] / 1000 < at_least: + return False, f"{detail}; wanted at least {at_least} kN" + return True, detail + + +def check_master_controller(rows, from_distance, to_distance, at_most): + """The master controller of the vehicle stays at or below a position while it runs between two points of its + way (metres travelled, as in `distance`), e.g. at 0 where the scenery tells the driver to coast.""" + dist = _distances(rows) + window = [(d, r) for d, r in zip(dist, rows) if from_distance <= d <= to_distance] + if not window: + return False, f"never got between {from_distance} and {to_distance} m (travelled {dist[-1] if dist else 0:.0f} m)" + d, top = max(window, key=lambda item: item[1][COL_MASTER_CONTROLLER]) + detail = (f"between {from_distance} and {to_distance} m (t={window[0][1][COL_TIME]:.1f}-{window[-1][1][COL_TIME]:.1f}s) " + f"the master controller was at {top[COL_MASTER_CONTROLLER]:.0f} at most, at {d:.0f} m, t={top[COL_TIME]:.1f}s") + if top[COL_MASTER_CONTROLLER] > at_most: + return False, f"{detail}; wanted at most {at_most}" + return True, detail + + +def check_traction_power(rows, max_kw, min_peak_kw=None): + """The power at the wheels, the traction force times the vehicle speed, stays at or below max_kw + and, given min_peak_kw, reaches it, e.g. a dual-mode vehicle on its genset (eu07/maszyna#536).""" + if not rows or len(rows[0]) <= COL_VEHICLE_VELOCITY or rows[0][COL_VEHICLE_VELOCITY] is None: + return False, "the physicslog has no vehicle speed column" + power = [abs(r[COL_TRACTION_FORCE]) * abs(r[COL_VEHICLE_VELOCITY]) / 3.6 / 1000 for r in rows] + peak = max(range(len(rows)), key=power.__getitem__) + r = rows[peak] + detail = (f"peak {power[peak]:.0f} kW at t={r[COL_TIME]:.1f}s, v={r[COL_VEHICLE_VELOCITY]:.1f} km/h, " + f"Ft={r[COL_TRACTION_FORCE] / 1000:.1f} kN") + if power[peak] > max_kw: + return False, f"{detail}, above {max_kw} kW" + if min_peak_kw is not None and power[peak] < min_peak_kw: + return False, f"{detail}, below {min_peak_kw} kW" + return True, detail + + CHECKS = { + "master_controller": check_master_controller, + "traction": check_traction, "slips": check_slips, "slip_clears": check_slip_clears, "holds_still": check_holds_still, @@ -551,6 +829,9 @@ CHECKS = { "stays_stopped": check_stays_stopped, "distance": check_distance, "ends_moving": check_ends_moving, + "traction_power": check_traction_power, + "keeps_moving": check_keeps_moving, + "starts_again": check_starts_again, } @@ -571,19 +852,46 @@ def check_log_lacks(log, pattern): # checks on the text of the run's log.txt rather than on the physicslog rows +OVERLAP_LINE = re.compile(r"derailment: the bodies overlap by up to ([\d.]+) m(?: \((.*?)\))? over the last second, " + r"([\d.]+) m now(, all at rest)?") + + +def check_no_overlap(log, max_transient, max_at_rest): + """physics.derailment new: the bodies of the vehicles off the track (and of those near them) don't go into each + other: the log has the most they overlapped by every second; at most `max_transient` m at any time, and at most + `max_at_rest` m once all of them came to rest.""" + lines = [m for m in (OVERLAP_LINE.search(line) for line in log.splitlines()) if m] + if not lines: + return False, "no line of the overlap of the bodies in the log" + worst = max(lines, key=lambda m: float(m.group(1))) + rest = next((m for m in reversed(lines) if m.group(4)), None) + detail = f"most {float(worst.group(1)):.2f} m" + (f" ({worst.group(2)})" if worst.group(2) else "") + if rest is None: + return False, detail + ", the vehicles never all came to rest" + detail += f", {float(rest.group(3)):.2f} m at rest" + failed = [] + if float(worst.group(1)) > max_transient: + failed.append(f"over {max_transient} m on the way") + if float(rest.group(3)) > max_at_rest: + failed.append(f"over {max_at_rest} m at rest") + return not failed, detail + ("" if not failed else ": " + "; ".join(failed)) + + LOG_CHECKS = { "log_contains": check_log_contains, "log_lacks": check_log_lacks, + "no_overlap": check_no_overlap, } def check_couples(box, vehicle, other): """The two vehicles couple in the run and stay coupled to its end; coupled from the start doesn't count.""" - numbers = {name: number for number, name in box.vehicles.items()} - unknown = [name for name in (vehicle, other) if name not in numbers] + # the simulator reads the names of a scenery in lower case, whatever the scenery (or the case) writes + numbers = {name.lower(): number for number, name in box.vehicles.items()} + unknown = [name for name in (vehicle, other) if name.lower() not in numbers] if unknown: return False, f"the black box has no vehicle {' nor '.join(unknown)}" - pair = {numbers[vehicle], numbers[other]} + pair = {numbers[vehicle.lower()], numbers[other.lower()]} # of the two vehicles of a coupling the one with the lower number tells it, each change of that coupler # under the same vehicle and side: the record which coupled the two, for as long as they stay coupled made, parted = {}, None @@ -605,9 +913,353 @@ def check_couples(box, vehicle, other): f"{ends[c.other_side]} one of {box.vehicles[c.other]}, coupling 0x{c.flags:02X}") +def check_parts(box, vehicle, other, before=None): + """The two vehicles, coupled to each other, come apart in the run: a coupler broken, or uncoupled.""" + numbers = {name.lower(): number for number, name in box.vehicles.items()} + unknown = [name for name in (vehicle, other) if name.lower() not in numbers] + if unknown: + return False, f"the black box has no vehicle {' nor '.join(unknown)}" + pair = {numbers[vehicle.lower()], numbers[other.lower()]} + # the record of the coupler which let go: coupled to the other vehicle before, the coupler itself no more + c = next((c for c in box.couplings if {c.vehicle, c.previous_other} == pair + and c.previous_flags & COUPLING_COUPLER and not c.flags & COUPLING_COUPLER), None) + if c is None: + return False, f"none of the {len(box.couplings)} coupling record(s) of the black box parts {vehicle} and {other}" + if before is not None and c.time > before: + return False, f"{vehicle} and {other} came apart at t={c.time:.1f}s, after {before:g}s" + ends = ("front", "rear") + return True, (f"at t={c.time:.1f}s the {ends[c.side]} coupler of {box.vehicles[c.vehicle]} let go of " + f"{box.vehicles[c.previous_other]}, coupling 0x{c.previous_flags:02X} before") + + +def _vehicle_states(box, vehicle): + """The states of the vehicle named, or None and why not.""" + numbers = {name.lower(): number for number, name in box.vehicles.items()} + number = numbers.get(vehicle.lower()) + if number is None: + return None, f"the black box has no vehicle {vehicle}" + states = box.states.get(number) + if not states: + return None, f"the black box has no state of {vehicle}" + return states, "" + + +def _driver_change(states, to): + """The first state with the driver `to` after one with another driver; None when there is none.""" + return next((now for before, now in zip(states, states[1:]) if now.driver == to and before.driver != to), None) + + +def check_driver_changes(box, vehicle, to, after=0.0, before=None): + """The vehicle gets the driver `to` (none, ai, user) between the times given, and keeps it to the end.""" + states, why = _vehicle_states(box, vehicle) + if states is None: + return False, why + wanted = BLACKBOX_DRIVERS[to] + names = {number: name for name, number in BLACKBOX_DRIVERS.items()} + change = _driver_change(states, wanted) + if change is None: + return False, f"{vehicle} starts with driver {names.get(states[0].driver)} and never changes to {to}" + if change.time < after or (before is not None and change.time > before): + return False, f"{vehicle} got driver {to} at t={change.time:.1f}s, outside {after:g}..{before if before is not None else 'end'}" + later = next((s for s in states if s.time > change.time and s.driver != wanted), None) + if later is not None: + return False, f"{vehicle} got driver {to} at t={change.time:.1f}s but {names.get(later.driver)} at t={later.time:.1f}s" + return True, f"{vehicle} has driver {to} from t={change.time:.1f}s to the end (t={box.end_time:.1f}s)" + + +def check_stops_driverless(box, vehicle, min_speed, within, stop_speed=0.5, max_creep=1.0, hold=60.0, + min_deceleration=None, max_deceleration=None): + """The vehicle loses its driver at `min_speed` or faster, stands `within` seconds later and stays where it + stopped, to the end of the recording or until it gets a driver again. With the decelerations, the mean one of + that stop (from the speed and the way to the stop, m/s²) has to be within them: how well the train brakes.""" + states, why = _vehicle_states(box, vehicle) + if states is None: + return False, why + left = _driver_change(states, BLACKBOX_DRIVERS["none"]) + if left is None: + return False, f"{vehicle} never loses its driver" + if abs(left.speed) < min_speed: + return False, f"{vehicle} lost its driver at t={left.time:.1f}s at {abs(left.speed):.1f} km/h, below {min_speed}" + after = [s for s in states if s.time >= left.time] + stop = next((s for s in after if abs(s.speed) <= stop_speed), None) + if stop is None or stop.time - left.time > within: + took = "never" if stop is None else f"after {stop.time - left.time:.0f}s" + return False, f"{vehicle} lost its driver at t={left.time:.1f}s at {abs(left.speed):.1f} km/h and stood {took} (limit {within}s)" + # left alone until the recording ends, or a driver comes again + crewed = next((s for s in after if s.time > stop.time and s.driver != BLACKBOX_DRIVERS["none"]), None) + until = crewed.time if crewed else box.end_time + alone = "until a driver came" if crewed else "to the end" + if until - stop.time < hold: + return False, f"{vehicle} stood at t={stop.time:.1f}s, with no driver for {until - stop.time:.0f}s more {alone} (hold {hold}s)" + # a standing vehicle is listed again only in the keyframes, or when it moves + standing = [s for s in after if stop.time <= s.time <= until] + fastest = max(abs(s.speed) for s in standing) + creep = max(math.dist(s.position, stop.position) for s in standing) + if fastest > stop_speed or creep > max_creep: + return False, f"{vehicle} stood at t={stop.time:.1f}s, then moved {creep:.1f} m at up to {fastest:.1f} km/h with no driver" + way = sum(math.dist(a.position, b.position) for a, b in zip(after, after[1:]) if b.time <= stop.time) + stopped = (f"{vehicle} lost its driver at t={left.time:.1f}s at {abs(left.speed):.1f} km/h, stood {stop.time - left.time:.0f}s " + f"and {way:.0f} m later") + # v² / 2s: the black box lists a vehicle once a second, so the way is closer to the truth than the time + deceleration = (abs(left.speed) / 3.6) ** 2 / (2 * way) if way > 0 else math.inf + if ((min_deceleration is not None and deceleration < min_deceleration) + or (max_deceleration is not None and deceleration > max_deceleration)): + bounds = f"{min_deceleration if min_deceleration is not None else 0:g}..{max_deceleration if max_deceleration is not None else 'any'}" + return False, f"{stopped}: a mean deceleration of {deceleration:.2f} m/s², outside {bounds}" + return True, f"{stopped} ({deceleration:.2f} m/s²), moved {creep:.2f} m in the {until - stop.time:.0f}s {alone}" + + +def check_moves(box, vehicle, min_speed, direction="front"): + """The vehicle reaches `min_speed` with its front end leading, or its rear one (the physicslog has no direction).""" + states, why = _vehicle_states(box, vehicle) + if states is None: + return False, why + sign = {"front": 1.0, "rear": -1.0}[direction] + fastest = max(states, key=lambda s: sign * s.speed) + if sign * fastest.speed < min_speed: + return False, f"{vehicle} never reaches {min_speed} km/h {direction} end leading, at most {sign * fastest.speed:.1f}" + first = next(s for s in states if sign * s.speed >= min_speed) + return True, f"{vehicle} runs {direction} end leading: {min_speed} km/h at t={first.time:.1f}s, up to {sign * fastest.speed:.1f} km/h" + + +def check_leaves_track(box, vehicle, cause=None, min_offset=None, max_offset=None, min_distance=None, max_distance=None, + lying=None): + """The vehicle leaves the track (physics.derailment new) and comes to rest off it: what derailed it, how far from + the axis of the track (either side) and how far it went on the ground, and whether it ends on its side.""" + numbers = {name.lower(): number for number, name in box.vehicles.items()} + number = numbers.get(vehicle.lower()) + if number is None: + return False, f"the black box has no vehicle {vehicle}" + records = [d for d in box.derailments if d.vehicle == number] + left = next((d for d in records if d.phase == 0), None) + if left is None: + return False, f"{vehicle} never left the track ({len(box.derailments)} derailment record(s) of others)" + rest = next((d for d in records if d.phase == 1 and d.time >= left.time), None) + detail = (f"{vehicle} left the track at t={left.time:.1f}s at {abs(left.speed):.0f} km/h " + f"({DERAILMENT_CAUSES.get(left.cause, left.cause)})") + if rest is None: + return False, detail + ", and never came to rest" + detail += (f", came to rest at t={rest.time:.1f}s {rest.travelled:.1f} m on, {rest.offset:+.1f} m from the axis of the " + f"track, roll {math.degrees(rest.roll):+.0f} deg{', on its side' if rest.lying else ''}") + failed = [] + if cause is not None and DERAILMENT_CAUSES.get(left.cause) != cause: + failed.append(f"derailed by {DERAILMENT_CAUSES.get(left.cause, left.cause)}, wanted {cause}") + if min_offset is not None and abs(rest.offset) < min_offset: + failed.append(f"offset under {min_offset} m") + if max_offset is not None and abs(rest.offset) > max_offset: + failed.append(f"offset over {max_offset} m") + if min_distance is not None and rest.travelled < min_distance: + failed.append(f"went under {min_distance} m") + if max_distance is not None and rest.travelled > max_distance: + failed.append(f"went over {max_distance} m") + if lying is not None and rest.lying != lying: + failed.append("lying on its side" if rest.lying else "upright") + return not failed, detail + ("" if not failed else ": " + "; ".join(failed)) + + +def check_consist_folds(box, vehicles, min_bend, min_folds=1, alternate=False, both_sides=False): + """The vehicles of a train (names, front to back, comma separated) left the track (physics.derailment new) and came + to rest folded up: at least `min_folds` of the bends between neighbours at rest (the angle between their headings, + either way along) are `min_bend` degrees or more; with `alternate` the bends of neighbouring joints turn opposite + ways, a zigzag; with `both_sides` some of them rest on one side of the track and some on the other.""" + numbers = {name.lower(): number for number, name in box.vehicles.items()} + names = [name.strip() for name in vehicles.split(",") if name.strip()] + rests = [] + for name in names: + number = numbers.get(name.lower()) + rests.append(next((d for d in box.derailments if number is not None and d.vehicle == number and d.phase == 1), None)) + if all(rest is None for rest in rests): + return False, f"none of {', '.join(names)} came to rest off the track" + bends = [] + for first, second in zip(rests, rests[1:]): + if first is None or second is None: + bends.append(None) + continue + # either way along: a vehicle turned about in the train has its heading the other way + bends.append(math.degrees(math.remainder(math.remainder(second.heading - first.heading, 2 * math.pi), math.pi))) + folds = [bend for bend in bends if bend is not None and abs(bend) >= min_bend] + sides = {1 if rest.offset > 0 else -1 for rest in rests if rest is not None and abs(rest.offset) > 0.5} + detail = "at rest: " + "; ".join( + f"{name} " + ("on the track" if rest is None else + f"{rest.travelled:.0f} m on, {rest.offset:+.1f} m, heading {math.degrees(rest.heading):+.0f} deg") + for name, rest in zip(names, rests)) + detail += "; bends " + ", ".join("-" if bend is None else f"{bend:+.0f}" for bend in bends) + " deg" + failed = [] + if len(folds) < min_folds: + failed.append(f"{len(folds)} bend(s) of {min_bend} deg or more, wanted {min_folds}") + if alternate: + pairs = [(a, b) for a, b in zip(bends, bends[1:]) if a is not None and b is not None + and abs(a) >= min_bend and abs(b) >= min_bend] + if not pairs or any(a * b > 0 for a, b in pairs): + failed.append("the bends don't alternate") + if both_sides and len(sides) < 2: + failed.append("all on one side of the track") + return not failed, detail + ("" if not failed else ": " + "; ".join(failed)) + + +def _along_track(track, x, z): + """Where the point (x, z) lies by the track: its level distance [m] from the line of the track, and how far along + the track [m] from its first point that nearest point of the line is.""" + best, at, run_length = math.inf, 0.0, 0.0 + if len(track.points) == 1: + return math.hypot(x - track.points[0][0], z - track.points[0][2]), 0.0 + for (ax, _, az), (bx, _, bz) in zip(track.points, track.points[1:]): + dx, dz = bx - ax, bz - az + length = dx * dx + dz * dz + share = 0.0 if length == 0.0 else max(0.0, min(1.0, ((x - ax) * dx + (z - az) * dz) / length)) + offset = math.hypot(x - (ax + share * dx), z - (az + share * dz)) + if offset < best: + best, at = offset, run_length + share * math.sqrt(length) + run_length += math.sqrt(length) + return best, at + + +def _track_length(track): + return sum(math.hypot(b[0] - a[0], b[2] - a[2]) for a, b in zip(track.points, track.points[1:])) + + +def _track_label(track): + return f"{track.name or '#' + str(track.number)}" + (f" (way {track.branch})" if track.kind == 1 else "") + + +class _TrackMap: + """The tracks of a black box as a network: the ends of the tracks (and of the ways of the switches) that meet are + one node, each track an edge of its length between its two ends.""" + + JOINT = 0.3 # ends closer than this [m], level, meet + + def __init__(self, tracks): + self.tracks = tracks + self.lengths = [_track_length(t) for t in tracks] + nodes = [] # (x, z) of each node + self.ends = [] # the nodes of the first and the last point of each track + for track in tracks: + pair = [] + for x, _, z in (track.points[0], track.points[-1]): + node = next((i for i, (nx, nz) in enumerate(nodes) if math.hypot(nx - x, nz - z) < self.JOINT), None) + if node is None: + nodes.append((x, z)) + node = len(nodes) - 1 + pair.append(node) + self.ends.append(tuple(pair)) + self.edges = {} # node: [(other node, length)] + for (a, b), length in zip(self.ends, self.lengths): + self.edges.setdefault(a, []).append((b, length)) + self.edges.setdefault(b, []).append((a, length)) + + def places(self, position, max_offset): + """The tracks the position lies on: within max_offset [m] of their line, (track index, offset, along).""" + x, _, z = position + found = [(i, *_along_track(t, x, z)) for i, t in enumerate(self.tracks)] + near = [f for f in found if f[1] <= max_offset] + return near or [min(found, key=lambda f: f[1])] + + def distance(self, one, other, limit): + """The shortest way [m] along the tracks between two places (track index, offset, along), up to `limit` + (beyond it, infinity).""" + (i, _, s), (j, _, t) = one, other + if i == j: + return abs(s - t) + start = {self.ends[i][0]: s, self.ends[i][1]: self.lengths[i] - s} + goal = {self.ends[j][0]: t, self.ends[j][1]: self.lengths[j] - t} + reached = dict(start) + queue = [(cost, node) for node, cost in start.items()] + heapq.heapify(queue) + best = math.inf + while queue: + cost, node = heapq.heappop(queue) + if cost > reached.get(node, math.inf) or cost >= min(best, limit): + continue + if node in goal: + best = min(best, cost + goal[node]) + for nxt, length in self.edges.get(node, []): + if cost + length < reached.get(nxt, math.inf): + reached[nxt] = cost + length + heapq.heappush(queue, (cost + length, nxt)) + return best if best <= limit else math.inf + + +def _coupled_pairs(box, chosen, upto): + """The pairs of vehicles (by number) among `chosen` whose couplers hold each other at the time `upto`.""" + held = {} + for c in box.couplings: + if c.time > upto: + break + held[(c.vehicle, c.side)] = (c.other, c.flags) + return {tuple(sorted((vehicle, other))) for (vehicle, _), (other, flags) in held.items() + if flags & COUPLING_COUPLER and vehicle in chosen and other in chosen} + + +def check_on_track(box, vehicles, max_offset=0.75, max_detour=5.0): + """Every vehicle whose name starts with `vehicles` stays on the line of a track in every state the black box has of + it, and the vehicles coupled to each other stay on one way: the way along the tracks from one to the other is no + more than `max_detour` [m] longer than the straight line between them. A vehicle thrown sideways has its middle off + any track; one with its bogies on two tracks that part too, once they are apart; and a train whose vehicles went + two ways at a switch runs on with two coupled vehicles on two tracks, side by side, with the way between them back + through the switch.""" + if not box.tracks: + return False, "the black box has no map of the tracks" + chosen = {number: name for number, name in box.vehicles.items() if name.lower().startswith(vehicles.lower())} + if not chosen: + return False, f"the black box has no vehicle named {vehicles}..." + network = _TrackMap(box.tracks) + # the states of the chosen vehicles by time: a vehicle is listed when it moved, or every 60 s + times = sorted({s.time for number in chosen for s in box.states.get(number, [])}) + if not times: + return False, f"the black box has no state of {', '.join(chosen.values())}" + latest, index, places = {}, {number: 0 for number in chosen}, {} + worst_offset, worst_detour, failures = None, None, [] + for when in times: + for number in chosen: + states = box.states.get(number, []) + while index[number] < len(states) and states[index[number]].time <= when: + latest[number] = states[index[number]] + index[number] += 1 + for number, state in latest.items(): + if (number, state.time) in places: + continue + places[(number, state.time)] = network.places(state.position, max_offset) + nearest = min(places[(number, state.time)], key=lambda p: p[1]) + if worst_offset is None or nearest[1] > worst_offset[0]: + worst_offset = (nearest[1], chosen[number], state, box.tracks[nearest[0]]) + for one, other in _coupled_pairs(box, chosen, when): + if one not in latest or other not in latest: + continue + straight = math.dist(latest[one].position, latest[other].position) + at_one, at_other = places[(one, latest[one].time)], places[(other, latest[other].time)] + way = min(network.distance(a, b, straight + 1000.0) for a in at_one for b in at_other) + detour = way - straight + if worst_detour is None or detour > worst_detour[0]: + worst_detour = (detour, chosen[one], chosen[other], when, at_one, at_other) + offset, name, state, track = worst_offset + where = f"{name} at t={state.time:.1f}s ({abs(state.speed):.1f} km/h) {offset:.2f} m off {_track_label(track)}" + if offset > max_offset: + failures.append(f"{where}, more than {max_offset} m") + detail = f"the farthest off a track {where}" + if worst_detour is not None: + detour, one, other, when, at_one, at_other = worst_detour + tracks = (f"{_track_label(box.tracks[min(at_one, key=lambda p: p[1])[0]])} and " + f"{_track_label(box.tracks[min(at_other, key=lambda p: p[1])[0]])}") + length = "no way along the tracks" if math.isinf(detour) else f"the way along the tracks {detour:.1f} m longer than the straight line" + said = f"{one} and {other}, coupled, at t={when:.1f}s on {tracks}: {length}" + if detour > max_detour: + failures.append(f"{said}, more than {max_detour} m") + detail += f"; of the coupled ones {said}" + if failures: + return False, "; ".join(failures) + return True, f"{len(chosen)} vehicle(s), {detail}" + + # checks on the black box of the run rather than on the physicslog rows BLACKBOX_CHECKS = { + "leaves_track": check_leaves_track, + "consist_folds": check_consist_folds, "couples": check_couples, + "parts": check_parts, + "driver_changes": check_driver_changes, + "stops_driverless": check_stops_driverless, + "moves": check_moves, + "on_track": check_on_track, } @@ -637,22 +1289,49 @@ def describe_exit(code: int | None) -> str: return f"{code} ({name})" if name else f"{code} (0x{code & 0xFFFFFFFF:08X}, a crash?)" -def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool, say) -> bool: - case = json.loads((CASES_DIR / f"{name}.json").read_text(encoding="utf-8")) +def load_case(name: str) -> dict: + return json.loads((CASES_DIR / f"{name}.json").read_text(encoding="utf-8")) + + +def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool, say, seed: str | None = None) -> str: + """Runs the case and returns PASS or FAIL; for a case marked `xfail` (a known, reported bug) XFAIL + when it fails as expected, and XPASS when it passes, which means the mark has to go.""" + case = load_case(name) + ok = _run_case(name, case, exe, game_dir, timespeed, watch, say, seed) + if "xfail" not in case or watch: + return "PASS" if ok else "FAIL" + if ok: + say(f" XPASS the case passes although it is marked xfail ({case['xfail']}): remove the mark") + return "XPASS" + say(f" XFAIL fails as expected: {case['xfail']}") + return "XFAIL" + + +def exclusive_case(case: dict) -> bool: + """A case on a mission of the base scenery with the physicslog on: it removes every physicslog written + while it ran, those of other cases running at the time too, so it has to run alone.""" + return "vehicle" in case and case.get("physicslog", True) + + +def _run_case(name: str, case: dict, exe: Path, game_dir: Path, timespeed: float, watch: bool, say, + seed: str | None = None) -> bool: say(f"\n=== {name}: {case.get('description', '')}") out = OUT_DIR / name shutil.rmtree(out, ignore_errors=True) out.mkdir(parents=True) - # the lead vehicle is named after the case, so parallel runs never share a physicslog - vehicle = f"autotest_{name}" - scenery = build_scenery(case, game_dir, name, vehicle) - ini = out / "autotest.ini" - # the case's own settings go last, over the common ones - ini.write_text(TEST_INI.format(timespeed=timespeed) + "".join(line + "\n" for line in case.get("ini", [])), - encoding="ascii") - physicslog = game_dir / "physicslog" / f"{vehicle}.dat" - + # the lead vehicle is named after the case, so parallel runs never share a physicslog. a case on a + # mission of the base scenery (strip_trainsets false) names one of the scenery's own vehicles instead + own_vehicle = "vehicle" in case + vehicle = case.get("vehicle", f"autotest_{name}") + # a long run on a scenery with dozens of AI trains would write a physicslog for each of them into the + # game dir (3-4 kB per second of simulation and train); such a case turns them off and relies on the + # result of the test mode and on the log + with_physicslog = case.get("physicslog", True) + needs_physicslog = [c["type"] for c in case.get("checks", []) if c["type"] not in LOG_CHECKS] + if not with_physicslog and (watch or needs_physicslog): + sys.exit(f"{name}: with physicslog off a case can have log checks only ({', '.join(LOG_CHECKS)}), " + "and can't run with --watch") duration = float(case["duration"]) if "duration" in case else None # a case that only records `duration` seconds ends on the test timeout; one that says # how the test ends (a pass event, a signal passed at danger...) expects that result @@ -661,8 +1340,27 @@ def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool sys.exit(f"{name}: expect must be one of {', '.join(RESULTS)}") if watch and duration is None: sys.exit(f"{name}: --watch needs a case with duration") - result = run_simulator(exe, game_dir, scenery, ini, physicslog, - duration, float(case.get("timeout", 600)), watch, say) + + ini = out / "autotest.ini" + # the case's own settings go last, over the common ones; then the seed of this run of the suite, if any + settings = [*case.get("ini", []), *([f"randomseed {seed}"] if seed else [])] + ini.write_text(TEST_INI.format(timespeed=timespeed, physicslog="yes" if with_physicslog else "no") + + "".join(line + "\n" for line in settings), encoding="ascii") + physicslog = game_dir / "physicslog" / f"{vehicle}.dat" + started = time.time() - 1 + # from here on the case has files of its own in the game dir (the vehicle variants, the timetable) + try: + scenery = build_scenery(case, game_dir, name, vehicle) + result = run_simulator(exe, game_dir, scenery, ini, physicslog, + duration, float(case.get("timeout", 600)), watch, say, + expect_rows=with_physicslog and not own_vehicle) + finally: + # the case's own files go from the game dir also when the run is broken off (ctrl+c) + timetable_path(game_dir, name).unlink(missing_ok=True) + remove_vehicle_variants(case, game_dir, name) + # a case that asked for no geometry cache (file.binary.terrain no) leaves none of an earlier run behind + if any(line.split()[:2] == ["file.binary.terrain", "no"] for line in case.get("ini", [])): + scenery_cache(game_dir, name).unlink(missing_ok=True) # the logs are ours alone (named after the case scenery), move them out of the game dir for kind, path in result.logs.items(): @@ -672,6 +1370,17 @@ def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool # other trains of the case with a driver, named _, log too for other in physicslog.parent.glob(f"*_{vehicle}.dat"): shutil.move(other, out / other.name) + # on a mission of the base scenery every train with a driver logs under its own name, the road vehicles + # too (250 files and 740 MB after 900 s of Wrzosy): the ones written in this run are removed, nothing + # checks them (so such a case can't share the game dir with another run at the time: main() runs it + # alone, see exclusive_case()). a file still held open by another simulator is left where it is + if own_vehicle and with_physicslog: + for other in physicslog.parent.glob("*.dat"): + try: + if other.stat().st_mtime >= started: + other.unlink() + except OSError as error: + say(f" left {other.name} in the game dir: {error}") # the black box is named after the case scenery too if result.blackbox: result.blackbox = Path(shutil.move(result.blackbox, out / f"{vehicle}.blackbox")) @@ -694,14 +1403,17 @@ def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool say(f" {'PASS' if passed else 'FAIL'} exit code {describe_exit(result.exit_code)}{watchdog}, expected {expect}") ok &= passed # a run cut short (the real time watchdog, an error, a crash, or closed by us) could have been writing - # the scenery's geometry cache; the simulator checks only the header of it, so the next runs would read - # a truncated one. it is written again on the next run + # the scenery's geometry cache. the simulator writes it through .sbt.tmp and turns down a cut-short + # one, but older builds wrote it in place and checked only its header, so the next runs would read a + # truncated one. either is written again on the next run if result.failure or (not watch and got in (None, "error", WALL_TIMEOUT)): - scenery_cache(game_dir, name).unlink(missing_ok=True) + cache = scenery_cache(game_dir, name) + cache.unlink(missing_ok=True) + cache.with_name(cache.name + ".tmp").unlink(missing_ok=True) if result.failure: say(f" FAIL {result.failure}") ok = False - if not result.rows and case.get("checks"): + if not result.rows and needs_physicslog: if not result.failure: say(f" FAIL no physicslog for '{vehicle}'") return False @@ -751,6 +1463,10 @@ def main() -> int: help="with --watch: simulation time multiplier, the simulator offers 1, 5, 20 and 60 (default 1)") ap.add_argument("-j", "--jobs", type=int, default=1, help="cases run at once, each in a simulator of its own (default 1)") + ap.add_argument("--seed", help="seed of the simulator's random numbers for this run (randomseed), a number or a " + "word; the default is the fixed one of the test mode. For bugs that show up only sometimes") + ap.add_argument("--slow", action="store_true", + help="with no cases named: run the ones marked slow too (they are skipped otherwise)") args = ap.parse_args() if not args.game_dir: @@ -763,6 +1479,12 @@ def main() -> int: missing = [n for n in names if not (CASES_DIR / f"{n}.json").exists()] if missing: sys.exit("no such case: " + ", ".join(missing)) + # a case marked slow (a whole mission on a big scenery, many minutes) runs when named, or with --slow + if not args.cases and not args.slow: + slow = [n for n in names if load_case(n).get("slow")] + if slow: + names = [n for n in names if n not in slow] + print(f"skipped {len(slow)} slow case(s), run them by name or with --slow: {', '.join(slow)}") started = time.monotonic() results = {} @@ -770,28 +1492,38 @@ def main() -> int: def say(line, progress=False): print(line, flush=True) for n in names: - results[n] = run_case(n, exe, game_dir, args.timespeed, args.watch, say) + results[n] = run_case(n, exe, game_dir, args.timespeed, args.watch, say, args.seed) else: + # a case on a mission of the base scenery removes the physicslogs written while it ran, so it runs + # alone, after the others + alone = [n for n in names if exclusive_case(load_case(n))] + together = [n for n in names if n not in alone] + if alone: + print(f"run alone after the others, they clear the physicslogs of the game dir: {', '.join(alone)}") # each case prints its block when it is done, so parallel output does not interleave def job(n): lines = [] def say(line, progress=False): if not progress: lines.append(line) - ok = run_case(n, exe, game_dir, args.timespeed, args.watch, say) - return n, ok, lines + status = run_case(n, exe, game_dir, args.timespeed, args.watch, say, args.seed) + return n, status, lines with ThreadPoolExecutor(max_workers=args.jobs) as pool: - for n in names: + for n in together: print(f"started {n}", flush=True) - for fut in as_completed([pool.submit(job, n) for n in names]): - n, ok, lines = fut.result() + for fut in as_completed([pool.submit(job, n) for n in together]): + n, status, lines = fut.result() print("\n".join(lines), flush=True) - results[n] = ok + results[n] = status + for n in alone: + results[n] = run_case(n, exe, game_dir, args.timespeed, args.watch, + lambda line, progress=False: print(line, flush=True), args.seed) print(f"\n=== summary ({time.monotonic() - started:.0f}s)") for n in names: - print(f" {'PASS' if results[n] else 'FAIL'} {n}") - return 0 if all(results.values()) else 1 + print(f" {results[n]:5} {n}") + # a known failure keeps the suite green; one that stopped failing doesn't, so that its mark gets removed + return 0 if all(status in ("PASS", "XFAIL") for status in results.values()) else 1 if __name__ == "__main__": diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index b8e324e3b..3de990dec 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -38,6 +38,10 @@ add_executable(${UNIT_TESTS_NAME} "${CMAKE_SOURCE_DIR}/rendering/common/freecameramotion.cpp" # and the http client the editor fetches its aids with "${CMAKE_SOURCE_DIR}/editor/editorHttp.cpp" + # and what the switch tool tells of the drives of the switches + "${CMAKE_SOURCE_DIR}/editor/editorSwitchDrives.cpp" + # the camera, for the order of its rotations (test_camera.cpp) + "${CMAKE_SOURCE_DIR}/vehicle/Camera.cpp" ${UNIT_TEST_CASES}) # the core library brings the game's build settings along @@ -45,7 +49,7 @@ target_link_libraries(${UNIT_TESTS_NAME} PRIVATE eu07_core) # the script screen host, tested with the real runtimes (test_script_screen_host.cpp) target_sources(${UNIT_TESTS_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/scripting/scriptscreens.cpp") if (WITH_LUA) - target_sources(${UNIT_TESTS_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/scripting/luaprogram.cpp" "${CMAKE_SOURCE_DIR}/stb/stb_image.c") + target_sources(${UNIT_TESTS_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/scripting/luaprogram.cpp" "${CMAKE_SOURCE_DIR}/scripting/luasandbox.cpp" "${CMAKE_SOURCE_DIR}/stb/stb_image.c") endif() if (WITH_WASM) target_sources(${UNIT_TESTS_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/scripting/wasmprogram.cpp") diff --git a/tests/unit/COVERAGE.md b/tests/unit/COVERAGE.md index 5e2c55696..71870c892 100644 --- a/tests/unit/COVERAGE.md +++ b/tests/unit/COVERAGE.md @@ -81,7 +81,15 @@ These are run by the game, by vehicles it has or by the cab, the AI or the scene The core library (`eu07_core`) and the test binary hold more than the physics: the parser of the game's text files, the helpers of `utilities.cpp`, the PLC of a vehicle, the parts of the vehicles and of the simulation moved out of the big classes to be tested, and the hosts of the script screens. The sections above don't cover them. Their numbers are lines run, from the report of the Coverage workflow. -The tables show the run before the tests of the parser, the helpers and the PLC (`test_parser.cpp`, `test_utilities.cpp`, `test_ladder_logic.cpp`) were written. What those tests add is measured by the Coverage run of the pull request which brings them, and shown in the summary of that run. +The per-file table further down is from the run before the tests of the parser, the helpers and the PLC (`test_parser.cpp`, `test_utilities.cpp`, `test_ladder_logic.cpp`) were written. With them, in the Coverage run of master `bac9954a` (2026-11-11, after #333; GCC 13.3, unoptimised, gcov): + +| File | Lines run, before | Lines run, with the tests | Functions run, with the tests | +|---|---|---|---| +| `scripting/ladderlogic.cpp` | 4.1% (9 of 217) | 98.2% (213 of 217) | 11 of 11 | +| `utilities/parser.cpp` | 40.0% (170 of 425) | 97.6% (415 of 425) | 41 of 41 | +| `utilities/utilities.cpp` | 28.2% (82 of 291) | 95.5% (299 of 313) | 51 of 51 | + +`utilities.cpp` grew by 22 lines on master between the two runs (`user_cache_path`, `utf8_to_win1250`). All 62 files of the game in that report together: lines 83.5% (15411 of 18464), functions 85.5% (1378 of 1612), branches 59.5% (15503 of 26046). The totals aren't comparable with the run below: the report holds 13 more files, from the merges in between. **The run measured:** pull request #325 on 2026-11-11 (its commit `33cedc45` merged into master `10c7527a`), GCC 13.3, unoptimised, gcov lines. All 49 files of the game in the report together: lines 84.4% (10305 of 12204), functions 85.0% (927 of 1090), branches 62.3% (10325 of 16578). @@ -114,8 +122,10 @@ The tables show the run before the tests of the parser, the helpers and the PLC Notes to the table: - The small headers with the logic of a single part are all run in full: `vehicle/doorwings.h`, `gaugeduplicates.h`, `gaugepositions.h`, `holdcoillever.h`, `lightsprogrammer.h`, `mainctrlact.h`, `mirrors.h`, `scripting/scriptscreendrawing.h`, `scriptscreenkernels.h`, `scriptscreenprogram.h`, `scriptscreens.h`, `utilities/dictionary.h` and `vehicle/blackbox.h`. -- `vehicle/brakesetting.cpp` and `vehicle/odometer.cpp` (the brake setting of the wagons, the odometer store) joined the library on master after that run. They have tests (`test_brake_setting.cpp`, `test_odometer.cpp`) and no numbers yet. +- `vehicle/brakesetting.cpp` and `vehicle/odometer.cpp` (the brake setting of the wagons, the odometer store) joined the library on master after that run. In the run of `bac9954a` their tests (`test_brake_setting.cpp`, `test_odometer.cpp`) run 94.1% (144 of 153) and 87.9% (189 of 215) of their lines, and all 14 and 26 of 28 of their functions. - The script hosts (`scriptscreens.cpp`, `luaprogram.cpp`, `wasmprogram.cpp`) aren't in the library. The test binary compiles them itself, with the real runtimes. +- `vehicle/Camera.cpp` isn't in the library either. The test binary compiles it for the order of the camera's rotations (`test_camera.cpp`, #414), with stubs for the command queue and the clock that `TCamera::Update()` reaches for. +- The colour of the smoke of a cold diesel (#413) isn't tested: the fix is in `smoke_source::update()` (`rendering/particles.cpp`), which needs the world environment (sky, sun, precipitation, sounds) and a whole `TDynamicObject` to link. - `scene/scenelayers.h`, `scene/scenenode.h` and `scene/scenenodegroups.h` are in the report with a few lines each: the parser reports the files it includes to the scenery, which the tests replace with stubs (`engine_stubs.cpp`). ### The parser, the helpers and the PLC @@ -137,9 +147,8 @@ The tests are written for the first two columns, and for what the game doesn't c - The messages of the log (`Failed to open file`, `Bad include`) are run, and not checked: the log of the tests is a stub. - A buffer type which is neither a file nor a text (the `default:` of the constructor) can't be given without an invalid value of the type. - **`utilities.cpp`:** - - `Now()`, `user_config_path()`, `user_cache_path()` and `true_random_seed()` depend on the clock, the environment and the entropy source of the system. The tests call them and check the shape of the result. The branches for a system without the variables or without an entropy source aren't run, and those of the other systems aren't compiled. + - `Now()`, `user_config_path()`, `user_cache_path()` and `true_random_seed()` depend on the clock, the environment and the entropy source of the system. The tests call them and check the shape of the result. The branches for a system without the variables or without an entropy source aren't run, and those of the other systems aren't compiled. The choice among the XDG variables and the home folder which Linux makes is apart from the environment (`xdg_base_directory()`) and tested on every system. - `FileCased()` looks through the working folder for a name given without a folder, and through the folder of the file elsewhere; on Windows it only asks whether the file is there. The search is run on Linux only. - - `Bezogonkow()` gives other letters with MSVC than with GCC and Clang, see the findings. The test takes either, told by the entry of the table the difference starts at, so each build checks the half it is. - **`ladderlogic.cpp`:** the two `return`s marked "not reachable" after the switches over the kind of an element. **Code nothing in the game runs** (checked against the whole source tree): @@ -201,12 +210,12 @@ The tests record the behaviour as it is. The following points may deserve a look - `deserialize_map()` (`utilities.h`, the sound overrides) therefore reads an empty key from an empty file, and one from a file ending with a line break; in a file with Windows line ends its values keep the carriage return. The game's `sound_overrides.txt` is a single line without a line break. - The separators given as a null pointer are taken as none by the tokenizer, but passed on to `strcmp` for a token of 7 characters or more starting with `i`, which crashes (tried by hand, not kept as a test). No caller gives a null pointer. - **The helpers (`utilities.cpp`, `utilities.h`):** - - `Bezogonkow()`, which takes the marks off the letters for the timetable and the on-screen texts: its table has a `±` in the source, a UTF-8 file. MSVC makes one byte of it, GCC and Clang two, which moves every entry from 0xB2 on by one. With MSVC the 18 polish letters come out as `ACELNOSZZacelnoszz`; with GCC as `ALELDNSZZ,le,dnszl`: `Ć` as L, `Ń` as D, `Ó` as N, `ą` and `ł` as a comma, `ć` as l, `ń` as d, `ó` as n, `ż` as l, only `Ę` and `ę` by luck as themselves. The Linux and macOS builds of the game show the names of the stations that way. The test checks whichever table the build has (the GCC one was tried with the table alone, compiled by GCC 6.3). + - `Bezogonkow()`, which takes the marks off the letters for the file names, the scripts and the multiplayer texts: its table had a `±` written as the character in the source, a UTF-8 file. MSVC made one byte of it, GCC and Clang two, which moved every entry from 0xB2 on by one: with GCC the 18 polish letters came out as `ALELDNSZZ,le,dnszl`. Fixed with MaSzyna-EU07/maszyna#94: the entry is written as the byte `±`, and the test checks the one table in every build. - `to_minutes_str()` reads past its table of raised digits for minutes with a fraction of 0.99 or more, and before it for negative minutes, which `CompareTime()` can give it for a timetable whose times go back. Tried by hand, both ended in `std::bad_alloc`, the text read from outside of the table being no text; not kept as a test. A width under 2 throws `std::length_error`. - `stol_def()` gives its default only for an empty text. A text which isn't a number gives 0 (the flags of an event, the log setting). - `split_string_and_number()` throws for a name with a hyphen which no digit follows (`a-b`), and for a number too big. The gamepad bindings and the PLC use it on names from files. - `extract_value()` throws `std::out_of_range` when the key is the last thing in the text with nothing after its `=`. With a space after the `=`, the next `key=value` is taken for the value. - - `seed_of()` takes a word starting with digits for the number in front (`12abc` is 12), so different words can stand for the same seed. + - `seed_of()` took a word starting with digits for the number in front (`12abc` was 12), so different words could stand for the same seed, and a seed of 0 stood for none. Fixed: the whole text has to be the number, anything else is a word, and whether a seed was given is kept apart (`random_seed_given`). - `erase_extension()` cuts at the dot of a folder when the file has none (`dir.d/file` becomes `dir`). - `Round()` adds a half and cuts the fraction, which rounds the negative numbers up: -1.6 becomes -1. - **The PLC (`ladderlogic.cpp`):** diff --git a/tests/unit/consist.cpp b/tests/unit/consist.cpp index a5f10d936..1f22632e6 100644 --- a/tests/unit/consist.cpp +++ b/tests/unit/consist.cpp @@ -74,6 +74,7 @@ void consist::step(track const &Track, double Dt) { for (std::size_t i = 0; i < m_vehicles.size(); ++i) { m_positions[i] += m_vehicles[i]->fast_move(Track, Dt, TLocation{m_positions[i], 0.0, 0.0}); } + update_brake_pipes(Dt); } for (auto const &vehicle : m_vehicles) { vehicle->forces(Dt); @@ -90,6 +91,16 @@ void consist::step(track const &Track, double Dt) { for (std::size_t i = 0; i < m_vehicles.size(); ++i) { m_positions[i] += m_vehicles[i]->move(Track, Dt, TLocation{m_positions[i], 0.0, 0.0}, pipe); } + update_brake_pipes(Dt); +} + +void consist::update_brake_pipes(double Dt) const { + // vehicle_table::update_brake_pipes() + std::vector movers; + for (auto const &vehicle : m_vehicles) { + movers.push_back(&vehicle->mover()); + } + TMoverParameters::UpdatePipeCouplers(movers, Dt); } void consist::run(double Seconds, track const &Track, double Dt) { diff --git a/tests/unit/consist.h b/tests/unit/consist.h index 02001e042..2c982e446 100644 --- a/tests/unit/consist.h +++ b/tests/unit/consist.h @@ -45,6 +45,7 @@ public: private: void update_neighbours(); + void update_brake_pipes(double Dt) const; std::vector> m_vehicles; std::vector m_positions; // of the vehicles' middles along the track diff --git a/tests/unit/data/fiz/6dg_v1/6dg.json b/tests/unit/data/fiz/6dg_v1/6dg.json new file mode 100644 index 000000000..9ad99dec4 --- /dev/null +++ b/tests/unit/data/fiz/6dg_v1/6dg.json @@ -0,0 +1,55 @@ +{ + "_source": "pkp/6dg_v1/6dg.fiz", + "_comment": "converted by test_fiz.cpp from the game's definition with the files it includes, keeping what the game's loader reads", + "Param": {"Category": "train", "M": "70000", "Mred": "10000", "Vmax": "90", "PWR": "708", "SandCap": "300"}, + "Dimensions": {"L": "14.24", "H": "4.285", "W": "3.170", "Cx": "0.2"}, + "Wheels": {"D": "1.100", "AIM": "4000", "Tw": "1.435", "Axle": "Bo'Bo'", "Ad": "2.6", "Bd": "7.524", "Rmin": "80"}, + "Brake": {"BrakeValve": "LSt", "NBpA": "4", "MBF": "85.0", "MaxBP": "6.2", "MaxASBP": "2.0", "BCN": "4", "BCR": "0.1143", "BCD": "0.05", "BCM": "6.68", "HiPP": "5.0", "LoPP": "3.5", "Vv": "0.8", "MinCP": "7.5", "MaxCP": "8.5", "CompressorSpeed": "0.05", "CompressorPower": "Converter", "BVV": "200", "BRE": "0.9", "UBB1": "1", "UBB2": "12", "UBB3": "16", "HandlePipeUnlockPos": "-0.5", "LPOn": "2.75", "LPOff": "4.5"}, + "BuffCoupl": {"ControlType": "6Dg", "CType": "Screw", "kB": "9200", "DmaxB": "0.15", "FmaxB": "740", "kC": "4800", "DmaxC": "0.15", "FmaxC": "780", "beta": "0.58", "AllowedFlag": "39"}, + "Cntrl": {"BrakeSystem": "Pneumatic", "BCPN": "10", "BDelay1": "15", "BDelay2": "3", "BDelay3": "35", "BDelay4": "36", "ASB": "Manual", "LocalBrake": "PneumaticBrake", "MCPN": "6", "SCPN": "1", "AutoRelay": "Yes", "IniCDelay": "0.5", "SCDelay": "0.1", "BrakeDelays": "GP", "BrakeHandle": "MHZ_K8P", "LocBrakeHandle": "FD1", "ConverterStart": "Automatic", "ConverterStartDelay": "10", "FuelStart": "Automatic", "OilStart": "Automatic", "BrakeOpModes": "PN", "EIMCtrlType": "3", "DirChangeMaxPos": "3", "HAO": "No", "HMO": "Yes", "HGDP1": "2", "rows": [ + ["-1","0.7","-1","15","Pneumatic"], + ["0","0.5","-1","9","Pneumatic"], + ["1","0.46","-1","9","Pneumatic"], + ["2","0.42","-1","9","Pneumatic"], + ["3","0.38","-1","9","Pneumatic"], + ["4","0.34","-1","9","Pneumatic"], + ["5","0.29","-1","9","Pneumatic"], + ["6","0","-1","15","Pneumatic"] + ]}, + "Security": {"AwareSystem": "Active,CabSignal", "AwareDelay": "60", "SoundSignalDelay": "5", "MaxHoldTime": "1.0", "EmergencyBrakeDelay": "6", "RadioStop": "Yes"}, + "Light": {"Light": "Generator", "LGeneratorEngine": "ElectricSeriesMotor", "LMaxVoltage": "110", "LMaxCurrent": "91"}, + "Engine": {"AIM": "0.55", "EngineType": "DumbDE", "Trans": "17:75", "Ftmax": "219000", "Vhyp": "7", "Vadd": "5.5", "Cr": "1", "ShuntMode": "0", "WaterCoolingTemperature": "81", "WaterCoolingFanSpeed": "-1200", "WaterMaxTemperature": "85", "OilMinPressure": "0.15", "OilMinTemperature": "25", "OilMaxTemperature": "90", "HeaterMinTemperature": "55", "HeaterMaxTemperature": "60", "HeatKFS": "35", "HeatKFO": "30", "HeatKFE": "7", "HeatKW": "0.01", "HeatKV": "0.3", "HeatKFO2": "100"}, + "MotorParamTable": {"rows": [ + ["0","17.567","64","1500","15","800","1320"], + ["1","15","183.3","2000","49","800","1320"] + ]}, + "SpringBrake": {"Volume": "8", "MBF": "5", "MaxSP": "6", "ResetP": "4.0", "MinFP": "3.5", "PressOff": "4.5", "PressOn": "3.5", "ValveOnArea": "0.0002", "ValveOffArea": "0.0002", "ValvePNBArea": "0.002", "MTC": "4"}, + "WWList": {"Size": "6", "rows": [ + ["596","0","0","0"], + ["840","120","324","1150"], + ["1080","240","468","1350"], + ["1320","360","612","1550"], + ["1560","480","756","1750"], + ["1800","600","900","2000"], + ["1800","600","900","2000"] + ]}, + "SpeedControl": {"SpeedCtrl": "Yes", "OverrideManual": "Yes", "InitPwr": "0.3", "MaxPwrVel": "5", "StartVel": "2", "MinPwr": "0.3", "MaxPwr": "1.0", "MinVel": "0", "MaxVel": "120", "Offset": "-0.5", "kPpos": "0.1", "kPneg": "0.4", "kIpos": "0.06", "kIneg": "0.06", "BrakeIntervention": "Yes"}, + "LightsList": {"Size": "7", "Wrap": "no", "Default": "1", "rows": [ + ["0","0"], + ["34","34"], + ["38","34"], + ["22","34"], + ["16","1"], + ["1","16"], + ["21","34"] + ]}, + "UCList": {"Size": "6", "IntegratedBrakePN": "no", "IntegratedLocBrake": "yes", "IntegratedBrake": "no", "CtrlValStep": "0.05", "rows": [ + ["0","0","-1","0","-1","0.15","0.15","0","1","1"], + ["1","0","-1","0","0","0.00","0.00","1","3","1"], + ["2","0","-1","0","0","0.15","0.00","1","3","1"], + ["3","0","0","0","0","0.00","0.00","1","5","3"], + ["4","0","0","1","0","0.00","0.15","3","5","5"], + ["5","0","0","1","0","0.00","0.00","3","6","5"], + ["6","0","0","1","1","0.15","0.15","5","6","5"] + ]} +} diff --git a/tests/unit/data/fiz/README.md b/tests/unit/data/fiz/README.md index 514fb6287..f5be32563 100644 --- a/tests/unit/data/fiz/README.md +++ b/tests/unit/data/fiz/README.md @@ -20,6 +20,7 @@ Every `.json` here is a vehicle picked up by `test_fiz.cpp`: record the paramete | `3wl_v2/3wl.fiz` | 3WL | - | ESt3 | - | ManualBrake | Screw | | `430w_v2/430w.fiz` | 430W | - | ESt3AL2HBG300 | - | ManualBrake | Screw | | `4e_v1/4e.fiz` | 4E | ElectricSeriesMotor | LSt | FV4a | PneumaticBrake | Screw | +| `6dg_v1/6dg.fiz` | 6Dg | DumbDE | LSt | MHZ_K8P | PneumaticBrake | Screw | | `bdhpumn_v3/bdhpumn.fiz` | BDHPUMN | - | KE | - | ManualBrake | Screw | | `bhp_v1/bhp-b.fiz` | BHP | - | ESt3AL2 | - | ManualBrake | Articulated | | `br285_v1/br285.fiz` | BR285 | DieselElectric | KE | MHZ_6P | PneumaticBrake | Screw | @@ -59,8 +60,9 @@ Every `.json` here is a vehicle picked up by `test_fiz.cpp`: record the paramete | `su45_v2/301d.fiz` | SU45 | DumbDE | LSt | FV4a | PneumaticBrake | Screw | | `su46_v2/303d.fiz` | SU46 | DumbDE | LSt | FV4a | PneumaticBrake | Screw | | `tem2_v2/tem2a.fiz` | TEM2 | DieselElectric | LSt | M394 | PneumaticBrake | Screw | +| `vectron_v1/wariant_7w.fiz` | VECTRON | ElectricInductionMotor | EStED | MHZ_K8P | PneumaticBrake | Screw | | `wm15_v1/wm15.fiz` | WM15 | Dumb | LSt | FV4a | PneumaticBrake | Screw | | `wmb10_v1/wmb10.fiz` | WMB10 | DieselEngine | LSt | FV4a | PneumaticBrake | Screw | | `z1_v2/152a.fiz` | Z1 | - | KE | - | ManualBrake | Screw | -The paths are those of the game's `.fiz` files. `elf_v1/inverter.fiz` is a part the Elf units include, not a vehicle. The 218M (V2NList), the SA134 (HTCList) and the 22WEc (ffBrakeList) are there for lists the others lack, the EP05 for its camshaft. The 214MA stands for the 214M railbus, whose own file repeats a section (TurboPos and MotorParamTable twice), which the definitions here can't hold. +The paths are those of the game's `.fiz` files. `elf_v1/inverter.fiz` is a part the Elf units include, not a vehicle. The 218M (V2NList), the SA134 (HTCList) and the 22WEc (ffBrakeList) are there for lists the others lack, the EP05 for its camshaft, the Vectron for its ED brake lever of its own (SplitEDPneumaticBrake). The 6Dg is there for its universal controller (UCList) setting the power in steps (CtrlValStep), converted alone from the game data of 2026-11 (SVN r9630, which added the key), the others staying as they were. The 214MA stands for the 214M railbus, whose own file repeats a section (TurboPos and MotorParamTable twice), which the definitions here can't hold. diff --git a/tests/unit/data/fiz/vectron_v1/wariant_7w.json b/tests/unit/data/fiz/vectron_v1/wariant_7w.json new file mode 100644 index 000000000..777f4a78b --- /dev/null +++ b/tests/unit/data/fiz/vectron_v1/wariant_7w.json @@ -0,0 +1,72 @@ +{ + "_source": "pkp/vectron_v1/wariant_7w.fiz", + "_comment": "converted by test_fiz.cpp from the game's definition with the files it includes, keeping what the game's loader reads", + "Param": {"Category": "train", "M": "90000", "Mred": "12000", "Vmax": "200", "PWR": "6400", "SandCap": "700"}, + "Load": {"MaxLoad": "7", "LoadQ": "pieces", "LoadAccepted": "pantstate", "LoadSpeed": "1", "UnLoadSpeed": "0.1"}, + "Dimensions": {"L": "18.925", "H": "3.95", "W": "2.95", "Cx": "0.1"}, + "Wheels": {"D": "1.250", "AIM": "4000", "Tw": "1.435", "Axle": "Bo'Bo'", "Ad": "3", "Bd": "9.5", "Rmin": "80"}, + "Brake": {"BrakeValve": "EStED", "NBpA": "4", "MBF": "50", "MaxBP": "3.7", "MaxLBP": "3.7", "BCN": "8", "RM": "0.81", "BCR": "0.127", "BCD": "0.04", "BCM": "2.7", "BCS": "0.8", "BSA": "0", "BM": "Disk2", "BVV": "125", "Vv": "0.8", "CompressorSpeed": "0.06", "CompressorPower": "Main", "MinCP": "8.5", "MaxCP": "9.9", "UBB1": "8", "UBB2": "2", "LPOn": "3.0", "LPOff": "4.5", "HandlePipeUnlockPos": "-1", "EmergencyCutsOffHandle": "Yes"}, + "SpringBrake": {"Volume": "10", "MBF": "8", "MaxSP": "5.5", "ResetP": "4.0", "MinFP": "3.5", "PressOff": "4.5", "PressOn": "3.5", "ValveOnArea": "0.0002", "ValveOffArea": "0.0002", "ValvePNBArea": "0.002", "MTC": "4"}, + "BuffCoupl": {"CType": "Screw", "kB": "9200", "DmaxB": "0.15", "FmaxB": "740", "kC": "4800", "DmaxC": "0.15", "FmaxC": "780", "beta": "0.58", "AllowedFlag": "103"}, + "Cntrl": {"BrakeSystem": "Pneumatic", "BrakeOpModes": "PN", "BCPN": "4", "BDelay1": "15", "BDelay2": "4", "BDelay3": "35", "BDelay4": "25", "ASB": "Automatic", "LocalBrake": "PneumaticBrake", "MCPN": "15", "SCPN": "40", "SpeedCtrlDelay": "0.5", "AutoRelay": "No", "MainInitTime": "10", "MainStart": "Manual", "IniCDelay": "0.5", "SCDelay": "0.1", "BrakeDelays": "GPR", "BrakeHandle": "MHZ_K8P", "LocBrakeHandle": "FD1", "ScndS": "Yes", "SBD": "0", "ConverterStart": "Automatic", "ConverterStartDelay": "10", "PantCompressorStart": "Automatic", "PantAutoValve": "Yes", "EIMCtrlType": "0", "HAO": "No", "HMO": "No", "HGDP1": "0.1", "OMP": "0.4", "DirChangeMaxPos": "0", "LocalBrakeTraxx": "No", "PantEPValveStart": "Manual", "PantEPValveSpring": "No", "HideDirStatusWhenMoving": "Yes", "HideDirStatusSpeed": "5", "AutomaticCabActivation": "No", "InactiveCabFlag": "161", "DCMB": "Yes", "DCDPP": "1.0", "IBTB": "Yes", "SBBBH": "Yes", "BBHT": "2.0", "MotorBlowersStart": "Converter", "SplitEDPneumaticBrake": "Yes", "DBPN": "15", "rows": [ + ["-1","0.8","-1","20","Pneumatic"], + ["0","0.5","-1","2","Pneumatic"], + ["1","0.46","-1","2","Pneumatic"], + ["2","0.42","-1","2","Pneumatic"], + ["3","0.38","-1","2","Pneumatic"], + ["4","0.34","-1","2","Pneumatic"], + ["5","0.29","-1","2","Pneumatic"], + ["6","0","-1","40","Pneumatic"], + ["LampRed=255","LampGreen=255","LampBlue=228"] + ]}, + "Security": {"AwareSystem": "Active,CabSignal,SeparateAcknowledge", "AwareDelay": "30", "SoundSignalDelay": "0", "MaxHoldTime": "1.0", "EmergencyBrakeDelay": "5", "RadioStop": "Yes"}, + "Light": {"Light": "Generator", "LGeneratorEngine": "ElectricSeriesMotor", "LMaxVoltage": "24", "LMaxCurrent": "155"}, + "Clima": {"Heating": "Main"}, + "Power": {"EnginePower": "CurrentCollector", "CollectorsNo": "2", "MaxVoltage": "4200", "MaxCurrent": "2000", "MinH": "0.38", "MinV": "1900", "MaxH": "2.4", "CSW": "1.4", "PhysicalLayout": "3", "PantType": "WBL85"}, + "Engine": {"EngineType": "ElectricInductionMotor", "Trans": "10:47", "dfic": "931", "dfmax": "1.67", "p": "2", "cfu": "29", "cim": "8.86", "icif": "0.642", "Uzmax": "2216", "Uzh": "2216", "DU": "20", "I0": "20", "fcfu": "30", "F0": "340", "a1": "0.35", "Pmax": "6400", "Fh": "150", "Ph": "5200", "Vh0": "5", "Vh1": "10", "Imax": "2500", "Flat": "Yes", "abed": "1", "edep": "1.5", "Imaxrpc": "500", "BRVto": "15", "MotorBlowersSustainTime": "30", "MotorBlowersStartVelocity": "0.1", "MotorBlowersSpeed": "-10"}, + "SpeedControl": {"SpeedCtrl": "Yes", "OverrideManual": "No", "InitPwr": "1.0", "MaxPwrVel": "-1", "StartVel": "-1", "VelStep": "5", "PwrStep": "0.01", "MinPwr": "0.0", "MaxPwr": "1.0", "MinVel": "0", "MaxVel": "200", "Offset": "0", "kPpos": "0.1", "kPneg": "0.2", "kIpos": "0.03", "kIneg": "0.03", "BrakeIntervention": "No", "SpeedCtrlType": "Time", "SpeedCtrlDelay": "0.5"}, + "Doors": {"OpenCtrl": "Mixed", "CloseCtrl": "Mixed", "DoorOpenWithPermit": "1", "DoorMaxShiftL": "2", "DoorsPermitLightBlinking": "0"}, + "Switches": {"Pantograph": "Impulse", "PantographPresets": "2|1|3|2", "PantographPresetDefault": "1", "ModernDimmer": "Yes"}, + "DimmerList": {"Size": "5", "Cycle": "no", "DefaultPos": "3", "rows": [ + ["yes","no","no"], + ["yes","yes","no"], + ["no","no","yes"], + ["no","no","no"], + ["no","yes","no"] + ]}, + "ffList": {"Size": "8", "rows": [ + ["0","0.2"], + ["1","0.2"], + ["9.2","0.6"], + ["24.6","0.8"], + ["30.0","0.8"], + ["30.0","1.74"], + ["35.2","2.07"], + ["35.2","2.44"], + ["49.8","3.388"] + ]}, + "LightsList": {"Size": "16", "Wrap": "Yes", "Default": "1", "rows": [ + ["0","0"], + ["17","0"], + ["4","0"], + ["16","1"], + ["1","16"], + ["21","34"], + ["34","0"], + ["21","0"], + ["37","0"], + ["33","0"], + ["22","34"], + ["36","0"], + ["21","0"], + ["21","0"], + ["38","34"], + ["38","0"] + ]}, + "WiperList": {"Size": "4", "Angle": "58", "rows": [ + ["0","0.7","0.0","0.5"], + ["3","0.7","7.0","0.5"], + ["3","0.7","0.7","0.0"], + ["3","0.5","0.5","0.0"] + ]} +} diff --git a/tests/unit/drive.cpp b/tests/unit/drive.cpp index b03eeac2d..02fc74c03 100644 --- a/tests/unit/drive.cpp +++ b/tests/unit/drive.cpp @@ -5,6 +5,7 @@ #include "doctest.h" #include "McZapkie/hamulce.h" +#include "vehicle/fieldshunting.h" namespace test { @@ -137,7 +138,8 @@ void close_line_breaker(driven const &Driven) { Driven.cab.MainSwitch(true); } -// the converter, the compressor and the motor blowers, once the line breaker is closed +// the converter, the compressor and the motor blowers, once the line breaker is closed; and the switch of the +// field shunting of a diesel-electric that has one (AutoRelay=Optional with FieldShuntSwitch=Yes), as the AI does void switch_auxiliaries_on(TMoverParameters &Cab) { Cab.ConverterSwitch(true); Cab.CompressorSwitch(true); @@ -147,6 +149,9 @@ void switch_auxiliaries_on(TMoverParameters &Cab) { Cab.MotorBlowersSwitch(true, side); } } + if (Cab.EngineType == TEngineType::DieselElectric && fieldshunting::has_switch(Cab.AutoRelayType, Cab.FieldShuntSwitch)) { + Cab.AutoRelaySwitch(true); + } } } // namespace diff --git a/tests/unit/engine_stubs.cpp b/tests/unit/engine_stubs.cpp index c1a807a32..52a503ac5 100644 --- a/tests/unit/engine_stubs.cpp +++ b/tests/unit/engine_stubs.cpp @@ -12,6 +12,10 @@ #include #include +#include +#include +#include +#include // settings --------------------------------------------------------------------------------------- @@ -34,9 +38,39 @@ bool log_enabled() { static bool const enabled{std::getenv("EU07_UNIT_TESTS_LOG") != nullptr}; return enabled; } + +// the lines kept for a test that checks what goes to the log, from any thread; see unit_tests_log_capture() +std::mutex &captured_mutex() { + static std::mutex mutex; + return mutex; +} + +std::optional> &captured_lines() { + static std::optional> lines; + return lines; +} + } // namespace +// for the tests: keeps every line logged from now on (true), or stops keeping them and forgets them (false) +void unit_tests_log_capture(bool const Enabled) { + std::scoped_lock lock{captured_mutex()}; + captured_lines() = Enabled ? std::make_optional>() : std::nullopt; +} + +// for the tests: the lines kept so far +std::vector unit_tests_logged_lines() { + std::scoped_lock lock{captured_mutex()}; + return captured_lines().value_or(std::vector{}); +} + void WriteLog(const char *str, logtype const, bool const isError) { + if (str != nullptr) { + std::scoped_lock lock{captured_mutex()}; + if (captured_lines().has_value()) { + captured_lines()->emplace_back(str); + } + } if (log_enabled() && str != nullptr) { (isError ? std::cerr : std::cout) << str << "\n"; } diff --git a/tests/unit/test_6dg_power_steps.cpp b/tests/unit/test_6dg_power_steps.cpp new file mode 100644 index 000000000..d8444d7e5 --- /dev/null +++ b/tests/unit/test_6dg_power_steps.cpp @@ -0,0 +1,219 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "drive.h" + +#include +#include + +// the 6Dg shunter as the game ships it (data/fiz/6dg_v1/6dg.json): the power demand of its universal controller +// (EIMCtrlType 3, UCList) moves in steps of 5% (UCList CtrlValStep=0.05, eu07/maszyna#412), and its diesel-electric +// drive follows the demand. the controller's positions in the 6Dg's table: 3 holds no power, 4 lowers the power +// to 0, 5 holds it, 6 raises it to 1, each at 0.15 a second after IniCDelay (0.5 s) + +using test::definition; +using test::vehicle; + +namespace { + +constexpr int no_power{3}; +constexpr int lower{4}; +constexpr int hold{5}; +constexpr int raise{6}; + +definition shipped() { + return definition::fiz("6dg_v1/6dg"); +} + +void move_to(vehicle &Loco, int const Position) { + // one notch at a time, as far as the controller goes + while (Loco->MainCtrlPos < Position) { + if (false == Loco->IncMainCtrl(1)) { + break; + } + } + while (Loco->MainCtrlPos > Position) { + if (false == Loco->DecMainCtrl(1)) { + break; + } + } + REQUIRE(Loco->MainCtrlPos == Position); +} + +// the 6Dg started up (engine running), its brakes released and its direction set, its controller holding no power +void get_ready(vehicle &Loco, test::track const &Track) { + auto driven{test::driving(Loco)}; + REQUIRE(test::start_up(driven, Track)); + test::release_brakes(driven.cab); + move_to(Loco, no_power); + for (int i = 0; i < 3 && Loco->DirActive <= 0; ++i) { + Loco->DirectionForward(); + } + REQUIRE(Loco->DirActive > 0); + // the brake pipe was charged during the start-up: the brakes release slowly (about a minute), and the pressure + // switch keeps the line contactors open while the brake cylinders hold over 2 bar + for (int second = 0; second < 180 && Loco->BrakePress > 0.1; ++second) { + test::drive(driven, Track, 1.0); + } + REQUIRE(Loco->BrakePress <= 0.1); + // the line contactors close on the first position past the ones with no power, as the driver passes it + move_to(Loco, lower); + test::drive(driven, Track, 1.0); + move_to(Loco, hold); + test::drive(driven, Track, 5.0); + REQUIRE(Loco->Mains); // the engine running + REQUIRE(Loco->StLinFlag); // the line contactors closed + REQUIRE(false == Loco->SpeedCtrlUnit.IsActive); // the demand of the controller drives, not the speed control + REQUIRE(Loco->eimic == doctest::Approx(0.0)); +} + +// a tap of the controller onto the given position and back onto holding, then a second of running +void tap(vehicle &Loco, int const Position, test::track const &Track) { + move_to(Loco, Position); + Loco.step(Track); + move_to(Loco, hold); + test::drive(test::driving(Loco), Track, 1.0); +} + +// the changes of the demand while the controller stays on the given position for Seconds +std::vector changes_held(vehicle &Loco, int const Position, double const Seconds, test::track const &Track) { + std::vector changes; + move_to(Loco, Position); + auto previous{Loco->eimic}; + for (int i = 0; i < std::lround(Seconds / 0.01); ++i) { + if (Loco->SecuritySystem.is_blinking()) { + Loco->SecuritySystemReset(); // the driver acknowledging the vigilance + } + Loco.step(Track); + if (std::abs(Loco->eimic - previous) > 1e-9) { + changes.push_back(Loco->eimic - previous); + previous = Loco->eimic; + } + } + return changes; +} + +} // namespace + +TEST_CASE("6Dg: the shipped definition sets the controller's power demand in steps of 5%") { + test::track const line{0.15, 0.0}; + vehicle loco{shipped(), 0.0, "test", 1}; + // the key as the game data has it, on the controller it acts on + REQUIRE(loco->EIMCtrlType == 3); + CHECK(loco->UniCtrlValStep == doctest::Approx(0.05)); + // the ends of the table: raising goes up to 1, lowering down to 0, 20 steps of 0.05 between them + auto const top{loco->UniCtrlList[raise].SetCtrlVal}; + auto const bottom{loco->UniCtrlList[lower].SetCtrlVal}; + REQUIRE(top == doctest::Approx(1.0)); + REQUIRE(bottom == doctest::Approx(0.0)); + REQUIRE(loco->UniCtrlList[raise].MaxCtrlVal == doctest::Approx(top)); + REQUIRE(loco->UniCtrlList[lower].MinCtrlVal == doctest::Approx(bottom)); + auto const steps{static_cast(std::lround((top - bottom) / 0.05))}; + CHECK(steps == 20); + get_ready(loco, line); + + SUBCASE("tapped: every tap moves the demand by one step, up to the top and down to the bottom, and no further") { + auto changed{0}; + for (int i = 1; i <= steps + 3; ++i) { + auto const before{loco->eimic}; + tap(loco, raise, line); + CAPTURE(i); + CHECK(loco->eimic == doctest::Approx(std::min(top, before + 0.05))); + CHECK(loco->eimic <= top + 1e-9); + CHECK(loco->eimic_real == doctest::Approx(loco->eimic)); // the demand reaching the drive + changed += std::abs(loco->eimic - before) > 1e-9 ? 1 : 0; + } + CHECK(changed == steps); + CHECK(loco->eimic == doctest::Approx(top)); + + changed = 0; + for (int i = 1; i <= steps + 3; ++i) { + auto const before{loco->eimic}; + tap(loco, lower, line); + CAPTURE(i); + CHECK(loco->eimic == doctest::Approx(std::max(bottom, before - 0.05))); + CHECK(loco->eimic >= bottom - 1e-9); + changed += std::abs(loco->eimic - before) > 1e-9 ? 1 : 0; + } + CHECK(changed == steps); + CHECK(loco->eimic == doctest::Approx(bottom)); + } + + SUBCASE("held: the demand goes over the whole range in steps of 0.05, never in between nor past the ends") { + // 20 steps of 0.05 at 0.15 a second take under 7 s, after the initial delay + auto const up{changes_held(loco, raise, 12.0, line)}; + CHECK(up.size() == static_cast(steps)); + for (auto const change : up) { + CHECK(change == doctest::Approx(0.05)); + } + CHECK(loco->eimic == doctest::Approx(top)); + auto const down{changes_held(loco, lower, 12.0, line)}; + CHECK(down.size() == static_cast(steps)); + for (auto const change : down) { + CHECK(change == doctest::Approx(-0.05)); + } + CHECK(loco->eimic == doctest::Approx(bottom)); + } +} + +TEST_CASE("6Dg: the diesel-electric drive follows the stepped demand") { + test::track const line{0.15, 0.0}; + struct reading { + double demand; + double revolutions; // of the engine, after the demand is set + double force; // tractive + double power; // of the generator + double speed; // reached after the same time + }; + std::vector readings; + for (auto const taps : {5, 10, 15, 20}) { + CAPTURE(taps); + test::reseed_random(); + vehicle loco{shipped(), 0.0, "test", 1}; + get_ready(loco, line); + for (int i = 0; i < taps; ++i) { + move_to(loco, raise); + loco.step(line); + move_to(loco, hold); + loco.step(line); + } + REQUIRE(loco->eimic == doctest::Approx(0.05 * taps)); + REQUIRE(loco->eimic_real == doctest::Approx(0.05 * taps)); + test::drive(test::driving(loco), line, 10.0); + readings.emplace_back(loco->eimic_real, loco->enrot, std::abs(loco->Ft), loco->EnginePower, std::abs(loco.speed())); + } + // at 0.25, 0.5, 0.75 and 1: the engine at 897, 1198, 1499 and (still running up to) 1800 rpm as the WWList table + // gives, about 28, 37, 48 and 59 kN, 87, 261, 445 and 663 kW, 14, 24, 28 and 30 km/h + for (std::size_t i = 1; i < readings.size(); ++i) { + CAPTURE(i); + INFO("demand " << readings[i].demand << ": " << readings[i].revolutions * 60.0 << " rpm, " << readings[i].force << " N, " << readings[i].power << " kW, " << readings[i].speed + << " km/h; before it " << readings[i - 1].revolutions * 60.0 << " rpm, " << readings[i - 1].force << " N, " << readings[i - 1].power << " kW, " + << readings[i - 1].speed << " km/h"); + CHECK(readings[i].demand > readings[i - 1].demand); + CHECK(readings[i].revolutions > readings[i - 1].revolutions); + CHECK(readings[i].force > readings[i - 1].force); + CHECK(readings[i].power > readings[i - 1].power); + CHECK(readings[i].speed > readings[i - 1].speed); + } +} + +TEST_CASE("6Dg: without CtrlValStep the demand moves continuously between the rows of the table, as before") { + test::track const line{0.15, 0.0}; + vehicle loco{shipped().remove("UCList", "CtrlValStep"), 0.0, "test", 1}; + REQUIRE(loco->UniCtrlValStep == 0.0); + get_ready(loco, line); + // a tap moves it by 0.01 only + tap(loco, raise, line); + CHECK(loco->eimic == doctest::Approx(0.01)); + // held, it goes on at the row's 0.15 a second after the initial delay, a little every step + auto const up{changes_held(loco, raise, 12.0, line)}; + CHECK(up.size() > 100); + for (auto const change : up) { + CHECK(change > 0.0); + CHECK(change < 0.05 - 1e-6); + } + CHECK(loco->eimic == doctest::Approx(1.0)); // up to the top of the table, as with the steps + auto const down{changes_held(loco, lower, 12.0, line)}; + CHECK(down.size() > 100); + CHECK(loco->eimic == doctest::Approx(0.0)); +} diff --git a/tests/unit/test_ai_power.cpp b/tests/unit/test_ai_power.cpp new file mode 100644 index 000000000..330f09e0a --- /dev/null +++ b/tests/unit/test_ai_power.cpp @@ -0,0 +1,105 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/aipower.h" + +// the AI driver of an electric vehicle standing with its pantographs up and no voltage at them: what it makes of +// it, and when it tells of it in the log (eu07/maszyna#421) + +namespace { + +using ai_power::stall; + +// standing with the pantographs up, past the end of the overhead wire +ai_power::state past_the_wire() { + ai_power::state state; + state.collector = true; + state.power = false; + state.standing = true; + state.pantographs_up = true; + state.wire = false; + return state; +} + +} // namespace + +TEST_CASE("ai power: standing with the pantographs up and no wire above them is a stall") { + CHECK(ai_power::check(past_the_wire()) == stall::no_wire); +} + +TEST_CASE("ai power: a wire above the raised pantographs which carries no voltage is told apart") { + auto state{past_the_wire()}; + state.wire = true; + + CHECK(ai_power::check(state) == stall::no_voltage); +} + +TEST_CASE("ai power: with the voltage there, or without a pantograph to take it, there is nothing to tell") { + auto powered{past_the_wire()}; + powered.power = true; // at the pantographs, or from the rest of the train through its high voltage cable + auto diesel{past_the_wire()}; + diesel.collector = false; + + CHECK(ai_power::check(powered) == stall::not_stalled); + CHECK(ai_power::check(diesel) == stall::not_stalled); +} + +TEST_CASE("ai power: moving, or the pantographs not up yet, it only waits") { + auto moving{past_the_wire()}; + moving.standing = false; // coasting through a gap of the wire, say + auto rising{past_the_wire()}; + rising.pantographs_up = false; // the air for the pantographs still being pumped up + + CHECK(ai_power::check(moving) == stall::waiting); + CHECK(ai_power::check(rising) == stall::waiting); +} + +TEST_CASE("ai power: a stall is reported once it lasted report_delay, and only once") { + ai_power::reporter reporter; + + CHECK_FALSE(reporter.update(stall::no_wire, 100.0).has_value()); + CHECK_FALSE(reporter.update(stall::no_wire, 100.0 + ai_power::report_delay - 0.5).has_value()); + auto const report{reporter.update(stall::no_wire, 100.0 + ai_power::report_delay)}; + REQUIRE(report.has_value()); + CHECK(*report == stall::no_wire); + // the driver keeps trying to prepare the vehicle, without telling of it again + CHECK_FALSE(reporter.update(stall::no_wire, 100.0 + ai_power::report_delay + 1.0).has_value()); + CHECK_FALSE(reporter.update(stall::no_wire, 1000.0).has_value()); +} + +TEST_CASE("ai power: the voltage coming back ends the stall, the next one is reported again") { + ai_power::reporter reporter; + reporter.update(stall::no_wire, 0.0); + REQUIRE(reporter.update(stall::no_wire, ai_power::report_delay).has_value()); + + // towed back under the wire: the vehicle gets prepared + CHECK_FALSE(reporter.update(stall::not_stalled, 100.0).has_value()); + // and later stands without voltage again, under a wire switched off this time + CHECK_FALSE(reporter.update(stall::no_voltage, 200.0).has_value()); + auto const report{reporter.update(stall::no_voltage, 200.0 + ai_power::report_delay)}; + REQUIRE(report.has_value()); + CHECK(*report == stall::no_voltage); +} + +TEST_CASE("ai power: moving or lowering the pantographs restarts the count but doesn't end a reported stall") { + ai_power::reporter reporter; + reporter.update(stall::no_wire, 0.0); + // the vehicle moves before the stall is reported: the count starts again once it stands + CHECK_FALSE(reporter.update(stall::waiting, 20.0).has_value()); + CHECK_FALSE(reporter.update(stall::no_wire, 25.0).has_value()); + CHECK_FALSE(reporter.update(stall::no_wire, 25.0 + ai_power::report_delay - 1.0).has_value()); + REQUIRE(reporter.update(stall::no_wire, 25.0 + ai_power::report_delay).has_value()); + // still with no voltage, the vehicle moved (pushed a bit) and stands again: no second report + CHECK_FALSE(reporter.update(stall::waiting, 100.0).has_value()); + CHECK_FALSE(reporter.update(stall::no_wire, 110.0).has_value()); + CHECK_FALSE(reporter.update(stall::no_wire, 110.0 + 2.0 * ai_power::report_delay).has_value()); +} + +TEST_CASE("ai power: the report names the vehicle, where it stands and why") { + auto const nowire{ai_power::message(stall::no_wire, "et21-367", {1817.4, 0.38, 4785.94})}; + auto const novoltage{ai_power::message(stall::no_voltage, "et21-367", {1817.4, 0.38, 4785.94})}; + + CHECK(nowire == "AI [et21-367]: can't start, no overhead wire above its raised pantographs (at 1817.40, 0.38, 4785.94); it waits for the voltage"); + CHECK(novoltage.find("no voltage in the overhead wire") != std::string::npos); + CHECK(novoltage.find("et21-367") != std::string::npos); +} diff --git a/tests/unit/test_ai_wire.cpp b/tests/unit/test_ai_wire.cpp new file mode 100644 index 000000000..070f8618f --- /dev/null +++ b/tests/unit/test_ai_wire.cpp @@ -0,0 +1,254 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/aiwire.h" + +#include +#include +#include + +// where the overhead wire is for the AI driver (vehicle/aiwire.h): a pantograph against a span of the wire, and how far +// short of its target a train stops to keep its pantograph under the wire. the scene query over these +// (basic_region::wire_over) needs the scene, which the unit tests don't link + +namespace { + +// a vehicle running along +z on level track, the pantograph's base point 4 m above the origin +glm::dvec3 const front{0.0, 0.0, 1.0}; +glm::dvec3 const up{0.0, 1.0, 0.0}; +glm::dvec3 const left{1.0, 0.0, 0.0}; +glm::dvec3 const pantograph{0.0, 4.0, 0.0}; +double const halfwidth{0.5}; + +// a 100 m span along the track, at height Height and Offset to the side, its middle at Middle along the track +ai_wire::contact along(double const Offset, double const Height, double const Middle = 0.0) { + return ai_wire::span_contact({Offset, Height, Middle - 50.0}, {0.0, 0.0, 100.0}, pantograph, front, up, left, + halfwidth); +} + +// the wire over the route up to Last metres from the head of the train +auto wire_to(double const Last) { + return [Last](double const Distance) { return Distance <= Last; }; +} + +} // namespace + +TEST_CASE("ai wire: a span centred over the pantograph is on the slide") { + auto const contact{along(0.0, 6.0)}; + + CHECK(contact.within); + CHECK(contact.vertical == doctest::Approx(2.0)); + CHECK(contact.horizontal == doctest::Approx(-halfwidth)); + CHECK(ai_wire::reaches(contact, 1.0, 3.0)); +} + +TEST_CASE("ai wire: a span at the very edge of the slide still touches it, one beyond it doesn't") { + auto const edge{along(halfwidth, 6.0)}; + CHECK(edge.horizontal == doctest::Approx(0.0)); + CHECK(ai_wire::reaches(edge, 1.0, 3.0)); + // either side + CHECK(ai_wire::reaches(along(-halfwidth, 6.0), 1.0, 3.0)); + + auto const beyond{along(halfwidth + 0.1, 6.0)}; + CHECK(beyond.within); + CHECK(beyond.horizontal == doctest::Approx(0.1)); + CHECK_FALSE(ai_wire::reaches(beyond, 1.0, 3.0)); +} + +TEST_CASE("ai wire: the wire is reached only within the given heights") { + auto const contact{along(0.0, 6.0)}; + + CHECK_FALSE(ai_wire::reaches(contact, 3.0, 9.0)); // too low: below the lowest height + CHECK_FALSE(ai_wire::reaches(contact, 0.0, 1.5)); // too high: a bridge's wire above the line + CHECK(ai_wire::reaches(contact, 2.0, 2.0)); // the limits are included +} + +TEST_CASE("ai wire: a span below the pantograph is crossed but out of reach") { + auto const contact{along(0.0, 3.0)}; + + CHECK(contact.within); + CHECK(contact.vertical == doctest::Approx(-1.0)); + CHECK_FALSE(ai_wire::reaches(contact, 0.0, 9.0)); +} + +TEST_CASE("ai wire: a span ahead of or behind the pantograph isn't crossed") { + auto const ahead{along(0.0, 6.0, 60.0)}; + CHECK_FALSE(ahead.within); + CHECK_FALSE(ai_wire::reaches(ahead, 0.0, 9.0)); + + CHECK_FALSE(along(0.0, 6.0, -60.0).within); + // the ends of the span have the tolerance of the vehicles: 0.001 of the span's length + CHECK(along(0.0, 6.0, 50.05).within); + CHECK(along(0.0, 6.0, -50.05).within); + CHECK_FALSE(along(0.0, 6.0, 50.2).within); +} + +TEST_CASE("ai wire: a span skewed against the track is met where it crosses the plane of the pantograph") { + // the zigzag of the wire: from 0.3 m to the right to 0.3 m to the left over 100 m + auto const zigzag{ai_wire::span_contact({-0.3, 6.0, -50.0}, {0.6, 0.0, 100.0}, pantograph + glm::dvec3{0, 0, 25.0}, + front, up, left, halfwidth)}; + CHECK(zigzag.within); + CHECK(zigzag.horizontal == doctest::Approx(0.15 - halfwidth)); + CHECK(ai_wire::reaches(zigzag, 1.0, 3.0)); + + // a sloping span from a tunnel portal, 1 m lower at its far end: the height where the plane crosses it + auto const sloping{ai_wire::span_contact({0.0, 6.0, -50.0}, {0.0, -1.0, 100.0}, pantograph + glm::dvec3{0, 0, 25.0}, + front, up, left, halfwidth)}; + CHECK(sloping.vertical == doctest::Approx(1.25)); + + // a span of a wire crossing the line at a right angle lies in the plane of the pantograph over the track, and is + // out of reach a step along the track (the division by zero trap) + auto const across{ai_wire::span_contact({-5.0, 6.0, 0.0}, {10.0, 0.0, 0.0}, pantograph, front, up, left, halfwidth)}; + CHECK(across.within); + CHECK(std::isfinite(across.vertical)); + CHECK_FALSE(ai_wire::reaches(across, 0.0, 9.0)); // its end, 5 m to the side + CHECK_FALSE(ai_wire::span_contact({-5.0, 6.0, 0.0}, {10.0, 0.0, 0.0}, pantograph + glm::dvec3{0, 0, 1.0}, front, up, + left, halfwidth) + .within); +} + +TEST_CASE("ai wire: the direction of travel doesn't change what the pantograph meets") { + auto const forward{along(0.3, 6.0)}; + auto const backward{ai_wire::span_contact({0.3, 6.0, -50.0}, {0.0, 0.0, 100.0}, pantograph, -front, up, -left, + halfwidth)}; + + CHECK(backward.within); + CHECK(backward.vertical == forward.vertical); + CHECK(backward.horizontal == forward.horizontal); +} + +TEST_CASE("ai wire: the span test gives the very numbers of the code the vehicles had before it was moved here") { + // the math of basic_cell::update_traction before it called span_contact, as it was there + struct legacy { + bool within; + double vertical; + double horizontal; + }; + auto const legacy_contact{[](glm::dvec3 const &pPoint1, glm::dvec3 const &vParametric, + glm::dvec3 const &pantographposition, glm::dvec3 const &vFront, glm::dvec3 const &vUp, + glm::dvec3 const &vLeft, double const fWidth) { + auto const paramfrontdot = glm::dot(vParametric, vFront); + auto const fRaParam = + -(glm::dot(pPoint1, vFront) - glm::dot(pantographposition, vFront)) / (paramfrontdot != 0.0 ? paramfrontdot : 0.001); + if (fRaParam < -0.001 || fRaParam > 1.001) { + return legacy{false, 0.0, 0.0}; + } + auto const vStyk = pPoint1 + fRaParam * vParametric; + auto const vGdzie = vStyk - pantographposition; + auto const fVertical = glm::dot(vGdzie, vUp); + auto const fHorizontal = std::abs(glm::dot(vGdzie, vLeft)) - fWidth; + return legacy{true, fVertical, fHorizontal}; + }}; + + // pseudo-random vehicles and spans around a point far from the origin, as in a real scenery + std::uint32_t seed{12345}; + auto const next{[&seed](double const Low, double const High) { + seed = seed * 1664525u + 1013904223u; + return Low + (High - Low) * (seed >> 8) / double(1u << 24); + }}; + int within{0}; + for (int sample = 0; sample < 2000; ++sample) { + auto const heading{next(0.0, 6.283185307179586)}; + auto const cant{next(-0.1, 0.1)}; + glm::dvec3 const vFront{std::sin(heading), next(-0.03, 0.03), std::cos(heading)}; + glm::dvec3 const vUp{std::sin(cant) * std::cos(heading), std::cos(cant), -std::sin(cant) * std::sin(heading)}; + auto const vLeft{glm::cross(vUp, vFront)}; + glm::dvec3 const position{next(-20000.0, 20000.0), next(100.0, 300.0), next(-20000.0, 20000.0)}; + auto const pantographposition{position + vUp * 4.2}; + auto const spanheading{heading + next(-0.05, 0.05)}; + glm::dvec3 const vParametric{60.0 * std::sin(spanheading), next(-0.5, 0.5), 60.0 * std::cos(spanheading)}; + auto const pPoint1{position + glm::dvec3{next(-1.0, 1.0), next(5.0, 7.0), next(-1.0, 1.0)} - vParametric * next(-0.2, 1.2)}; + auto const fWidth{next(0.4, 0.7)}; + + auto const old{legacy_contact(pPoint1, vParametric, pantographposition, vFront, vUp, vLeft, fWidth)}; + auto const now{ai_wire::span_contact(pPoint1, vParametric, pantographposition, vFront, vUp, vLeft, fWidth)}; + CAPTURE(sample); + REQUIRE(now.within == old.within); + if (old.within) { + ++within; + // bit for bit + REQUIRE(now.vertical == old.vertical); + REQUIRE(now.horizontal == old.horizontal); + } + } + // both kinds were tried + CHECK(within > 200); + CHECK(within < 1800); +} + +TEST_CASE("ai wire: a stop with the wire over the pantograph stays where it is") { + auto const everywhere{[](double) { return true; }}; + CHECK(ai_wire::wire_shortfall(everywhere, 20.0, 130.0) == 0.0); + + // the wire ends between the pantographs: the rear one the train relies on is under it, with the margin ahead + CHECK(ai_wire::wire_shortfall(wire_to(118.0), 20.0, 130.0) == 0.0); + // gaps behind the pantograph don't matter + auto const gap_behind{[](double const Distance) { return Distance <= 90.0 || Distance >= 95.0; }}; + CHECK(ai_wire::wire_shortfall(gap_behind, 20.0, 130.0) == 0.0); +} + +TEST_CASE("ai wire: a stop past the end of the wire is moved back to put the pantograph under the wire") { + // the head stops at 130 m, the pantograph 20 m behind it at 110 m; the wire ends at 100 m. 2 m steps back to the + // first place with the wire over the pantograph and 3 m ahead of it: 96 m + CHECK(ai_wire::wire_shortfall(wire_to(100.0), 20.0, 130.0) == doctest::Approx(14.0)); + // the wire ends right at the pantograph: no margin ahead + CHECK(ai_wire::wire_shortfall(wire_to(110.0), 20.0, 130.0) == doctest::Approx(4.0)); + // a gap in the wire at the pantograph: the stop goes before the gap + auto const gap{[](double const Distance) { return Distance <= 107.0 || Distance >= 112.0; }}; + CHECK(ai_wire::wire_shortfall(gap, 20.0, 130.0) == doctest::Approx(6.0)); +} + +TEST_CASE("ai wire: the margin of wire ahead of the pantograph") { + // exactly the margin ahead: fine + CHECK(ai_wire::wire_shortfall(wire_to(113.0), 20.0, 130.0) == 0.0); + // a little less: one step back + CHECK(ai_wire::wire_shortfall(wire_to(112.9), 20.0, 130.0) == doctest::Approx(2.0)); + // other margins and steps + CHECK(ai_wire::wire_shortfall(wire_to(100.0), 20.0, 130.0, 0.0, 1.0) == doctest::Approx(10.0)); + CHECK(ai_wire::wire_shortfall(wire_to(100.0), 20.0, 130.0, 5.0, 1.0) == doctest::Approx(15.0)); +} + +TEST_CASE("ai wire: without the wire within the walk back the stop stays where it is") { + auto const nowhere{[](double) { return false; }}; + CHECK(ai_wire::wire_shortfall(nowhere, 20.0, 130.0) == 0.0); + + // the pantograph at 110 m: the wire ends more than 300 m back + CHECK(ai_wire::wire_shortfall(wire_to(-200.0), 20.0, 130.0) == 0.0); + // the last place looked at is 300 m back + CHECK(ai_wire::wire_shortfall(wire_to(-187.0), 20.0, 130.0) == doctest::Approx(300.0)); + CHECK(ai_wire::wire_shortfall(wire_to(-187.0), 20.0, 130.0, 3.0, 2.0, 298.0) == 0.0); +} + +TEST_CASE("ai wire: a stop without a coverage or a step to walk with stays where it is") { + CHECK(ai_wire::wire_shortfall({}, 20.0, 130.0) == 0.0); + CHECK(ai_wire::wire_shortfall(wire_to(100.0), 20.0, 130.0, 3.0, 0.0) == 0.0); + CHECK(ai_wire::wire_shortfall(wire_to(100.0), 20.0, 130.0, 3.0, -2.0) == 0.0); +} + +TEST_CASE("ai wire: the walk back asks for the places the 2 m steps give") { + std::vector asked; + auto const recording{[&asked](double const Distance) { + asked.push_back(Distance); + return Distance <= 100.0; + }}; + ai_wire::wire_shortfall(recording, 20.0, 130.0); + + // the pantograph's place and the margin ahead, then the steps back; the margin is asked only where the place is + // under the wire + std::vector const expected{110.0, 108.0, 106.0, 104.0, 102.0, 100.0, 103.0, 98.0, 101.0, 96.0, 99.0}; + CHECK(asked == expected); +} + +TEST_CASE("ai wire: which stops keep the pantograph under the wire") { + using ai_wire::stop_kind; + // the stops of a train that runs with the wire + CHECK(ai_wire::stops_under_wire(true, true, false, stop_kind::track_end)); + CHECK(ai_wire::stops_under_wire(true, true, false, stop_kind::timetable_stop)); + // a signal is a wait, the vehicle to couple to may stand without the wire + CHECK_FALSE(ai_wire::stops_under_wire(true, true, false, stop_kind::signal)); + CHECK_FALSE(ai_wire::stops_under_wire(true, true, false, stop_kind::coupling)); + // without a current collector, with the voltage made up, where the scenery says to coast or lower the pantographs + CHECK_FALSE(ai_wire::stops_under_wire(false, true, false, stop_kind::track_end)); + CHECK_FALSE(ai_wire::stops_under_wire(true, false, false, stop_kind::track_end)); + CHECK_FALSE(ai_wire::stops_under_wire(true, true, true, stop_kind::timetable_stop)); +} diff --git a/tests/unit/test_blackbox.cpp b/tests/unit/test_blackbox.cpp index cad1920a1..77e3e55f4 100644 --- a/tests/unit/test_blackbox.cpp +++ b/tests/unit/test_blackbox.cpp @@ -439,6 +439,43 @@ TEST_CASE("blackbox: the camera and the couplings are written field by field") { } } +TEST_CASE("blackbox: a vehicle off the track is written field by field") { + std::ostringstream file; + blackbox::writer out{file}; + out.header(); + blackbox::derailment_state state; + state.time = 21.5; + state.vehicle = 6; + state.phase = blackbox::derailment_phases::at_rest; + state.cause = blackbox::derailment_causes::overturned; + state.position = {100.0, 2.5, -40.0}; + state.heading = 0.75f; + state.speed_kmh = 0.0f; + state.offset = -12.25f; + state.roll = -1.5f; + state.travelled = 87.5f; + state.lying = true; + out.derailment(state); + auto const all{records(file.str())}; + REQUIRE(all.size() == 1); + CHECK(all[0].type == blackbox::record::derailment); + reader derailment{all[0].payload}; + CHECK(derailment.get() == 21.5); + CHECK(derailment.get() == 6); + CHECK(derailment.get() == 1); + CHECK(derailment.get() == 2); + CHECK(derailment.get() == 100.0); + CHECK(derailment.get() == 2.5); + CHECK(derailment.get() == -40.0); + CHECK(derailment.get() == 0.75f); + CHECK(derailment.get() == 0.0f); + CHECK(derailment.get() == -12.25f); + CHECK(derailment.get() == -1.5f); + CHECK(derailment.get() == 87.5f); + CHECK(derailment.get() == 1); + CHECK(derailment.done()); +} + TEST_CASE("blackbox: a look at the vehicles takes 25 bytes a vehicle") { std::ostringstream file; blackbox::writer out{file}; diff --git a/tests/unit/test_brake_charge.cpp b/tests/unit/test_brake_charge.cpp new file mode 100644 index 000000000..238d0bef0 --- /dev/null +++ b/tests/unit/test_brake_charge.cpp @@ -0,0 +1,169 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/brakecharge.h" + +// a standing train starts only with its brake pipe and auxiliary reservoirs charged (TController, the consist check) + +using brake_charge::charged; +using brake_charge::state; + +TEST_CASE("brake charge: a train charged to within the margin may start") { + state s; + CHECK(charged(s, 5.0, 5.0, 0.0)); + s = {}; + CHECK(charged(s, 5.0 - brake_charge::margin, 5.0, 0.0)); + s = {}; + // the last wagon of a long train, for good below the working pressure from what leaks along the pipe + CHECK(charged(s, 4.62, 5.0, 0.0)); +} + +TEST_CASE("brake charge: a train prepared from cold waits while its pipe fills") { + state s; + // the pipe of the last wagon empty, then filling by 0.1 bar every 5 s + auto level{0.0}; + auto time{0.0}; + while (level < 5.0 - brake_charge::margin - 0.05) { + CHECK_FALSE(charged(s, level, 5.0, time)); + CHECK_FALSE(s.stalled); + level += 0.1; + time += 5.0; + } + CHECK(charged(s, 5.0 - brake_charge::margin, 5.0, time)); + CHECK(s.going); +} + +TEST_CASE("brake charge: a charge that stops rising lets the train go after the stall time") { + state s; + // a hose not connected: the last wagon stays at 3.2 bar + CHECK_FALSE(charged(s, 3.2, 5.0, 100.0)); + CHECK_FALSE(charged(s, 3.21, 5.0, 130.0)); // less than the gain that counts + CHECK_FALSE(charged(s, 3.21, 5.0, 100.0 + brake_charge::stall_time - 0.1)); + CHECK(charged(s, 3.21, 5.0, 100.0 + brake_charge::stall_time)); + CHECK(s.stalled); + // and stays let go + CHECK(charged(s, 3.2, 5.0, 300.0)); +} + +TEST_CASE("brake charge: a train let go stays let go while its charge rises again as it starts") { + // the train went on a stalled charge; starting, the brakes release and the pipe refills behind them + state s; + REQUIRE_FALSE(charged(s, 4.3, 5.0, 0.0)); + REQUIRE(charged(s, 4.3, 5.0, brake_charge::stall_time)); + CHECK(charged(s, 4.35, 5.0, brake_charge::stall_time + 1.0)); + CHECK(charged(s, 4.4, 5.0, brake_charge::stall_time + 2.0)); + SUBCASE("until the train is to stand again: the next start is checked anew") { + s.going = false; + CHECK_FALSE(charged(s, 4.42, 5.0, brake_charge::stall_time + 3.0)); + CHECK(charged(s, 4.6, 5.0, brake_charge::stall_time + 4.0)); + } +} + +TEST_CASE("brake charge: a train with nothing to charge with yet isn't let go for a stall") { + // prepared from cold: the pipe empty, the engine not started, no air in the main reservoir + state s; + // a look every 5 s for ten times the stall time + auto const looks{static_cast(10.0 * brake_charge::stall_time / 5.0)}; + for (auto i{0}; i < looks; ++i) { + CHECK_FALSE(charged(s, 0.0, 5.0, 5.0 * i, false)); + } + CHECK_FALSE(s.stalled); + CHECK_FALSE(s.going); + // the engine runs, the pipe fills + auto const start{10.0 * brake_charge::stall_time}; + CHECK_FALSE(charged(s, 0.0, 5.0, start, true)); + // the stall time counts from when there was air to charge with + CHECK_FALSE(charged(s, 0.0, 5.0, start + brake_charge::stall_time - 10.0, true)); + CHECK_FALSE(charged(s, 2.0, 5.0, start + brake_charge::stall_time + 10.0, true)); + CHECK(charged(s, 4.6, 5.0, start + brake_charge::stall_time + 60.0, true)); +} + +TEST_CASE("brake charge: a slow but steady charge isn't taken for a stall") { + state s; + auto time{0.0}; + auto level{2.0}; + // 0.03 bar every 50 s: above the gain within the stall time + for (auto i{0}; i < 20; ++i) { + CHECK_FALSE(charged(s, level, 5.0, time)); + level += 0.03; + time += 50.0; + } + CHECK_FALSE(s.stalled); +} + +TEST_CASE("brake charge: a lower working pressure (the reductor turned down) lowers the charge asked for") { + state s; + CHECK(charged(s, 4.35, 4.8, 0.0)); + s = {}; + CHECK_FALSE(charged(s, 4.25, 4.8, 0.0)); +} + +TEST_CASE("brake charge: the locomotive brake holds the train only with the margin over the grade force") { + using brake_charge::locomotive_brake_holds; + // the 752 with about 720 t: 17 kN on -2.4 per mille, 30 kN on -4.3, against about 100 kN of its brake + CHECK(locomotive_brake_holds(100000.0, 17000.0)); + CHECK(locomotive_brake_holds(100000.0, -30000.0)); + CHECK(locomotive_brake_holds(110001.0, 100000.0)); + CHECK_FALSE(locomotive_brake_holds(100000.0, 100000.0)); + CHECK_FALSE(locomotive_brake_holds(0.0, 1000.0)); + CHECK(locomotive_brake_holds(0.0, 0.0)); +} + +TEST_CASE("brake charge: the locomotive brake holds with no more than the wheels pass on to the rails") { + using brake_charge::locomotive_brake_force; + // an ST43 of 116 t: 1031 kN at the brake blocks, 0.25 of its weight on the rails + CHECK(locomotive_brake_force(1031000.0, 116000.0 * 9.81) == doctest::Approx(284490.0)); + // a weak brake stays what it is + CHECK(locomotive_brake_force(50000.0, 116000.0 * 9.81) == doctest::Approx(50000.0)); + CHECK(locomotive_brake_force(0.0, 116000.0 * 9.81) == doctest::Approx(0.0)); + CHECK(locomotive_brake_force(-1.0, 116000.0 * 9.81) == doctest::Approx(0.0)); +} + +TEST_CASE("brake charge: standing not charged, the release of the locomotive brake waits") { + using brake_charge::release_waits; + // the train brake already off: what is left on is the locomotive brake, which holds the train while it charges + CHECK(release_waits(false, true, false)); +} + +TEST_CASE("brake charge: the release doesn't wait once the train is charged, or once it moves") { + using brake_charge::release_waits; + CHECK_FALSE(release_waits(true, true, false)); + // in motion a release is braking control, not a start + CHECK_FALSE(release_waits(false, false, false)); + CHECK_FALSE(release_waits(true, false, false)); +} + +TEST_CASE("brake charge: the train brake may come off while the train charges") { + using brake_charge::release_waits; + // released, the train brake fills the pipe, which is what charges the train + CHECK_FALSE(release_waits(false, true, true)); +} + +TEST_CASE("brake charge: with the train brake applied the train charges to the head of the pipe, not to an empty one") { + using brake_charge::reference; + // released: the working pressure + CHECK(reference(4.7, 5.0, false) == doctest::Approx(5.0)); + // the first service position: what the head of the pipe has + CHECK(reference(4.65, 5.0, true) == doctest::Approx(4.65)); + // a pipe emptied, or just being filled: no lower than a full service application leaves, with the margin a train + // is charged within. an SM42 with 32 wagons at 0.02 bar counted as charged the moment its brake was applied + CHECK(reference(0.02, 5.0, true) == doctest::Approx(4.0)); + state s; + CHECK_FALSE(brake_charge::charged(s, 0.02, reference(0.02, 5.0, true), 0.0)); + // an overcharged pipe doesn't raise it + CHECK(reference(5.4, 5.0, true) == doctest::Approx(5.0)); +} + +TEST_CASE("brake charge: the light application that holds a charging train stays on when the order to go comes") { + using brake_charge::holds_application; + CHECK(holds_application(true, false, true, 1.0)); + CHECK(holds_application(true, false, true, 0.75)); + // charged, or moving: the start releases it + CHECK_FALSE(holds_application(true, true, true, 1.0)); + CHECK_FALSE(holds_application(true, false, false, 1.0)); + // a train the locomotive brake holds has no such application + CHECK_FALSE(holds_application(false, false, true, 1.0)); + // a stronger application comes off down to the first position; a released handle has nothing to hold + CHECK_FALSE(holds_application(true, false, true, 2.0)); + CHECK_FALSE(holds_application(true, false, true, 0.0)); +} diff --git a/tests/unit/test_brake_handles.cpp b/tests/unit/test_brake_handles.cpp index 889beb338..f74edfc03 100644 --- a/tests/unit/test_brake_handles.cpp +++ b/tests/unit/test_brake_handles.cpp @@ -265,3 +265,81 @@ TEST_CASE("brake handles: the Knorr St113 EP brake needs the control of the cab unit.run(0.1); CHECK(ep_brake(unit, 0.0, 10.0) < 0.1); } + +// the Knorr St113 of the EN57 (TSt113, derived from TH14K1) over a service application, lap and release: its +// control chamber (GetCP), the brake pipe and the cylinder, against the values the code gave when the test was +// written, at 1e-9. a change of the handle's code which shouldn't alter anything has to keep them +namespace { + +struct st113_sample { + double cp; // the handle's control chamber + double pipe; // the brake pipe + double cylinder; + double ep; // the EP intensity the handle gives +}; + +std::vector st113_run() { + test::reseed_random(); + vehicle real{definition::fiz("en57_v1/6bai")}; + REQUIRE(real->BrakeHandle == TBrakeHandle::St113); + REQUIRE(real->Handle != nullptr); + real.hold_main_reservoir(std::max(real->MaxCompressor, 8.0)); + auto &handle{*real->Handle}; + std::vector samples; + auto const sample{[&] { samples.push_back({handle.GetCP(), real->PipePress, real->BrakePress, handle.GetEP()}); }}; + auto const hold{[&](double Position, std::initializer_list Seconds) { + real->BrakeLevelSet(Position); + for (auto const seconds : Seconds) { + real.run(seconds); + sample(); + } + }}; + sample(); // before the first step: the chamber as Init left it + hold(handle.GetPos(bh_RP), {1.0, 30.0, 30.0}); // charged in the running position + hold(handle.GetPos(bh_MB), {1.0, 5.0}); // the first step of the service brake + hold(handle.GetPos(bh_FB), {1.0, 2.0, 5.0, 10.0}); // full service + hold(handle.GetPos(bh_NP), {5.0}); // lap + hold(handle.GetPos(bh_RP), {1.0, 5.0, 10.0, 30.0}); // released + hold(handle.GetPos(bh_EB), {1.0, 5.0}); // emergency + hold(handle.GetPos(bh_FS), {1.0, 3.0}); // filling stroke + hold(handle.GetPos(bh_RP), {10.0, 60.0}); // released again + return samples; +} + +} // namespace + +TEST_CASE("brake handles: the pressures of the Knorr St113 of the EN57 over an application and a release") { + // {control chamber, brake pipe, cylinder, EP} after each hold of st113_run(), as the code gave them + std::vector const expected{ + {0, 3.5, 6, 0}, + {4.9984786171489723, 4.9985239614132073, 3.8589217414374479, -1}, + {4.9987671731417445, 4.9988125312381184, 9.6079198677899244e-17, -1}, + {4.9991258752288621, 4.9991713394295099, 9.6079198677899244e-17, -1}, + {4.9533680060376426, 4.9530025463238161, 9.6079198677899244e-17, 0}, + {4.8311329228109479, 4.8310446333333399, 9.6079198677899244e-17, 0}, + {4.7310321436160523, 4.7325637973526726, 9.6079198677899244e-17, 0}, + {4.5872331917154092, 4.5890657213751611, 9.6079198677899244e-17, 0}, + {4.1778305377419631, 4.1793406294291415, 1.6739519661380537, 0}, + {3.355298669598576, 3.3569433138107754, 2.5006765921012648, 0}, + {3.340608574818968, 3.3406062128010463, 2.5006765921012648, 0}, + {4.9982940431020717, 4.9983393759288948, 1.805897475684926, -1}, + {4.9983349224059745, 4.9983802579817755, 0.096548127644583259, -1}, + {4.9984201641741199, 4.9984655050733862, 0.062980447840665657, -1}, + {4.9987011353434028, 4.998746490639209, 9.2221356484789066e-17, -1}, + {0.005419548331438478, 0.0049542946616295885, 2.0688047473966584, 0}, + {1.1051369154140042e-16, 1.1051359148828238e-16, 2.5210994451474482, 0}, + {7.9894372542519436, 7.9895176172361353, 1.9107481967960043, 0}, + {7.9894891501326404, 7.9895615214846529, 0.36406880055594204, 0}, + {6.2299691431411732, 6.2285260180794131, 0.068969473862745739, -1}, + {4.9988917107669719, 4.9989370736220264, 1.0102243333979078e-16, -1}, + }; + auto const samples{st113_run()}; + REQUIRE(samples.size() == expected.size()); + for (std::size_t i = 0; i < samples.size(); ++i) { + CAPTURE(i); + CHECK(samples[i].cp == doctest::Approx(expected[i].cp).epsilon(1e-9)); + CHECK(samples[i].pipe == doctest::Approx(expected[i].pipe).epsilon(1e-9)); + CHECK(samples[i].cylinder == doctest::Approx(expected[i].cylinder).epsilon(1e-9)); + CHECK(samples[i].ep == doctest::Approx(expected[i].ep).epsilon(1e-9)); + } +} diff --git a/tests/unit/test_brake_pipe.cpp b/tests/unit/test_brake_pipe.cpp new file mode 100644 index 000000000..664f7262d --- /dev/null +++ b/tests/unit/test_brake_pipe.cpp @@ -0,0 +1,118 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "McZapkie/MOVER.h" +#include "McZapkie/hamulce.h" +#include "consist.h" +#include "vehicle.h" + +// the air exchange through the brake hoses between the vehicles of a train (TMoverParameters::UpdatePipeCouplers()). +// taken in one explicit step of 0.01 s, the hose between two short freight wagons carried twice the air which evens +// out their pipes: the pipes overshot each other in turns, and an ESt3 distributor saw the pipe pressure up to +// 0.28 bar off what was in it, lapped at the first stage of braking and kept the AI's train from leaving +// (eu07/maszyna#368) + +namespace { + +using test::definition; + +// a freight train standing charged: a locomotive and Wagons empty two-axle freight wagons with ESt3, set to G +void freight_train(test::consist &Train, int const Wagons) { + Train.add(definition::fiz("st44_v2/m62-1151")); + for (int i = 0; i < Wagons; ++i) { + auto &wagon{Train.add(definition::fiz("3wl_v2/3wl"))}; + wagon->BrakeDelaySwitch(bdelay_G); + REQUIRE(wagon->BrakeValve == TBrakeValve::ESt3); + REQUIRE(wagon->Spg == doctest::Approx(0.792)); // the pipe of a freight wagon + } + Train[0].hold_brake_pipe(5.0); // the locomotive's driver's valve in the running position +} + +// a passenger train standing charged: a locomotive and Cars passenger cars with ESt4, set to R +void passenger_train(test::consist &Train, int const Cars) { + Train.add(definition::fiz("st44_v2/m62-1151")); + for (int i = 0; i < Cars; ++i) { + auto &car{Train.add(definition::fiz("11xa_v2/93a"))}; + REQUIRE(car->Spg == doctest::Approx(0.507)); // the pipe of a passenger car + } + Train[0].hold_brake_pipe(5.0); +} + +// the time [s] until the brake pipe of the train's last vehicle is 0.5 bar down, once the locomotive holds its pipe +// at Pressure [bar], the physics stepping by Dt +double application_time(test::consist &Train, double const Pressure, double const Dt) { + auto &last{Train[Train.size() - 1]}; + auto const start{last->PipePress}; + Train[0].hold_brake_pipe(Pressure); + auto time{0.0}; + while (last->PipePress > start - 0.5 && time < 60.0) { + Train.step({}, Dt); + time += Dt; + } + return time; +} + +// the same train standing a minute, then braked from the locomotive, all of it in steps of Dt +template +double application_time(Builder Train, int const Vehicles, double const Pressure, double const Dt) { + test::consist train; + Train(train, Vehicles); + train.run(60.0, {}, Dt); + return application_time(train, Pressure, Dt); +} + +} // namespace + +TEST_CASE("brake pipe: the distributors of a standing freight train see the pressure in the pipe, and none of them brakes") { + test::consist train; + freight_train(train, 37); + // standing a while, the locomotive keeping the pipe charged + train.run(300.0); + for (std::size_t i = 1; i < train.size(); ++i) { + CAPTURE(i); + auto &wagon{train[i].mover()}; + // the distributor's valve chamber follows the pressure the distributor works with: the pipe's own + CHECK(std::abs(wagon.Hamulec->GetVRP() - wagon.PipePress) < 0.005); + CHECK(wagon.PipePress > 4.9); + // released, as the AI wants every vehicle before it starts (TController::CheckVehicles()) + CHECK((wagon.Hamulec->GetBrakeStatus() & (b_on | b_hld)) == 0); + CHECK(wagon.BrakePress < 0.1); + } + // the exchange between the 14 m wagons takes 3 sub-steps of a step of 0.01 s + CHECK(train[1]->PipeCouplersSubsteps(0.01) == 3); +} + +TEST_CASE("brake pipe: an application from the locomotive reaches the end of a freight train as with a short step") { + // a light application, the locomotive's pipe 1 bar down: the last wagon's pipe 0.5 bar down as soon as in the + // step of 0.001 s, at which the exchange through the hoses converges + auto const converged{application_time(freight_train, 37, 4.0, 0.001)}; + auto const usual{application_time(freight_train, 37, 4.0, 0.01)}; + CAPTURE(converged); + CAPTURE(usual); + CHECK(converged < 60.0); + CHECK(usual == doctest::Approx(converged).epsilon(0.1)); + // a full service application + auto const convergedfull{application_time(freight_train, 37, 3.5, 0.001)}; + auto const usualfull{application_time(freight_train, 37, 3.5, 0.01)}; + CAPTURE(convergedfull); + CAPTURE(usualfull); + CHECK(usualfull == doctest::Approx(convergedfull).epsilon(0.1)); +} + +TEST_CASE("brake pipe: a passenger train, whose exchange was stable in one step, brakes as with a short step") { + test::consist train; + passenger_train(train, 10); + train.run(300.0); + for (std::size_t i = 1; i < train.size(); ++i) { + CAPTURE(i); + auto &car{train[i].mover()}; + CHECK(std::abs(car.Hamulec->GetVRP() - car.PipePress) < 0.005); + CHECK((car.Hamulec->GetBrakeStatus() & (b_on | b_hld)) == 0); + CHECK(car.BrakePress < 0.1); + } + auto const converged{application_time(passenger_train, 10, 3.5, 0.001)}; + auto const usual{application_time(passenger_train, 10, 3.5, 0.01)}; + CAPTURE(converged); + CAPTURE(usual); + CHECK(usual == doctest::Approx(converged).epsilon(0.05)); +} diff --git a/tests/unit/test_brake_releaser.cpp b/tests/unit/test_brake_releaser.cpp new file mode 100644 index 000000000..ce2c9fb20 --- /dev/null +++ b/tests/unit/test_brake_releaser.cpp @@ -0,0 +1,131 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/brakereleaser.h" + +// when the AI works the brake releaser of its locomotive (TController::control_releaser). in stage 3 of uncoupling +// the locomotive pushes towards the cut it leaves, until the screw coupler slackens enough to be let go +// (TController::UpdateDisconnect). the consist brakes applied in stage 2 hold the locomotive too, and only the +// releaser lets it go. the releaser was worked only while the driver wanted to speed up (AccDesired above +// -0.05), so a signal at stop the cut stood across after the direction change, which caps the speed at 0, left the +// locomotive braked and the uncoupling went on for good (SM42 at Debica on L053). + +namespace { + +// a locomotive standing in stage 3 of uncoupling, braked by the consist's brake application of stage 2 +brake_releaser::conditions compressing_buffers(double const Acceleration) { + brake_releaser::conditions state; + state.acceleration_desired = Acceleration; + state.pipe_pressure = 3.8; + state.cylinder_pressure = 1.5; + state.control_pressure = 5.0; + state.velocity = 0.0; + state.pressing = true; + state.compressing_buffers = true; + return state; +} + +// a locomotive standing braked at the head of a train with a charged brake pipe, about to start off +brake_releaser::conditions standing_braked(double const Acceleration) { + brake_releaser::conditions state; + state.acceleration_desired = Acceleration; + state.pipe_pressure = 5.0; + state.cylinder_pressure = 1.0; + state.control_pressure = 5.0; + state.velocity = 0.0; + return state; +} + +} // namespace + +TEST_CASE("brake releaser: stage 3 of uncoupling releases the locomotive whatever the driver's acceleration") { + for (auto const acceleration : {0.3, 0.0, -0.05, -0.2, -0.9}) { + CAPTURE(acceleration); + auto const wanted{brake_releaser::decide(compressing_buffers(acceleration))}; + CHECK(wanted.actuate); + CHECK_FALSE(wanted.fill_pipe); + } +} + +TEST_CASE("brake releaser: stage 3 of uncoupling leaves a released locomotive alone") { + for (auto const acceleration : {0.3, -0.9}) { + CAPTURE(acceleration); + auto state{compressing_buffers(acceleration)}; + state.cylinder_pressure = 0.05; + CHECK_FALSE(brake_releaser::decide(state).actuate); + } +} + +TEST_CASE("brake releaser: pressing outside stage 3 still needs the driver to want to speed up") { + // the direction changes of stages 2 and 4, and coupling, are as before: the releaser goes on only with + // AccDesired above -0.05 + auto state{compressing_buffers(0.3)}; + state.compressing_buffers = false; + CHECK(brake_releaser::decide(state).actuate); + state.acceleration_desired = -0.05; + CHECK_FALSE(brake_releaser::decide(state).actuate); + state.acceleration_desired = -0.9; + CHECK_FALSE(brake_releaser::decide(state).actuate); +} + +TEST_CASE("brake releaser: starting off releases a braked locomotive below 1 km/h") { + CHECK(brake_releaser::decide(standing_braked(0.3)).actuate); + CHECK_FALSE(brake_releaser::decide(standing_braked(-0.05)).actuate); + + auto moving{standing_braked(0.3)}; + moving.velocity = 1.0; + CHECK_FALSE(brake_releaser::decide(moving).actuate); + + auto lightly{standing_braked(0.3)}; + lightly.cylinder_pressure = 0.4; + CHECK_FALSE(brake_releaser::decide(lightly).actuate); + + // the control reservoir not charged: releasing would vent it + auto uncharged{standing_braked(0.3)}; + uncharged.control_pressure = 4.9; + CHECK_FALSE(brake_releaser::decide(uncharged).actuate); + // unless the train brake is held on purpose to start uphill + uncharged.uphill_start = true; + CHECK(brake_releaser::decide(uncharged).actuate); +} + +TEST_CASE("brake releaser: an empty brake pipe is filled up when the driver wants to speed up") { + auto state{standing_braked(0.3)}; + state.pipe_pressure = 2.9; + state.cylinder_pressure = 0.0; + auto const wanted{brake_releaser::decide(state)}; + CHECK(wanted.actuate); + CHECK(wanted.fill_pipe); + + state.acceleration_desired = -0.2; + auto const braking{brake_releaser::decide(state)}; + CHECK_FALSE(braking.actuate); + CHECK_FALSE(braking.fill_pipe); +} + +TEST_CASE("brake releaser: an overcharged brake pipe turns the releaser off, in stage 3 of uncoupling too") { + auto starting{standing_braked(0.3)}; + starting.pipe_pressure = 5.3; + CHECK_FALSE(brake_releaser::decide(starting).actuate); + + auto uncoupling{compressing_buffers(-0.9)}; + uncoupling.pipe_pressure = 5.3; + CHECK_FALSE(brake_releaser::decide(uncoupling).actuate); +} + +TEST_CASE("brake releaser: a train charging its brakes standing gets an empty pipe filled up before the order to go") { + // a train placed cold, its pipe below the lock of the driver's brake valve, waits for its brakes to charge + // before the first start (#444): the pipe is unlocked as it stands, not only once the driver wants to go + auto state{standing_braked(-0.2)}; + state.pipe_pressure = 1.5; + state.charging_standing = true; + auto const wanted{brake_releaser::decide(state)}; + CHECK(wanted.actuate); + CHECK(wanted.fill_pipe); + + // once the pipe is above the lock the locomotive stays braked: venting it is a rule for the start only + state.pipe_pressure = 3.5; + auto const charging{brake_releaser::decide(state)}; + CHECK_FALSE(charging.actuate); + CHECK_FALSE(charging.fill_pipe); +} diff --git a/tests/unit/test_brake_setting.cpp b/tests/unit/test_brake_setting.cpp index 5034bf3c5..39b0e2117 100644 --- a/tests/unit/test_brake_setting.cpp +++ b/tests/unit/test_brake_setting.cpp @@ -474,6 +474,29 @@ TEST_CASE("brake setting: a bank engine's run counts as a train, shunting doesn' CHECK(false == brake_setting::is_cut_out(car.mover())); } +TEST_CASE("brake setting: the AI looks at its train under the orders it drives it under, Connect included") { + CHECK(brake_setting::inspects_train(Shunt, false)); + CHECK(brake_setting::inspects_train(Loose_shunt, false)); + CHECK(brake_setting::inspects_train(Obey_train, false)); + CHECK(brake_setting::inspects_train(Bank, false)); + // the run up to the wagons: a locomotive standing cold has its hand brake to release first + CHECK(brake_setting::inspects_train(Connect, false)); + CHECK(brake_setting::inspects_train(Connect | Change_direction, false)); + // but not at the coupling: the wagons just coupled wait for the next order, which may leave some of them + CHECK(false == brake_setting::inspects_train(Connect, true)); + CHECK(false == brake_setting::inspects_train(Connect | Change_direction, true)); + // a train run with a coupling on it is still a train run + CHECK(brake_setting::inspects_train(Obey_train | Connect, true)); + CHECK(brake_setting::inspects_train(Shunt, true)); + // standing, starting or stopping the engine, turning round, uncoupling: nothing to look at + CHECK(false == brake_setting::inspects_train(Wait_for_orders, false)); + CHECK(false == brake_setting::inspects_train(Prepare_engine, false)); + CHECK(false == brake_setting::inspects_train(Release_engine, false)); + CHECK(false == brake_setting::inspects_train(Change_direction, false)); + CHECK(false == brake_setting::inspects_train(Disconnect, false)); + CHECK(false == brake_setting::inspects_train(Jump_to_first_order, false)); +} + TEST_CASE("brake setting: R+Mg brakes as hard as R at speed, the rapid stage of an LSt kept") { // the inspector sets R+Mg (Cw-1 §18.2), the bits of R and Mg together: the valves test the bit of R, not // the whole setting, so the high stage of R at speed stays on with Mg. the EU07's LSt given an Mg here diff --git a/tests/unit/test_braking_curve.cpp b/tests/unit/test_braking_curve.cpp index 7102d06e0..6bcf92fc7 100644 --- a/tests/unit/test_braking_curve.cpp +++ b/tests/unit/test_braking_curve.cpp @@ -154,6 +154,41 @@ TEST_CASE("braking curve: a train with a worked out brake table plans along the } } +TEST_CASE("braking curve: the train brake handle or the independent brake counts as braking") { + CHECK_FALSE(braking_curve::brake_acting(0.0, 0.0)); + // the handle in its release or filling positions is below running + CHECK_FALSE(braking_curve::brake_acting(-1.0, 0.0)); + CHECK(braking_curve::brake_acting(1.0, 0.0)); + CHECK(braking_curve::brake_acting(0.5, 0.0)); + // a light locomotive or a railcar alone brakes with the independent brake, the handle stays in running + CHECK(braking_curve::brake_acting(0.0, 0.25)); + CHECK(braking_curve::brake_acting(-1.0, 1.0)); + CHECK(braking_curve::brake_acting(2.0, 0.5)); +} + +TEST_CASE("braking curve: a vehicle braking with its independent brake uses the whole distance, as with the train brake") { + // before, only the train brake handle counted: a light locomotive that had put its independent brake on still + // planned, on every look, to stop short by the distance the brake takes to fill, so it slowed down too early + // and crawled the last tens of metres to the stop + flat_table const light; + auto const table{light.table()}; + auto approach{stop_at(60.0, 300.0)}; + approach.offset = 20.0; + approach.fill_horizon = 8.0; + approach.brake_applied = braking_curve::brake_acting(0.0, 0.3); + + auto const demand{braking_curve::demand(approach, &table)}; + + CHECK(demand == doctest::Approx(braking_curve::shaped_demand(60.0, 0.0, 280.0 + 0.1 / 25.92, 0.0, table))); + auto trainbrake{approach}; + trainbrake.brake_applied = braking_curve::brake_acting(1.0, 0.0); + CHECK(demand == doctest::Approx(braking_curve::demand(trainbrake, &table))); + auto released{approach}; + released.brake_applied = braking_curve::brake_acting(0.0, 0.0); + // with no brake on, the room to fill is kept, and more is asked for + CHECK(braking_curve::demand(released, &table) < demand); +} + TEST_CASE("braking curve: a train gets the demand it got before the curve moved out of the AI") { // a table that grips harder as the train slows, on a gradient; the demands were worked out with the // code of TController::adjust_desired_speed_for_braking_curve before the move (origin/master 80fd5aad) diff --git a/tests/unit/test_camera.cpp b/tests/unit/test_camera.cpp new file mode 100644 index 000000000..684fadb56 --- /dev/null +++ b/tests/unit/test_camera.cpp @@ -0,0 +1,156 @@ +#include "stdafx.h" +#include "doctest.h" + +#include +#include +#include +#include + +#include "input/command.h" +#include "utilities/Timer.h" +#include "vehicle/Camera.h" + +// the view matrix of the camera (TCamera::SetMatrix): the pitch (Angle.x) and the yaw (Angle.y) give the line of sight, +// the roll (Angle.z) turns the view about that line, wherever the camera looks. The roll comes from the sway of the cab +// (drivermode.cpp) or the angles of a camera entry of the scenery. Multiplied in last, it once acted about the world's z +// axis instead, and nodded the view up and down when looking out of a side window (623c4f82, put back in #414). +// vehicle/Camera.cpp isn't in the core library; the test binary compiles it itself (tests/unit/CMakeLists.txt) + +// the parts of the engine TCamera::Update() reaches for, which no test here runs: the command queue and the clock +// (simulation::Commands itself is in test_script_screen_host.cpp) +bool command_queue::pop(command_data &, uint32_t const) { // NOSONAR signature from input/command.h + return false; +} + +double Timer::GetDeltaRenderTime() { // NOSONAR signature from utilities/Timer.h + return 0.0; +} + +namespace { + +// the axes of the view in the world, from the view matrix +struct view_axes { + glm::dvec3 eye; + glm::dvec3 forward; // the line of sight + glm::dvec3 up; + glm::dvec3 right; +}; + +view_axes axes(TCamera const &Camera) { + glm::dmat4 matrix{1.0}; + REQUIRE(Camera.SetMatrix(matrix)); + auto const toworld{glm::inverse(matrix)}; + return { + glm::dvec3{toworld * glm::dvec4{0.0, 0.0, 0.0, 1.0}}, + glm::dvec3{toworld * glm::dvec4{0.0, 0.0, -1.0, 0.0}}, + glm::dvec3{toworld * glm::dvec4{0.0, 1.0, 0.0, 0.0}}, + glm::dvec3{toworld * glm::dvec4{1.0, 0.0, 0.0, 0.0}}}; +} + +void check_equal(glm::dvec3 const &Actual, glm::dvec3 const &Expected) { + CAPTURE(Actual.x); + CAPTURE(Actual.y); + CAPTURE(Actual.z); + CHECK(Actual.x == doctest::Approx(Expected.x).epsilon(1e-9)); + CHECK(Actual.y == doctest::Approx(Expected.y).epsilon(1e-9)); + CHECK(Actual.z == doctest::Approx(Expected.z).epsilon(1e-9)); +} + +// the free camera, at Position, turned by Angle (pitch, yaw, roll) +TCamera free_camera(glm::dvec3 const &Position, glm::vec3 const &Angle) { + TCamera camera; + camera.Init(Position, glm::dvec3{Angle}, nullptr); + return camera; +} + +struct turn { + float pitch; + float yaw; +}; + +// the camera looking ahead (-z), out of the left and the right side window, back, up and down at an angle +std::vector const turns{ + {0.f, 0.f}, + {0.f, static_cast(std::numbers::pi / 2)}, + {0.3f, static_cast(-std::numbers::pi / 2)}, + {-0.4f, static_cast(std::numbers::pi)}, + {0.2f, 0.7f}, + {-0.6f, -2.1f}, +}; + +std::vector const rolls{0.1f, -0.2f, 0.5f}; + +} // namespace + +TEST_CASE("camera: the pitch and the yaw give the line of sight, the roll leaves it as it is (#414)") { + glm::dvec3 const position{120.0, 4.5, -300.0}; + for (auto const &turn : turns) { + auto const pitch{static_cast(turn.pitch)}; + auto const yaw{static_cast(turn.yaw)}; + // the yaw from -z towards -x, the pitch up from the ground, as TCamera::RaLook() works them out + glm::dvec3 const sight{-std::sin(yaw) * std::cos(pitch), std::sin(pitch), -std::cos(yaw) * std::cos(pitch)}; + for (auto const roll : {0.f, rolls[0], rolls[1], rolls[2]}) { + CAPTURE(turn.pitch); + CAPTURE(turn.yaw); + CAPTURE(roll); + auto const view{axes(free_camera(position, {turn.pitch, turn.yaw, roll}))}; + check_equal(view.eye, position); + check_equal(view.forward, sight); + } + } +} + +TEST_CASE("camera: the roll turns the view about the line of sight, wherever the camera looks (#414)") { + for (auto const &turn : turns) { + auto const level{axes(free_camera({}, {turn.pitch, turn.yaw, 0.f}))}; + for (auto const roll : rolls) { + CAPTURE(turn.pitch); + CAPTURE(turn.yaw); + CAPTURE(roll); + auto const rolled{axes(free_camera({}, {turn.pitch, turn.yaw, roll}))}; + auto const angle{static_cast(roll)}; + // the up of the view leans towards the left by the roll, and stays square to the line of sight + check_equal(rolled.up, std::cos(angle) * level.up - std::sin(angle) * level.right); + check_equal(rolled.right, std::cos(angle) * level.right + std::sin(angle) * level.up); + CHECK(glm::dot(rolled.up, rolled.forward) == doctest::Approx(0.0).epsilon(1e-9)); + } + } +} + +// the camera in the cab: the eye in the cab, looking at a point ahead of the vehicle (TCamera::LookAt), the head turned +// by the yaw and the pitch, the sway of the cab given as the roll. The camera needs no more of the vehicle than that it +// has one, so the vehicle is a zeroed block of its size, never used as an object (as the neighbours in vehicle.cpp) +static_assert(alignof(TDynamicObject) <= __STDCPP_DEFAULT_NEW_ALIGNMENT__); + +TEST_CASE("camera: in the cab, the sway leaves the view out of a side window level (#414)") { + std::vector vehicle(sizeof(TDynamicObject)); // zeroed + + glm::dvec3 const eye{10.0, 2.0, -5.0}; + // the vehicle heading north-east on level track + auto const ahead{glm::normalize(glm::dvec3{1.0, 0.0, -1.0})}; + glm::dvec3 const left{ahead.z, 0.0, -ahead.x}; // the vehicle's left, flat + + for (auto const head : {-1, 1}) { // turned to the right, to the left + for (auto const roll : {0.1f, -0.15f}) { + CAPTURE(head); + CAPTURE(roll); + + TCamera camera; + camera.Init(eye, {}, reinterpret_cast(vehicle.data())); // NOSONAR see above + camera.LookAt = eye + ahead; + camera.vUp = {0.f, 1.f, 0.f}; + camera.Angle = {0.f, static_cast(head * std::numbers::pi / 2), roll}; + + auto const view{axes(camera)}; + check_equal(view.eye, eye); + // out of the window to the left or the right, still level, whatever the sway (the yaw is a float, a hair + // off a right angle) + auto const yaw{static_cast(camera.Angle.y)}; + check_equal(view.forward, std::sin(yaw) * left + std::cos(yaw) * ahead); + CHECK(glm::dot(view.forward, static_cast(head) * left) == doctest::Approx(1.0).epsilon(1e-6)); + // the sway tilts the view about that line by its angle + CHECK(glm::dot(view.up, view.forward) == doctest::Approx(0.0).epsilon(1e-9)); + CHECK(view.up.y == doctest::Approx(std::cos(static_cast(roll))).epsilon(1e-9)); + } + } +} diff --git a/tests/unit/test_camera_views.cpp b/tests/unit/test_camera_views.cpp new file mode 100644 index 000000000..2529efbb9 --- /dev/null +++ b/tests/unit/test_camera_views.cpp @@ -0,0 +1,386 @@ +#include "stdafx.h" +#include "doctest.h" + +#include +#include + +#include "vehicle/cameraviews.h" + +// the outside views of the train that go with one of its vehicles (eu07/maszyna#551): orbit, shunting from above, +// beside a coupling, trackside. The camera follows from the place of the vehicle and the keys alone. + +namespace { + +using cameraviews::move_keys; + +// a 20 m coach standing at Position, facing Front +cameraviews::vehicle_pose coach(glm::dvec3 const &Position = {100.0, 50.0, 200.0}, glm::dvec3 const &Front = {0.0, 0.0, -1.0}) { + cameraviews::vehicle_pose pose; + pose.position = Position; + pose.front = Front; + pose.length = 20.0; + pose.width = 3.0; + pose.height = 4.0; + return pose; +} + +double flat_distance(glm::dvec3 const &A, glm::dvec3 const &B) { + return std::hypot(A.x - B.x, A.z - B.z); +} + +// a key held, as TCamera::Velocity has it outside the cab +double constexpr key{1.0}; + +} // namespace + +TEST_CASE("camera views: the orbit starts outside the vehicle, ahead of it on its left, above the rails") { + auto const pose{coach()}; + auto const orbit{cameraviews::orbit_start(pose)}; + auto const place{cameraviews::orbit_placement(orbit, pose)}; + auto const centre{cameraviews::orbit_centre(pose)}; + + CHECK(place.target == centre); + CHECK(glm::distance(place.eye, centre) == doctest::Approx(orbit.radius)); + CHECK(orbit.radius >= cameraviews::orbit_min_radius(pose)); + auto const offset{place.eye - centre}; + CHECK(glm::dot(offset, pose.front) > 0.0); // ahead + CHECK(glm::dot(offset, glm::dvec3{-1.0, 0.0, 0.0}) > 0.0); // on the left of a vehicle facing -z + CHECK(place.eye.y > pose.position.y + pose.height); +} + +TEST_CASE("camera views: the orbit radius stays between the body of the vehicle and its limit") { + auto const pose{coach()}; + auto orbit{cameraviews::orbit_start(pose)}; + // the up arrow held for a minute brings the camera as close as the body lets it + for (int frame = 0; frame < 600; ++frame) { + orbit = cameraviews::orbit_moved(orbit, move_keys{0.0, 0.0, -key}, {}, 0.1, pose); + } + CHECK(orbit.radius == doctest::Approx(cameraviews::orbit_min_radius(pose))); + // the diagonal of the body, so it's outside at any angle + CHECK(orbit.radius > 0.5 * std::hypot(pose.length, pose.width)); + + for (int frame = 0; frame < 600; ++frame) { + orbit = cameraviews::orbit_moved(orbit, move_keys{0.0, 0.0, key}, {}, 0.1, pose); + } + CHECK(orbit.radius == doctest::Approx(cameraviews::orbit_max_radius)); + + // a radius not set yet becomes the default one of the vehicle + cameraviews::orbit unset; + CHECK(cameraviews::orbit_clamped(unset, pose).radius == doctest::Approx(cameraviews::orbit_start(pose).radius)); +} + +TEST_CASE("camera views: the orbit keeps above the rails however low it goes") { + auto const pose{coach()}; + for (auto const radius : {12.0, 25.0, 100.0, 250.0}) { + CAPTURE(radius); + auto orbit{cameraviews::orbit_start(pose)}; + orbit.radius = radius; + for (int frame = 0; frame < 300; ++frame) { + orbit = cameraviews::orbit_moved(orbit, move_keys{0.0, -key, 0.0}, {}, 0.1, pose); + } + auto const place{cameraviews::orbit_placement(orbit, pose)}; + CHECK(place.eye.y >= pose.position.y + cameraviews::rail_clearance - 1e-9); + CHECK(orbit.elevation >= cameraviews::orbit_min_elevation - 1e-9); + } + // up to its highest it doesn't go over the top + auto orbit{cameraviews::orbit_start(pose)}; + for (int frame = 0; frame < 300; ++frame) { + orbit = cameraviews::orbit_moved(orbit, move_keys{0.0, key, 0.0}, {}, 0.1, pose); + } + CHECK(orbit.elevation == doctest::Approx(cameraviews::orbit_max_elevation)); + // the mouse moved up a lot at once is held the same way + orbit = cameraviews::orbit_moved(orbit, {}, {10.0, 0.0}, 0.0, pose); + CHECK(orbit.elevation == doctest::Approx(cameraviews::orbit_lowest_elevation(pose, orbit.radius))); +} + +TEST_CASE("camera views: the left key takes the orbit clockwise around the vehicle, as a step to the left") { + auto const pose{coach()}; + cameraviews::orbit orbit; + orbit.radius = 30.0; + orbit = cameraviews::orbit_clamped(orbit, pose); + auto const ahead{cameraviews::orbit_placement(orbit, pose)}; + CHECK(glm::dot(ahead.eye - ahead.target, pose.front) > 0.0); + + // a little to the left from in front of the vehicle: the camera comes round to its right side + auto const moved{cameraviews::orbit_moved(orbit, move_keys{-key, 0.0, 0.0}, {}, 0.5, pose)}; + CHECK(moved.azimuth < orbit.azimuth); + auto const place{cameraviews::orbit_placement(moved, pose)}; + CHECK((place.eye - place.target).x > 0.0); // the right of a vehicle facing -z is +x + + // so does the mouse moved to the right (TCamera::Angle.y goes down) + CHECK(cameraviews::orbit_moved(orbit, {}, {0.0, -0.2}, 0.0, pose).azimuth == doctest::Approx(orbit.azimuth - 0.2)); + + // all the way round, the azimuth stays within half a turn either way + auto round{orbit}; + for (int frame = 0; frame < 200; ++frame) { + round = cameraviews::orbit_moved(round, move_keys{key, 0.0, 0.0}, {}, 0.1, pose); + REQUIRE(std::abs(round.azimuth) <= std::numbers::pi + 1e-9); + } +} + +TEST_CASE("camera views: the orbit turns with the vehicle and moves with it") { + auto const north{coach({0.0, 10.0, 0.0}, {0.0, 0.0, -1.0})}; + // the same vehicle further on, turned to face east (+x) on a slope + auto const east{coach({500.0, 20.0, -300.0}, glm::normalize(glm::dvec3{1.0, 0.05, 0.0}))}; + auto const orbit{cameraviews::orbit_start(north)}; + + auto const before{cameraviews::orbit_placement(orbit, north)}; + auto const after{cameraviews::orbit_placement(orbit, east)}; + auto const a{before.eye - before.target}; + auto const b{after.eye - after.target}; + CHECK(b.y == doctest::Approx(a.y)); + // a quarter turn clockwise from above: -z becomes +x, so the offset (x, z) becomes (-z, x) + CHECK(b.x == doctest::Approx(-a.z)); + CHECK(b.z == doctest::Approx(a.x)); + CHECK(after.target == cameraviews::orbit_centre(east)); +} + +TEST_CASE("camera views: a longer vehicle picked keeps the orbit outside its body") { + auto const shortvehicle{coach()}; + auto longvehicle{coach()}; + longvehicle.length = 40.0; + cameraviews::orbit orbit; + orbit.radius = cameraviews::orbit_min_radius(shortvehicle); + orbit = cameraviews::orbit_clamped(orbit, longvehicle); + CHECK(orbit.radius == doctest::Approx(cameraviews::orbit_min_radius(longvehicle))); + CHECK(orbit.radius > 20.0); +} + +TEST_CASE("camera views: the shunting view looks straight down, the way the user drives up the screen") { + auto const pose{coach()}; + cameraviews::topdown view; + view = cameraviews::topdown_clamped(view, pose, 100.0); + CHECK(view.height >= cameraviews::topdown_min_height(pose)); + + auto const place{cameraviews::topdown_placement(view, pose, 1)}; + CHECK(place.eye.x == doctest::Approx(pose.position.x)); + CHECK(place.eye.z == doctest::Approx(pose.position.z)); + CHECK(place.eye.y == doctest::Approx(pose.position.y + view.height)); + CHECK(place.target.x == doctest::Approx(place.eye.x)); + CHECK(place.target.z == doctest::Approx(place.eye.z)); + CHECK(place.up.z == doctest::Approx(-1.0)); // the front of the vehicle up the screen + + // driven from the rear cab, its rear is up the screen + CHECK(cameraviews::topdown_placement(view, pose, -1).up.z == doctest::Approx(1.0)); + + // the vehicle turned to face east: the screen turns with it + auto const east{coach({0.0, 0.0, 0.0}, {1.0, 0.0, 0.0})}; + CHECK(cameraviews::topdown_placement(view, east, 1).up.x == doctest::Approx(1.0)); +} + +TEST_CASE("camera views: the shunting view moves along and across the train and up, within its limits") { + auto const pose{coach()}; + auto const along{60.0}; + auto view{cameraviews::topdown_clamped({}, pose, along)}; + auto const height{view.height}; + + // the up arrow moves it up the screen, the way the user drives + auto const forward{cameraviews::topdown_moved(view, move_keys{0.0, 0.0, -key}, 1.0, pose, along)}; + CHECK(forward.along > 0.0); + auto const place{cameraviews::topdown_placement(forward, pose, -1)}; + CHECK(place.eye.z > pose.position.z); // driven from the rear cab, up the screen is +z + // the right arrow to the right of the screen + auto const right{cameraviews::topdown_moved(view, move_keys{key, 0.0, 0.0}, 1.0, pose, along)}; + CHECK(cameraviews::topdown_placement(right, pose, 1).eye.x > pose.position.x); + CHECK(cameraviews::topdown_placement(right, pose, -1).eye.x < pose.position.x); + + for (int frame = 0; frame < 600; ++frame) { + view = cameraviews::topdown_moved(view, move_keys{key, -key, -key}, 0.1, pose, along); + } + CHECK(view.along == doctest::Approx(along)); + CHECK(view.across == doctest::Approx(cameraviews::topdown_max_across)); + CHECK(view.height == doctest::Approx(cameraviews::topdown_min_height(pose))); + CHECK(view.height < height); + for (int frame = 0; frame < 600; ++frame) { + view = cameraviews::topdown_moved(view, move_keys{0.0, key, 0.0}, 0.1, pose, along); + } + CHECK(view.height == doctest::Approx(cameraviews::topdown_max_height)); +} + +TEST_CASE("camera views: the way the user drives, seen from another vehicle of the train") { + glm::dvec3 const north{0.0, 0.0, -1.0}; + glm::dvec3 const south{0.0, 0.0, 1.0}; + CHECK(cameraviews::driving_facing(north, north, 1) == 1); + CHECK(cameraviews::driving_facing(north, north, -1) == -1); + CHECK(cameraviews::driving_facing(north, north, 0) == 1); // no cab occupied counts as the front one + // a vehicle turned round in the train + CHECK(cameraviews::driving_facing(south, north, 1) == -1); + CHECK(cameraviews::driving_facing(south, north, -1) == 1); +} + +TEST_CASE("camera views: [ and ] step through the vehicles of the train and stop at its ends") { + CHECK(cameraviews::step_index(2, 5, 1) == 3); + CHECK(cameraviews::step_index(2, 5, -1) == 1); + CHECK(cameraviews::step_index(0, 5, -1) == 0); + CHECK(cameraviews::step_index(4, 5, 1) == 4); + CHECK(cameraviews::step_index(1, 5, 10) == 4); + CHECK(cameraviews::step_index(3, 1, 1) == 0); // a vehicle alone + CHECK(cameraviews::step_index(3, 0, 1) == 0); // no train + // a picked vehicle beyond the end of a train which got shorter + CHECK(cameraviews::step_index(7, 3, 0) == 2); +} + +TEST_CASE("camera views: the head and the tail of a train are its ends the way it goes") { + std::vector const positions{{0.0, 0.0, 0.0}, {0.0, 0.0, 20.0}, {0.0, 0.0, 40.0}}; + CHECK(cameraviews::train_ends(positions, {0.0, 0.0, -1.0}) == std::pair{0, 2}); + CHECK(cameraviews::train_ends(positions, {0.0, 0.0, 1.0}) == std::pair{2, 0}); + CHECK(cameraviews::train_ends({}, {0.0, 0.0, 1.0}) == std::pair{-1, -1}); +} + +TEST_CASE("camera views: the coupling view starts where another vehicle comes closer") { + auto const count{5}; + CHECK(cameraviews::first_coupling(-1.0, -1.0, count) == 0); + CHECK(cameraviews::first_coupling(30.0, -1.0, count) == 0); + CHECK(cameraviews::first_coupling(-1.0, 30.0, count) == count); + CHECK(cameraviews::first_coupling(50.0, 10.0, count) == count); + CHECK(cameraviews::first_coupling(10.0, 50.0, count) == 0); + // a vehicle too far away doesn't count + CHECK(cameraviews::first_coupling(-1.0, cameraviews::coupler_watch_range + 1.0, count) == 0); +} + +TEST_CASE("camera views: the coupling view stands beside the coupler and steps back for the vehicle coming closer") { + cameraviews::coupler coupler; + coupler.position = {0.0, 10.0, -10.0}; + coupler.outward = {0.0, 0.0, -1.0}; + coupler.width = 3.0; + cameraviews::coupler_view const view; + + auto const alone{cameraviews::coupler_placement(view, coupler, nullptr)}; + CHECK(alone.eye.x == doctest::Approx(-(1.5 + view.distance))); // on the left of the outward way, -x + CHECK(alone.eye.z > coupler.position.z); // a little back towards its vehicle + CHECK(alone.eye.y == doctest::Approx(coupler.position.y + cameraviews::buffer_height + view.height)); + CHECK(alone.target.z < coupler.position.z); // looking out past the coupler + + // a vehicle 30 m away: the camera steps back from the track and looks between the two couplers + glm::dvec3 const other{0.0, 10.0, -40.0}; + auto const coming{cameraviews::coupler_placement(view, coupler, &other)}; + CHECK(coming.eye.x < alone.eye.x); + CHECK(coming.target.z == doctest::Approx(-25.0)); + CHECK(coming.target.y == doctest::Approx(10.0 + cameraviews::buffer_height)); + // closer, the camera comes back to the track with it + glm::dvec3 const closer{0.0, 10.0, -12.0}; + CHECK(cameraviews::coupler_placement(view, coupler, &closer).eye.x == doctest::Approx(alone.eye.x)); + // far away, it stops stepping back + glm::dvec3 const distant{0.0, 10.0, -500.0}; + CHECK(cameraviews::coupler_placement(view, coupler, &distant).eye.x == doctest::Approx(-(1.5 + cameraviews::coupler_max_distance))); +} + +TEST_CASE("camera views: the keys of the coupling view") { + cameraviews::coupler_view view; + view = cameraviews::coupler_moved(view, move_keys{key, 0.0, 0.0}, 0.1); + CHECK(view.side == -1.0); + view = cameraviews::coupler_moved(view, {}, 0.1); + CHECK(view.side == -1.0); // stays on its side without the key + view = cameraviews::coupler_moved(view, move_keys{-key, 0.0, 0.0}, 0.1); + CHECK(view.side == 1.0); + for (int frame = 0; frame < 600; ++frame) { + view = cameraviews::coupler_moved(view, move_keys{0.0, key, key}, 0.1); + } + CHECK(view.distance == doctest::Approx(cameraviews::coupler_max_distance)); + CHECK(view.height == doctest::Approx(cameraviews::coupler_max_height)); + for (int frame = 0; frame < 600; ++frame) { + view = cameraviews::coupler_moved(view, move_keys{0.0, -key, -key}, 0.1); + } + CHECK(view.distance == doctest::Approx(cameraviews::coupler_min_distance)); + CHECK(view.height == doctest::Approx(cameraviews::coupler_min_height)); + // the lowest still above the rails + CHECK(cameraviews::buffer_height + cameraviews::coupler_min_height > 0.0); +} + +TEST_CASE("camera views: along an arc of the line, and its curvature from two vehicles") { + glm::dvec3 const start{0.0, 5.0, 0.0}; + glm::dvec3 const north{0.0, 0.0, -1.0}; + auto const [straight, straightway]{cameraviews::along_arc(start, north, 0.0, 100.0)}; + CHECK(straight.z == doctest::Approx(-100.0)); + CHECK(straight.y == doctest::Approx(5.0)); + CHECK(straightway.z == doctest::Approx(-1.0)); + + // a quarter of a circle of 500 m to the left: from going north to going west + auto const radius{500.0}; + auto const [point, way]{cameraviews::along_arc(start, north, 1.0 / radius, 0.5 * std::numbers::pi * radius)}; + CHECK(point.x == doctest::Approx(-radius)); + CHECK(point.z == doctest::Approx(-radius)); + CHECK(way.x == doctest::Approx(-1.0)); + CHECK(way.z == doctest::Approx(0.0).epsilon(1e-9)); + + // two vehicles 25 m apart on that circle, the one ahead turned to the left of the one behind + auto const angle{25.0 / radius}; + glm::dvec3 const centre{-radius, 0.0, 0.0}; + glm::dvec3 const behind{0.0, 0.0, 0.0}; + glm::dvec3 const ahead{centre + glm::dvec3{radius * std::cos(angle), 0.0, -radius * std::sin(angle)}}; + glm::dvec3 const aheadway{-std::sin(angle), 0.0, -std::cos(angle)}; + auto const curvature{cameraviews::line_curvature(ahead, aheadway, behind, north)}; + CHECK(curvature == doctest::Approx(1.0 / radius).epsilon(0.01)); + // the other way round it turns to the right + CHECK(cameraviews::line_curvature(ahead, glm::dvec3{-aheadway.x, 0.0, aheadway.z}, behind, north) < 0.0); + // too close to tell + CHECK(cameraviews::line_curvature(behind, aheadway, behind, north) == 0.0); +} + +TEST_CASE("camera views: the railfan waits for the train ahead of it and moves on once it's gone by") { + cameraviews::train_motion train; + train.direction = {0.0, 0.0, -1.0}; + train.head = {0.0, 0.0, 0.0}; + train.tail = {0.0, 0.0, 100.0}; + train.speed = 20.0; // 72 km/h + train.width = 3.0; + + cameraviews::trackside view; + REQUIRE(cameraviews::trackside_expired(view, train)); + view = cameraviews::trackside_next(view, train); + REQUIRE(view.placed); + // ahead of the head by the 15 s it needs to get there, beside the line on the right, at the eye of a man + CHECK(view.spot.z == doctest::Approx(-20.0 * cameraviews::trackside_lead_time)); + CHECK(view.spot.x == doctest::Approx(1.5 + cameraviews::trackside_distance)); + CHECK(view.spot.y == doctest::Approx(cameraviews::trackside_eye_height)); + + // the train comes and goes by: the railfan stays until its tail is well past + auto const spot{view.spot}; + for (int step = 0; step < 50; ++step) { + auto const run{10.0 * step}; + auto passing{train}; + passing.head.z -= run; + passing.tail.z -= run; + auto const tailpast{spot.z - passing.tail.z}; + CAPTURE(run); + CHECK(cameraviews::trackside_expired(view, passing) == (tailpast > cameraviews::trackside_passed)); + } + // and then walks to the other side of the line, ahead again + auto gone{train}; + gone.head.z -= 500.0; + gone.tail.z -= 500.0; + auto const next{cameraviews::trackside_next(view, gone)}; + CHECK(next.side == -view.side); + CHECK(next.spot.x == doctest::Approx(-(1.5 + cameraviews::trackside_distance))); + CHECK(next.spot.z < gone.head.z); + CHECK(false == cameraviews::trackside_expired(next, gone)); +} + +TEST_CASE("camera views: the railfan's spot ahead keeps to the line in a curve, and nearby when the train stands") { + cameraviews::train_motion train; + train.direction = {0.0, 0.0, -1.0}; + train.speed = 40.0; + auto const radius{400.0}; + train.curvature = 1.0 / radius; + cameraviews::trackside const view; + auto const next{cameraviews::trackside_next(view, train)}; + // the centre of the curve is on the left of the head, the railfan on the right of the line: outside the circle + glm::dvec3 const centre{-radius, 0.0, 0.0}; + CHECK(flat_distance(next.spot, centre) == doctest::Approx(radius + 0.5 * train.width + cameraviews::trackside_distance)); + // no further round than a quarter of the circle + CHECK(next.spot.z >= -radius - 1e-6); + + // a train standing still gets a railfan at the shortest lead + auto standing{train}; + standing.speed = 0.0; + standing.curvature = 0.0; + auto const nearby{cameraviews::trackside_next(view, standing)}; + CHECK(nearby.spot.z == doctest::Approx(-cameraviews::trackside_min_lead)); + // and as long as it stands, the railfan stays + CHECK(false == cameraviews::trackside_expired(nearby, standing)); + // a train gone far away (moved by the user, or a long way back) gets a new railfan + auto away{standing}; + away.head = {0.0, 0.0, 2000.0}; + away.tail = {0.0, 0.0, 2100.0}; + CHECK(cameraviews::trackside_expired(nearby, away)); +} diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp new file mode 100644 index 000000000..6aee28e98 --- /dev/null +++ b/tests/unit/test_collisions.cpp @@ -0,0 +1,1506 @@ +#include "stdafx.h" +#include "doctest.h" +#include "consist.h" +#include "drive.h" +#include "vehicle.h" +#include "McZapkie/collision.h" +#include "McZapkie/MOVER.h" +#include "utilities/Globals.h" + +#include +#include +#include +#include + +// collisions past the buffers with physics.collisions new (McZapkie/collision.h): the crush of the ends, the override, +// the push off the track, and what they do in trains of real vehicles + +using test::consist; +using test::definition; +using test::vehicle; +namespace cl = collision; + +namespace { + +constexpr double kmh{1.0 / 3.6}; + +// the given model of collisions for the test, restored after it +class model_setting { +public: + explicit model_setting(global_settings::collision_model Model) : m_previous{Global.collisions} { Global.collisions = Model; } + ~model_setting() { Global.collisions = m_previous; } + model_setting(model_setting const &) = delete; + model_setting &operator=(model_setting const &) = delete; + +private: + global_settings::collision_model m_previous; +}; + +// the given setting of a global flag for the test, restored after it +class flag_setting { +public: + flag_setting(bool &Flag, bool Enabled) : m_flag{Flag}, m_previous{Flag} { m_flag = Enabled; } + ~flag_setting() { m_flag = m_previous; } + flag_setting(flag_setting const &) = delete; + flag_setting &operator=(flag_setting const &) = delete; + +private: + bool &m_flag; + bool m_previous; +}; + +// ---- the hit of two masses on the stop of their buffers, the way the vehicles take it + +struct pair_outcome { + double crush1{0.0}; + double crush2{0.0}; + double velocity1{0.0}; + double velocity2{0.0}; + double peak{0.0}; // force +}; + +// the first mass runs at the velocity into the second one standing, their buffers pressed all the way already; the +// springs carry the given force while pressed, stepped by Dt as the vehicles are: the springs over the step first, the +// hit after them +pair_outcome hit_pair(cl::end_state First, cl::end_state Second, double const Mass1, double const Mass2, double const Velocity, double const Springs, double const Dt) { + pair_outcome result; + auto velocity1{Velocity}; + auto velocity2{0.0}; + for (int step = 0; step < 1000000; ++step) { + velocity1 -= Springs * Dt / Mass1; + velocity2 += Springs * Dt / Mass2; + auto const closing{velocity1 - velocity2}; + if (closing <= 0.0) { + break; + } + cl::hit_input input; + input.velocity = closing; + input.mass1 = Mass1; + input.mass2 = Mass2; + input.restitution = 0.2; + input.stiffness = 1.4e8; + input.springs = Springs; + input.dt = Dt; + auto const hit{cl::hit(First, Second, input)}; + if (false == hit.crushing) { + // elastic: bounced apart with the restitution + auto const reduced{Mass1 * Mass2 / (Mass1 + Mass2)}; + auto const impulse{reduced * closing * (1.0 + input.restitution)}; + velocity1 -= impulse / Mass1; + velocity2 += impulse / Mass2; + break; + } + velocity1 -= hit.impulse / Mass1; + velocity2 += hit.impulse / Mass2; + First.crush += hit.crush1; + Second.crush += hit.crush2; + result.peak = std::max(result.peak, hit.force); + if (hit.velocity <= 0.0) { + break; + } + } + result.crush1 = First.crush; + result.crush2 = Second.crush; + result.velocity1 = velocity1; + result.velocity2 = velocity2; + return result; +} + +cl::crush_curve const wagon_curve{cl::default_crush(cl::vehicle_kind::wagon)}; +cl::crush_curve const locomotive_curve{cl::default_crush(cl::vehicle_kind::locomotive)}; + +// ---- trains of real vehicles + +bool derailed(TMoverParameters const &Vehicle) { + return TestFlag(Vehicle.DamageFlag, dtrain_out); +} + +double crush_of(TMoverParameters const &Vehicle) { + return std::max(Vehicle.Couplers[end::front].crush, Vehicle.Couplers[end::rear].crush); +} + +// a mixed freight train as the PoC has it: every third wagon from the given one an empty two-axle 3WL (10.5 t), the +// rest 430W coal wagons loaded full (80 t) +definition mixed_wagon(int const Index) { + return definition::fiz(Index % 3 == 1 ? "3wl_v2/3wl" : "430w_v2/430w"); +} + +vehicle &add_mixed(consist &Train, int const Index, int const Coupling, double const Velocity, double const Gap) { + auto &wagon{Train.add(mixed_wagon(Index), 0, Coupling, Velocity, Gap)}; + if (Index % 3 != 1) { + wagon->AssignLoad("coal", 59.5f); + wagon->ComputeMass(); + } + return wagon; +} + +struct crash_outcome { + int derailed{0}; + int overridden{0}; + int pushed{0}; + int crushed{0}; // ends crushed past the mark + int broken{0}; // couplings torn off + double crush{0.0}; // the deepest crush of an end + bool locomotive{false}; // it derailed + std::string list; // what happened to which vehicle, for the messages +}; + +// the PoC of G14: a locomotive (EU07, 80 t) with 12 mixed wagons running into the rear of 8 mixed wagons standing +// braked, in emergency, on a straight track or in a curve +crash_outcome freight_crash(double const Speed, double const Radius, double const Dt = 0.01) { + test::track track; + track.radius = Radius; + consist train; + // the standing train, the wagon it's hit at last; its brakes charged, then in emergency + constexpr int standing{8}; + for (int i = standing - 1; i >= 0; --i) { + add_mixed(train, i, consist::full_coupling, 0.0, 0.0).hold_brake_pipe(5.0); + } + train.run(90.0, track); + for (int i = 0; i < standing; ++i) { + train[i].hold_brake_pipe(0.0); + } + train.run(30.0, track); + // the train running into it, its locomotive leading, a metre short of the hit + train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, Speed, 1.0); + for (int i = 0; i < 12; ++i) { + add_mixed(train, i, consist::full_coupling, Speed, 0.0); + } + train.run(12.0, track, Dt); + + crash_outcome result; + for (std::size_t i = 0; i < train.size(); ++i) { + auto const &vehicle{train[i].mover()}; + auto const name{i < standing ? std::format("standing {}", standing - 1 - i) : i == standing ? std::string{"locomotive"} : std::format("running {}", i - standing - 1)}; + for (auto const end : {end::front, end::rear}) { + if (vehicle.Couplers[end].crush >= cl::crush_mark) { + ++result.crushed; + } + } + result.crush = std::max(result.crush, crush_of(vehicle)); + if (derailed(vehicle)) { + ++result.derailed; + result.overridden += vehicle.CollisionDerail == COLLISION_OVERRIDE; + result.pushed += vehicle.CollisionDerail == COLLISION_PUSHED_OFF; + result.locomotive = result.locomotive || i == standing; + result.list += std::format("{} ({:.1f} t) {}; ", name, vehicle.TotalMass / 1000.0, vehicle.CollisionDerail == COLLISION_OVERRIDE ? "overrode" : "pushed off"); + } + else if (crush_of(vehicle) >= cl::crush_mark) { + result.list += std::format("{} crushed {:.2f} m; ", name, crush_of(vehicle)); + } + } + for (std::size_t i = 0; i + 1 < train.size(); ++i) { + result.broken += train[i]->Couplers[end::rear].broken; + } + return result; +} + +// a locomotive running into a loaded coal wagon standing free, both on the rails: the crush of the pair after the hit +double locomotive_into_wagon(double const Speed, double const Dt) { + consist train; + auto &wagon{train.add(definition::fiz("430w_v2/430w"))}; + wagon->AssignLoad("coal", 59.5f); + wagon->ComputeMass(); + // behind the wagon, running forwards into its rear end + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, Speed, 0.5)}; + train.run(3.0, {}, Dt); + return wagon->Couplers[end::rear].crush + locomotive->Couplers[end::front].crush; +} + +// the energy the crush of both ends of the pair took, by their curves [J] +double crush_energy(TMoverParameters const &First, int const FirstEnd, TMoverParameters const &Second, int const SecondEnd) { + return First.crush_curve_at(FirstEnd).energy(0.0, First.Couplers[FirstEnd].crush) + Second.crush_curve_at(SecondEnd).energy(0.0, Second.Couplers[SecondEnd].crush); +} + +// what the buffers of EN 15551 of the two ends take in [J] +double capacity_of(TMoverParameters const &First, int const FirstEnd, TMoverParameters const &Second, int const SecondEnd) { + return cl::buffer_capacity(First.Couplers[FirstEnd].collision, First.collision_kind()) + cl::buffer_capacity(Second.Couplers[SecondEnd].collision, Second.collision_kind()); +} + +// the kinetic energy of the relative motion of two vehicles closing in at the velocity [J] +double relative_energy(TMoverParameters const &First, TMoverParameters const &Second, double const Velocity) { + auto const mass{First.TotalMass * Second.TotalMass / (First.TotalMass + Second.TotalMass)}; + return 0.5 * mass * Velocity * Velocity; +} + +struct contact_outcome { + double crush{0.0}; // of both ends [m] + double energy{0.0}; // the crush took [J] + double available{0.0}; // the kinetic energy of the hit past the buffers of EN 15551 [J] + bool derailed{false}; // either vehicle +}; + +// the second vehicle runs into the rear end of the first one standing, Gap metres short of the hit (negative: the +// buffers pressed that far already), unbraked and alone on the track +contact_outcome contact(definition const &Front, definition const &Back, double const Speed, double const Gap, double const Seconds = 5.0, double const Dt = 0.01) { + consist train; + auto &front{train.add(Front)}; + auto &back{train.add(Back, 0, coupling::faux, Speed, Gap)}; + train.run(Seconds, {}, Dt); + contact_outcome result; + result.crush = front->Couplers[end::rear].crush + back->Couplers[end::front].crush; + result.energy = crush_energy(front.mover(), end::rear, back.mover(), end::front); + result.available = std::max(0.0, relative_energy(front.mover(), back.mover(), Speed * kmh) - capacity_of(front.mover(), end::rear, back.mover(), end::front)); + result.derailed = derailed(front.mover()) || derailed(back.mover()); + return result; +} + +// a coach of data/wagon.json of the given mass without its rotating masses +definition coach(double const Mass) { + return definition::load("wagon").set("Param", "M", Mass); +} + +// Y / Q of the leading wheel of the vehicle at the end pressed in by its coupling, as check_pushed_off() takes it +double pushed_ratio_of(TMoverParameters const &Vehicle, int const End, double const OtherLength, double const Radius) { + cl::pushed_vehicle pushed; + pushed.mass = Vehicle.TotalMass - Vehicle.Mred; + pushed.axles = Vehicle.NAxles > 0 ? Vehicle.NAxles : 4; + pushed.length = Vehicle.Dim.L; + pushed.pivots = Vehicle.BDist; + pushed.axle_base = Vehicle.ADist > 0.0 ? Vehicle.ADist : Vehicle.BDist; + cl::pushed_end end; + end.force = std::max(0.0, (End == end::front ? -1.0 : 1.0) * Vehicle.Couplers[End].CForce); + end.other_length = OtherLength; + end.crush = Vehicle.Couplers[End].crush; + return cl::pushed_ratio(pushed, end, Radius); +} + +// a loaded 430W coal wagon +vehicle &add_loaded(consist &Train, int const Coupling, double const Velocity, double const Gap) { + auto &wagon{Train.add(definition::fiz("430w_v2/430w"), 0, Coupling, Velocity, Gap)}; + wagon->AssignLoad("coal", 59.5f); + wagon->ComputeMass(); + return wagon; +} + +} // namespace + +// ---- the crush curve + +TEST_CASE("collisions: the crush curve, a peak, a plateau, packing down, and the limit") { + auto const &curve{wagon_curve}; + CHECK(curve.force(0.0) == doctest::Approx(3.0e6)); + CHECK(curve.force(0.049) == doctest::Approx(3.0e6)); + CHECK(curve.force(0.05) == doctest::Approx(2.0e6)); + CHECK(curve.force(0.79) == doctest::Approx(2.0e6)); + // 2 / m past 0.8 m: a metre further it's three times the plateau + CHECK(curve.force(1.3) == doctest::Approx(2.0e6 * (1.0 + 2.0 * 0.5))); + CHECK_FALSE(std::isfinite(curve.force(1.5))); + // the energy is the area under it + CHECK(curve.energy(0.0, 0.05) == doctest::Approx(3.0e6 * 0.05)); + CHECK(curve.energy(0.0, 0.8) == doctest::Approx(3.0e6 * 0.05 + 2.0e6 * 0.75)); + CHECK(curve.energy(0.8, 1.3) == doctest::Approx(0.5 * (2.0e6 + 4.0e6) * 0.5)); + CHECK(curve.energy(0.0, 0.3) + curve.energy(0.3, 1.0) == doctest::Approx(curve.energy(0.0, 1.0))); + // past the limit there's nothing more to crush + CHECK(curve.energy(1.5, 3.0) == 0.0); + + // the kinds of vehicles; a crash zone gives a steady force with no peak + CHECK(locomotive_curve.peak > wagon_curve.peak); + auto const zone{cl::default_crush(cl::vehicle_kind::crash_zone)}; + CHECK(zone.force(0.0) == doctest::Approx(zone.force(0.5))); + // the keys of the .fiz override the defaults of the kind + cl::end_definition given; + given.plateau = 1.0e6; + given.crash_zone = true; + auto const own{cl::crush_of(given, cl::vehicle_kind::coach)}; + CHECK(own.plateau == doctest::Approx(1.0e6)); + CHECK(own.densify == doctest::Approx(zone.densify)); + CHECK(cl::anticlimber_of(given, cl::vehicle_kind::coach)); + CHECK_FALSE(cl::anticlimber_of({}, cl::vehicle_kind::locomotive)); +} + +TEST_CASE("collisions: the buffers of EN 15551, their stroke and energy") { + for (auto const category : {cl::buffer_category::A, cl::buffer_category::B, cl::buffer_category::C, cl::buffer_category::L, cl::buffer_category::passenger}) { + auto const rated{cl::rating(category)}; + for (auto const progression : {0.0, 0.5, 0.9}) { + auto const curve{cl::buffer_curve(category, progression)}; + CHECK(curve.travel == doctest::Approx(rated.stroke)); + // two buffers side by side + CHECK(curve.energy(curve.travel) == doctest::Approx(2.0 * rated.energy)); + } + } + CHECK(cl::rating(cl::buffer_category::A).energy < cl::rating(cl::buffer_category::C).energy); + CHECK(cl::buffer_category_of('C') == cl::buffer_category::C); + CHECK_FALSE(cl::buffer_category_of('X').has_value()); + // the triangle of category A: 2 x 30 kJ over 105 mm is about 1.1 MN at the end of the stroke, 570 kN a buffer + CHECK(cl::buffer_curve(cl::buffer_category::A, 0.0).end_force() == doctest::Approx(4.0 * 30.0e3 / 0.105)); +} + +// ---- the hit + +TEST_CASE("collisions: a hit the steel takes stays elastic, a harder one crushes the weaker end") { + cl::hit_input input; + input.mass1 = 80.0e3; + input.mass2 = 80.0e3; + input.stiffness = 1.4e8; + input.dt = 0.01; + // 40 t reduced: the steel takes 3 MN at 3 / sqrt(1.4e8 * 4e4) = 1.27 m/s + input.velocity = 1.0; + CHECK_FALSE(cl::hit({wagon_curve, 0.0}, {wagon_curve, 0.0}, input).crushing); + input.velocity = 5.0; + auto const hit{cl::hit({locomotive_curve, 0.0}, {wagon_curve, 0.0}, input)}; + REQUIRE(hit.crushing); + // the wagon gives, the locomotive doesn't; at its peak force for the whole step + CHECK(hit.crush1 == 0.0); + CHECK(hit.crush2 > 0.0); + CHECK(hit.force == doctest::Approx(3.0e6)); + CHECK(hit.impulse == doctest::Approx(3.0e6 * 0.01)); + CHECK(hit.duration == doctest::Approx(0.01)); + CHECK(hit.velocity == doctest::Approx(5.0 - 3.0e6 * 0.01 / 40.0e3)); + // with the springs carrying a part of the force, the hit adds the rest + input.springs = 1.0e6; + auto const sprung{cl::hit({locomotive_curve, 0.0}, {wagon_curve, 0.0}, input)}; + CHECK(sprung.impulse == doctest::Approx(2.0e6 * 0.01)); + // two alike crush alike + input.springs = 0.0; + auto const alike{cl::hit({wagon_curve, 0.0}, {wagon_curve, 0.0}, input)}; + CHECK(alike.crush1 == doctest::Approx(alike.crush2)); + // a wall: the end crushed all the way doesn't give, the other one does + auto const wall{cl::hit({wagon_curve, 2.0}, {wagon_curve, 0.0}, input)}; + CHECK(wall.crush1 == 0.0); + CHECK(wall.crush2 > 0.0); + // both crushed all the way: rigid, the legacy exchange + CHECK_FALSE(cl::hit({wagon_curve, 2.0}, {wagon_curve, 2.0}, input).crushing); +} + +TEST_CASE("collisions: the crush doesn't depend on the step, and it takes the energy of the hit") { + struct pair { + char const *name; + double mass1; + double mass2; + double velocity; + double springs; + }; + for (auto const &[name, mass1, mass2, velocity, springs] : { + pair{"80 t into 80 t at 25 km/h", 80.0e3, 80.0e3, 25.0 * kmh, 0.0}, + pair{"80 t into 80 t at 40 km/h, the springs at 1 MN", 80.0e3, 80.0e3, 40.0 * kmh, 1.0e6}, + pair{"80 t into 12 t at 40 km/h", 80.0e3, 12.0e3, 40.0 * kmh, 0.5e6}, + pair{"300 t into 80 t at 35 km/h, past the densification", 300.0e3, 80.0e3, 35.0 * kmh, 0.0}, + }) { + CAPTURE(name); + auto const fine{hit_pair({locomotive_curve, 0.0}, {wagon_curve, 0.0}, mass1, mass2, velocity, springs, 0.001)}; + REQUIRE(fine.crush2 > 0.05); + CHECK(fine.crush1 == 0.0); + for (auto const dt : {0.005, 0.01, 0.05}) { + CAPTURE(dt); + auto const coarse{hit_pair({locomotive_curve, 0.0}, {wagon_curve, 0.0}, mass1, mass2, velocity, springs, dt)}; + CHECK(coarse.crush2 == doctest::Approx(fine.crush2).epsilon(0.02)); + // the momentum stays with the pair + CHECK(mass1 * coarse.velocity1 + mass2 * coarse.velocity2 == doctest::Approx(mass1 * velocity)); + // never past the force the wagon gives at: its peak, or what it packed down to + CHECK(coarse.peak <= std::max(wagon_curve.peak, wagon_curve.force(coarse.crush2)) * (1.0 + 1e-9)); + } + if (springs == 0.0) { + // the energy of the relative motion goes into the crush, but for what the steel takes back + auto const reduced{mass1 * mass2 / (mass1 + mass2)}; + auto const kinetic{0.5 * reduced * velocity * velocity}; + auto const crushforce{wagon_curve.force(fine.crush2)}; + auto const elastic{crushforce * crushforce / (2.0 * 1.4e8)}; + CHECK(wagon_curve.energy(0.0, fine.crush2) == doctest::Approx(kinetic - elastic).epsilon(0.01)); + } + } +} + +TEST_CASE("collisions: the crush of two pairs of masses at the speeds of the table") { + // 80 t on 80 t: the steel takes the hit up to 1.3 m/s past the buffers; at 25 km/h the two ends alike crush by + // 0.4 m between them, the 0.97 MJ at 3 MN to 0.05 m each and at 2 MN past it (the buffers aren't here) + auto const slow{hit_pair({wagon_curve, 0.0}, {wagon_curve, 0.0}, 80.0e3, 80.0e3, 1.2, 0.0, 0.01)}; + CHECK(slow.crush1 + slow.crush2 == 0.0); + auto const hard{hit_pair({wagon_curve, 0.0}, {wagon_curve, 0.0}, 80.0e3, 80.0e3, 25.0 * kmh, 0.0, 0.01)}; + CHECK(hard.crush1 + hard.crush2 > 0.2); + CHECK(hard.crush1 + hard.crush2 < 0.5); +} + +// ---- override + +TEST_CASE("collisions: the lighter or the higher vehicle climbs onto the other one, both past a deeper crush") { + cl::override_input input; + input.mass1 = 80.0e3; + input.mass2 = 80.0e3; + input.height1 = 1.040; + input.height2 = 1.040; + SUBCASE("a shallow crush holds") { + input.crush1 = 0.3; + auto const result{cl::override_of(input)}; + CHECK_FALSE(result.first); + CHECK_FALSE(result.second); + } + SUBCASE("alike: past 0.35 m they hold, past 0.6 m both climb") { + input.crush1 = 0.4; + CHECK_FALSE(cl::override_of(input).first); + input.crush2 = 0.25; + auto const result{cl::override_of(input)}; + CHECK(result.first); + CHECK(result.second); + } + SUBCASE("the lighter one climbs past 0.35 m") { + input.mass1 = 12.0e3; + input.crush1 = 0.4; + auto const result{cl::override_of(input)}; + CHECK(result.first); + CHECK_FALSE(result.second); + } + SUBCASE("40 mm higher, the higher one climbs") { + input.height2 = 1.000; + input.crush1 = 0.2; + input.crush2 = 0.2; + auto const result{cl::override_of(input)}; + CHECK(result.first); + CHECK_FALSE(result.second); + } + SUBCASE("interlocked anticlimbers hold them until the crush zone of an end is used up") { + input.anticlimbers = true; + input.zone1 = 0.8; + input.zone2 = 0.8; + input.height2 = 1.000; + input.mass1 = 40.0e3; + input.crush1 = 0.5; + input.crush2 = 0.5; + auto const held{cl::override_of(input)}; + CHECK_FALSE(held.first); + CHECK_FALSE(held.second); + input.crush1 = 0.85; + auto const spent{cl::override_of(input)}; + CHECK(spent.first); + CHECK(spent.second); + } +} + +// ---- pushed off the track + +TEST_CASE("collisions: an empty two-axle wagon between loaded ones in a curve of 150 m is pushed off past the safe push of EN 15566") { + // the vehicles of data/fiz: the 3WL empty (10.5 t, two axles 6 m apart), between 430W coal wagons + vehicle empty{definition::fiz("3wl_v2/3wl")}; + vehicle loaded{definition::fiz("430w_v2/430w")}; + cl::pushed_vehicle wagon; + wagon.mass = empty->TotalMass - empty->Mred; + wagon.axles = empty->NAxles; + wagon.length = empty->Dim.L; + wagon.pivots = empty->BDist; + wagon.axle_base = empty->ADist > 0.0 ? empty->ADist : empty->BDist; + REQUIRE(wagon.axles == 2); + cl::pushed_end end; + end.other_length = loaded->Dim.L; + auto const ratio = [&](double const Force, double const Radius) { + end.force = Force; + return cl::pushed_ratio(wagon, end, Radius); + }; + // 250 kN on the pair of buffers in a curve of 150 m is safe (EN 15566, 4.2); 600 kN pushes it off + CHECK(ratio(250.0e3, 150.0) < 1.2); + CHECK(ratio(250.0e3, 150.0) > 0.5); + CHECK(ratio(600.0e3, 150.0) > 1.2); + // the wider the curve the more it takes; on a straight track the empty wagon lifts off past 1.5 MN: the force + // pitching it takes the load off its leading wheels + CHECK(ratio(600.0e3, 500.0) < ratio(600.0e3, 150.0)); + CHECK(ratio(600.0e3, 0.0) < 1.2); + CHECK(ratio(1.5e6, 0.0) < 1.2); + CHECK(ratio(2.5e6, 0.0) > 1.2); + // a crushed end no longer holds the ends in line + end.crush = 0.5; + CHECK(ratio(1.5e6, 0.0) > 1.2); + end.crush = 0.0; + + // the loaded wagon, four axles, takes it + cl::pushed_vehicle heavy; + heavy.mass = loaded->TotalMass - loaded->Mred + 59.5e3; + heavy.axles = loaded->NAxles; + heavy.length = loaded->Dim.L; + heavy.pivots = loaded->BDist; + heavy.axle_base = loaded->ADist; + end.force = 600.0e3; + CHECK(cl::pushed_ratio(heavy, end, 150.0) < 0.5); + + // past 3 MN on a straight track the push takes the whole load off its leading wheels: they lift off the rail + CHECK_FALSE(cl::pushed_forces(wagon, end, 0.0).lifted()); + end.force = 3.5e6; + CHECK(cl::pushed_forces(wagon, end, 0.0).lifted()); + CHECK(cl::pushed_ratio(wagon, end, 0.0) > 1e8); +} + +TEST_CASE("collisions: the flange climbs while the wheels roll on, a lifted wheel goes in a short time") { + SUBCASE("Y / Q over the limit over 2 m rolled, however long the steps") { + cl::pushed_monitor monitor; + CHECK_FALSE(monitor.update(true, 0.7, false, 0.03)); + CHECK_FALSE(monitor.update(true, 0.7, false, 0.03)); + CHECK(monitor.distance() == doctest::Approx(1.4)); + CHECK(monitor.update(true, 0.7, false, 0.03)); + } + SUBCASE("a break starts it over") { + cl::pushed_monitor monitor; + CHECK_FALSE(monitor.update(true, 1.5, false, 0.03)); + CHECK_FALSE(monitor.update(false, 0.1, false, 0.03)); + CHECK_FALSE(monitor.update(true, 1.5, false, 0.03)); + CHECK(monitor.update(true, 0.5, false, 0.03)); + } + SUBCASE("standing, it never climbs, however long the push holds") { + cl::pushed_monitor monitor; + auto climbed{false}; + for (int step = 0; step < 100000; ++step) { + climbed = climbed || monitor.update(true, 0.0, false, 0.01); + } + CHECK_FALSE(climbed); + CHECK(monitor.distance() == 0.0); + } + SUBCASE("the wheels lifted off the rail for 0.05 s, standing or not") { + cl::pushed_monitor monitor; + CHECK_FALSE(monitor.update(true, 0.0, true, 0.03)); + CHECK_FALSE(monitor.update(false, 0.0, false, 0.01)); + CHECK_FALSE(monitor.update(true, 0.0, true, 0.03)); + CHECK(monitor.update(true, 0.0, true, 0.03)); + } + SUBCASE("a reset clears both") { + cl::pushed_monitor monitor; + monitor.update(true, 1.9, true, 0.04); + monitor.reset(); + CHECK(monitor.distance() == 0.0); + CHECK(monitor.time() == 0.0); + CHECK_FALSE(monitor.update(true, 0.05, true, 0.005)); + } +} + +TEST_CASE("collisions: a locomotive at its starting effort against a braked train doesn't push the empty wagon off at a stand") { + // the reviewer's case: an ST44 pressing a rake with an empty two-axle wagon right in front of it, in a yard curve. + // the push is over the climbing limit of the empty wagon, but nothing rolls: a wheel which doesn't roll doesn't + // climb. the time criterion pushed it off in five steps of 0.01 s. the ST44 gives some 390 kN, at the climbing + // limit of the empty wagon in a curve of 150 m: the yard curve is one of 120 m, to be past it + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + test::track line; + line.radius = 120.0; + consist train; + constexpr int wagons{4}; + for (int i = 0; i < wagons; ++i) { + add_loaded(train, consist::full_coupling, 0.0, 0.0).hold_brake_pipe(5.0); + } + auto &empty{train.add(definition::fiz("3wl_v2/3wl"))}; + empty.hold_brake_pipe(5.0); + train.run(90.0, line); + for (std::size_t i = 0; i < train.size(); ++i) { + train[i].hold_brake_pipe(0.0); + } + train.run(30.0, line); + auto &locomotive{train.add(definition::fiz("st44_v2/m62-1151"), 1, coupling::faux, 0.0, 0.0)}; + test::driven const driver{locomotive.mover(), locomotive.mover(), locomotive.mover(), [&train](double const Seconds, test::track const &Track) { train.run(Seconds, Track); }}; + REQUIRE(test::start_up(driver, line)); + test::release_brakes(locomotive.mover()); + for (int i = 0; i < 3 && locomotive->DirActive <= 0; ++i) { + locomotive->DirectionForward(); + } + test::drive(driver, line, 10.0); + auto const start{empty->DistCounter}; + auto pushed{0.0}; + auto worst{0.0}; + auto const watch = [&]() { + pushed = std::max(pushed, -locomotive->Couplers[end::front].CForce); + worst = std::max(worst, pushed_ratio_of(empty.mover(), end::rear, locomotive->Dim.L, line.radius)); + }; + // the line contactors close at the first position, once their delay and the pressure switch let them + locomotive->IncMainCtrl(1); + for (int i = 0; i < 90 && false == locomotive->StLinFlag; ++i) { + test::drive(driver, line, 1.0); + } + for (int i = 0; i < 60 && false == locomotive->IsMainCtrlMaxPowerPos(); ++i) { + locomotive->IncMainCtrl(1); + test::drive(driver, line, 1.0); + watch(); + } + for (int i = 0; i < 60; ++i) { + test::drive(driver, line, 1.0); + watch(); + } + auto const rolled{(empty->DistCounter - start) * 1000.0}; + MESSAGE(std::format("ST44 pushing at up to {:.0f} kN, the empty 3WL at Y/Q {:.2f}, rolled {:.3f} m", pushed / 1000.0, worst, rolled)); + REQUIRE(worst >= derailment::climbing_limit); + CHECK(rolled < 0.5); + CHECK_FALSE(derailed(empty.mover())); + CHECK(empty->CollisionDerail == NONE); +} + +TEST_CASE("collisions: a locomotive running onto an empty wagon at 9 km/h doesn't push it off with the peak of the springs") { + // the reviewer's case: an 80 t locomotive onto a free empty 3WL in a curve of 150 m. the springs of the buffers + // press past the climbing limit for some 0.06 s, the wagon rolls a few centimetres meanwhile + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + test::track curve; + curve.radius = 150.0; + consist train; + auto &empty{train.add(definition::fiz("3wl_v2/3wl"))}; + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, 9.0, 0.5)}; + auto pushed{0.0}; + auto worst{0.0}; + auto over{0}; // steps past the climbing limit + for (int step = 0; step < 500; ++step) { + train.step(curve); + pushed = std::max(pushed, empty->Couplers[end::rear].CForce); + auto const ratio{pushed_ratio_of(empty.mover(), end::rear, locomotive->Dim.L, curve.radius)}; + worst = std::max(worst, ratio); + over += ratio >= derailment::climbing_limit; + } + MESSAGE(std::format("EU07 at 9 km/h onto the empty 3WL: up to {:.0f} kN, Y/Q {:.2f}, {} steps of 0.01 s past the limit, the wagon at {:.1f} km/h", pushed / 1000.0, worst, over, + empty.speed())); + REQUIRE(worst >= derailment::climbing_limit); + REQUIRE(over >= 5); + CHECK_FALSE(derailed(empty.mover())); + CHECK_FALSE(derailed(locomotive.mover())); +} + +TEST_CASE("collisions: a train propelling an empty wagon into a braked one in a curve pushes it off as it rolls on") { + // the genuine push off: the empty 3WL leading a heavy train at 15 km/h, the train pressing it on into a braked + // rake through the curve while it all slides along + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + test::track curve; + curve.radius = 150.0; + consist train; + constexpr int standing{4}; + for (int i = 0; i < standing; ++i) { + add_loaded(train, consist::full_coupling, 0.0, 0.0).hold_brake_pipe(5.0); + } + train.run(90.0, curve); + for (int i = 0; i < standing; ++i) { + train[i].hold_brake_pipe(0.0); + } + train.run(30.0, curve); + auto &empty{train.add(definition::fiz("3wl_v2/3wl"), 0, coupling::faux, 15.0, 1.0)}; + train.add(definition::fiz("4e_v1/4e"), 0, consist::full_coupling, 15.0, 0.0); + for (int i = 0; i < 6; ++i) { + add_loaded(train, consist::full_coupling, 15.0, 0.0); + } + auto const start{empty->DistCounter}; + train.run(10.0, curve); + MESSAGE(std::format("the empty 3WL: derailed {}, {}, rolled {:.2f} m", derailed(empty.mover()), empty->CollisionDerail == COLLISION_PUSHED_OFF ? "pushed off" : "not pushed off", + (empty->DistCounter - start) * 1000.0)); + CHECK(empty->CollisionDerail == COLLISION_PUSHED_OFF); +} + +// ---- recovery + +TEST_CASE("collisions: a repaired vehicle has its ends rebuilt and is back on the rails") { + // resetconsist: the crush of the ends shifted the stop of the buffers, the next hit of the repaired consist would + // have started from it; and a vehicle derailed in a collision kept its reason and the state of the push + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + consist train; + auto &wagon{add_loaded(train, coupling::faux, 0.0, 0.0)}; + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, 30.0, 0.5)}; + train.run(3.0); + REQUIRE(wagon->Couplers[end::rear].crush + locomotive->Couplers[end::front].crush > cl::override_crush); + REQUIRE((derailed(wagon.mover()) || derailed(locomotive.mover()))); + for (auto *vehicle : {&wagon, &locomotive}) { + auto &mover{vehicle->mover()}; + mover.repair_damage(); + CHECK(mover.DamageFlag == 0); + CHECK(mover.Derailed == derailment::outcome::none); + CHECK(mover.CollisionDerail == NONE); + CHECK(mover.pushed_off_monitor.distance() == 0.0); + CHECK(mover.pushed_off_monitor.time() == 0.0); + for (auto const &coupler : mover.Couplers) { + CHECK(coupler.crush == 0.0); + CHECK(coupler.contact.absorbed() == 0.0); + CHECK(coupler.contact.crush_work() == 0.0); + CHECK_FALSE(coupler.hit_handled); + CHECK(coupler.hit_force == 0.0); + CHECK_FALSE(coupler.crush_monitored); + CHECK_FALSE(coupler.inside_reported); + } + } +} + +TEST_CASE("collisions: the repair of a coupler torn off by the crush rebuilds its end") { + vehicle wagon{definition::fiz("430w_v2/430w")}; + auto &coupler{wagon->Couplers[end::rear]}; + coupler.crush = 0.3; + coupler.broken = true; + coupler.hit_force = 2.0e6; + SetFlag(wagon->DamageFlag, dtrain_coupling); + REQUIRE(wagon->repair_coupler(end::rear)); + CHECK(coupler.crush == 0.0); + CHECK(coupler.hit_force == 0.0); + CHECK_FALSE(coupler.broken); + CHECK_FALSE(TestFlag(wagon->DamageFlag, dtrain_coupling)); +} + +TEST_CASE("collisions: SetDamage taking the derailment off clears the collision's") { + vehicle wagon{definition::fiz("3wl_v2/3wl")}; + wagon->derail_in_collision(COLLISION_PUSHED_OFF, "test"); + REQUIRE(wagon->CollisionDerail == COLLISION_PUSHED_OFF); + REQUIRE(wagon->Derailed == derailment::outcome::off_rails); + wagon->RunCommand("SetDamage", dtrain_out, -1); + CHECK(wagon->CollisionDerail == NONE); + CHECK(wagon->Derailed == derailment::outcome::none); + CHECK_FALSE(TestFlag(wagon->DamageFlag, dtrain_out)); +} + +// ---- the model of eu07.ini + +TEST_CASE("collisions: the legacy rule with physics.collisions old, the crush with new") { + flag_setting const crashdamage{Global.crash_damage, true}; + struct collision { + char const *name; + char const *front; + char const *back; + double speed; // of the back one, running into the front one standing + bool frontout_old; + bool backout_old; + bool frontout_new; + bool backout_new; + int monitored; // the hits the monitor tells of + }; + // the legacy rule: over 15 km/h weighed by the ratio of the masses. the crush: the light wagon is crushed deep and + // climbs onto the locomotive at 60 km/h; two locomotives at 25 km/h crush their ends 0.1-0.3 m and stay on the rails + // the monitor tells of each hit once: the wagon derailed by the legacy rule is a wall the locomotive presses on into + // until it springs back, the same hit (the wall slowing down took the pair from parting at the start of a step to + // closing in at 0.3 km/h, which was told of as a second hit); the locomotives derailed both stay where they are + for (auto const &[name, front, back, speed, frontout_old, backout_old, frontout_new, backout_new, monitored] : { + collision{"locomotive into a wagon at 60", "3wl_v2/3wl", "4e_v1/4e", 60.0, true, false, true, false, 1}, + collision{"locomotive into a locomotive at 25", "4e_v1/4e", "4e_v1/4e", 25.0, true, true, false, false, 1}, + collision{"locomotive into a locomotive at 50", "4e_v1/4e", "4e_v1/4e", 50.0, true, true, true, true, 1}, + }) { + CAPTURE(name); + // monitor: the legacy rule, and the log tells of the crush once + for (auto const model : {global_settings::collision_model::old, global_settings::collision_model::physical, global_settings::collision_model::monitor}) { + auto const physical{model == global_settings::collision_model::physical}; + CAPTURE(name_of(model)); + model_setting const setting{model}; + consist train; + train.add(definition::fiz(front)); + train.add(definition::fiz(back), 0, coupling::faux, speed, 20.0); + train.run(10.0); + CHECK(derailed(train[0].mover()) == (physical ? frontout_new : frontout_old)); + CHECK(derailed(train[1].mover()) == (physical ? backout_new : backout_old)); + auto const crush{train[0]->Couplers[end::rear].crush + train[1]->Couplers[end::front].crush}; + if (physical) { + MESSAGE(name, ": crush ", crush, " m"); + CHECK(crush > 0.05); + } + else { + CHECK(crush == 0.0); + } + CHECK(train[0]->crush_reports + train[1]->crush_reports == (model == global_settings::collision_model::monitor ? monitored : 0)); + } + } +} + +TEST_CASE("collisions: the names of the models in eu07.ini") { + using model = global_settings::collision_model; + CHECK(collision_model_of("new") == model::physical); + CHECK(collision_model_of("old") == model::old); + CHECK(collision_model_of("monitor") == model::monitor); + // a name it doesn't know is the default + CHECK(collision_model_of("physical") == model::physical); + CHECK(global_settings{}.collisions == model::physical); + for (auto const value : {model::old, model::physical, model::monitor}) { + CHECK(collision_model_of(name_of(value)) == value); + } + CHECK(name_of(model::physical) == "new"); +} + +TEST_CASE("collisions: the model of the collisions goes apart from the one of the derailment") { + // the crush with the legacy draw of the derailment in a curve, the legacy collisions with the criteria + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const derailment : {global_settings::derailment_model::old, global_settings::derailment_model::physical}) { + for (auto const collisions : {global_settings::collision_model::old, global_settings::collision_model::physical}) { + auto const previous{Global.derailment}; + Global.derailment = derailment; + model_setting const setting{collisions}; + consist train; + train.add(definition::fiz("4e_v1/4e")); + train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, 25.0, 20.0); + train.run(10.0); + Global.derailment = previous; + auto const crush{train[0]->Couplers[end::rear].crush + train[1]->Couplers[end::front].crush}; + CHECK((crush > 0.05) == (collisions == global_settings::collision_model::physical)); + } + } +} + +TEST_CASE("collisions: the crush of a locomotive hitting a wagon doesn't depend on the step, nor on the model of the coupling") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const physics : {false, true}) { + CAPTURE(physics); + flag_setting const couplerphysics{Global.coupler_physics, physics}; + flag_setting const everywhere{Global.coupler_physics_all, physics}; + auto const fine{locomotive_into_wagon(30.0, 0.001)}; + auto const game{locomotive_into_wagon(30.0, 0.01)}; + auto const coarse{locomotive_into_wagon(30.0, 0.05)}; + MESSAGE(std::format("30 km/h, couplerphysics {}: crush {:.3f} / {:.3f} / {:.3f} m with dt 0.001 / 0.01 / 0.05 s", physics, fine, game, coarse)); + REQUIRE(fine > 0.05); + // the step of the game, and a step five times as long, which the buffers past the crush aren't made for + CHECK(game == doctest::Approx(fine).epsilon(0.1)); + CHECK(coarse == doctest::Approx(fine).epsilon(0.5)); + } + // the models of the coupling differ in their buffers, not past them + { + auto const legacy{locomotive_into_wagon(30.0, 0.01)}; + flag_setting const couplerphysics{Global.coupler_physics, true}; + flag_setting const everywhere{Global.coupler_physics_all, true}; + CHECK(locomotive_into_wagon(30.0, 0.01) == doctest::Approx(legacy).epsilon(0.3)); + } + // slow enough, the buffers take it all + CHECK(locomotive_into_wagon(5.0, 0.01) == 0.0); +} + +TEST_CASE("collisions: automatic couplers hit too fast don't catch, the ends crush; torn off, they don't couple again") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + auto const automatic{definition::load("wagon").set("BuffCoupl", "CType", "Automatic").set("BuffCoupl", "AutomaticFlag", coupling::coupler | coupling::brakehose)}; + for (auto const speed : {20.0, 30.0, 45.0}) { + CAPTURE(speed); + vehicle moving{automatic, speed, "moving"}; + vehicle standing{automatic, 0.0, "standing"}; + test::pair pair{moving, end::front, standing, end::rear, 1.0}; + auto coupled{false}; + auto fast{false}; // coupled while closing in faster than the couplers catch + for (int i = 0; i < 1000; ++i) { + auto const closing{moving->CollisionVelocity(end::front, standing.mover(), end::rear)}; + pair.step(); + fast = fast || (pair.coupled() && false == coupled && closing > TMoverParameters::SafeCollisionVelocity); + coupled = coupled || pair.coupled(); + } + auto const crush{moving->Couplers[end::front].crush + standing->Couplers[end::rear].crush}; + MESSAGE(speed, " km/h: crush ", crush, " m, derailed ", derailed(moving.mover()), " ", derailed(standing.mover()), ", coupled later ", coupled); + CHECK_FALSE(fast); + CHECK(crush > 0.0); + // crushed past the draw gear, the coupler is gone; short of it, the wagons may roll together again slowly + // after the hit, and couple then + if (std::max(moving->Couplers[end::front].crush, standing->Couplers[end::rear].crush) >= cl::draw_gear_crush) { + CHECK_FALSE(coupled); + CHECK((moving->Couplers[end::front].broken || standing->Couplers[end::rear].broken)); + } + // the two alike: neither climbs onto the other until the crush is deep enough for both to + CHECK(derailed(moving.mover()) == derailed(standing.mover())); + CHECK(derailed(moving.mover()) == (crush > cl::override_both)); + } +} + +TEST_CASE("collisions: road vehicles keep the legacy rule") { + // the traffic of a scenery: cars and buses have no underframe to crush; over 15 km/h weighed by the masses they + // derail, as with physics.collisions old (found running line 107: two cars of its traffic, 119 km/h head-on) + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const model : {global_settings::collision_model::old, global_settings::collision_model::physical, global_settings::collision_model::monitor}) { + model_setting const setting{model}; + consist road; + road.add(definition::fiz("road/man/nl293")); + road.add(definition::fiz("road/man/nl293"), 0, coupling::faux, 40.0, 5.0); + road.run(5.0); + CHECK(derailed(road[0].mover())); + CHECK(derailed(road[1].mover())); + CHECK(road[0]->Couplers[end::rear].crush == 0.0); + CHECK(road[1]->CollisionDerail == NONE); + CHECK(road[0]->crush_reports + road[1]->crush_reports == 0); + } +} + +TEST_CASE("collisions: a vehicle off the rails by the new model stays in the chain of forces") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + consist train; + auto &wagon{train.add(definition::fiz("430w_v2/430w"))}; + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, 10.0, 0.5)}; + wagon->derail_in_collision(COLLISION_PUSHED_OFF, "for the test"); + REQUIRE(derailed(wagon.mover())); + auto const before{wagon->TotalMass * wagon->V + locomotive->TotalMass * locomotive->V}; + // the hit is over within a second, the friction of the derailed wagon slows the pair down over it + train.run(1.0); + auto const after{wagon->TotalMass * wagon->V + locomotive->TotalMass * locomotive->V}; + // pushed along, not a wall the locomotive bounces off + CHECK(wagon.speed() > 1.0); + CHECK(locomotive.speed() > 0.0); + CHECK(after < before); + CHECK(after > 0.5 * before); + // and it slides on with the friction of the ballast, stopping before long + train.run(10.0); + CHECK(std::abs(wagon.speed()) < 0.1); +} + +TEST_CASE("collisions: a freight train running into a standing one, the cases of the PoC of G14") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + struct crash { + double speed; + double radius; + }; + for (auto const &[speed, radius] : {crash{10.0, 0.0}, crash{15.0, 0.0}, crash{15.0, 190.0}, crash{25.0, 0.0}, crash{25.0, 190.0}, crash{40.0, 0.0}, crash{40.0, 190.0}}) { + CAPTURE(speed); + CAPTURE(radius); + auto const result{freight_crash(speed, radius)}; + MESSAGE(std::format("{:.0f} km/h, R {:.0f}: {} derailed ({} overrode, {} pushed off), {} ends crushed (deepest {:.2f} m), {} couplings broken: {}", speed, radius, result.derailed, + result.overridden, result.pushed, result.crushed, result.crush, result.broken, result.list)); + if (speed <= 10.0) { + // the buffers take it + CHECK(result.derailed == 0); + CHECK(result.crushed == 0); + } + } +} + +TEST_CASE("collisions: identical units built to EN 15227 at 36 km/h") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + // two coaches of data/wagon.json (42.2 t) a unit, their ends crash zones with anticlimbers, unbraked + auto const unit = [](bool const Anticlimbers, double const Height) { + return definition::load("wagon").set("BuffCoupl", "CrashZone", "Yes").set("BuffCoupl", "AntiClimber", Anticlimbers ? "Yes" : "No").set("BuffCoupl", "BufferHeight", Height); + }; + auto const crash = [&](bool const Anticlimbers, double const Speed, double const Offset) { + consist train; + train.add(unit(Anticlimbers, 1.040)); + train.add(unit(Anticlimbers, 1.040)); + train.add(unit(Anticlimbers, 1.040 + Offset), 0, coupling::faux, Speed, 1.0); + train.add(unit(Anticlimbers, 1.040 + Offset), 0, consist::full_coupling, Speed); + train.run(6.0); + struct { + double crush; + double inner; + int derailed; + bool higher; + } result{train[1]->Couplers[end::rear].crush + train[2]->Couplers[end::front].crush, std::max(crush_of(train[0].mover()), crush_of(train[3].mover())), 0, + derailed(train[2].mover())}; + for (std::size_t i = 0; i < train.size(); ++i) { + result.derailed += derailed(train[i].mover()); + } + return result; + }; + SUBCASE("scenario 1: the crush stays in the zones, nothing climbs") { + auto const result{crash(true, 36.0, 0.04)}; + MESSAGE("36 km/h, 40 mm offset: crush ", result.crush, " m, the far ends ", result.inner, " m"); + CHECK(result.crush > 0.2); + CHECK(result.crush < 2.0 * 0.8); + CHECK(result.derailed == 0); + } + SUBCASE("the same units without the anticlimbers override") { + auto const result{crash(false, 36.0, 0.0)}; + CHECK(result.derailed >= 2); + } + SUBCASE("slower, without the anticlimbers, the higher one climbs") { + auto const result{crash(false, 32.0, 0.04)}; + MESSAGE("32 km/h, 40 mm offset: crush ", result.crush, " m"); + CHECK(result.crush > cl::override_crush); + CHECK(result.crush < cl::override_both); + CHECK(result.higher); + CHECK(result.derailed == 1); + auto const held{crash(true, 32.0, 0.04)}; + CHECK(held.derailed == 0); + } +} + +// ---- the energy of the hit: what the buffers of EN 15551 take in never crushes (found running every scenario of the +// install: calkowo_v2_kontenera, baltyk_sdm) + +TEST_CASE("collisions: the buffers of EN 15551 of an end take in their energy, of the category given or by the kind") { + CHECK(cl::buffer_capacity({}, cl::vehicle_kind::wagon) == doctest::Approx(60.0e3)); + CHECK(cl::buffer_capacity({}, cl::vehicle_kind::locomotive) == doctest::Approx(60.0e3)); + CHECK(cl::buffer_capacity({}, cl::vehicle_kind::coach) == doctest::Approx(60.0e3)); + CHECK(cl::default_buffers(cl::vehicle_kind::coach) == cl::buffer_category::passenger); + cl::end_definition category_c; + category_c.buffers = cl::buffer_category::C; + CHECK(cl::buffer_capacity(category_c, cl::vehicle_kind::wagon) == doctest::Approx(140.0e3)); + // the key of the .fiz + vehicle wagon{definition::load("wagon").set("BuffCoupl", "BufferCategory", "B")}; + REQUIRE(wagon->Couplers[end::front].collision.buffers.has_value()); + CHECK(*wagon->Couplers[end::front].collision.buffers == cl::buffer_category::B); + CHECK(cl::buffer_capacity(wagon->Couplers[end::rear].collision, wagon->collision_kind()) == doctest::Approx(100.0e3)); +} + +TEST_CASE("collisions: the budget of a contact, by what the hit brings to the buffers") { + cl::contact_energy contact; + // not touching: nothing + contact.update(false, false, 1.0, 0.0, 0.0, 0.01); + CHECK(contact.absorbed() == 0.0); + // pressed in, closing: the springs take in their work + contact.update(true, false, 1.0, 1.0e6, 0.05, 0.01); + CHECK(contact.absorbed() == doctest::Approx(10.0e3)); + // pressed all the way, they take in nothing more + contact.update(true, true, 1.0, 1.4e6, 0.3, 0.01); + CHECK(contact.absorbed() == doctest::Approx(10.0e3)); + // the kinetic energy and what the buffers took, past their capacity + CHECK(contact.budget(40.0e3, 2.0, 60.0e3) == doctest::Approx(0.5 * 40.0e3 * 4.0 + 10.0e3 - 60.0e3)); + // the springs of the .fiz taking in more than the buffers of EN 15551: no more than the kinetic energy + CHECK(contact.budget(40.0e3, 2.0, 5.0e3) == doctest::Approx(0.5 * 40.0e3 * 4.0)); + // springing back they hold no more than their springs pressed in + contact.update(true, false, -0.5, 0.2e6, 0.02, 0.01); + CHECK(contact.absorbed() == doctest::Approx(0.5 * 0.2e6 * 0.02)); + // a train pushing at a stand: the oscillation of the pair never builds the energy up + for (int i = 0; i < 6000; ++i) { + auto const closing{0.05 * std::sin(i * 0.3)}; + contact.update(true, false, closing, 0.3e6 + 1.0e6 * closing, 0.03, 0.01); + } + CHECK(contact.absorbed() < 0.5 * 0.35e6 * 0.03 + 0.35e6 * 0.05 * 0.01 * 12.0); + // parted: a new contact + contact.crushed(5.0e3); + CHECK(contact.crush_work() == doctest::Approx(5.0e3)); + contact.update(false, false, 0.0, 0.0, 0.0, 0.01); + CHECK(contact.absorbed() == 0.0); + CHECK(contact.crush_work() == 0.0); +} + +TEST_CASE("collisions: the crush of a hit takes no more than its energy past the buffers, with any step") { + // two masses at the stop of their buffers from the start (nothing taken in by the springs), the budget of the + // crush taken anew in every step of the hit, as the vehicles take it + struct masses { + double mass1; + double mass2; + }; + constexpr double capacity{120.0e3}; + constexpr double springs{1.2e6}; + for (auto const &[mass1, mass2] : {masses{80.0e3, 80.0e3}, masses{117.0e3, 84.0e3}, masses{300.0e3, 20.0e3}, masses{36.0e3, 41.6e3}}) { + auto const reduced{mass1 * mass2 / (mass1 + mass2)}; + for (auto const speed : {2.0, 5.0, 8.0, 12.0, 20.0, 30.0, 45.0, 60.0}) { + for (auto const dt : {0.001, 0.003, 0.01, 0.02, 0.03}) { + CAPTURE(mass1); + CAPTURE(mass2); + CAPTURE(speed); + CAPTURE(dt); + cl::end_state first{locomotive_curve, 0.0}; + cl::end_state second{wagon_curve, 0.0}; + auto velocity1{speed * kmh}; + auto velocity2{0.0}; + auto work{0.0}; + for (int step = 0; step < 100000; ++step) { + auto const start{velocity1 - velocity2}; + velocity1 -= springs * dt / mass1; + velocity2 += springs * dt / mass2; + auto const closing{velocity1 - velocity2}; + if (closing <= 0.0) { + break; + } + cl::hit_input input; + input.velocity = closing; + input.start_velocity = start; + input.mass1 = mass1; + input.mass2 = mass2; + input.stiffness = 1.4e8; + input.springs = springs; + input.dt = dt; + input.budget = 0.5 * reduced * start * start - capacity; + auto const hit{cl::hit(first, second, input)}; + if (false == hit.crushing) { + break; + } + CHECK(hit.work <= input.budget * (1.0 + 1e-9) + 1e-6); + work += hit.work; + first.crush += hit.crush1; + second.crush += hit.crush2; + velocity1 -= hit.impulse / mass1; + velocity2 += hit.impulse / mass2; + if (hit.velocity <= 0.0) { + break; + } + } + auto const available{std::max(0.0, 0.5 * reduced * (speed * kmh) * (speed * kmh) - capacity)}; + auto const crushed{locomotive_curve.energy(0.0, first.crush) + wagon_curve.energy(0.0, second.crush)}; + CHECK(work <= available + 1.0); + CHECK(crushed <= available * 1.001 + 1.0); + if (available <= 0.0) { + CHECK(first.crush + second.crush == 0.0); + } + } + } + } +} + +TEST_CASE("collisions: the crush of two vehicles takes no more than the energy of the hit past the buffers, with any step") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + struct pair_of { + char const *name; + definition front; + definition back; + }; + for (auto const &[name, front, back] : {pair_of{"EU07 into EU07", definition::fiz("4e_v1/4e"), definition::fiz("4e_v1/4e")}, + pair_of{"SU45 into SM42", definition::fiz("sm42_v1/6d1"), definition::fiz("su45_v2/301d")}, + pair_of{"EU07 into a wagon", definition::fiz("430w_v2/430w"), definition::fiz("4e_v1/4e")}}) { + for (auto const speed : {2.0, 5.0, 10.0, 15.0, 20.0, 30.0, 45.0, 60.0}) { + for (auto const dt : {0.001, 0.01, 0.03}) { + CAPTURE(name); + CAPTURE(speed); + CAPTURE(dt); + auto const result{contact(front, back, speed, 0.5, 4.0, dt)}; + // the explicit steps of the springs before the stop rate what they took in a little off. at 0.03 s, 0.5 m a + // step at 60 km/h, the legacy movement of the vehicles past the stop gives the hit energy of its own (the + // crush goes past what it is at 0.01 s and 0.001 s): the budget doesn't bind there, every step of the hit + // is within it (the test of the hit of two masses above), the same crush as before the budget + CHECK(result.energy <= result.available * (dt > 0.02 ? 1.15 : 1.05) + 5.0e3); + if (result.available <= 0.0) { + CHECK(result.crush == 0.0); + } + } + } + } +} + +TEST_CASE("collisions: two locomotives (117 t and 84 t) touching at walking speed don't crush (calkowo_v2_kontenera)") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + auto const su45{definition::fiz("su45_v2/301d")}; + auto const sm42{definition::fiz("sm42_v1/6d1")}; + { + vehicle check{su45}; + CHECK(check->TotalMass == doctest::Approx(117.0e3).epsilon(0.02)); + } + for (auto const physics : {false, true}) { + CAPTURE(physics); + flag_setting const couplerphysics{Global.coupler_physics, physics}; + flag_setting const everywhere{Global.coupler_physics_all, physics}; + for (auto const speed : {5.0, 5.8, 6.0}) { + CAPTURE(speed); + // a hit from a metre away + { + auto const result{contact(sm42, su45, speed, 1.0)}; + CHECK(result.crush == 0.0); + CHECK_FALSE(result.derailed); + } + // put down by the scenery with the buffers pressed in, up to past their stop, closing in: the log of the run + // had 5.8 km/h at the stop, both ends crushed, deeper hit after hit until both overrode + for (auto const overlap : {0.1, 0.4, 1.0}) { + CAPTURE(overlap); + auto const result{contact(sm42, su45, speed, -overlap, 10.0)}; + CHECK(result.crush == 0.0); + CHECK_FALSE(result.derailed); + } + } + } +} + +TEST_CASE("collisions: locomotives put down inside each other don't crush, whatever their springs make of them") { + // calkowo_v2_kontenera puts an SM42 on an SU45 with their middles 2.7 m apart: the springs at the stops of both + // ends and the neighbours found at either end shook them up to 9-13 km/h, past the energy of the buffers + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const speed : {0.0, 10.0, 15.0}) { + CAPTURE(speed); + auto const result{contact(definition::fiz("sm42_v1/6d1"), definition::fiz("su45_v2/301d"), speed, -3.0, 10.0)}; + CHECK(result.crush == 0.0); + CHECK_FALSE(result.derailed); + } + // a hit from a distance at the same speeds crushes past the energy of the buffers + CHECK(contact(definition::fiz("sm42_v1/6d1"), definition::fiz("su45_v2/301d"), 20.0, 0.5).crush > 0.0); +} + +TEST_CASE("collisions: two coaches (36 t and 41.6 t) at 8 km/h don't crush, nor run into a wall (baltyk_sdm)") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + auto const light{coach(34.3e3)}; + auto const heavy{coach(39.9e3)}; + { + vehicle check{light}; + CHECK(check->TotalMass == doctest::Approx(36.0e3).epsilon(0.01)); + CHECK(vehicle{heavy}->TotalMass == doctest::Approx(41.6e3).epsilon(0.01)); + } + for (auto const speed : {5.0, 8.0}) { + CAPTURE(speed); + // a hit from a metre away, and one with the buffers pressed all the way already, as the coach knocked onto the + // other one by the hit of the train on the vehicle derailed at the end of the track + for (auto const gap : {1.0, -0.25}) { + CAPTURE(gap); + auto const result{contact(light, heavy, speed, gap)}; + CHECK(result.crush == 0.0); + CHECK_FALSE(result.derailed); + } + } + // the vehicle derailed the legacy way is a wall that the coach runs into + for (auto const gap : {1.0, -0.25}) { + CAPTURE(gap); + consist train; + auto &wall{train.add(light)}; + wall->Derail(END_OF_TRACK); + REQUIRE(derailed(wall.mover())); + auto &running{train.add(heavy, 0, coupling::faux, 5.0, gap)}; + train.run(5.0); + CHECK(wall->Couplers[end::rear].crush + running->Couplers[end::front].crush == 0.0); + CHECK(running->CollisionDerail == NONE); + } +} + +TEST_CASE("collisions: a locomotive pushing a standing braked train at full power doesn't crush") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + test::track const line{0.15, 0.0, test::catenary_3kv}; + // the diesel-electric keeps its full power at a stand (an electric one trips its overload relays there) + for (auto const *path : {"su45_v2/301d"}) { + CAPTURE(path); + consist train; + // four loaded coal wagons, braked in emergency once their brakes are charged + constexpr int wagons{4}; + for (int i = 0; i < wagons; ++i) { + add_mixed(train, 0, consist::full_coupling, 0.0, 0.0).hold_brake_pipe(5.0); + } + train.run(90.0, line); + for (int i = 0; i < wagons; ++i) { + train[i].hold_brake_pipe(0.0); + } + train.run(30.0, line); + // the locomotive behind them, touching, driven forwards into them at full power + auto &locomotive{train.add(definition::fiz(path), 1, coupling::faux, 0.0, 0.0)}; + test::driven const driver{locomotive.mover(), locomotive.mover(), locomotive.mover(), [&train](double const Seconds, test::track const &Track) { train.run(Seconds, Track); }}; + REQUIRE(test::start_up(driver, line)); + test::release_brakes(locomotive.mover()); + for (int i = 0; i < 3 && locomotive->DirActive <= 0; ++i) { + locomotive->DirectionForward(); + } + test::drive(driver, line, 10.0); + auto pushed{0.0}; + auto seconds{0}; // pushing with 100 kN or more + auto const push = [&]() { + auto const force{std::max(0.0, -locomotive->Couplers[end::front].CForce)}; + pushed = std::max(pushed, force); + seconds += force >= 100.0e3; + }; + // the line contactors close at the first position, once their delay and the pressure switch let them + locomotive->IncMainCtrl(1); + for (int i = 0; i < 90 && false == locomotive->StLinFlag; ++i) { + test::drive(driver, line, 1.0); + } + for (int i = 0; i < 60 && false == locomotive->IsMainCtrlMaxPowerPos(); ++i) { + locomotive->IncMainCtrl(1); + test::drive(driver, line, 1.0); + push(); + } + for (int i = 0; i < 60; ++i) { + test::drive(driver, line, 1.0); + push(); + } + MESSAGE(std::format("{}: pushing at up to {:.0f} kN, {} s at 100 kN or more, at {:.1f} km/h at the end", path, pushed / 1000.0, seconds, locomotive.speed())); + CHECK(pushed > 200.0e3); + CHECK(seconds >= 55); + for (std::size_t i = 0; i < train.size(); ++i) { + CAPTURE(i); + CHECK(crush_of(train[i].mover()) == 0.0); + CHECK_FALSE(derailed(train[i].mover())); + } + } +} + +TEST_CASE("collisions: vehicles put down with their buffers pressed in don't crush") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const physics : {false, true}) { + CAPTURE(physics); + flag_setting const couplerphysics{Global.coupler_physics, physics}; + flag_setting const everywhere{Global.coupler_physics_all, physics}; + for (auto const overlap : {0.1, 0.3, 0.6}) { + CAPTURE(overlap); + for (auto const &[front, back] : {std::pair{definition::fiz("sm42_v1/6d1"), definition::fiz("su45_v2/301d")}, std::pair{coach(34.3e3), coach(39.9e3)}, + std::pair{definition::fiz("3wl_v2/3wl"), definition::fiz("4e_v1/4e")}}) { + auto const result{contact(front, back, 0.0, -overlap, 10.0)}; + CHECK(result.crush == 0.0); + CHECK_FALSE(result.derailed); + } + } + } +} + +TEST_CASE("collisions: the monitor goes by the energy of the hit as well") { + flag_setting const crashdamage{Global.crash_damage, true}; + model_setting const monitor{global_settings::collision_model::monitor}; + // a hit the buffers take in: the monitor tells of nothing + for (auto const gap : {1.0, -0.4}) { + CAPTURE(gap); + consist train; + train.add(definition::fiz("sm42_v1/6d1")); + train.add(definition::fiz("su45_v2/301d"), 0, coupling::faux, 5.8, gap); + train.run(5.0); + CHECK(train[0]->crush_reports + train[1]->crush_reports == 0); + } + // one past them it does + consist train; + train.add(definition::fiz("4e_v1/4e")); + train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, 25.0, 20.0); + train.run(10.0); + CHECK(train[0]->crush_reports + train[1]->crush_reports == 1); +} + +// ---- the legacy derailment (physics.derailment old or monitor) in a train, with physics.collisions new + +namespace { + +// what the vehicles of the train did to each other +struct train_damage { + double crush{0.0}; // the deepest crush of an end [m] + double energy{0.0}; // the crush of all the ends took [J] + int derailed{0}; // in a collision + int broken{0}; // couplings torn off + std::string list; // which vehicle, for the messages +}; + +train_damage damage_of(consist &Train) { + train_damage result; + for (std::size_t i = 0; i < Train.size(); ++i) { + auto const &vehicle{Train[i].mover()}; + result.crush = std::max(result.crush, crush_of(vehicle)); + for (auto const end : {end::front, end::rear}) { + result.energy += vehicle.crush_curve_at(end).energy(0.0, vehicle.Couplers[end].crush); + } + result.derailed += vehicle.CollisionDerail != NONE; + if (i + 1 < Train.size()) { + result.broken += vehicle.Couplers[end::rear].broken; + } + if (crush_of(vehicle) > 0.0 || vehicle.CollisionDerail != NONE) { + result.list += std::format("{} crushed {:.2f} m{}; ", i, crush_of(vehicle), vehicle.CollisionDerail != NONE ? ", derailed" : ""); + } + } + return result; +} + +// the kinetic energy of the vehicles of the train [J] +double kinetic_of(consist &Train) { + auto energy{0.0}; + for (std::size_t i = 0; i < Train.size(); ++i) { + energy += 0.5 * Train[i]->TotalMass * Train[i]->V * Train[i]->V; + } + return energy; +} + +} // namespace + +TEST_CASE("collisions: the cut of the speed of the legacy derailment is no hit inside the train (moczniki_eu06_eu07, tomaszewo_raj49843)") { + // the legacy derailment takes 35 % of the speed of the vehicle off in a step: the coaches coupled behind it, at the + // speed they had, ran into it at a third of the speed of the train, crushed their ends and rode up onto it + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const physics : {false, true}) { + CAPTURE(physics); + flag_setting const couplerphysics{Global.coupler_physics, physics}; + flag_setting const everywhere{Global.coupler_physics_all, physics}; + // an SU46 with its coaches at 95 km/h, as in moczniki_eu06_eu07; an electric locomotive at 48 km/h, as in + // tomaszewo_raj49843 + for (auto const &[path, speed] : {std::pair{"su46_v2/303d", 95.0}, std::pair{"4e_v1/4e", 48.0}}) { + CAPTURE(path); + // too fast in a curve, the draw in the movement of the vehicle; off the end of the track, in its next step + for (auto const reason : {TOO_HIGH_SPEED, END_OF_TRACK}) { + CAPTURE(reason); + consist train; + auto &locomotive{train.add(definition::fiz(path), 0, coupling::faux, speed)}; + for (int i = 0; i < 3; ++i) { + train.add(coach(41.0e3), 0, consist::full_coupling, speed); + } + train.run(2.0); + if (reason == END_OF_TRACK) { + locomotive.damage_track(dtrack_norail); + } + else { + locomotive->Derail(reason); + } + train.step(); + REQUIRE(derailed(locomotive.mover())); + // the train loses the speed with it + for (std::size_t i = 1; i < train.size(); ++i) { + CAPTURE(i); + CHECK(train[i].speed() == doctest::Approx(locomotive.speed()).epsilon(0.03)); + } + train.run(15.0); + auto const damage{damage_of(train)}; + INFO(damage.list); + CHECK(damage.crush < cl::crush_mark); + CHECK(damage.derailed == 0); + CHECK(damage.broken == 0); + } + } + } +} + +TEST_CASE("collisions: the train behind a vehicle that ran off the end of the track doesn't crush into it (l053-sluzba-2-night, l053_calkowo-sluzba-tlk-1, linia61_osobowy3)") { + // the vehicle derailed the legacy way at the end of the track stopped as a wall the train behind it ran into: the + // vehicles behind it pressed into each other past their stops, and crushed by more than the energy of the train + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const physics : {false, true}) { + CAPTURE(physics); + flag_setting const couplerphysics{Global.coupler_physics, physics}; + flag_setting const everywhere{Global.coupler_physics_all, physics}; + // pulled: an M62 leading wagons of 22 t at 30 km/h (l053_calkowo-sluzba-tlk-1, linia61_osobowy3); pushed: an SM42 + // at the back of wagons of 35 t at 33 km/h, the leading wagon goes off (l053-sluzba-2-night) + for (auto const pushed : {false, true}) { + CAPTURE(pushed); + auto const speed{pushed ? 33.0 : 30.0}; + consist train; + if (false == pushed) { + train.add(definition::fiz("st44_v2/m62-1151"), 0, coupling::faux, speed); + } + constexpr int wagons{6}; + for (int i = 0; i < wagons; ++i) { + auto &wagon{train.add(definition::fiz("430w_v2/430w"), 0, consist::full_coupling, speed)}; + if (pushed) { + wagon->AssignLoad("coal", 12.0f); + wagon->ComputeMass(); + } + } + if (pushed) { + train.add(definition::fiz("sm42_v1/6d1"), 0, consist::full_coupling, speed); + } + train.run(2.0); + auto const kinetic{kinetic_of(train)}; + train[0].damage_track(dtrack_norail); + train.run(20.0); + REQUIRE(derailed(train[0].mover())); + auto const damage{damage_of(train)}; + INFO(damage.list); + MESSAGE(std::format("{}: crush {:.3f} m, {:.0f} kJ of the {:.0f} kJ of the train", pushed ? "pushed" : "pulled", damage.crush, damage.energy / 1000.0, kinetic / 1000.0)); + CHECK(damage.crush < cl::crush_mark); + CHECK(damage.energy <= kinetic); + CHECK(damage.derailed == 0); + CHECK(damage.broken == 0); + for (std::size_t i = 1; i < train.size(); ++i) { + CAPTURE(i); + CHECK_FALSE(derailed(train[i].mover())); + } + } + } +} + +TEST_CASE("collisions: the buffers of vehicles found inside each other take in nothing for the budget of the crush") { + cl::contact_energy contact; + // pressed in at 2 m/s under 1 MN for 0.1 s: 200 kJ, past the 120 kJ the buffers of both ends take + contact.update(true, false, 2.0, 1.0e6, 0.1, 0.1); + REQUIRE(contact.absorbed() == doctest::Approx(200.0e3)); + CHECK(contact.budget(11.0e3, 1.7, 120.0e3) > 0.0); + // found inside each other: what their springs made of it is no hit (l053_calkowo-sluzba-tlk-1: 163 kJ "in the + // buffers" let a pair crush with 15 kJ of motion) + contact.inside(); + CHECK(contact.absorbed() == 0.0); + contact.update(true, false, 2.0, 1.0e6, 0.1, 0.1); + CHECK(contact.absorbed() == 0.0); + CHECK(contact.budget(11.0e3, 1.7, 120.0e3) < 0.0); + // the buffers apart, the next contact is a hit again + contact.update(false, false, 0.0, 0.0, 0.0, 0.01); + contact.update(true, false, 2.0, 1.0e6, 0.1, 0.1); + CHECK(contact.absorbed() == doctest::Approx(200.0e3)); +} + +TEST_CASE("collisions: a pair parting at the start of the step isn't crushed (l053_calkowo-sluzba-tlk-1, linia61_osobowy3)") { + // the log had "closing at -7.1 km/h at the start of the step" on a crush of a pair knocked back onto each other in + // the step: the legacy collision takes such a knock, a pair still closing in at the start of a step is a hit + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const parting : {true, false}) { + CAPTURE(parting); + consist train; + auto &front{train.add(definition::fiz("430w_v2/430w"))}; + // behind it with the buffers pressed to their stop, moving back away from it, or standing + auto &back{train.add(definition::fiz("430w_v2/430w"), 0, coupling::faux, parting ? -3.0 : 0.0, -0.3)}; + // one step, the way the consist steps it, with the vehicle behind knocked forwards onto the front one between + // the forces and the movement, as a hit of another vehicle in the step does + constexpr double dt{0.01}; + for (auto *vehicle : {&front, &back}) { + vehicle->begin_step(); + } + for (auto *vehicle : {&front, &back}) { + vehicle->forces(dt); + } + REQUIRE((front->Couplers[end::rear].closing < 0.0) == parting); + back->V = 25.0 * kmh; + for (auto *vehicle : {&front, &back}) { + vehicle->move({}, dt, (*vehicle)->Loc, 5.0); + } + auto const crush{front->Couplers[end::rear].crush + back->Couplers[end::front].crush}; + if (parting) { + CHECK(crush == 0.0); + // the legacy collision pushed them apart + CHECK(back->V < 25.0 * kmh); + } + else { + // closing in from a stand, the knock is a hit past the energy of the buffers + CHECK(crush > 0.0); + } + } +} diff --git a/tests/unit/test_compartment_lights.cpp b/tests/unit/test_compartment_lights.cpp new file mode 100644 index 000000000..bff60e440 --- /dev/null +++ b/tests/unit/test_compartment_lights.cpp @@ -0,0 +1,80 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +using test::definition; +using test::vehicle; + +// the compartment lights lamp of the cab (i-compartmentlights:) shows CompartmentLights.is_active of the cab's own +// vehicle, which LightsCheck() works out from the low voltage power and the compartment lights switch (eu07/maszyna#456) +// NOTE: the checks call LightsCheck() the way the vehicle update does, after setting the power by hand + +namespace { + +void lights_check(vehicle &Car) { + Car->LightsCheck(0.01); +} + +} // namespace + +TEST_CASE("compartment lights: the lights need low voltage power and the switch") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + REQUIRE(car->CompartmentLights.start_type == start_t::manual); + car->Power24vIsAvailable = false; + car->Power110vIsAvailable = false; + + car->CompartmentLightsSwitch(true, range_t::local); // switch on, no power + lights_check(car); + CHECK_FALSE(car->CompartmentLights.is_active); + + car->Power110vIsAvailable = true; // converter on + lights_check(car); + CHECK(car->CompartmentLights.is_active); + CHECK(car->CompartmentLights.intensity == doctest::Approx(1.0)); + + car->Power110vIsAvailable = false; // battery only: the lights stay on, dimmed + car->Power24vIsAvailable = true; + lights_check(car); + CHECK(car->CompartmentLights.is_active); + CHECK(car->CompartmentLights.intensity == doctest::Approx(0.5)); + + car->Power24vIsAvailable = false; // no power at all + lights_check(car); + CHECK_FALSE(car->CompartmentLights.is_active); +} + +TEST_CASE("compartment lights: the off switch turns the lights off, the on switch back on") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + car->Power110vIsAvailable = true; + + lights_check(car); + CHECK_FALSE(car->CompartmentLights.is_active); // manual start: off until switched on + + // push buttons: the on button latches the lights, they stay on once it is released + car->CompartmentLightsSwitch(true, range_t::local); + lights_check(car); + car->CompartmentLightsSwitch(false, range_t::local); + lights_check(car); + CHECK(car->CompartmentLights.is_active); + + car->CompartmentLightsSwitchOff(true, range_t::local); + lights_check(car); + CHECK_FALSE(car->CompartmentLights.is_active); + car->CompartmentLightsSwitchOff(false, range_t::local); + lights_check(car); + CHECK_FALSE(car->CompartmentLights.is_active); // still off once the off button is released +} + +TEST_CASE("compartment lights: lights started automatically come on with the power alone") { + vehicle car{definition::fiz("elf_v1/21we-a").set("Cntrl", "CompartmentLightsStart", "Automatic")}; + REQUIRE(car->CompartmentLights.start_type == start_t::automatic); + car->Power24vIsAvailable = false; + car->Power110vIsAvailable = false; + + lights_check(car); + CHECK_FALSE(car->CompartmentLights.is_active); + + car->Power110vIsAvailable = true; + lights_check(car); + CHECK(car->CompartmentLights.is_active); +} diff --git a/tests/unit/test_compartment_lights_switch.cpp b/tests/unit/test_compartment_lights_switch.cpp new file mode 100644 index 000000000..b9ba78398 --- /dev/null +++ b/tests/unit/test_compartment_lights_switch.cpp @@ -0,0 +1,227 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +#include "vehicle/compartmentlightsswitch.h" + +using test::definition; +using test::vehicle; + +// the compartment lights commands of the cab (TTrain::OnCommand_compartmentlightsenable/disable/toggle): whether the +// command for one request (on: CompartmentLights.is_enabled, off: is_disabled) also withdraws the other one. In a cab +// without compartmentlights_sw: and without the push buttons (the CD 810 cab A) the keyboard toggle, ctrl+;, turned +// the lights on and off once, then never again: the off request stayed set alongside the on one. In a cab with the +// compartmentlightson_sw: / compartmentlightsoff_sw: push buttons (the EN57-2000) the toggle sent the key release to the +// other command than the press, picked again from the state the press had changed: the pressed button never withdrew +// its request and the lights were off only while ctrl+; was held. + +TEST_CASE("compartment lights switch: which command withdraws the other request") { + // a two-state compartmentlights_sw: holds one request at a time + CHECK(compartment_lights_switch::withdraws_other_request(true, true, false)); + CHECK(compartment_lights_switch::withdraws_other_request(true, true, true)); + // a push type compartmentlights_sw: withdraws both requests itself, when it's released + CHECK_FALSE(compartment_lights_switch::withdraws_other_request(true, false, false)); + CHECK_FALSE(compartment_lights_switch::withdraws_other_request(true, false, true)); + // no compartmentlights_sw:, the push button of the other request withdraws it when it's released + CHECK_FALSE(compartment_lights_switch::withdraws_other_request(false, false, true)); + CHECK_FALSE(compartment_lights_switch::withdraws_other_request(false, true, true)); + // no compartmentlights_sw: and no push button: nothing else would withdraw it + CHECK(compartment_lights_switch::withdraws_other_request(false, false, false)); + CHECK(compartment_lights_switch::withdraws_other_request(false, true, false)); +} + +namespace { + +// the compartment lights controls a cab's .mmd may have +struct cab_controls { + bool has_switch{false}; // compartmentlights_sw: + bool switch_is_toggle{true}; // its type (a gauge is a toggle type unless declared otherwise) + bool has_on_button{false}; // compartmentlightson_sw: + bool has_off_button{false}; // compartmentlightsoff_sw: +}; + +// the effect of the cab's commands on the vehicle, as TTrain::OnCommand_compartmentlightsenable/disable/toggle do it +// NOTE: LightsCheck() runs between the press and the release, as the vehicle update does between two frames +void lights_check(vehicle &Car) { + Car->LightsCheck(0.01); +} + +void enable_press(vehicle &Car, cab_controls const &Cab) { + Car->CompartmentLightsSwitch(true, range_t::local); + if (compartment_lights_switch::withdraws_other_request(Cab.has_switch, Cab.switch_is_toggle, Cab.has_off_button)) { + Car->CompartmentLightsSwitchOff(false, range_t::local); + } +} + +void enable_release(vehicle &Car, cab_controls const &Cab) { + using enum range_t; + if (Cab.has_switch && false == Cab.switch_is_toggle) { + Car->CompartmentLightsSwitch(false, local); + Car->CompartmentLightsSwitchOff(false, local); + } + if (Cab.has_on_button) { + Car->CompartmentLightsSwitch(false, local); + } +} + +void disable_press(vehicle &Car, cab_controls const &Cab) { + Car->CompartmentLightsSwitchOff(true, range_t::local); + if (compartment_lights_switch::withdraws_other_request(Cab.has_switch, Cab.switch_is_toggle, Cab.has_on_button)) { + Car->CompartmentLightsSwitch(false, range_t::local); + } +} + +void disable_release(vehicle &Car, cab_controls const &Cab) { + using enum range_t; + if (Cab.has_switch && false == Cab.switch_is_toggle) { + Car->CompartmentLightsSwitch(false, local); + Car->CompartmentLightsSwitchOff(false, local); + } + if (Cab.has_off_button) { + Car->CompartmentLightsSwitchOff(false, local); + } +} + +// a click on the control of the command (or its own key): the press, then the release +void enable(vehicle &Car, cab_controls const &Cab) { + enable_press(Car, Cab); + lights_check(Car); + enable_release(Car, Cab); + lights_check(Car); +} + +void disable(vehicle &Car, cab_controls const &Cab) { + disable_press(Car, Cab); + lights_check(Car); + disable_release(Car, Cab); + lights_check(Car); +} + +// the keyboard toggle picks the command from the state on the press, the key held down for a few frames; the release +// goes to both commands, the press changed the state it would be picked from +void toggle(vehicle &Car, cab_controls const &Cab) { + if (auto const &lights{Car->CompartmentLights}; false == lights.is_active && false == lights.is_enabled) { + enable_press(Car, Cab); + } + else { + disable_press(Car, Cab); + } + for (auto frame = 0; frame < 3; ++frame) { + lights_check(Car); + } + enable_release(Car, Cab); + disable_release(Car, Cab); + lights_check(Car); +} + +// the Elf (21WE-a), its compartment lights started by hand, with the converter running +void power_up(vehicle &Car) { + REQUIRE(Car->CompartmentLights.start_type == start_t::manual); + Car->Power110vIsAvailable = true; + lights_check(Car); + REQUIRE_FALSE(Car->CompartmentLights.is_active); +} + +} // namespace + +TEST_CASE("compartment lights switch: the keyboard toggle works every time in a cab without the switch") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + power_up(car); + cab_controls const cab{}; // no compartmentlights_sw:, no push buttons, like the CD 810 cab A + + for (auto press = 1; press <= 6; ++press) { + CAPTURE(press); + toggle(car, cab); + // odd presses turn the lights on, even ones off + CHECK(car->CompartmentLights.is_active == (press % 2 == 1)); + // one request at a time + CHECK_FALSE((car->CompartmentLights.is_enabled && car->CompartmentLights.is_disabled)); + } +} + +TEST_CASE("compartment lights switch: the keyboard toggle in a cab with the two-state switch, as before") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + power_up(car); + cab_controls const cab{.has_switch = true, .switch_is_toggle = true}; + + for (auto press = 1; press <= 4; ++press) { + CAPTURE(press); + toggle(car, cab); + CHECK(car->CompartmentLights.is_active == (press % 2 == 1)); + // the switch holds the request of its position + CHECK(car->CompartmentLights.is_enabled == (press % 2 == 1)); + CHECK(car->CompartmentLights.is_disabled == (press % 2 == 0)); + } +} + +TEST_CASE("compartment lights switch: the push type switch withdraws both requests when released, as before") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + power_up(car); + cab_controls const cab{.has_switch = true, .switch_is_toggle = false}; + + for (auto press = 1; press <= 4; ++press) { + CAPTURE(press); + toggle(car, cab); + CHECK(car->CompartmentLights.is_active == (press % 2 == 1)); + CHECK_FALSE(car->CompartmentLights.is_enabled); + CHECK_FALSE(car->CompartmentLights.is_disabled); + } +} + +TEST_CASE("compartment lights switch: the on and off push buttons latch the lights, as before") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + power_up(car); + cab_controls const cab{.has_on_button = true, .has_off_button = true}; + + for (auto round = 1; round <= 2; ++round) { + CAPTURE(round); + // each button withdraws its own request when it's released, the lights stay as they were put + enable(car, cab); + CHECK(car->CompartmentLights.is_active); + CHECK_FALSE(car->CompartmentLights.is_enabled); + CHECK_FALSE(car->CompartmentLights.is_disabled); + disable(car, cab); + CHECK_FALSE(car->CompartmentLights.is_active); + CHECK_FALSE(car->CompartmentLights.is_enabled); + CHECK_FALSE(car->CompartmentLights.is_disabled); + } +} + +TEST_CASE("compartment lights switch: the keyboard toggle latches the lights in a cab with the on and off push buttons") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + power_up(car); + cab_controls const cab{.has_on_button = true, .has_off_button = true}; // no compartmentlights_sw:, like the EN57-2000 + + for (auto press = 1; press <= 6; ++press) { + CAPTURE(press); + toggle(car, cab); + // odd presses turn the lights on, even ones off, and they stay so after the key is released + CHECK(car->CompartmentLights.is_active == (press % 2 == 1)); + // both push buttons are back in the neutral position, neither request is left behind + CHECK_FALSE(car->CompartmentLights.is_enabled); + CHECK_FALSE(car->CompartmentLights.is_disabled); + } +} + +TEST_CASE("compartment lights switch: the keyboard toggle and the on and off push buttons work together") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + power_up(car); + cab_controls const cab{.has_on_button = true, .has_off_button = true}; + + toggle(car, cab); + REQUIRE(car->CompartmentLights.is_active); + // the off button turns off what the key turned on... + disable(car, cab); + CHECK_FALSE(car->CompartmentLights.is_active); + // ...and the key turns on what the off button turned off + toggle(car, cab); + CHECK(car->CompartmentLights.is_active); + toggle(car, cab); + CHECK_FALSE(car->CompartmentLights.is_active); + enable(car, cab); + CHECK(car->CompartmentLights.is_active); + toggle(car, cab); + CHECK_FALSE(car->CompartmentLights.is_active); + CHECK_FALSE(car->CompartmentLights.is_enabled); + CHECK_FALSE(car->CompartmentLights.is_disabled); +} diff --git a/tests/unit/test_controls.cpp b/tests/unit/test_controls.cpp index 4e5255ff4..ba9404482 100644 --- a/tests/unit/test_controls.cpp +++ b/tests/unit/test_controls.cpp @@ -4,6 +4,7 @@ #include "drive.h" #include "McZapkie/hamulce.h" +#include "utilities/Globals.h" #include "utilities/utilities.h" // characterisation of the controls a driver and a crew use besides driving and braking: doors, direction and @@ -495,6 +496,14 @@ TEST_CASE("controls: a freight wagon loaded and braked") { } TEST_CASE("controls: a locomotive running into a standing wagon") { + // the legacy collisions of physics.collisions old: derailed, the wagon is a wall (test_collisions.cpp has the new) + struct legacy { + global_settings::collision_model previous{Global.collisions}; + legacy() { Global.collisions = global_settings::collision_model::old; } + ~legacy() { Global.collisions = previous; } + legacy(legacy const &) = delete; + legacy &operator=(legacy const &) = delete; + } const model; for (auto const speed : {5.0, 15.0, 40.0}) { CAPTURE(speed); scenario scenario{std::format("controls/collision/{} kmh", static_cast(speed)), motion()}; diff --git a/tests/unit/test_couplers.cpp b/tests/unit/test_couplers.cpp index bbb1c0dd9..19421c52b 100644 --- a/tests/unit/test_couplers.cpp +++ b/tests/unit/test_couplers.cpp @@ -49,6 +49,19 @@ private: bool m_previous{Global.crash_damage}; }; +// the legacy collisions of physics.collisions old for the test, restored after it: the rule of the safe closing speed +// weighed by the ratio of the masses (the crush of the ends of the new model is in test_collisions.cpp) +class legacy_collisions { +public: + legacy_collisions() { Global.collisions = global_settings::collision_model::old; } + ~legacy_collisions() { Global.collisions = m_previous; } + legacy_collisions(legacy_collisions const &) = delete; + legacy_collisions &operator=(legacy_collisions const &) = delete; + +private: + global_settings::collision_model m_previous{Global.collisions}; +}; + } // namespace // issue #86: automatic couplers used to catch at any closing speed, so the vehicles never collided nor derailed @@ -202,6 +215,7 @@ TEST_CASE("couplers: a wagon rolling slowly into a standing one couples with it" TEST_CASE("couplers: a wagon hitting a standing one too fast doesn't couple, nor once the hit has slowed it down") { crash_damage_setting const crashdamage{true}; + legacy_collisions const legacy; auto moving{automatic_wagon(30.0, "moving")}; auto standing{automatic_wagon(0.0, "standing")}; test::pair pair{moving, end::front, standing, end::rear, 1.0}; @@ -268,6 +282,7 @@ TEST_CASE("couplers: the automatic coupling locked by a hit is unlocked once the TEST_CASE("couplers: a hit a little too fast for the couplers bounces the vehicles apart, uncoupled and on the rails") { crash_damage_setting const crashdamage{true}; + legacy_collisions const legacy; auto moving{automatic_wagon(20.0, "moving")}; auto standing{automatic_wagon(0.0, "standing")}; test::pair pair{moving, end::front, standing, end::rear, 1.0}; @@ -281,6 +296,7 @@ TEST_CASE("couplers: a hit a little too fast for the couplers bounces the vehicl TEST_CASE("couplers: a hit too fast for the couplers derails the vehicles over the limit adjusted for their mass ratio") { crash_damage_setting const crashdamage{true}; + legacy_collisions const legacy; SUBCASE("equal masses: both derail") { auto moving{automatic_wagon(30.0, "moving")}; @@ -318,6 +334,7 @@ TEST_CASE("couplers: a hit too fast for the couplers derails the vehicles over t TEST_CASE("couplers: wagons running head-on into each other couple only up to the safe closing speed") { crash_damage_setting const crashdamage{true}; + legacy_collisions const legacy; SUBCASE("7 + 7 km/h, the couplers catch") { auto first{automatic_wagon(7.0, "first")}; diff --git a/tests/unit/test_couplers_trains.cpp b/tests/unit/test_couplers_trains.cpp index 926964dbe..cbe002bb1 100644 --- a/tests/unit/test_couplers_trains.cpp +++ b/tests/unit/test_couplers_trains.cpp @@ -3,6 +3,7 @@ #include "consist.h" #include "scenario.h" +#include "utilities/Globals.h" #include "utilities/utilities.h" // characterisation of the couplers between vehicles: coupling and uncoupling by hand (Attach, DettachStatus, @@ -14,6 +15,22 @@ using test::definition; using test::scenario; using namespace test::channels; +namespace { + +// the given model of collisions for the test, restored after it +class model_setting { +public: + explicit model_setting(global_settings::collision_model Model) : m_previous{Global.collisions} { Global.collisions = Model; } + ~model_setting() { Global.collisions = m_previous; } + model_setting(model_setting const &) = delete; + model_setting &operator=(model_setting const &) = delete; + +private: + global_settings::collision_model m_previous; +}; + +} // namespace + TEST_CASE("couplers: coupled by hand, touching or apart, of the same kind or not") { consist train; auto &locomotive{train.add(definition::fiz("4e_v1/4e")).mover()}; @@ -147,7 +164,9 @@ TEST_CASE("couplers: a coupler broken, with its brake hose torn off") { TEST_CASE("couplers: collisions fast enough to derail") { // a locomotive running into a standing wagon from behind, and a wagon running backwards into a standing - // locomotive; over 15 km/h, weighed by the ratio of the masses, the vehicles derail + // locomotive; over 15 km/h, weighed by the ratio of the masses, the vehicles derail. the legacy rule of + // physics.collisions old: the new model crushes the ends (test_collisions.cpp) + model_setting const legacy{global_settings::collision_model::old}; struct collision { char const *name; char const *frontpath; diff --git a/tests/unit/test_crew.cpp b/tests/unit/test_crew.cpp new file mode 100644 index 000000000..d70cbfb4e --- /dev/null +++ b/tests/unit/test_crew.cpp @@ -0,0 +1,313 @@ +#include "stdafx.h" +#include "doctest.h" +#include "consist.h" +#include "drive.h" + +#include "McZapkie/hamulce.h" +#include "vehicle/crew.h" + +// a driver put in a vehicle or taken off it by a "Crew:" putvalues event (eu07/maszyna#510): reading the +// command, what gets done about it in each state of the vehicle, and the state a train is left in when the driver +// in charge of it is taken off. the game's side (finding the vehicle, creating and deleting the driver) is run by +// the scenario cases, tests/scenarios/cases/*crew* + +using test::consist; +using test::definition; +using test::track; +using test::vehicle; + +namespace { + +track const line{0.15, 0.0, test::catenary_3kv}; + +// the train started up by its driver, brakes released, then under power for Seconds: a notch a second up to the +// given position of the main controller +void get_under_way(consist &Train, int const Position, double const Seconds) { + auto driver{test::driving(Train)}; + REQUIRE(test::start_up(driver, line)); + test::release_brakes(driver.cab); + for (int i = 0; i < 3 && driver.cab.DirActive <= 0; ++i) { + driver.cab.DirectionForward(); + } + test::drive(driver, line, 20.0); + driver.controlling.IncMainCtrl(1); + for (int i = 0; i < 90 && false == driver.controlling.StLinFlag; ++i) { + test::drive(driver, line, 1.0); + } + for (int i = 0; i < 60 && driver.controlling.MainCtrlPos < Position; ++i) { + driver.controlling.IncMainCtrl(1); + test::drive(driver, line, 1.0); + } + test::drive(driver, line, Seconds); +} + +// seconds until the train stands, up to Limit. nobody attends to it: the driver is gone +double seconds_to_stop(consist &Train, double const Limit) { + auto seconds{0.0}; + while (seconds < Limit && std::abs(Train[0].speed()) > 0.01) { + Train.run(1.0, line); + seconds += 1.0; + } + return seconds; +} + +crew::vehicle_state const empty_locomotive{.has_cab = true}; +crew::vehicle_state const ai_driven{.has_cab = true, .has_driver = true, .driver_is_ai = true}; + +} // namespace + +TEST_CASE("crew: the command is told by its prefix, in this case only") { + CHECK(crew::is_command("Crew:EP07-424")); + CHECK(crew::is_command("Crew:")); + CHECK_FALSE(crew::is_command("crew:ep07-424")); + CHECK_FALSE(crew::is_command("CREW:EP07-424")); + CHECK_FALSE(crew::is_command("Crew")); + CHECK_FALSE(crew::is_command("Timetable:Crew:1")); + CHECK_FALSE(crew::is_command("SetVelocity")); + CHECK_FALSE(crew::is_command("")); +} + +TEST_CASE("crew: the vehicle is named in the text, as the scenery keeps its names") { + // the examples of the issue: Shift+4 a crew in cab A, Shift+5 in cab B, Shift+6 the crew off + auto const front{crew::parse("Crew:EP07-424", 1.0, 0.0)}; + CHECK(front.vehicle == "ep07-424"); + CHECK(front.cab_valid); + CHECK(front.cab == 1); + CHECK(front.flags == 0); + + auto const rear{crew::parse("Crew:EP07-424", -1.0, 0.0)}; + CHECK(rear.cab_valid); + CHECK(rear.cab == -1); + + auto const off{crew::parse("Crew:EP07-424", 0.0, 0.0)}; + CHECK(off.cab_valid); + CHECK(off.cab == 0); + + SUBCASE("only the ASCII letters are folded, as the scenery parser folds them") { + // "Ś" of windows-1250 (0x8C) and the two bytes of "Ł" in UTF-8 stay as they are + std::string const name{"SM42-\x8C\xC5\x81" "A"}; + CHECK(crew::parse("Crew:" + name, 1.0, 0.0).vehicle == "sm42-\x8C\xC5\x81" "a"); + } + SUBCASE("no name: the vehicle which set the event off") { + auto const activator{crew::parse("Crew:", 1.0, 0.0)}; + CHECK(activator.vehicle.empty()); + CHECK(activator.cab_valid); + } + SUBCASE("a name with a colon in it is kept whole") { + CHECK(crew::parse("Crew:a:b", 1.0, 0.0).vehicle == "a:b"); + } + SUBCASE("the second value is kept for later, nothing reads it yet") { + CHECK(crew::parse("Crew:x", 0.0, 1.0).flags == 1); + CHECK(crew::parse("Crew:x", 0.0, 3.0).flags == 3); + } +} + +TEST_CASE("crew: a cab other than 1, -1 or 0 is not guessed at") { + for (auto const cab : {2.0, -2.0, 0.5, -0.5, 1.5, 100.0}) { + CAPTURE(cab); + auto const request{crew::parse("Crew:ep07-424", cab, 0.0)}; + CHECK_FALSE(request.cab_valid); + CHECK(crew::decide(request, empty_locomotive) == crew::action::refuse_cab); + CHECK(crew::decide(request, ai_driven) == crew::action::refuse_cab); + } +} + +TEST_CASE("crew: text which is not the command asks for nothing") { + auto const request{crew::parse("SetVelocity", 1.0, 0.0)}; + CHECK(request.vehicle.empty()); + CHECK_FALSE(request.cab_valid); + CHECK_FALSE(crew::changes_crew(crew::decide(request, empty_locomotive))); +} + +TEST_CASE("crew: a vehicle without a driver gets an AI one in the cab asked for") { + CHECK(crew::decide(crew::parse("Crew:x", 1.0, 0.0), empty_locomotive) == crew::action::add_front); + CHECK(crew::decide(crew::parse("Crew:x", -1.0, 0.0), empty_locomotive) == crew::action::add_rear); +} + +TEST_CASE("crew: no second driver in a vehicle, and none in a vehicle without a cab") { + CHECK(crew::decide(crew::parse("Crew:x", 1.0, 0.0), ai_driven) == crew::action::refuse_crewed); + CHECK(crew::decide(crew::parse("Crew:x", -1.0, 0.0), ai_driven) == crew::action::refuse_crewed); + // a wagon, or a car of a unit without a cab + CHECK(crew::decide(crew::parse("Crew:x", 1.0, 0.0), crew::vehicle_state{}) == crew::action::refuse_no_cab); +} + +TEST_CASE("crew: no second driver in charge of a consist") { + auto const second{crew::vehicle_state{.has_cab = true, .consist_driven = true}}; + CHECK(crew::decide(crew::parse("Crew:x", 1.0, 0.0), second) == crew::action::refuse_consist_driven); + CHECK(crew::decide(crew::parse("Crew:x", -1.0, 0.0), second) == crew::action::refuse_consist_driven); +} + +TEST_CASE("crew: the AI driver is taken off, in charge of the consist or not") { + CHECK(crew::decide(crew::parse("Crew:x", 0.0, 0.0), ai_driven) == crew::action::remove); + auto helper{ai_driven}; + helper.consist_driven = true; + CHECK(crew::decide(crew::parse("Crew:x", 0.0, 0.0), helper) == crew::action::remove); + // AI drivers ride vehicles without a cab of their own too (a car of a unit set as driven in the scenery) + auto const nocab{crew::vehicle_state{.has_driver = true, .driver_is_ai = true}}; + CHECK(crew::decide(crew::parse("Crew:x", 0.0, 0.0), nocab) == crew::action::remove); +} + +TEST_CASE("crew: taking the driver off a vehicle which has none does nothing") { + auto const decision{crew::decide(crew::parse("Crew:x", 0.0, 0.0), empty_locomotive)}; + CHECK(decision == crew::action::nothing); + CHECK_FALSE(crew::changes_crew(decision)); +} + +TEST_CASE("crew: a vehicle with a user in it is left alone") { + // the user drives; the user sits in the cab while the autopilot drives; the user sits in a vehicle whose + // controller is the AI's (a cab of the game bound to the vehicle is what counts) + auto const driving{crew::vehicle_state{.has_cab = true, .has_driver = true, .driver_is_ai = false, .occupied = true}}; + auto const autopilot{crew::vehicle_state{.has_cab = true, .has_driver = true, .driver_is_ai = true, .occupied = true}}; + auto const human{crew::vehicle_state{.has_cab = true, .has_driver = true, .driver_is_ai = false}}; + for (auto const &state : {driving, autopilot, human}) { + for (auto const cab : {1.0, -1.0, 0.0}) { + CAPTURE(cab); + auto const decision{crew::decide(crew::parse("Crew:x", cab, 0.0), state)}; + CHECK(decision == crew::action::refuse_user); + CHECK_FALSE(crew::changes_crew(decision)); + } + } +} + +TEST_CASE("crew: only adding and removing change the crew, and every outcome has its words for the log") { + using enum crew::action; + for (auto const action : {add_front, add_rear, remove}) { + CHECK(crew::changes_crew(action)); + CHECK_FALSE(crew::describe(action).empty()); + } + for (auto const action : {nothing, refuse_cab, refuse_user, refuse_crewed, refuse_no_cab, refuse_consist_driven}) { + CHECK_FALSE(crew::changes_crew(action)); + CHECK_FALSE(crew::describe(action).empty()); + } + // the scenario cases look for these in the log + CHECK(crew::describe(add_front) == "an AI driver takes cab A"); + CHECK(crew::describe(add_rear) == "an AI driver takes cab B"); + CHECK(crew::describe(remove) == "the AI driver leaves"); + CHECK(crew::describe(refuse_user).starts_with("refused")); +} + +TEST_CASE("crew: a locomotive under power left by its driver stops and stays braked") { + test::reseed_random(); + consist train; + train.add(definition::fiz("4e_v1/4e"), 1); + get_under_way(train, 20, 30.0); + auto &eu07{train[0].mover()}; + REQUIRE(train[0].speed() > 20.0); + REQUIRE(eu07.MainCtrlPos > 0); + REQUIRE(eu07.Mains); + + crew::secure(eu07, eu07); + + CHECK(eu07.MainCtrlPos == eu07.MainCtrlNoPowerPos()); + CHECK(eu07.ScndCtrlPos == 0); + CHECK(eu07.BrakeCtrlPos == static_cast(eu07.Handle->GetPos(bh_EB))); + CHECK(eu07.CabActive == 0); + CHECK(eu07.CabOccupied == 0); + CHECK_FALSE(eu07.CabMaster); + + auto const stoppedafter{seconds_to_stop(train, 120.0)}; + CAPTURE(stoppedafter); + CHECK(std::abs(train[0].speed()) <= 0.01); + CHECK(eu07.PipePress < 1.0); // vented by the emergency position + CHECK(eu07.BrakePress > 2.0); + // it keeps standing, also on a slope, with the engine as the driver left it + train.run(120.0, track{0.15, 0.02, test::catenary_3kv}); + CHECK(std::abs(train[0].speed()) <= 0.01); + CHECK(eu07.Mains); + CHECK(eu07.Im == doctest::Approx(0.0)); +} + +TEST_CASE("crew: what the AI held is let go when the driver leaves") { + test::reseed_random(); + vehicle cab{definition::load("cab_vehicle")}; + cab->DirActive = 1; + cab->WarningSignal = 1; + cab->signal_departure(true); + cab->Sandbox(true); + REQUIRE(cab->DepartureSignal); + REQUIRE(cab->SandDose); + + crew::secure(cab.mover(), cab.mover()); + + CHECK(cab->WarningSignal == 0); + CHECK_FALSE(cab->DepartureSignal); + CHECK_FALSE(cab->SandDose); +} + +TEST_CASE("crew: a train left by its driver is braked through the whole of it") { + test::reseed_random(); + consist train; + train.add(definition::fiz("4e_v1/4e"), 1); + train.add(definition::fiz("11xa_v2/93a")); + train.add(definition::fiz("11xa_v2/93a")); + get_under_way(train, 20, 40.0); + auto &eu07{train[0].mover()}; + auto &last{train[2].mover()}; + REQUIRE(train[0].speed() > 15.0); + REQUIRE(last.BrakePress < 0.1); + + crew::secure(eu07, eu07); + + auto const stoppedafter{seconds_to_stop(train, 180.0)}; + CAPTURE(stoppedafter); + CHECK(std::abs(train[0].speed()) <= 0.01); + CHECK(std::abs(train[2].speed()) <= 0.01); + CHECK(last.PipePress < 1.0); + CHECK(last.BrakePress > 1.0); +} + +TEST_CASE("crew: a standing locomotive left by its driver is braked too") { + test::reseed_random(); + consist train; + train.add(definition::fiz("4e_v1/4e"), 1); + auto driver{test::driving(train)}; + REQUIRE(test::start_up(driver, line)); + test::release_brakes(driver.cab); + auto &eu07{train[0].mover()}; + // the cylinders of a locomotive started up cold take their time to empty + for (int i = 0; i < 180 && eu07.BrakePress >= 0.1; ++i) { + test::drive(driver, line, 1.0); + } + REQUIRE(eu07.BrakePress < 0.1); + + crew::secure(eu07, eu07); + + // on a slope it would roll away with the brakes off + train.run(120.0, track{0.15, 0.02, test::catenary_3kv}); + CHECK(eu07.BrakePress > 2.0); + CHECK(std::abs(train[0].speed()) <= 0.01); +} + +TEST_CASE("crew: the power an integrated handle asked for goes when the driver leaves") { + test::reseed_random(); + // the handle's demand (eimic) is worked out only while a driver is in charge of the vehicle; left as it + // was, the unit would go on pulling with nobody in it + vehicle impuls{definition::fiz("impuls_v1/31we-a_pr"), 60.0, "impuls", 1}; + impuls->CabActivisation(); + impuls->MainCtrlPos = impuls->MainCtrlPosNo; + impuls->eimic = 0.8; + impuls->eimic_real = 0.8; + + crew::secure(impuls.mover(), impuls.mover()); + + CHECK(impuls->MainCtrlPos == impuls->MainCtrlNoPowerPos()); + CHECK(impuls->eimic == 0.0); + CHECK(impuls->eimic_real == 0.0); + CHECK(impuls->BrakeCtrlPos == static_cast(impuls->Handle->GetPos(bh_EB))); + CHECK(impuls->CabOccupied == 0); +} + +TEST_CASE("crew: a road vehicle left by its driver gets the brake the driver stops it with") { + test::reseed_random(); + vehicle bus{definition::fiz("road/man/nl293"), 40.0, "bus", 1}; + REQUIRE(bus->BrakeSystem == TBrakeSystem::Individual); + REQUIRE(bus->LocalBrakePosA == 0.0); + bus->CabActivisation(); + + crew::secure(bus.mover(), bus.mover()); + + CHECK(bus->LocalBrakePosA == 1.0); + CHECK(bus->MainCtrlPos == bus->MainCtrlNoPowerPos()); + bus.run(60.0, track{0.6, 0.0, 0.0, 2}); + CHECK(std::abs(bus.speed()) <= 0.01); +} diff --git a/tests/unit/test_derail_motion.cpp b/tests/unit/test_derail_motion.cpp new file mode 100644 index 000000000..5423f2400 --- /dev/null +++ b/tests/unit/test_derail_motion.cpp @@ -0,0 +1,1093 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "vehicle/derailmotion.h" +#include "McZapkie/derailment.h" +#include "McZapkie/MOVER.h" +#include "utilities/Globals.h" + +#include +#include +#include +#include +#include +#include + +// a vehicle off the rails moving on the ground by itself (physics.derailment new): vehicle/derailmotion.h, and what +// the vehicle of TMoverParameters makes of it + +using test::definition; +using test::vehicle; +namespace dm = derail_motion; +namespace dr = derailment; + +namespace { + +constexpr double kmh{1.0 / 3.6}; +constexpr double degree{std::numbers::pi / 180.0}; + +// the given model of derailment for the test, restored after it +class model_setting { +public: + explicit model_setting(global_settings::derailment_model Model) : m_previous{Global.derailment} { Global.derailment = Model; } + ~model_setting() { Global.derailment = m_previous; } + model_setting(model_setting const &) = delete; + model_setting &operator=(model_setting const &) = delete; + +private: + global_settings::derailment_model m_previous; +}; + +// EU07 (4E of data/fiz): its dimensions and the centre of gravity of its body +dm::vehicle_shape eu07() { + dm::vehicle_shape shape; + shape.length = 15.915; + shape.width = 2.903; + shape.height = 4.348; + shape.centre_of_gravity = dr::default_centre_of_gravity(4.348, dr::vehicle_class::powered); + shape.contact_spacing = dr::contact_spacing(1.435); + shape.base = 8.0; + return shape; +} + +// the lateral acceleration [m/s2] the wheels of EU07 lift at: the wheel unloading of derailment.h reaches 1 +double const eu07_tipping{dr::overturning_acceleration(eu07().centre_of_gravity, dr::contact_spacing(1.435))}; + +// the track along +z at the height 0, its left (+x) the outside of the curve +dm::start leaving(double const Speed, dm::cause const Reason, int const Outward = 0, double const Acceleration = 0.0) { + dm::start start; + start.position = glm::dvec3{0.0}; + start.front = glm::dvec3{0.0, 0.0, 1.0}; + start.line = start.front; + start.speed = Speed; + start.reason = Reason; + start.outward = Outward; + start.acceleration = Acceleration; + return start; +} + +// the ground across the track, along +z: the top of the ballast 0.2 m under the rails out to 3 m each side, then the +// Slope (rise per metre outwards, negative down) to the Depth under the top (above it, rising). as a scenery has it, +// a level ground lies under it all, at the lowest of it: what is over the ceiling asked for isn't found, that is +class profile final : public dm::ground { +public: + profile(double const Slope, double const Depth, bool const Bothsides = false) : m_slope{Slope}, m_depth{Depth}, m_bothsides{Bothsides} {} + std::optional height(double const X, double, double const Ceiling) const override { + constexpr double top{-0.2}; + constexpr double edge{3.0}; + auto const across{m_bothsides ? std::abs(X) : X}; + auto const floor{std::min(top, top + std::clamp(m_slope * 1e6, -std::abs(m_depth), std::abs(m_depth)))}; + auto surface{top}; + if (across > edge) { + surface += std::clamp(m_slope * (across - edge), -std::abs(m_depth), std::abs(m_depth)); + } + return surface <= Ceiling ? surface : floor; + } + +private: + double m_slope; + double m_depth; + bool m_bothsides; +}; + +struct outcome { + double time{0.0}; + double travelled{0.0}; + double along{0.0}; + double across{0.0}; + double tipping{0.0}; + double roll{0.0}; + double height{0.0}; + bool lying{false}; + double lying_at{-1.0}; // the time it came to lie on its side, -1 never +}; + +// the vehicle slides as TMoverParameters drives it: its speed along the heading falls with the friction of the motion +// and the gravity of the grade under it, the distance of each step goes to the motion +outcome slide(dm::start const &Start, dm::ground const &Ground, double const Dt = 0.01, dm::vehicle_shape const &Shape = eu07(), double const Seconds = 60.0) { + dm::body body; + body.begin(Start, Shape, Ground); + auto speed{Start.speed}; + outcome result; + while (result.time < Seconds) { + auto const direction{speed >= 0.0 ? 1.0 : -1.0}; + auto const deceleration{dm::gravity * (body.friction() * direction + body.grade())}; + auto next{speed - deceleration * Dt}; + if (next * speed <= 0.0 && std::abs(body.grade()) <= body.friction()) { + next = 0.0; + } + auto const reversals{body.reversals()}; + body.step(Dt, 0.5 * (speed + next) * Dt, next, Ground); + speed = (body.reversals() - reversals) % 2 != 0 ? -next : next; + result.time += Dt; + if (body.lying() && result.lying_at < 0.0) { + result.lying_at = result.time; + } + if (body.at_rest()) { + break; + } + } + result.travelled = body.travelled(); + result.along = body.along(); + result.across = body.across(); + result.tipping = body.tipping(); + result.roll = body.roll(); + result.height = body.current().position.y; + result.lying = body.lying(); + return result; +} + +dm::flat_ground const ballast{-0.2}; + +} // namespace + +TEST_CASE("derail motion: the distance it slides goes with the square of the speed and against the friction") { + auto const fast{dm::stopping_distance(133.0 * kmh, dr::off_rails_friction)}; + auto const slow{dm::stopping_distance(40.0 * kmh, dr::off_rails_friction)}; + REQUIRE(fast.has_value()); + REQUIRE(slow.has_value()); + CHECK(*fast == doctest::Approx(232.0).epsilon(0.01)); + CHECK(*slow == doctest::Approx(21.0).epsilon(0.01)); + CHECK(*fast / *slow == doctest::Approx(133.0 * 133.0 / (40.0 * 40.0)).epsilon(1e-9)); + // on its side + CHECK(*dm::stopping_distance(133.0 * kmh, dr::overturned_friction) == doctest::Approx(*fast * 0.3 / 0.5).epsilon(1e-9)); + // uphill sooner, downhill further, down a slope steeper than the friction it doesn't stop + CHECK(*dm::stopping_distance(40.0 * kmh, 0.3, 0.05) < *slow); + CHECK(*dm::stopping_distance(40.0 * kmh, 0.3, -0.05) > *slow); + CHECK_FALSE(dm::stopping_distance(40.0 * kmh, 0.3, -0.4).has_value()); + + SUBCASE("the vehicle off the end of the track slides as far, straight on, upright") { + for (auto const speed : {133.0, 40.0}) { + CAPTURE(speed); + auto const result{slide(leaving(speed * kmh, dm::cause::end_of_track), ballast)}; + MESSAGE(std::format("off the end of the track at {:.0f} km/h: {:.1f} m in {:.1f} s", speed, result.travelled, result.time)); + CHECK(result.travelled == doctest::Approx(*dm::stopping_distance(speed * kmh, dr::off_rails_friction)).epsilon(0.02)); + CHECK(result.along == doctest::Approx(result.travelled).epsilon(1e-6)); + CHECK(std::abs(result.across) < 1e-6); + CHECK(result.tipping == 0.0); + // on the top of the ballast, not on the rails nor under the ground + CHECK(result.height == doctest::Approx(-0.2)); + } + } + SUBCASE("the friction along it rises from the one on its wheels to the one on its side") { + CHECK(dm::sliding_friction(0.0, false) == dr::off_rails_friction); + CHECK(dm::sliding_friction(dm::body::half_turn, false) == dr::overturned_friction); + CHECK(dm::sliding_friction(0.5 * dm::body::half_turn, false) == doctest::Approx(0.5 * (dr::off_rails_friction + dr::overturned_friction))); + CHECK(dm::sliding_friction(0.0, true) == dm::guided_friction); + } +} + +TEST_CASE("derail motion: the way it leaves the track by what derailed it") { + SUBCASE("off the end of the track and in a collision: straight on") { + CHECK(dm::departure_angle(dm::cause::end_of_track, 30.0, 10.0) == 0.0); + CHECK(dm::departure_angle(dm::cause::collision, 30.0, 10.0) == 0.0); + auto const result{slide(leaving(100.0 * kmh, dm::cause::collision, 1, 5.0), ballast)}; + CHECK(std::abs(result.across) < 1e-6); + } + SUBCASE("the flange climbing the rail: towards the rail it climbed, out of the curve, upright") { + for (auto const outward : {1, -1}) { + CAPTURE(outward); + auto const result{slide(leaving(100.0 * kmh, dm::cause::off_rails, outward, 3.0), ballast)}; + MESSAGE(std::format("climbed out of the curve to the {}: {:.1f} m across in {:.1f} m", outward > 0 ? "left" : "right", result.across, result.travelled)); + CHECK(result.across * outward > 1.0); + CHECK(result.tipping == 0.0); + CHECK_FALSE(result.lying); + } + // the faster the speed against the sideways one, the smaller the angle + CHECK(dm::departure_angle(dm::cause::off_rails, 40.0, 3.0) < dm::departure_angle(dm::cause::off_rails, 10.0, 3.0)); + CHECK(dm::departure_angle(dm::cause::off_rails, 0.1, 1000.0) == dm::most_departure); + } + SUBCASE("backwards, out of the curve as well") { + auto const result{slide(leaving(-100.0 * kmh, dm::cause::off_rails, 1, 3.0), ballast)}; + CHECK(result.along < -10.0); + CHECK(result.across > 1.0); + } + SUBCASE("overturned: out of the curve, falling on its side there") { + for (auto const outward : {1, -1}) { + CAPTURE(outward); + auto const result{slide(leaving(120.0 * kmh, dm::cause::overturned, outward, 2.0 * eu07_tipping), ballast)}; + MESSAGE(std::format("overturned to the {}: {:.1f} m across in {:.1f} m, on its side after {:.2f} s", outward > 0 ? "left" : "right", result.across, result.travelled, result.lying_at)); + CHECK(result.across * outward > 1.0); + CHECK(result.lying); + CHECK(result.tipping * outward == doctest::Approx(dm::body::half_turn)); + CHECK(result.roll * outward == doctest::Approx(dm::body::half_turn)); + // lying on its side on the top of the ballast, the origin of its model is half the width of its body up + CHECK(result.height == doctest::Approx(-0.2 + 0.5 * eu07().width)); + } + } + SUBCASE("pulled off by a coupling: to the side it is pulled to") { + auto const result{slide(leaving(50.0 * kmh, dm::cause::pulled_off, -1, 2.0), ballast)}; + CHECK(result.across < -0.1); + } +} + +TEST_CASE("derail motion: tipping over goes as far as the overturning went over its limit") { + // the curve keeps pushing it out while its outer wheels are on the rail: the further over the limit, the sooner it lies + auto const barely{slide(leaving(120.0 * kmh, dm::cause::overturned, 1, 1.2 * eu07_tipping), ballast)}; + auto const well{slide(leaving(120.0 * kmh, dm::cause::overturned, 1, 2.0 * eu07_tipping), ballast)}; + auto const hard{slide(leaving(120.0 * kmh, dm::cause::overturned, 1, 5.0 * eu07_tipping), ballast)}; + MESSAGE(std::format("on its side after {:.2f} / {:.2f} / {:.2f} s at a wheel unloading of 1.2 / 2 / 5", barely.lying_at, well.lying_at, hard.lying_at)); + REQUIRE(barely.lying); + REQUIRE(well.lying); + REQUIRE(hard.lying); + CHECK(barely.lying_at > well.lying_at); + CHECK(well.lying_at > hard.lying_at); + // it takes its time to fall over, it doesn't jump onto its side + CHECK(hard.lying_at > 0.3); + + SUBCASE("a body on the rails stays upright, on a level ground it isn't tipped by anything") { + auto const upright{slide(leaving(120.0 * kmh, dm::cause::off_rails, 1, 2.0 * eu07_tipping), ballast)}; + CHECK(upright.tipping == 0.0); + } + SUBCASE("slowing down below the limit, the curve doesn't tip it any more") { + dm::body body; + body.begin(leaving(30.0 * kmh, dm::cause::overturned, 1, 1.05 * eu07_tipping), eu07(), ballast); + // stopped at once: the curve pushes it out no more, it falls back on its wheels + body.step(0.01, 0.0, 0.0, ballast); + for (int step = 0; step < 300; ++step) { + body.step(0.01, 0.0, 0.0, ballast); + } + CHECK_FALSE(body.guided()); + CHECK(body.tipping() == 0.0); + } +} + +TEST_CASE("derail motion: the ground under it") { + SUBCASE("off the edge of an embankment it slides down the slope and falls on its side towards the bottom") { + // 1:1.5 down 4 m to the left, the vehicle leaving the track 4 degrees to the left at 60 km/h + profile const embankment{-1.0 / 1.5, 4.0}; + auto start{leaving(60.0 * kmh, dm::cause::off_rails)}; + start.front = glm::dvec3{std::sin(4.0 * degree), 0.0, std::cos(4.0 * degree)}; + auto const result{slide(start, embankment)}; + MESSAGE(std::format("down the embankment: {:.1f} m across, {:.1f} m down, tipped {:.0f} degrees, after {:.1f} m", result.across, -0.2 - result.height, result.tipping / degree, result.travelled)); + CHECK(result.across > 4.0); + // lying on the slope, its body half its width up off the ground + CHECK(result.height < -1.5); + CHECK(result.lying); + CHECK(result.tipping > 0.0); + } + SUBCASE("on a gentle slope it stays upright, leaning with the ground") { + profile const gentle{-1.0 / 6.0, 4.0}; + auto start{leaving(80.0 * kmh, dm::cause::off_rails)}; + start.front = glm::dvec3{std::sin(6.0 * degree), 0.0, std::cos(6.0 * degree)}; + auto const result{slide(start, gentle)}; + CHECK_FALSE(result.lying); + CHECK(result.tipping == 0.0); + // leaning left, down the slope + CHECK(result.roll == doctest::Approx(std::atan(1.0 / 6.0)).epsilon(0.05)); + } + SUBCASE("a lower centre of gravity tips over on a steeper slope only") { + // a 1:2.2 slope, 24 degrees: the steepest one EU07 stands on is 1:2.8 (20 degrees), a flat wagon tips past 1:1.7 + profile const slope{-1.0 / 2.2, 6.0}; + auto start{leaving(50.0 * kmh, dm::cause::off_rails)}; + start.front = glm::dvec3{std::sin(10.0 * degree), 0.0, std::cos(10.0 * degree)}; + auto low{eu07()}; + low.centre_of_gravity = 0.9; + low.height = 2.0; + CHECK(slide(start, slope).lying); + CHECK_FALSE(slide(start, slope, 0.01, low).lying); + } + SUBCASE("in a cutting it climbs the bank, stops sooner and leans (here falls) back towards the track") { + profile const cutting{1.0 / 1.5, 4.0}; + auto start{leaving(60.0 * kmh, dm::cause::off_rails)}; + start.front = glm::dvec3{std::sin(4.0 * degree), 0.0, std::cos(4.0 * degree)}; + auto const level{slide(start, ballast)}; + auto const result{slide(start, cutting)}; + MESSAGE(std::format("into a cutting: {:.1f} m against {:.1f} m on a level ground, roll {:.0f} degrees", result.travelled, level.travelled, result.roll / degree)); + CHECK(result.travelled < level.travelled); + CHECK(result.height > -0.2); + CHECK(result.roll < 0.0); + } + SUBCASE("it doesn't sink into the ground, it falls off a step") { + // off a wall 3 m high + profile const wall{-100.0, 3.0}; + auto start{leaving(40.0 * kmh, dm::cause::off_rails)}; + start.front = glm::dvec3{std::sin(20.0 * degree), 0.0, std::cos(20.0 * degree)}; + dm::body body; + body.begin(start, eu07(), wall); + auto lowest{0.0}; + auto speed{start.speed}; + for (int index = 0; index < 1000; ++index) { + auto const next{std::max(0.0, speed - dm::gravity * body.friction() * 0.01)}; + body.step(0.01, 0.5 * (speed + next) * 0.01, next, wall); + speed = next; + auto const &position{body.current().position}; + auto const ground{*wall.height(position.x, position.z, 1e9)}; + CHECK(position.y >= ground - 1e-9); + lowest = std::min(lowest, position.y); + } + CHECK(lowest < -3.0); + } +} + +TEST_CASE("derail motion: the same with steps of 0.01, 0.03 and 0.05 s") { + profile const embankment{-1.0 / 1.5, 4.0}; + auto down{leaving(60.0 * kmh, dm::cause::off_rails)}; + down.front = glm::dvec3{std::sin(4.0 * degree), 0.0, std::cos(4.0 * degree)}; + auto const overturning{leaving(120.0 * kmh, dm::cause::overturned, -1, 2.0 * eu07_tipping)}; + auto const climbing{leaving(100.0 * kmh, dm::cause::off_rails, 1, 3.0)}; + auto const fine{slide(down, embankment, 0.01)}; + auto const finetip{slide(overturning, ballast, 0.01)}; + auto const fineclimb{slide(climbing, ballast, 0.01)}; + for (auto const dt : {0.03, 0.05}) { + CAPTURE(dt); + auto const coarse{slide(down, embankment, dt)}; + CHECK(coarse.travelled == doctest::Approx(fine.travelled).epsilon(0.02)); + CHECK(coarse.across == doctest::Approx(fine.across).epsilon(0.05)); + CHECK(coarse.lying == fine.lying); + auto const coarsetip{slide(overturning, ballast, dt)}; + CHECK(coarsetip.travelled == doctest::Approx(finetip.travelled).epsilon(0.02)); + CHECK(coarsetip.across == doctest::Approx(finetip.across).epsilon(0.02)); + CHECK(coarsetip.lying_at == doctest::Approx(finetip.lying_at).epsilon(0.1)); + auto const coarseclimb{slide(climbing, ballast, dt)}; + CHECK(coarseclimb.across == doctest::Approx(fineclimb.across).epsilon(0.02)); + } +} + +TEST_CASE("derail motion: the ground of the scenery") { + SUBCASE("the triangles of the terrain") { + std::vector triangles; + // a square 10 m wide at 2 m rising to 4 m along x, and a roof over half of it at 10 m + triangles.push_back({glm::dvec3{0.0, 2.0, 0.0}, glm::dvec3{10.0, 4.0, 0.0}, glm::dvec3{10.0, 4.0, 10.0}}); + triangles.push_back({glm::dvec3{0.0, 2.0, 0.0}, glm::dvec3{10.0, 4.0, 10.0}, glm::dvec3{0.0, 2.0, 10.0}}); + triangles.push_back({glm::dvec3{0.0, 10.0, 0.0}, glm::dvec3{5.0, 10.0, 0.0}, glm::dvec3{0.0, 10.0, 10.0}}); + dm::mesh_ground const terrain{triangles, glm::dvec2{-5.0, -5.0}, glm::dvec2{15.0, 15.0}, 2.0}; + CHECK(terrain.size() == 3); + CHECK(*terrain.height(5.0, 5.0, 8.0) == doctest::Approx(3.0)); + CHECK(*terrain.height(7.5, 2.5, 8.0) == doctest::Approx(3.5)); + // under the roof the ground, over it the roof + CHECK(*terrain.height(1.0, 1.0, 8.0) == doctest::Approx(2.2)); + CHECK(*terrain.height(1.0, 1.0, 12.0) == doctest::Approx(10.0)); + CHECK_FALSE(terrain.height(12.0, 5.0, 8.0).has_value()); + CHECK_FALSE(terrain.height(50.0, 5.0, 8.0).has_value()); + CHECK(terrain.covers(14.0, -4.0)); + CHECK_FALSE(terrain.covers(16.0, 0.0)); + // the area of another vehicle: inside the one gathered or not + CHECK(terrain.covers(glm::dvec2{-5.0, -5.0}, glm::dvec2{15.0, 15.0})); + CHECK(terrain.covers(glm::dvec2{0.0, 2.0}, glm::dvec2{10.0, 12.0})); + CHECK_FALSE(terrain.covers(glm::dvec2{0.0, 2.0}, glm::dvec2{10.0, 16.0})); + CHECK_FALSE(terrain.covers(glm::dvec2{-6.0, 0.0}, glm::dvec2{0.0, 1.0})); + // cut down to the ground under a vehicle at rest: the triangles reaching into it, the same height there + auto const under{terrain.cropped(glm::dvec2{6.0, 0.0}, glm::dvec2{9.0, 4.0})}; + CHECK(under.size() == 2); + CHECK(*under.height(7.5, 2.5, 8.0) == doctest::Approx(3.5)); + CHECK(under.covers(6.0, 4.0)); + CHECK_FALSE(under.covers(5.0, 2.0)); + CHECK_FALSE(under.height(5.0, 2.0, 8.0).has_value()); + CHECK(terrain.cropped(glm::dvec2{0.5, 0.5}, glm::dvec2{1.0, 1.0}).size() == 3); + CHECK(terrain.cropped(glm::dvec2{20.0, 20.0}, glm::dvec2{30.0, 30.0}).size() == 0); + } + SUBCASE("the bed of the track over the terrain, level ground without one") { + dm::formation bed; + bed.point = glm::dvec3{0.0, 10.0, 0.0}; + bed.direction = glm::dvec3{0.0, 0.0, 1.0}; + bed.half_width = 2.0; + CHECK(bed.height(1.5, 100.0) == doctest::Approx(9.8)); + CHECK(bed.height(-2.0, -50.0) == doctest::Approx(9.8)); + CHECK(bed.height(3.5, 0.0) == doctest::Approx(9.8 - 1.0)); + dm::flat_ground const low{7.0}; + dm::site const embankment{&low, bed}; + CHECK(*embankment.height(0.0, 0.0, 12.0) == doctest::Approx(9.8)); + CHECK(*embankment.height(4.0, 0.0, 12.0) == doctest::Approx(9.8 - 2.0 / 1.5)); + CHECK(*embankment.height(20.0, 0.0, 12.0) == doctest::Approx(7.0)); + dm::site const bare{nullptr, bed}; + CHECK(*bare.height(20.0, 0.0, 12.0) == doctest::Approx(9.8)); + } +} + +TEST_CASE("derail motion: a coupling pulling sideways") { + // EU07, 80 t on 4 axles: a wheel carries 98 kN + CHECK(dm::pull_ratio(300e3, 0.0, 80e3, 4) == 0.0); + CHECK(dm::pull_ratio(300e3, 30.0 * degree, 80e3, 4) == doctest::Approx(0.5 * 150e3 / (80e3 * dm::gravity / 8.0))); + CHECK(dm::pull_ratio(-300e3, -30.0 * degree, 80e3, 4) == dm::pull_ratio(300e3, 30.0 * degree, 80e3, 4)); + // an empty wagon of 20 t goes over the climbing limit with a force the locomotive takes + CHECK(dm::pull_ratio(300e3, 30.0 * degree, 20e3, 4) > dr::climbing_limit); + CHECK(dm::pull_ratio(300e3, 30.0 * degree, 80e3, 4) < dr::climbing_limit); +} + +TEST_CASE("derail motion: the vehicle leaves the track with physics.derailment new only") { + test::track curve; + curve.radius = 300.0; + auto const critical{dr::overturning_speed(300.0, 0.0, eu07().centre_of_gravity, 1.435) / kmh}; + + SUBCASE("new: derailed by the criteria it leaves the track, then slides with the friction of the motion") { + model_setting const physical{global_settings::derailment_model::physical}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical + 20.0}; + for (int step = 0; step < 10; ++step) { + eu07vehicle.step(curve); + } + REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned); + CHECK(eu07vehicle->DerailCause == dm::cause::overturned); + CHECK(eu07vehicle->DerailAcceleration > eu07_tipping); + CHECK(eu07vehicle->leaves_track()); + eu07vehicle->OffTrack.begin(leaving(eu07vehicle->V, eu07vehicle->DerailCause, 1, eu07vehicle->DerailAcceleration), eu07(), ballast); + CHECK_FALSE(eu07vehicle->leaves_track()); + // tipping over on its outer wheels it hardly slows down + auto const start{eu07vehicle->V}; + for (int step = 0; step < 20; ++step) { + eu07vehicle.step(curve); + } + auto const deceleration{(start - eu07vehicle->V) / 0.2}; + CHECK(deceleration == doctest::Approx(dm::guided_friction * dr::gravity * 80.0 / 96.0).epsilon(0.1)); + // back on the rails, not off the track any more, and what derailed it forgotten + eu07vehicle->repair_damage(); + CHECK_FALSE(eu07vehicle->OffTrack.active()); + CHECK_FALSE(eu07vehicle->leaves_track()); + CHECK(eu07vehicle->DerailCause == dm::cause::off_rails); + CHECK(eu07vehicle->DerailAcceleration == 0.0); + } + SUBCASE("new: off the end of the track it slides on its wheels, straight on") { + model_setting const physical{global_settings::derailment_model::physical}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 40.0}; + eu07vehicle.damage_track(dtrack_norail); + eu07vehicle.step(); + REQUIRE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + CHECK(eu07vehicle->Derailed == dr::outcome::off_rails); + CHECK(eu07vehicle->DerailCause == dm::cause::end_of_track); + CHECK(eu07vehicle->leaves_track()); + } + SUBCASE("new: a vehicle pulled off by a coupling, upright, to the side it was pulled to") { + model_setting const physical{global_settings::derailment_model::physical}; + vehicle pulled{definition::fiz("4e_v1/4e"), 40.0}; + pulled->pull_off(-1, 5.0, "test"); + CHECK(TestFlag(pulled->DamageFlag, dtrain_out)); + CHECK(pulled->Derailed == dr::outcome::off_rails); + CHECK(pulled->DerailCause == dm::cause::pulled_off); + CHECK(pulled->DerailSide == -1); + CHECK(pulled->leaves_track()); + pulled->repair_damage(); + CHECK(pulled->DerailCause == dm::cause::off_rails); + CHECK(pulled->DerailAcceleration == 0.0); + CHECK(pulled->DerailSide == 0); + } +} + +TEST_CASE("derail motion: with physics.derailment monitor and old the vehicle stays on the track, as before") { + test::track curve; + curve.radius = 300.0; + for (auto const model : {global_settings::derailment_model::monitor, global_settings::derailment_model::old}) { + auto const number{static_cast(model)}; + CAPTURE(number); + model_setting const setting{model}; + vehicle fast{definition::fiz("4e_v1/4e"), 160.0}; + for (int step = 0; step < 600; ++step) { + fast.step(curve); + } + REQUIRE(TestFlag(fast->DamageFlag, dtrain_out)); + CHECK(fast->Derailed == dr::outcome::none); + CHECK_FALSE(fast->leaves_track()); + CHECK_FALSE(fast->OffTrack.active()); + // stopped dead by the legacy model + CHECK(fast->V == doctest::Approx(0.0).epsilon(0.01)); + vehicle ending{definition::fiz("4e_v1/4e"), 40.0}; + ending.damage_track(dtrack_norail); + ending.step(); + REQUIRE(TestFlag(ending->DamageFlag, dtrain_out)); + CHECK(ending->Derailed == dr::outcome::none); + CHECK_FALSE(ending->leaves_track()); + // nor is a vehicle pulled off it + vehicle pulled{definition::fiz("4e_v1/4e"), 40.0}; + pulled->pull_off(1, 5.0, "test"); + CHECK_FALSE(TestFlag(pulled->DamageFlag, dtrain_out)); + } +} + +// ---- the yaw of the body, the train folding up, the scatter + +namespace { + +// a coach of 40 t, 24.5 m over the buffers +dm::vehicle_shape coach() { + dm::vehicle_shape shape; + shape.length = 24.5; + shape.width = 2.825; + shape.height = 4.05; + shape.centre_of_gravity = dr::default_centre_of_gravity(4.05, dr::vehicle_class::unpowered); + shape.contact_spacing = dr::contact_spacing(1.435); + shape.base = 17.2; + shape.mass = 40e3; + return shape; +} + +// an end of the body: its front (Front) or its rear, at the height of the buffers +dm::end_point end_of(dm::body const &Body, bool const Front) { + // over its base, as TDynamicObject takes it + auto const half{0.5 * Body.shape().length * (Front ? 1.0 : -1.0)}; + return dm::end_point{Body.base() + glm::dvec3{0.0, dm::buffer_height, 0.0} + Body.axis() * half, Front ? Body.axis() : -Body.axis(), Body.tipping()}; +} + +struct car { + dm::body body; + double speed{0.0}; + double gap{0.0}; // of the coupling behind it +}; + +// the train of bodies off the track on level ground as TMoverParameters and TDynamicObject drive it: their buffers and +// couplings a spring of 2 MN/m with its damping, the longitudinal motion of each from the forces of its couplings along +// its heading and the friction of its motion; the forces across turn them. Dt the step [s]; till all stop or 30 s +std::vector run_train(std::vector> const &Starts, dm::vehicle_shape const &Shape, double const Dt = 0.01) { + std::vector train(Starts.size()); + for (std::size_t index = 0; index < train.size(); ++index) { + train[index].body.begin(Starts[index].first, Shape, ballast, Starts[index].second); + train[index].speed = Starts[index].first.speed; + } + for (std::size_t index = 0; index + 1 < train.size(); ++index) { + train[index].gap = dm::meet(end_of(train[index].body, false), end_of(train[index + 1].body, true)).gap; + } + constexpr double stiffness{2e6}; + auto const damping{0.3 * 2.0 * std::sqrt(stiffness * Shape.mass)}; + constexpr double slack{0.05}; + for (int step = 0; step * Dt < 30.0; ++step) { + std::vector> ends(train.size()); + for (std::size_t index = 0; index + 1 < train.size(); ++index) { + auto &ahead{train[index]}; + auto &behind{train[index + 1]}; + auto const rear{dm::meet(end_of(ahead.body, false), end_of(behind.body, true))}; + auto const front{dm::meet(end_of(behind.body, true), end_of(ahead.body, false))}; + auto const closing{(ahead.gap - rear.gap) / Dt}; + ahead.gap = rear.gap; + auto compression{0.0}; + if (rear.gap < 0.0) { + compression = std::max(0.0, -stiffness * rear.gap + damping * closing); + } + else if (rear.gap > slack) { + compression = std::min(0.0, -stiffness * (rear.gap - slack) + damping * closing); + } + ends[index][1] = dm::force_on(rear, compression); + ends[index + 1][0] = dm::force_on(front, compression); + } + auto moving{false}; + for (std::size_t index = 0; index < train.size(); ++index) { + auto &item{train[index]}; + auto const push{glm::dot(ends[index][0].force + ends[index][1].force, item.body.heading()) / Shape.mass}; + auto const friction{dm::gravity * item.body.friction()}; + auto next{item.speed + push * Dt}; + if (std::abs(next) <= friction * Dt) { + next = 0.0; + } + else { + next -= (next > 0.0 ? 1.0 : -1.0) * friction * Dt; + } + auto const reversals{item.body.reversals()}; + item.body.step(Dt, 0.5 * (item.speed + next) * Dt, next, ballast, ends[index]); + item.speed = (item.body.reversals() - reversals) % 2 != 0 ? -next : next; + moving |= (false == item.body.at_rest()); + } + if (false == moving) { + break; + } + } + return train; +} + +// a train of four coaches at 133 km/h overturning out of the curve to the left, the leading one ploughing into the +// ground; each scattered by the seed, or none of them +std::vector> overturning_train(std::uint32_t const Seed, bool const Scattered = true) { + std::vector> starts; + for (int index = 0; index < 4; ++index) { + auto start{leaving(133.0 * kmh, dm::cause::overturned, 1, 2.0 * eu07_tipping)}; + // one after the other along the way they leave the track + auto const angle{dm::departure_angle(start.reason, start.speed, start.acceleration)}; + start.position = -index * coach().length * glm::dvec3{std::sin(angle), 0.0, std::cos(angle)}; + auto scatter{Scattered ? dm::draw_scatter(dm::seed_of(Seed, std::format("coach{}", index))) : dm::scatter{}}; + if (index == 0 && Scattered) { + // the leading one ploughs into the ground: held back harder all the way, the ones behind push into it + scatter.friction_front *= 1.5; + scatter.friction_rear *= 1.5; + } + starts.emplace_back(start, scatter); + } + return starts; +} + +// the bends between the bodies of the train, from the front [rad] +std::vector bends(std::vector const &Train) { + std::vector result; + for (std::size_t index = 0; index + 1 < Train.size(); ++index) { + result.push_back(std::remainder(Train[index + 1].body.yaw() - Train[index].body.yaw(), 2.0 * std::numbers::pi)); + } + return result; +} + +std::string described(std::vector const &Train) { + std::string result; + for (auto const &item : Train) { + result += std::format(" [{:.1f} m along, {:+.1f} m across, yaw {:+.1f} deg]", item.body.along(), item.body.across(), item.body.yaw() / degree); + } + return result; +} + +} // namespace + +TEST_CASE("derail motion: the buffers and the coupling of two ends") { + // two ends facing each other, the second 10 degrees to the left of the axis of the first, the buffers pressed 20 mm + dm::end_point const first{glm::dvec3{0.0, 1.0, 0.0}, glm::dvec3{0.0, 0.0, 1.0}}; + auto const angle{10.0 * degree}; + dm::end_point const second{glm::dvec3{0.0, 1.0, -0.02}, -glm::dvec3{std::sin(angle), 0.0, std::cos(angle)}}; + auto const pressed{dm::meet(first, second)}; + CHECK(pressed.bend == doctest::Approx(angle)); + CHECK(pressed.gap == doctest::Approx(-0.02 * std::cos(0.5 * angle))); + CHECK(pressed.overlap == doctest::Approx(1.0)); + // the push of the buffers: against the bisector of the bend, through the inner buffer (to the left); less far out + // once the push is more than a buffer takes + auto const light{dm::force_on(pressed, 200e3)}; + CHECK(light.force.z == doctest::Approx(-200e3 * std::cos(0.5 * angle))); + CHECK(light.force.x == doctest::Approx(-200e3 * std::sin(0.5 * angle))); + CHECK(light.point.x == doctest::Approx(dm::buffer_half_spacing * std::cos(0.5 * angle)).epsilon(1e-3)); + auto const heavy{dm::force_on(pressed, 4.0 * dm::buffer_limit)}; + CHECK(heavy.point.x == doctest::Approx(0.25 * dm::buffer_half_spacing * std::cos(0.5 * angle)).epsilon(1e-3)); + // a body lower by a buffer head misses the buffers of the other one: the push goes through the middle of the beams + dm::end_point low{second}; + low.point.y -= dm::buffer_head; + CHECK(dm::force_on(dm::meet(first, low), 200e3).point.x == doctest::Approx(0.0)); + // the coupling pulls towards the other beam, taken 1 m to the side + dm::end_point aside{second}; + aside.point = glm::dvec3{1.0, 1.0, 0.5}; + auto const pulled{dm::meet(first, aside)}; + CHECK(pulled.gap == doctest::Approx(std::hypot(1.0, 0.5)).epsilon(0.1)); + auto const pull{dm::force_on(pulled, -100e3)}; + CHECK(pull.force.x == doctest::Approx(100e3 / std::hypot(1.0, 0.5))); + // gone past each other side by side: the coupling stretched + aside.point = glm::dvec3{3.0, 1.0, -5.0}; + CHECK(dm::meet(first, aside).gap > 5.0); + // a body turned about, its end facing the same way as the first one, 5 m behind it: they don't press each other + dm::end_point const about{glm::dvec3{0.0, 1.0, -5.0}, glm::dvec3{0.0, 0.0, 1.0}}; + CHECK(dm::meet(first, about).gap == doctest::Approx(5.0)); +} + +TEST_CASE("derail motion: the yaw of the body") { + auto shape{eu07()}; + shape.mass = 80e3; + SUBCASE("a push off the middle turns it, the friction under it holds it against a small one") { + for (auto const side : {1.0, -1.0}) { + CAPTURE(side); + dm::body body; + body.begin(leaving(0.0, dm::cause::off_rails), shape, ballast); + // 300 kN across at the front end, to the Side: it turns its front that way + std::array ends{}; + ends[0] = dm::end_force{glm::dvec3{side * 300e3, 0.0, 0.0}, glm::dvec3{0.0, 1.0, 0.5 * shape.length}}; + for (int step = 0; step < 50; ++step) { + body.step(0.01, 0.0, 0.0, ballast, ends); + } + CHECK(body.yaw_rate() * side > 0.0); + CHECK(body.yaw() * side > 0.0); + // through the middle along the body it doesn't turn it + dm::body straight; + straight.begin(leaving(0.0, dm::cause::off_rails), shape, ballast); + ends[0] = dm::end_force{glm::dvec3{0.0, 0.0, -300e3}, glm::dvec3{0.0, 1.0, 0.5 * shape.length}}; + straight.step(0.5, 0.0, 0.0, ballast, ends); + CHECK(straight.yaw() == 0.0); + // 30 kN across: the friction holds it, once it stands on the ground + dm::flat_ground const rails{0.0}; + dm::body held; + held.begin(leaving(0.0, dm::cause::off_rails), shape, rails); + ends[0] = dm::end_force{glm::dvec3{side * 30e3, 0.0, 0.0}, glm::dvec3{0.0, 1.0, 0.5 * shape.length}}; + held.step(0.5, 0.0, 0.0, rails, ends); + CHECK(held.yaw() == 0.0); + CHECK(held.at_rest()); + } + } + SUBCASE("the friction under it stops the turning, sliding or standing") { + for (auto const speed : {0.0, 30.0}) { + CAPTURE(speed); + dm::scatter spin; + spin.yaw_rate = 0.5; + dm::body body; + body.begin(leaving(speed, dm::cause::off_rails), shape, ballast, spin); + auto current{speed}; + auto most{0.0}; + auto halfway{0.0}; + for (int step = 0; step < 3000 && false == body.at_rest(); ++step) { + auto const next{std::max(0.0, current - dm::gravity * body.friction() * 0.01)}; + body.step(0.01, 0.5 * (current + next) * 0.01, next, ballast); + if (current > 0.5 * speed && next <= 0.5 * speed) { + halfway = body.yaw_rate(); + } + current = next; + most = std::max(most, std::abs(body.yaw_rate())); + } + MESSAGE(std::format("set turning at 0.5 rad/s at {:.0f} m/s: turned {:.1f} deg", speed, body.yaw() / degree)); + CHECK(body.at_rest()); + CHECK(body.yaw_rate() == 0.0); + // it never turns faster than it was set to + CHECK(most <= 0.5 + 1e-9); + CHECK(body.yaw() > 0.0); + // standing it stops within a turn of a few degrees; sliding fast, little holds it (the friction under it goes + // almost all against the way it slides), it slows the turning as it slows down + if (speed > 0.0) { + CHECK(halfway < 0.4); + CHECK(body.yaw() < 180.0 * degree); + } + else { + CHECK(body.yaw() < 15.0 * degree); + } + } + } + SUBCASE("a body going askew slides harder, and the way it goes turns to the body") { + dm::scatter askew; + askew.yaw = 20.0 * degree; + dm::body body; + body.begin(leaving(30.0, dm::cause::off_rails), shape, ballast, askew); + CHECK(body.friction() > dr::off_rails_friction); + CHECK(body.friction() < dm::lateral_friction); + auto const before{std::abs(std::remainder(std::atan2(body.heading().x, body.heading().z) - body.yaw(), 2.0 * std::numbers::pi))}; + auto current{30.0}; + for (int step = 0; step < 100; ++step) { + auto const next{current - dm::gravity * body.friction() * 0.01}; + body.step(0.01, 0.5 * (current + next) * 0.01, next, ballast); + current = next; + } + auto const after{std::abs(std::remainder(std::atan2(body.heading().x, body.heading().z) - body.yaw(), 2.0 * std::numbers::pi))}; + CHECK(after < before); + } +} + +TEST_CASE("derail motion: a train off the track pushed from behind folds into a zigzag") { + // the leading one held back harder, the ones behind push into it: a chaotic matter, so over eight seeds most of the + // trains fold, and the folds next to each other turn opposite ways + auto foldedtrains{0}; + auto pairs{0}; + auto zigzags{0}; + for (std::uint32_t seed = 1; seed <= 8; ++seed) { + CAPTURE(seed); + auto const train{run_train(overturning_train(seed), coach())}; + auto const bent{bends(train)}; + MESSAGE((std::format("seed {} at rest:", seed) + described(train))); + for (auto const &item : train) { + CHECK(item.body.at_rest()); + } + auto folds{0}; + for (std::size_t index = 0; index < bent.size(); ++index) { + if (std::abs(bent[index]) > 10.0 * degree) { + ++folds; + if (index + 1 < bent.size() && std::abs(bent[index + 1]) > 10.0 * degree) { + ++pairs; + zigzags += (bent[index] * bent[index + 1] < 0.0 ? 1 : 0); + } + } + } + foldedtrains += (folds > 0 ? 1 : 0); + } + MESSAGE(std::format("{} of 8 trains folded, {} of {} neighbouring folds turn opposite ways", foldedtrains, zigzags, pairs)); + CHECK(foldedtrains >= 4); + CHECK(pairs >= 2); + CHECK(zigzags * 4 >= pairs * 3); + SUBCASE("without the bite and the scatter it stays in line") { + auto const straight{run_train(overturning_train(1, false), coach())}; + MESSAGE((std::string{"unscattered at rest:"} + described(straight))); + for (auto const bend : bends(straight)) { + CHECK(std::abs(bend) < 1.0 * degree); + } + } +} + +TEST_CASE("derail motion: the scatter") { + SUBCASE("the same seed, the same scatter; another seed, another one") { + auto const one{dm::draw_scatter(dm::seed_of(7, "coach1"))}; + auto const again{dm::draw_scatter(dm::seed_of(7, "coach1"))}; + auto const other{dm::draw_scatter(dm::seed_of(8, "coach1"))}; + auto const next{dm::draw_scatter(dm::seed_of(7, "coach2"))}; + CHECK(one.departure == again.departure); + CHECK(one.friction_front == again.friction_front); + CHECK(one.dig_in == again.dig_in); + CHECK(one.yaw != other.yaw); + CHECK(one.yaw != next.yaw); + auto bites{0}; + for (std::uint32_t seed = 0; seed < 300; ++seed) { + auto const scatter{dm::draw_scatter(seed)}; + CHECK(std::abs(scatter.departure) <= 0.01); + CHECK(std::abs(scatter.yaw) <= 0.02); + CHECK(std::abs(scatter.yaw_rate) <= 0.02); + CHECK(scatter.friction_front >= 0.85); + CHECK(scatter.friction_rear <= 1.15); + CHECK((scatter.dig_in < 0.0 || (scatter.dig_in >= 0.2 && scatter.dig_in <= 1.5))); + bites += (scatter.dig_in >= 0.0 ? 1 : 0); + } + CHECK(bites > 150); + CHECK(bites < 250); + } + SUBCASE("the train: the same seed, the same way; another seed, another way") { + auto const one{bends(run_train(overturning_train(1), coach()))}; + auto const again{bends(run_train(overturning_train(1), coach()))}; + auto const othertrain{run_train(overturning_train(2), coach())}; + auto const other{bends(othertrain)}; + MESSAGE((std::string{"seed 2 at rest:"} + described(othertrain))); + CHECK(one == again); + auto apart{0.0}; + for (std::size_t index = 0; index < one.size(); ++index) { + apart = std::max(apart, std::abs(one[index] - other[index])); + } + MESSAGE(std::format("the bends of seed 1 and seed 2 differ by {:.1f} deg at most", apart / degree)); + CHECK(apart > 2.0 * degree); + } + SUBCASE("the same with steps of 0.01, 0.03 and 0.05 s") { + auto starts{overturning_train(3)}; + starts.resize(1); + auto const fine{run_train(starts, coach(), 0.01)}; + for (auto const dt : {0.03, 0.05}) { + CAPTURE(dt); + auto const coarse{run_train(starts, coach(), dt)}; + CHECK(coarse[0].body.travelled() == doctest::Approx(fine[0].body.travelled()).epsilon(0.02)); + CHECK(coarse[0].body.across() == doctest::Approx(fine[0].body.across()).epsilon(0.05)); + CHECK(coarse[0].body.yaw() == doctest::Approx(fine[0].body.yaw()).epsilon(0.05)); + } + } +} + +// ---- the bodies running into each other + +namespace { + +// a body off the track and the speed its vehicle goes with along its heading, as TMoverParameters keeps it +struct slider { + dm::body body; + double speed{0.0}; +}; + +dm::footprint print_of(dm::body const &Body) { + return dm::footprint_of(Body.current(), Body.shape().length, Body.shape().width, Body.shape().height); +} + +dm::contact_body contact_of(dm::body const &Body) { + dm::contact_body result; + result.mass = Body.shape().mass; + result.base = Body.base(); + result.velocity = Body.velocity(); + result.yaw_rate = Body.yaw_rate(); + result.gyration = Body.gyration(); + return result; +} + +// the kinetic energy of the body per its motion along and about the vertical [J] +double energy_of(dm::contact_body const &Body) { + return 0.5 * Body.mass * (glm::dot(Body.velocity, Body.velocity) + Body.gyration * Body.yaw_rate * Body.yaw_rate); +} + +// the hit of two bodies as vehicle_table::update_off_track_contacts() takes it: the impulse, the kick of each, the two +// moved apart by the overlap; the depth of it [m] +double touch(slider &First, slider &Second) { + auto const hit{dm::collide(print_of(First.body), print_of(Second.body))}; + if (false == hit.has_value()) { + return 0.0; + } + auto const first{contact_of(First.body)}; + auto const second{contact_of(Second.body)}; + auto const impulse{dm::contact_impulse(*hit, first, second)}; + auto const [velocity, yawrate]{dm::impulse_change(first, -impulse, hit->point)}; + auto const [othervelocity, otheryawrate]{dm::impulse_change(second, impulse, hit->point)}; + if (glm::length(impulse) > 0.0) { + First.body.kick(velocity, yawrate); + First.speed = First.body.speed(); + Second.body.kick(othervelocity, otheryawrate); + Second.speed = Second.body.speed(); + } + auto const correction{dm::contact_correction * std::max(0.0, hit->depth - dm::contact_slop)}; + First.body.nudge(-hit->normal * (0.5 * correction)); + Second.body.nudge(hit->normal * (0.5 * correction)); + return hit->depth; +} + +void slide_on(slider &Item, double const Dt) { + auto const friction{dm::gravity * Item.body.friction()}; + auto next{Item.speed}; + if (std::abs(next) <= friction * Dt) { + next = 0.0; + } + else { + next -= (next > 0.0 ? 1.0 : -1.0) * friction * Dt; + } + auto const reversals{Item.body.reversals()}; + Item.body.step(Dt, 0.5 * (Item.speed + next) * Dt, next, ballast); + Item.speed = (Item.body.reversals() - reversals) % 2 != 0 ? -next : next; +} + +struct hit_outcome { + double most{0.0}; // the deepest the two went into each other [m] + double resting{0.0}; // at rest + double furthest{0.0}; // the furthest the first one got along +z [m] + glm::dvec3 first{0.0}; // where the bodies came to rest + glm::dvec3 second{0.0}; + double second_yaw{0.0}; +}; + +// a coach upright at Speed along +z into another one standing Distance ahead of it, turned by the Angle, offset +// Across; the step Dt +hit_outcome run_into(double const Speed, double const Angle, double const Across = 0.0, double const Dt = 0.01, double const Distance = 40.0) { + slider first; + first.body.begin(leaving(Speed, dm::cause::end_of_track), coach(), ballast); + first.speed = Speed; + slider second; + auto standing{leaving(0.0, dm::cause::end_of_track)}; + standing.position = glm::dvec3{Across, 0.0, Distance}; + standing.front = glm::dvec3{std::sin(Angle), 0.0, std::cos(Angle)}; + second.body.begin(standing, coach(), ballast); + hit_outcome result; + for (int step = 0; step * Dt < 30.0; ++step) { + result.most = std::max(result.most, touch(first, second)); + slide_on(first, Dt); + slide_on(second, Dt); + result.furthest = std::max(result.furthest, first.body.base().z); + if (first.body.at_rest() && second.body.at_rest()) { + break; + } + } + result.resting = touch(first, second); + result.first = first.body.base(); + result.second = second.body.base(); + result.second_yaw = second.body.yaw(); + return result; +} + +} // namespace + +TEST_CASE("derail motion: the footprint of a body and two bodies in each other") { + dm::pose upright; + auto const print{dm::footprint_of(upright, 24.5, 2.8, 4.0)}; + CHECK(print.half_length == doctest::Approx(12.25 - dm::buffer_length)); + CHECK(print.half_width == doctest::Approx(1.4)); + CHECK(print.low == doctest::Approx(0.0)); + CHECK(print.high == doctest::Approx(4.0)); + // on its side to the left: as wide on the ground as it is high, all of it to the left, as low as it is wide + dm::pose lying; + lying.left = glm::dvec3{0.0, -1.0, 0.0}; + lying.up = glm::dvec3{1.0, 0.0, 0.0}; + lying.position = glm::dvec3{0.0, 1.4, 0.0}; + auto const side{dm::footprint_of(lying, 24.5, 2.8, 4.0)}; + CHECK(side.half_width == doctest::Approx(2.0)); + CHECK(side.centre.x == doctest::Approx(2.0)); + CHECK(side.high - side.low == doctest::Approx(2.8)); + // side by side 2.5 m apart: 0.3 m in each other, out of the first to the left (+x) + auto beside{print}; + beside.centre.x = 2.5; + auto const hit{dm::collide(print, beside)}; + REQUIRE(hit.has_value()); + CHECK(hit->depth == doctest::Approx(0.3)); + CHECK(hit->normal.x == doctest::Approx(1.0)); + // apart, or one over the other: no contact + beside.centre.x = 3.0; + CHECK_FALSE(dm::collide(print, beside).has_value()); + beside.centre.x = 2.5; + beside.low = 3.9; + beside.high = 7.0; + CHECK_FALSE(dm::collide(print, beside).has_value()); + // the lying one beside the upright one, low as it is: they hit + CHECK(dm::collide(print, side).has_value()); +} + +TEST_CASE("derail motion: an impulse never adds energy") { + // two bodies meeting at all kinds of points and angles, turning or not, one of them on the rails or not + auto worst{-1e9}; + for (int index = 0; index < 400; ++index) { + auto const draw = [index](int Which) { return std::sin(index * 12.9898 + Which * 78.233) * 0.5 + 0.5; }; + dm::contact hit; + auto const angle{draw(1) * 2.0 * std::numbers::pi}; + hit.normal = glm::dvec3{std::cos(angle), 0.0, std::sin(angle)}; + hit.point = glm::dvec3{draw(2) * 20.0 - 10.0, 0.0, draw(3) * 6.0 - 3.0}; + hit.depth = 0.1; + dm::contact_body first{40e3, glm::dvec3{0.0}, glm::dvec3{draw(4) * 40.0 - 20.0, 0.0, draw(5) * 40.0 - 20.0}, draw(6) - 0.5, 50.0}; + dm::contact_body second{80e3, glm::dvec3{draw(7) * 6.0, 0.0, draw(8) * 6.0}, glm::dvec3{draw(9) * 10.0 - 5.0, 0.0, 0.0}, draw(10) - 0.5, 22.0}; + if (index % 3 == 0) { + second.guided = true; + second.guide = glm::dvec3{1.0, 0.0, 0.0}; + second.yaw_rate = 0.0; + } + auto const before{energy_of(first) + energy_of(second)}; + auto const impulse{dm::contact_impulse(hit, first, second)}; + auto const [velocity, yawrate]{dm::impulse_change(first, -impulse, hit.point)}; + auto const [othervelocity, otheryawrate]{dm::impulse_change(second, impulse, hit.point)}; + first.velocity += velocity; + first.yaw_rate += yawrate; + second.velocity += othervelocity; + second.yaw_rate += otheryawrate; + auto const after{energy_of(first) + energy_of(second)}; + worst = std::max(worst, after - before); + CHECK(after <= before * (1.0 + 1e-9) + 1e-6); + } + MESSAGE(std::format("the most energy an impulse added: {:.3g} J", worst)); +} + +TEST_CASE("derail motion: a body running into another one doesn't go through it") { + SUBCASE("head on into the side of one standing across: it stops at it, pushes it, never through") { + auto const result{run_into(20.0, 0.5 * std::numbers::pi)}; + MESSAGE(std::format("at 20 m/s into the side of a coach: {:.2f} m in at most, {:.3f} m at rest, its front got to z {:.1f} (the side of the other at {:.1f}), the other pushed to z {:.1f}", result.most, result.resting, result.furthest + 0.5 * coach().length, 40.0 - 0.5 * coach().width, result.second.z)); + CHECK(result.most < 0.6); + CHECK(result.resting < 0.05); + // the first one stays behind the other one: its middle never gets past the other's + CHECK(result.furthest < result.second.z); + // the other one is pushed on + CHECK(result.second.z > 40.5); + } + SUBCASE("glancing off the end of one standing in line, offset: it goes past it, pushed aside, not into it") { + auto const result{run_into(15.0, 0.0, 2.0)}; + MESSAGE(std::format("at 15 m/s, 2 m aside, into the end of a coach: {:.2f} m in at most, {:.3f} m at rest; at rest {:.1f} m apart across", result.most, result.resting, std::abs(result.second.x - result.first.x))); + CHECK(result.resting < 0.05); + CHECK(result.most < 0.6); + } + SUBCASE("the same with steps of 0.01, 0.03 and 0.05 s") { + auto const fine{run_into(20.0, 0.5 * std::numbers::pi, 0.0, 0.01)}; + for (auto const dt : {0.03, 0.05}) { + CAPTURE(dt); + auto const coarse{run_into(20.0, 0.5 * std::numbers::pi, 0.0, dt)}; + CHECK(coarse.second.z == doctest::Approx(fine.second.z).epsilon(0.03)); + CHECK(coarse.first.z == doctest::Approx(fine.first.z).epsilon(0.03)); + CHECK(coarse.resting < 0.05); + } + } +} + +TEST_CASE("derail motion: two bodies folded past a right angle stay apart") { + // a coach turned 100 degrees off the next one, their ends together at the joint (in each other by a metre at the + // start), sliding on: they push apart within half a second, at rest not in each other + slider first; + auto start{leaving(10.0, dm::cause::end_of_track)}; + first.body.begin(start, coach(), ballast); + first.speed = 10.0; + slider second; + auto const angle{100.0 * degree}; + auto other{leaving(5.0, dm::cause::end_of_track)}; + // its front end at the rear end of the first one, folded to the left + glm::dvec3 const front{std::sin(angle), 0.0, std::cos(angle)}; + other.front = front; + other.position = glm::dvec3{0.0, 0.0, -0.5 * coach().length} - front * (0.5 * coach().length - 1.0); + second.body.begin(other, coach(), ballast); + second.speed = 5.0; + auto most{0.0}; + for (int step = 0; step < 2000; ++step) { // 20 s in steps of 0.01 s + auto const depth{touch(first, second)}; + if (step > 50) { // after half a second + most = std::max(most, depth); + } + slide_on(first, 0.01); + slide_on(second, 0.01); + } + auto const resting{touch(first, second)}; + MESSAGE(std::format("folded 100 degrees: {:.2f} m in at most after half a second, {:.3f} m at rest", most, resting)); + CHECK(resting < 0.05); + CHECK(most < 0.1); +} + +TEST_CASE("derail motion: a body hitting one on the rails from the side") { + // a coach off the track at 10 m/s into the side of one standing on the rails (along x): the one on the rails takes + // none of it along them, the first stops against it (bounces off), and the push across the rails is over what + // its wheels hold + dm::contact hit; + hit.normal = glm::dvec3{0.0, 0.0, 1.0}; + hit.point = glm::dvec3{0.0, 0.0, 0.0}; + hit.depth = 0.05; + dm::contact_body first{40e3, glm::dvec3{0.0, 0.0, -10.0}, glm::dvec3{0.0, 0.0, 10.0}, 0.0, 50.0}; + dm::contact_body second{40e3, glm::dvec3{0.0, 0.0, 1.4}, glm::dvec3{0.0}, 0.0, 50.0, true, glm::dvec3{1.0, 0.0, 0.0}}; + auto const impulse{dm::contact_impulse(hit, first, second)}; + auto const [velocity, yawrate]{dm::impulse_change(first, -impulse, hit.point)}; + auto const [othervelocity, otheryawrate]{dm::impulse_change(second, impulse, hit.point)}; + CHECK(glm::length(othervelocity) == doctest::Approx(0.0)); + CHECK(first.velocity.z + velocity.z == doctest::Approx(-10.0 * dm::contact_restitution)); + // the push across the rails over a frame of 0.05 s against the wheels of a coach of 40 t on 4 axles + auto const ratio{dm::pull_ratio(std::abs(impulse.z) / 0.05, 0.5 * std::numbers::pi, 40e3, 4)}; + MESSAGE(std::format("the hit across the rails at 10 m/s: Y/Q {:.1f}", ratio)); + CHECK(ratio > 3.0 * dr::climbing_limit); + // a hit at an angle along the rails pushes it along them + hit.normal = glm::normalize(glm::dvec3{1.0, 0.0, 1.0}); + first.velocity = glm::dvec3{10.0, 0.0, 10.0}; + auto const slanted{dm::contact_impulse(hit, first, second)}; + CHECK(dm::impulse_change(second, slanted, hit.point).first.x > 0.5); +} diff --git a/tests/unit/test_derailment.cpp b/tests/unit/test_derailment.cpp new file mode 100644 index 000000000..3afca6a26 --- /dev/null +++ b/tests/unit/test_derailment.cpp @@ -0,0 +1,345 @@ +#include "stdafx.h" +#include "doctest.h" +#include "McZapkie/derailment.h" + +#include +#include + +// the criteria of derailment (McZapkie/derailment.h): overturning by the lateral acceleration the cant doesn't +// balance, the flange climbing the rail by Nadal's Y/Q, either held over 2 m + +namespace dr = derailment; + +namespace { + +constexpr double kmh{1.0 / 3.6}; + +// the cant [rad] of the height of the outer rail [mm] on the standard gauge +double cant(double const Millimetres) { + return std::asin(Millimetres / 1000.0 / dr::contact_spacing(1.435)); +} + +// the centres of gravity the vehicles of data/fiz get without a CoGH of their own +// EU07 (4E): 80 t, a body 4.348 m high +double const eu07{dr::default_centre_of_gravity(4.348, dr::vehicle_class::powered)}; +// the 430W coal wagon: 20.5 t, a body 3.235 m high, 59.5 t of coal +double const coal_wagon{dr::default_centre_of_gravity(3.235, dr::vehicle_class::unpowered)}; +double const coal_wagon_loaded{dr::loaded_centre_of_gravity(coal_wagon, 20500.0, 59500.0, 1.0, 0.0, 3.235)}; + +} // namespace + +TEST_CASE("derailment: Nadal's limit of Y/Q") { + // 70 degrees of the flange: 1.34 with a friction of 0.3, 1.2 with 0.36, the limit the criterion takes + CHECK(dr::nadal_limit(dr::flange_angle, 0.3) == doctest::Approx(1.342).epsilon(0.001)); + CHECK(dr::nadal_limit(dr::flange_angle, 0.36) == doctest::Approx(dr::climbing_limit).epsilon(0.01)); + // a steeper flange holds more, a higher friction less + CHECK(dr::nadal_limit(dr::flange_angle + 0.05, 0.3) > dr::nadal_limit(dr::flange_angle, 0.3)); + CHECK(dr::nadal_limit(dr::flange_angle, 0.5) < dr::nadal_limit(dr::flange_angle, 0.3)); +} + +TEST_CASE("derailment: the centre of gravity") { + CHECK(eu07 == doctest::Approx(1.65).epsilon(0.01)); + CHECK(coal_wagon == doctest::Approx(1.13).epsilon(0.01)); + // the load raises it: a full coal wagon is near 2 m, the limit of the railways for a loaded wagon is 2 to 2.5 m + CHECK(coal_wagon_loaded == doctest::Approx(1.94).epsilon(0.01)); + CHECK(dr::loaded_centre_of_gravity(coal_wagon, 20500.0, 30000.0, 0.5, 0.0, 3.235) > coal_wagon); + CHECK(dr::loaded_centre_of_gravity(coal_wagon, 20500.0, 30000.0, 0.5, 0.0, 3.235) < coal_wagon_loaded); + CHECK(dr::loaded_centre_of_gravity(coal_wagon, 20500.0, 0.0, 0.0, 0.0, 3.235) == coal_wagon); + // a body height of 2 m or less is the floor, the older meaning of the key: a 4 m high body then + CHECK(dr::default_centre_of_gravity(1.2, dr::vehicle_class::unpowered) == doctest::Approx(1.4)); +} + +TEST_CASE("derailment: the overturning speed by the radius and the cant") { + struct expected { + char const *vehicle; + double centre; + double radius; + double cant; // mm + double speed; // km/h + }; + // EU07 overturns at 108 km/h in a 300 m curve without cant, as the legacy criterion had it near 112 km/h; at + // 119 km/h with a cant of 100 mm. a full coal wagon at 98 km/h, an empty one at 137 km/h + for (auto const &[name, centre, radius, height, speed] : { + expected{"EU07", eu07, 150.0, 0.0, 77.6}, + expected{"EU07", eu07, 300.0, 0.0, 107.8}, + expected{"EU07", eu07, 300.0, 100.0, 119.0}, + expected{"EU07", eu07, 600.0, 150.0, 175.8}, + expected{"430W empty", coal_wagon, 300.0, 0.0, 136.9}, + expected{"430W empty", coal_wagon, 300.0, 100.0, 145.9}, + expected{"430W loaded", coal_wagon_loaded, 300.0, 0.0, 97.5}, + expected{"430W loaded", coal_wagon_loaded, 300.0, 100.0, 109.6}, + expected{"430W loaded", coal_wagon_loaded, 1200.0, 150.0, 230.5}, + }) { + CAPTURE(name); + CAPTURE(radius); + CAPTURE(height); + CHECK(dr::overturning_speed(radius, cant(height), centre, 1.435) / kmh == doctest::Approx(speed).epsilon(0.002)); + } + // on the faster side of 100 km/h, where the vibration is all there: v^2 / R - g sin(cant) + 0.05 g = g s / 2 h' + auto const leaning{eu07 + 0.4 * (eu07 - 0.5)}; + auto const limit{dr::gravity * 1.5 / (2.0 * leaning)}; + CHECK(dr::overturning_acceleration(eu07, 1.5) == doctest::Approx(limit)); + auto const speed{std::sqrt((limit - dr::vibration + dr::gravity * std::sin(cant(100.0))) * 300.0)}; + CHECK(dr::overturning_speed(300.0, cant(100.0), eu07, 1.435) == doctest::Approx(speed).epsilon(0.001)); + // the legacy criterion, the lateral acceleration over g times the gauge to the height of the vehicle, without cant + auto const legacy{std::sqrt(dr::gravity * 1.435 / 4.348 * 300.0)}; + CHECK(dr::overturning_speed(300.0, 0.0, eu07, 1.435) == doctest::Approx(legacy).epsilon(0.05)); + // faster on a wider curve, as its square root + CHECK(dr::overturning_speed(1200.0, 0.0, eu07, 1.435) / dr::overturning_speed(300.0, 0.0, eu07, 1.435) == doctest::Approx(2.0).epsilon(0.001)); + // the cant only helps + CHECK(dr::overturning_speed(300.0, cant(150.0), eu07, 1.435) > dr::overturning_speed(300.0, cant(60.0), eu07, 1.435)); + // no overturning on a straight track + CHECK(dr::overturning_speed(0.0, 0.0, eu07, 1.435) == 0.0); +} + +TEST_CASE("derailment: below the balancing speed the cant leans the vehicle into the curve") { + // 100 mm on the 1.5 m between the contact points of the wheels + CHECK(dr::unbalanced_acceleration(0.0, 300.0, cant(100.0)) == doctest::Approx(-dr::gravity * 0.1 / 1.5)); + // at the balancing speed nothing's left + auto const balanced{std::sqrt(dr::gravity * 0.1 / 1.5 * 300.0)}; + CHECK(dr::unbalanced_acceleration(balanced, 300.0, cant(100.0)) == doctest::Approx(0.0).epsilon(1e-9)); + // the sign of the radius and of the cant doesn't matter + CHECK(dr::unbalanced_acceleration(30.0, -300.0, -cant(100.0)) == doctest::Approx(dr::unbalanced_acceleration(30.0, 300.0, cant(100.0)))); +} + +TEST_CASE("derailment: the decision and the place don't depend on the step") { + // EU07 runs at a steady speed into a 300 m curve without cant 100 m ahead, the track checked at the end of each step + dr::vehicle_state eu07vehicle; + eu07vehicle.mass = 80000.0; + eu07vehicle.axles = 4; + eu07vehicle.length = 15.915; + eu07vehicle.axle_base = 3.05; + eu07vehicle.centre_of_gravity = eu07; + auto const critical{dr::overturning_speed(300.0, 0.0, eu07, 1.435)}; + constexpr double curve{100.0}; + + // where the vehicle overturns, if it does within 400 m + auto const run = [&](double const Speed, double const Step) -> std::optional { + dr::monitor monitor; + dr::track_state track; + auto distance{0.0}; + while (distance < 400.0) { + auto const travelled{Speed * Step}; + distance += travelled; + track.radius = distance >= curve ? 300.0 : 0.0; + if (monitor.update(eu07vehicle, track, Speed, travelled).result == dr::outcome::overturned) { + return distance; + } + } + return std::nullopt; + }; + + for (auto const step : {0.01, 0.05, 0.5}) { + CAPTURE(step); + // 5 % too fast: overturns 2 m into the curve, give or take the step it got there in + auto const fast{run(1.05 * critical, step)}; + REQUIRE(fast.has_value()); + CHECK(*fast >= curve + dr::window - 1.05 * critical * step - 1e-6); + CHECK(*fast <= curve + dr::window + 1.05 * critical * step + 1e-6); + // 5 % below it: never + CHECK_FALSE(run(0.95 * critical, step).has_value()); + } + auto const fine{run(1.05 * critical, 0.01)}; + auto const coarse{run(1.05 * critical, 0.5)}; + REQUIRE(fine.has_value()); + REQUIRE(coarse.has_value()); + CHECK(std::abs(coarse.value() - fine.value()) <= 1.05 * critical * 0.5); +} + +TEST_CASE("derailment: a peak shorter than the window doesn't derail") { + dr::stretch stretch; + CHECK_FALSE(stretch.update(true, 1.5)); + CHECK_FALSE(stretch.update(false, 0.5)); + CHECK_FALSE(stretch.update(true, 1.5)); + CHECK(stretch.update(true, 0.5)); + CHECK(stretch.distance() == doctest::Approx(2.0)); +} + +TEST_CASE("derailment: a vehicle without a mass never derails") { + // a definition without M (or with all of it in the rotating masses) gives no forces, not a lifted wheel + dr::vehicle_state massless; + massless.mass = 0.0; + dr::track_state track; + track.radius = 150.0; + CHECK(dr::flange_forces(massless, track, 30.0).ratio() == 0.0); + dr::monitor monitor; + for (int step = 0; step < 10; ++step) { + CHECK(monitor.update(massless, track, 30.0, 1.0).result == dr::outcome::none); + } +} + +TEST_CASE("derailment: pushing a light wagon between heavy vehicles in a curve") { + // the empty 3WL (10.5 t, 2 axles 6 m apart, 9.87 m long) between two EU07 in a 150 m curve: the more the train + // pushes, the more the couplings push the wagon out of the curve, the higher its Y/Q + dr::vehicle_state wagon; + wagon.mass = 10500.0; + wagon.axles = 2; + wagon.length = 9.87; + wagon.axle_base = 6.0; + wagon.centre_of_gravity = dr::default_centre_of_gravity(3.0, dr::vehicle_class::unpowered); + dr::track_state track; + track.radius = 150.0; + auto const speed{20.0 * kmh}; + + auto const ratio = [&](dr::vehicle_state Vehicle, double const Compression) { + for (auto &end : Vehicle.ends) { + end.compression = Compression; + end.other_length = 15.915; + } + return dr::flange_forces(Vehicle, track, speed).ratio(); + }; + auto previous{ratio(wagon, 0.0)}; + // the leading axle guides the wagon with the friction of its inner wheel: over 0.3 even unpushed + CHECK(previous > dr::tread_friction); + CHECK(previous < 0.4); + for (auto const compression : {100e3, 300e3, 600e3, 1000e3}) { + CAPTURE(compression); + auto const pushed{ratio(wagon, compression)}; + CHECK(pushed > previous); + previous = pushed; + } + // a loaded 430W in its place is pushed out less + dr::vehicle_state loaded; + loaded.mass = 80000.0; + loaded.axles = 4; + loaded.length = 14.028; + loaded.axle_base = 2.0; + loaded.centre_of_gravity = coal_wagon_loaded; + CHECK(ratio(loaded, 600e3) < ratio(wagon, 600e3)); + // pulled, the couplings draw the wagon into the curve: the flange of the inner wheel then + auto pulled{wagon}; + for (auto &end : pulled.ends) { + end.compression = -600e3; + end.other_length = 15.915; + } + CHECK(dr::flange_forces(pulled, track, speed).lateral < 0.0); + // on a twisted track the wheel is lighter, so the same push comes nearer the limit + auto const twisted{[&] { + auto const flat{ratio(wagon, 600e3)}; + track.uneven_cross = 30.0; + auto const result{ratio(wagon, 600e3)}; + track.uneven_cross = 0.0; + return result > flat; + }()}; + CHECK(twisted); + // on a bent rail, with a twist of 50 mm, the wagon pushed with 300 kN climbs the rail over 2 m, without falling over + track.damage = dr::track_damage::railbend; + track.uneven_cross = 50.0; + dr::monitor monitor; + auto pushed{wagon}; + for (auto &end : pushed.ends) { + end.compression = 300e3; + end.other_length = 15.915; + } + CHECK(monitor.update(pushed, track, speed, 1.0).result == dr::outcome::none); + auto const verdict{monitor.update(pushed, track, speed, 1.0)}; + CAPTURE(verdict.flange_ratio); + CAPTURE(verdict.unloading); + CHECK(verdict.unloading < 1.0); + CHECK(verdict.result == dr::outcome::off_rails); +} + +TEST_CASE("derailment: the damage flags of the track make the ride rougher, not the curve sharper") { + // line 107 has damage 31 on every track, for the jolts. a 401Ka wagon creeping at 28 km/h through a 282 m curve + // with a cant of 179 mm, pulled by a freight train, stays on: in the 2026-11-15 run with the flags scaling the + // whole lateral acceleration it overturned into the curve + dr::vehicle_state wagon; + wagon.mass = 23000.0; + wagon.axles = 4; + wagon.length = 14.7; + wagon.axle_base = 1.8; + wagon.centre_of_gravity = dr::default_centre_of_gravity(4.2, dr::vehicle_class::unpowered); + for (auto &end : wagon.ends) { + end.compression = -200e3; + end.other_length = 14.7; + } + dr::track_state track; + track.radius = 282.0; + track.cant = std::asin(0.179 / 1.5); + auto const speed{28.0 * kmh}; + auto const smooth{dr::body_acceleration(wagon, track, speed)}; + track.damage = 31; + auto const rough{dr::body_acceleration(wagon, track, speed)}; + // the sway grows, by what a rough track adds to the sway at that speed + CHECK(rough > smooth); + CHECK(rough - smooth == doctest::Approx(1.1 * dr::body_vibration(speed))); + CHECK(dr::unloading_ratio(rough, wagon.centre_of_gravity, 1.5) < 0.5); + CHECK(dr::flange_forces(wagon, track, speed).ratio() < 0.8); + // at speed the rough track still lowers the overturning speed some, as the legacy criterion's factor did + { + dr::vehicle_state eu07vehicle; + eu07vehicle.mass = 80000.0; + eu07vehicle.centre_of_gravity = eu07; + dr::track_state good; + good.radius = 300.0; + auto worn{good}; + worn.damage = 31; + CHECK(dr::body_acceleration(eu07vehicle, worn, 30.0) > dr::body_acceleration(eu07vehicle, good, 30.0)); + CHECK(dr::body_acceleration(eu07vehicle, worn, 30.0) - dr::body_acceleration(eu07vehicle, good, 30.0) == doctest::Approx(1.1 * dr::vibration)); + } +} + +TEST_CASE("derailment: the speed the flange climbs the rail at") { + dr::vehicle_state vehicle; + vehicle.mass = 80000.0; + vehicle.axles = 4; + vehicle.length = 16.0; + vehicle.axle_base = 3.0; + vehicle.centre_of_gravity = 1.65; + dr::track_state track; + track.radius = 300.0; + SUBCASE("a lone vehicle on a good track overturns first: its Y/Q stays under the limit") { + CHECK_FALSE(dr::climbing_speed(vehicle, track).has_value()); + } + SUBCASE("on a twisted track it climbs, at the speed Y/Q reaches the limit") { + // 50 mm of cross level takes half the load off the wheel + track.uneven_cross = 50.0; + auto const speed{dr::climbing_speed(vehicle, track)}; + REQUIRE(speed.has_value()); + CHECK(*speed > 0.0); + CHECK(dr::flange_forces(vehicle, track, *speed).ratio() >= dr::climbing_limit); + CHECK(dr::flange_forces(vehicle, track, *speed - 0.01).ratio() < dr::climbing_limit); + SUBCASE("the cant moves it up") { + track.cant = std::asin(0.1 / 1.5); + auto const canted{dr::climbing_speed(vehicle, track)}; + REQUIRE(canted.has_value()); + CHECK(*canted > *speed); + } + } + SUBCASE("pushed hard enough it climbs at a standstill: from the speed the cant balances") { + // an empty 3WL between heavy vehicles pushing 1 MN in a curve of 150 m, on 40 mm of cross level + vehicle.mass = 10500.0; + vehicle.axles = 2; + vehicle.length = 9.0; + vehicle.axle_base = 5.0; + vehicle.centre_of_gravity = 1.1; + vehicle.ends[0] = {1000000.0, 16.0}; + vehicle.ends[1] = {1000000.0, 16.0}; + track.radius = 150.0; + track.uneven_cross = 40.0; + auto const speed{dr::climbing_speed(vehicle, track)}; + REQUIRE(speed.has_value()); + CHECK(*speed == 0.0); + } +} + +TEST_CASE("derailment: the report of the log") { + dr::verdict verdict; + verdict.result = dr::outcome::overturned; + verdict.acceleration = 3.31; + verdict.unloading = 1.02; + verdict.flange_ratio = 0.55; + dr::vehicle_state vehicle; + vehicle.mass = 80000.0; + vehicle.centre_of_gravity = 1.65; + vehicle.ends[1].compression = 50000.0; + dr::track_state track; + track.radius = -300.0; + track.damage = 31; + auto const text{dr::report(verdict, vehicle, track, 113.0 / 3.6, "track_7")}; + CHECK(text == + "overturned at 113 km/h on track track_7, curve radius 300 m, cant 0 mm: lateral acceleration 3.31 m/s2, wheel unloading 1.02, Y/Q 0.55 (mass 80.0 t, centre of gravity 1.65 m," + " couplings pushing 0 / 50 kN, track damage 31, cross level 0 mm)"); + verdict.result = dr::outcome::off_rails; + CHECK(dr::report(verdict, vehicle, track, 20.0, "").starts_with("derailed, the flange climbed the rail at 72 km/h on track (none),")); +} diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp new file mode 100644 index 000000000..99b6c0417 --- /dev/null +++ b/tests/unit/test_derailment_vehicle.cpp @@ -0,0 +1,328 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "McZapkie/derailment.h" +#include "McZapkie/MOVER.h" +#include "utilities/Globals.h" + +#include + +// a vehicle too fast in a curve with physics.derailment of eu07.ini: the criteria of McZapkie/derailment.h checked by +// TMoverParameters::check_derailment(), and what the vehicle comes to off the rails + +using test::definition; +using test::vehicle; +namespace dr = derailment; + +namespace { + +constexpr double kmh{1.0 / 3.6}; + +// the given model of derailment for the test, restored after it +class model_setting { +public: + explicit model_setting(global_settings::derailment_model Model) : m_previous{Global.derailment} { Global.derailment = Model; } + ~model_setting() { Global.derailment = m_previous; } + model_setting(model_setting const &) = delete; + model_setting &operator=(model_setting const &) = delete; + +private: + global_settings::derailment_model m_previous; +}; + +// the centres of gravity of EU07 (4E) and of the 430W coal wagon of data/fiz, without a CoGH of their own +double const eu07{dr::default_centre_of_gravity(4.348, dr::vehicle_class::powered)}; +double const coal_wagon{dr::default_centre_of_gravity(3.235, dr::vehicle_class::unpowered)}; + +} // namespace + +TEST_CASE("derailment: a vehicle too fast in a curve") { + model_setting const physical{global_settings::derailment_model::physical}; + test::track curve; + curve.radius = 300.0; + auto const critical{dr::overturning_speed(300.0, 0.0, eu07, 1.435) / kmh}; + + SUBCASE("below the overturning speed it runs on") { + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical - 5.0}; + for (int step = 0; step < 300; ++step) { + eu07vehicle.step(curve); + } + CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + CHECK(eu07vehicle->Derailed == dr::outcome::none); + } + SUBCASE("over it, it falls over and slides to a stop on its side") { + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical + 5.0}; + CHECK(eu07vehicle->centre_of_gravity() == doctest::Approx(eu07)); + // 2 m at 113 km/h is 0.07 s + for (int step = 0; step < 10; ++step) { + eu07vehicle.step(curve); + } + REQUIRE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + CHECK(eu07vehicle->Derailed == dr::outcome::overturned); + CHECK_FALSE(eu07vehicle->Mains); + // not stopped dead as the legacy model has it: it slows down at half of g on the 80 of its 96 t + auto const start{eu07vehicle->V}; + CHECK(start > 0.95 * (critical + 5.0) * kmh); + for (int step = 0; step < 100; ++step) { + eu07vehicle.step(curve); + } + auto const deceleration{(start - eu07vehicle->V) / 1.0}; + CHECK(deceleration == doctest::Approx(0.5 * dr::gravity * 80.0 / 96.0).epsilon(0.05)); + for (int step = 0; step < 2000; ++step) { + eu07vehicle.step(curve); + } + CHECK(eu07vehicle->V == doctest::Approx(0.0)); + } + SUBCASE("a higher centre of gravity of its definition overturns it slower") { + vehicle high{definition::fiz("4e_v1/4e").set("Dimensions", "CoGH", 2.2), critical - 5.0}; + CHECK(high->centre_of_gravity() == doctest::Approx(2.2)); + for (int step = 0; step < 50; ++step) { + high.step(curve); + } + CHECK(high->Derailed == dr::outcome::overturned); + } + SUBCASE("the same with steps of 0.01 and 0.05 s") { + for (auto const dt : {0.01, 0.05}) { + CAPTURE(dt); + auto const steps{static_cast(std::lround(1.0 / dt))}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical + 2.0}; + for (auto step = 0; step < steps; ++step) { + eu07vehicle.step(curve, dt); + } + CHECK(eu07vehicle->Derailed == dr::outcome::overturned); + vehicle slower{definition::fiz("4e_v1/4e"), critical - 2.0}; + for (auto step = 0; step < steps; ++step) { + slower.step(curve, dt); + } + CHECK(slower->Derailed == dr::outcome::none); + } + } + SUBCASE("a load raises the centre of gravity") { + vehicle wagon{definition::fiz("430w_v2/430w")}; + auto const empty{wagon->centre_of_gravity()}; + CHECK(empty == doctest::Approx(coal_wagon)); + wagon->AssignLoad("coal", 59.5f); + wagon->ComputeMass(); + CHECK(wagon->centre_of_gravity() > empty + 0.5); + } +} + +TEST_CASE("derailment: the model of eu07.ini") { + test::track curve; + curve.radius = 300.0; + SUBCASE("off: no derailment at any speed") { + model_setting const off{global_settings::derailment_model::off}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 160.0}; + for (int step = 0; step < 300; ++step) { + eu07vehicle.step(curve); + } + CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + } + SUBCASE("old: the legacy draw stops the vehicle dead") { + model_setting const old{global_settings::derailment_model::old}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 160.0}; + for (int step = 0; step < 600; ++step) { + eu07vehicle.step(curve); + } + // far over its threshold the draw comes out at once + CHECK(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + CHECK(eu07vehicle->Derailed == dr::outcome::none); + CHECK(eu07vehicle->V == doctest::Approx(0.0).epsilon(0.01)); + } +} + +TEST_CASE("derailment: the brake hoses tear") { + model_setting const physical{global_settings::derailment_model::physical}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 150.0}; + eu07vehicle->Couplers[end::rear].CouplingFlag = coupling::coupler | coupling::brakehose; + test::track curve; + curve.radius = 300.0; + for (int step = 0; step < 20; ++step) { + eu07vehicle.step(curve); + } + REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned); + CHECK(eu07vehicle->AlarmChainFlag); +} + +TEST_CASE("derailment: a stopped derailed vehicle stays put on a gradient") { + // the friction of the ballast holds it, rather than the vehicle creeping and stopping in turn in every step, which + // kept the physics of its whole train awake (the run of line 107 went at half the speed after a derailment) + model_setting const physical{global_settings::derailment_model::physical}; + test::track curve; + curve.radius = 300.0; + curve.gradient = 0.01; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 150.0}; + for (int step = 0; step < 2000; ++step) { + eu07vehicle.step(curve); + } + REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned); + REQUIRE(eu07vehicle->V == 0.0); + auto still{true}; + for (int step = 0; step < 500; ++step) { + eu07vehicle.step(curve); + still = still && eu07vehicle->V == 0.0 && eu07vehicle->AccS == 0.0; + } + CHECK(still); +} + +TEST_CASE("derailment: a repaired vehicle is back on the rails") { + // resetconsist (the debug panel's "Stop and repair consist") clears the damage flags; the state of the criteria + // has to go with them, or a vehicle once derailed by the criteria slides on with their friction after a later + // derailment of any other kind, and the friction of the ballast keeps holding it once it stops + model_setting const physical{global_settings::derailment_model::physical}; + test::track curve; + curve.radius = 300.0; + curve.gradient = 0.02; + vehicle repaired{definition::fiz("4e_v1/4e"), 150.0}; + for (int step = 0; step < 2000; ++step) { + repaired.step(curve); + } + REQUIRE(repaired->Derailed == dr::outcome::overturned); + REQUIRE(repaired->V == 0.0); + repaired->repair_damage(); + CHECK(repaired->DamageFlag == 0); + CHECK(repaired->Derailed == dr::outcome::none); + CHECK(repaired->derailment_distance == 0.0); + CHECK(repaired->OffsetTrackH == 0.0); + CHECK(repaired->OffsetTrackV == 0.0); + + SUBCASE("a derailment of the legacy kind stops it dead, as one never derailed") { + test::track straight; + vehicle fresh{definition::fiz("4e_v1/4e"), 60.0}; + repaired->V = fresh->V; + repaired->AccS = 0.0; + repaired->Derail(TOO_HIGH_SPEED); + fresh->Derail(TOO_HIGH_SPEED); + REQUIRE(repaired->Derailed == dr::outcome::none); + auto const start{fresh->V}; + REQUIRE(start > 10.0); + for (int step = 0; step < 150; ++step) { + repaired.step(straight); + fresh.step(straight); + } + // the legacy model takes g off a derailed vehicle and holds it with a friction 1e20 times its own: 1.1 s from + // 39 km/h. with the friction of the overturned one (half of g on 80 of 96 t) it would still go at 23 km/h + CHECK(fresh->V == doctest::Approx(0.0).epsilon(0.01)); + CHECK(repaired->V == doctest::Approx(fresh->V).epsilon(0.01)); + } + SUBCASE("the friction of the ballast doesn't hold it any more") { + // unbraked on the gradient of 20 per mille it rolls away, at g / 50 less the running resistance + test::track straight; + straight.gradient = 0.02; + for (int step = 0; step < 300; ++step) { + repaired.step(straight); + } + CHECK(std::abs(repaired->V) > 0.4); + CHECK(std::abs(repaired->V) < 3.0 * 0.02 * dr::gravity); + } + SUBCASE("too fast in a curve again it derails again, by the criteria") { + repaired->V = 150.0 * kmh; + curve.gradient = 0.0; + for (int step = 0; step < 20; ++step) { + repaired.step(curve); + } + CHECK(repaired->Derailed == dr::outcome::overturned); + } +} + +TEST_CASE("derailment: SetDamage taking the derailment off puts the vehicle back on the rails") { + model_setting const physical{global_settings::derailment_model::physical}; + test::track curve; + curve.radius = 300.0; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 150.0}; + for (int step = 0; step < 20; ++step) { + eu07vehicle.step(curve); + } + REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned); + // another flag taken off leaves it derailed + eu07vehicle->RunCommand("SetDamage", dtrain_engine, 1); + eu07vehicle->RunCommand("SetDamage", dtrain_engine, -1); + CHECK(eu07vehicle->Derailed == dr::outcome::overturned); + CHECK(eu07vehicle->RunCommand("SetDamage", dtrain_out, -1)); + CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + CHECK(eu07vehicle->Derailed == dr::outcome::none); +} + +TEST_CASE("derailment: monitor tells again on the same track after a repair") { + model_setting const monitor{global_settings::derailment_model::monitor}; + test::track curve; + curve.radius = 300.0; + curve.name = "curve_1"; + auto const critical{dr::overturning_speed(300.0, 0.0, eu07, 1.435) / kmh}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical + 2.0}; + for (int step = 0; step < 100; ++step) { + eu07vehicle.step(curve); + } + REQUIRE(eu07vehicle->derailment_reports == 1); + eu07vehicle->repair_damage(); + CHECK_FALSE(eu07vehicle->derailment_reported.has_value()); + for (int step = 0; step < 100; ++step) { + eu07vehicle.step(curve); + } + CHECK(eu07vehicle->derailment_reports == 2); +} + +TEST_CASE("derailment: monitor, the legacy draw decides and the log tells what the criteria would do") { + model_setting const monitor{global_settings::derailment_model::monitor}; + test::track curve; + curve.radius = 300.0; + curve.name = "curve_1"; + auto const critical{dr::overturning_speed(300.0, 0.0, eu07, 1.435) / kmh}; + // over the speed the criteria overturn the EU07 at, under the threshold of the legacy draw (112 km/h) + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical + 2.0}; + REQUIRE(critical + 2.0 < 112.0); + for (int step = 0; step < 100; ++step) { + eu07vehicle.step(curve); + } + CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + CHECK(eu07vehicle->Derailed == dr::outcome::none); + // once on a track, however long it stays over the criteria + CHECK(eu07vehicle->derailment_reports == 1); + REQUIRE(eu07vehicle->derailment_reported.has_value()); + CHECK(*eu07vehicle->derailment_reported == &curve.name); + // and once more on the next one + test::track next{curve}; + next.name = "curve_2"; + for (int step = 0; step < 100; ++step) { + eu07vehicle.step(next); + } + CHECK(eu07vehicle->derailment_reports == 2); + CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + + SUBCASE("under the criteria nothing is told") { + vehicle slower{definition::fiz("4e_v1/4e"), critical - 5.0}; + for (int step = 0; step < 100; ++step) { + slower.step(curve); + } + CHECK(slower->derailment_reports == 0); + } + SUBCASE("far over the legacy threshold the legacy draw derails it, the legacy way") { + vehicle faster{definition::fiz("4e_v1/4e"), 160.0}; + for (int step = 0; step < 600; ++step) { + faster.step(curve); + } + CHECK(TestFlag(faster->DamageFlag, dtrain_out)); + CHECK(faster->Derailed == dr::outcome::none); + CHECK(faster->V == doctest::Approx(0.0).epsilon(0.01)); + } +} + +TEST_CASE("derailment: the names of the models in eu07.ini") { + using model = global_settings::derailment_model; + CHECK(derailment_model_of("new") == model::physical); + CHECK(derailment_model_of("old") == model::old); + CHECK(derailment_model_of("off") == model::off); + CHECK(derailment_model_of("no") == model::off); + CHECK(derailment_model_of("monitor") == model::monitor); + // a name it doesn't know is the default: monitor, the legacy draw decides and the criteria go to the log, until the + // speed limits of the bundled sceneries are checked against them + CHECK(derailment_model_of("physical") == model::monitor); + CHECK(derailment_model_of("") == model::monitor); + CHECK(global_settings{}.derailment == model::monitor); + CHECK_FALSE(global_settings{}.track_check); + // written back the way it's read + for (auto const value : {model::off, model::old, model::physical, model::monitor}) { + CHECK(derailment_model_of(name_of(value)) == value); + } + CHECK(name_of(model::physical) == "new"); +} diff --git a/tests/unit/test_door_wings.cpp b/tests/unit/test_door_wings.cpp index 290260f6a..9eff62441 100644 --- a/tests/unit/test_door_wings.cpp +++ b/tests/unit/test_door_wings.cpp @@ -2,6 +2,7 @@ #include "doctest.h" #include "vehicle/doorwings.h" +#include "utilities/parser.h" // the poses of the animated door wings (eu07/maszyna#512): a wing of the main model and its namesake in the low // poly interior get the same pose, worked out once from the door position of the mover @@ -52,3 +53,155 @@ TEST_CASE("door wings: a folding wing turns one way and its larger wing twice as CHECK(closed.larger == 0.f); CHECK(closed.step == 0.f); } + +// a wing with its own kind of animation (eu07/maszyna#70): animdoor: in the .mmd, for vehicles whose doors on one side +// aren't all alike, e.g. 111Ainw with folding doors at one end and wider ones at the other + +namespace { + +// the spec of the .fiz the entries start from: folding doors which turn by 80 degrees +door_wings::wing_spec const fizdoors{0, door_wings::fold_type, 80.f, 0.f}; + +// reads the entry after animdoor: from the text, starting from the spec of the .fiz +std::string read(std::string const &Entry, door_wings::wing_spec &Spec) { + Spec = fizdoors; + cParser parser(Entry, cParser::buffer_TEXT); + return door_wings::read_spec(parser, Spec); +} + +} // namespace + +TEST_CASE("door wings: the kinds of animation are named as DoorOpenMethod of the .fiz") { + CHECK(door_wings::type_from_name("Shift") == door_wings::shift_type); + CHECK(door_wings::type_from_name("Rotate") == door_wings::rotate_type); + CHECK(door_wings::type_from_name("Fold") == door_wings::fold_type); + CHECK(door_wings::type_from_name("Plug") == door_wings::plug_type); + // in any letter case + CHECK(door_wings::type_from_name("plug") == door_wings::plug_type); + CHECK(door_wings::type_from_name("SHIFT") == door_wings::shift_type); + // the same numbers as TMoverParameters::door_data::type + CHECK(door_wings::shift_type == 1); + CHECK(door_wings::rotate_type == 2); + CHECK(door_wings::fold_type == 3); + CHECK(door_wings::plug_type == 4); + CHECK_FALSE(door_wings::type_from_name("Roll").has_value()); + CHECK_FALSE(door_wings::type_from_name("").has_value()); +} + +TEST_CASE("door wings: an animdoor entry gives the wing its own kind, range and plug shift") { + door_wings::wing_spec spec; + CHECK(read("3 { type: Plug range: 0.9 rangeout: 0.06 } endmodels", spec).empty()); + CHECK(spec.number == 3); + CHECK(spec.type == door_wings::plug_type); + CHECK(spec.range == doctest::Approx(0.9f)); + CHECK(spec.range_out == doctest::Approx(0.06f)); +} + +TEST_CASE("door wings: the keys an animdoor entry leaves out keep the values of the .fiz") { + door_wings::wing_spec spec; + SUBCASE("only the kind") { + CHECK(read("2 { type: Rotate }", spec).empty()); + CHECK(spec.number == 2); + CHECK(spec.type == door_wings::rotate_type); + CHECK(spec.range == 80.f); + CHECK(spec.range_out == 0.f); + } + SUBCASE("only the range, keys in any letter case and order") { + CHECK(read("1 { Range: -95 }", spec).empty()); + CHECK(spec.type == door_wings::fold_type); + CHECK(spec.range == -95.f); + } + SUBCASE("nothing") { + CHECK(read("4 { }", spec).empty()); + CHECK(spec.number == 4); + CHECK(spec.type == fizdoors.type); + CHECK(spec.range == fizdoors.range); + } +} + +TEST_CASE("door wings: a faulty animdoor entry says what is wrong with it") { + door_wings::wing_spec spec; + CHECK(read("3 type: Shift range: 0.65", spec) == "no { after the wing number"); + CHECK(read("3 { type: Roll range: 0.65 }", spec) == "unknown door type \"Roll\""); + CHECK(read("3 { type: Shift range: 0,65 }", spec) == "bad number \"0,65\" for \"range:\""); + CHECK(read("3 { type: Shift range: wide }", spec) == "bad number \"wide\" for \"range:\""); + CHECK(read("3 { kind: Shift }", spec) == "no } after the keys, \"kind:\" is none of them"); + CHECK(read("3 { type: Shift range: }", spec) == "no value for \"range:\""); + CHECK(read("3 { type: Shift range: 0.65", spec) == "no } after the keys"); +} + +TEST_CASE("door wings: an animdoor entry without its } leaves the entries after it to the .mmd") { + // the first token that is neither a key nor the value of one ends the entry, and is read next by the caller + auto const next{[](std::string const &Text) { + door_wings::wing_spec spec{fizdoors}; + cParser parser(Text, cParser::buffer_TEXT); + auto const error{door_wings::read_spec(parser, spec)}; + std::vector rest; + std::string token; + do { + token.clear(); + parser.getTokens(1, false); + parser >> token; + if (false == token.empty()) { + rest.emplace_back(token); + } + } while (false == token.empty()); + return std::pair{error, rest}; + }}; + { + auto const [error, rest]{next("3 { type: Plug range: 0.9\nsounds: horn.wav\nlights: 1\nendmodels")}; + CHECK(error == "no } after the keys, \"sounds:\" is none of them"); + CHECK(rest == std::vector{"sounds:", "horn.wav", "lights:", "1", "endmodels"}); + } + { + auto const [error, rest]{next("3 { type: Plug range: endmodels")}; + CHECK(error == "no } after the keys, \"endmodels\" is none of them"); + CHECK(rest == std::vector{"endmodels"}); + } + { + // a whole entry leaves the rest as it is + auto const [error, rest]{next("3 { type: Plug range: 0.9 } sounds: horn.wav endmodels")}; + CHECK(error.empty()); + CHECK(rest == std::vector{"sounds:", "horn.wav", "endmodels"}); + } +} + +TEST_CASE("door wings: the parsed keys go into the spec, pairs of a key and its value") { + door_wings::wing_spec spec{fizdoors}; + CHECK(door_wings::parse_spec({"type:", "Shift", "range:", "0.65"}, spec).empty()); + CHECK(spec.type == door_wings::shift_type); + CHECK(spec.range == doctest::Approx(0.65f)); + CHECK(door_wings::parse_spec({"rangeout:"}, spec) == "no value for \"rangeout:\""); + CHECK(door_wings::parse_spec({}, spec).empty()); +} + +TEST_CASE("door wings: only the wings with an entry animate in their own way, the latest entry counts") { + std::vector specs; + CHECK(door_wings::find(specs, 1) == nullptr); + door_wings::store(specs, {3, door_wings::shift_type, 0.65f, 0.f}); + door_wings::store(specs, {4, door_wings::shift_type, 0.65f, 0.f}); + door_wings::store(specs, {3, door_wings::plug_type, 0.9f, 0.06f}); + CHECK(specs.size() == 2); + CHECK(door_wings::find(specs, 1) == nullptr); + CHECK(door_wings::find(specs, 2) == nullptr); + REQUIRE(door_wings::find(specs, 3) != nullptr); + CHECK(door_wings::find(specs, 3)->type == door_wings::plug_type); + CHECK(door_wings::find(specs, 3)->range == 0.9f); + REQUIRE(door_wings::find(specs, 4) != nullptr); + CHECK(door_wings::find(specs, 4)->type == door_wings::shift_type); +} + +TEST_CASE("door wings: a wing with its own range is as far along it as the door of its side") { + // folding doors of the .fiz turn by 80 degrees; the wide wing slides by 0.9 m + CHECK(door_wings::wing_position(0.f, 80.f, 0.9f) == 0.f); + CHECK(door_wings::wing_position(40.f, 80.f, 0.9f) == doctest::Approx(0.45f)); + CHECK(door_wings::wing_position(80.f, 80.f, 0.9f) == doctest::Approx(0.9f)); + // a wing turning the other way + CHECK(door_wings::wing_position(20.f, 80.f, -100.f) == doctest::Approx(-25.f)); + // no doors in the .fiz: the wing stays closed + CHECK(door_wings::wing_position(0.f, 0.f, 0.9f) == 0.f); + // the pose of the plug wing at the end of its range + auto const open{door_wings::plug(door_wings::wing_position(80.f, 80.f, 0.9f), 0.06f)}; + CHECK(open.x == doctest::Approx(0.06f)); + CHECK(open.z == doctest::Approx(0.87f)); +} diff --git a/tests/unit/test_drivingaid.cpp b/tests/unit/test_drivingaid.cpp new file mode 100644 index 000000000..b6ae1cc9d --- /dev/null +++ b/tests/unit/test_drivingaid.cpp @@ -0,0 +1,176 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "real_vehicles.h" + +#include "vehicle/drivingaid.h" +#include "McZapkie/hamulce.h" + +#include +#include +#include + +// the numbers of the driving aid panel's throttle and brakes lines: the ED braking shows (eu07/maszyna#558) and +// the local brake is left out where the cab has no control of it (eu07/maszyna#555) + +using test::definition; +using test::vehicle; + +namespace { + +// the cab controls of the vehicles here, as their cab definitions (.mmd) have them: the Vectron has a local brake +// lever and a joint controller whose braking range is its ED lever, the Traxx and the EU07 a local brake lever, +// the SM42 a joint controller whose braking range is the local brake, none of the 45 Elf cabs either of them +constexpr drivingaid::cab_controls vectron_cab{true, true}; +constexpr drivingaid::cab_controls lever_cab{true, false}; +constexpr drivingaid::cab_controls jointctrl_cab{false, true}; +constexpr drivingaid::cab_controls elf_cab{false, false}; + +drivingaid::readout read(vehicle &Vehicle, drivingaid::cab_controls const &Cab) { + return drivingaid::compute(drivingaid::from_movers(Vehicle.mover(), Vehicle.mover(), Cab)); +} + +// what the panel showed before: the throttle and brakes numbers, and the local brake always +drivingaid::readout before(TMoverParameters const &Mover) { + drivingaid::readout result; + result.throttle_first = Mover.EIMCtrlType > 0 ? std::max(0, static_cast(100.4 * Mover.eimic_real)) : Mover.MainCtrlPos; + result.throttle_second = Mover.EIMCtrlType > 0 ? Mover.MainCtrlPos : Mover.ScndCtrlPos; + result.brake_first = Mover.UniCtrlIntegratedBrakeCtrl ? std::max(0.0, -100.0 * Mover.eimic_real) : Mover.fBrakeCtrlPos; + result.local_brake = Mover.LocalBrakePosA * LocalBrakePosNo; + return result; +} + +test::track const line{0.15, 0.0, test::catenary_3kv}; + +} // namespace + +TEST_CASE("driving aid: the Vectron's ED lever shows as a negative throttle step, and its ED braking") { + vehicle vectron{definition::fiz("vectron_v1/wariant_7w"), 80.0 /* km/h */, "vectron", 1}; + REQUIRE(vectron->SplitEDPneumaticBrake); + REQUIRE(vectron->DynamicBrakeCtrlPosNo == 15); + REQUIRE(vectron->EIMCtrlType == 0); + + // lever at zero: the master controller, as before, and no ED braking + auto const idle{read(vectron, vectron_cab)}; + CHECK(idle.throttle_first == vectron->MainCtrlPos); + CHECK_FALSE(idle.ed_percent.has_value()); + CHECK(idle.show_local_brake); + + // six steps of the ED lever, as the cab's joint controller shows them + for (int step = 0; step < 6; ++step) { + REQUIRE(vectron->IncDynamicBrakeLevel(1.f)); + } + vectron.run(1.0, line); + REQUIRE(vectron->Vel > 15.0); // above Vh1, where the ED brake has its full demand + auto const braking{read(vectron, vectron_cab)}; + CHECK(braking.throttle_first == -6); + REQUIRE(vectron->eimic_real == doctest::Approx(-0.4)); + REQUIRE(braking.ed_percent.has_value()); + CHECK(*braking.ed_percent == 40); + // the train brake handle and the local brake, as before + CHECK(braking.brake_first == doctest::Approx(vectron->fBrakeCtrlPos)); + CHECK(braking.show_local_brake); + CHECK(braking.local_brake == doctest::Approx(0.0)); + + // the joint controller's braking range is the ED lever, so it isn't a local brake control + CHECK_FALSE(read(vectron, jointctrl_cab).show_local_brake); +} + +TEST_CASE("driving aid: the Traxx's ED braking from its master controller") { + vehicle traxx{definition::fiz("e186_v2/eu47"), 80.0 /* km/h */, "traxx", 1}; + REQUIRE(traxx->EIMCtrlType == 1); + REQUIRE_FALSE(traxx->SplitEDPneumaticBrake); + + CHECK_FALSE(read(traxx, lever_cab).ed_percent.has_value()); + // B+: the braking demand ramps towards full + traxx->MainCtrlPos = 0; + traxx.run(3.0, line); + REQUIRE(traxx->eimic_real < -0.2); + auto const braking{read(traxx, lever_cab)}; + REQUIRE(braking.ed_percent.has_value()); + CHECK(*braking.ed_percent == std::lround(-100.0 * traxx->eimic_real)); + // the drive demand stays at zero while braking, with the controller position next to it, as before + CHECK(braking.throttle_first == 0); + CHECK(braking.throttle_second == 0); + CHECK(braking.show_local_brake); +} + +TEST_CASE("driving aid: the Elf leaves out the local brake it has no control of, and shows its ED braking") { + vehicle elf{definition::fiz("elf_v1/21we-a"), 60.0 /* km/h */, "elf", 1}; + REQUIRE(elf->EIMCtrlType == 2); + // the definition has a local brake (LocalBrake=PneumaticBrake, LocBrakeHandle=FD1), the cab no control of it + REQUIRE(elf->LocalBrake == TLocalBrake::PneumaticBrake); + + auto const idle{read(elf, elf_cab)}; + CHECK_FALSE(idle.show_local_brake); + CHECK_FALSE(idle.ed_percent.has_value()); + + // the controller at its lowest braking position: the demand ramps towards full braking + elf->MainCtrlPos = 0; + elf.run(2.0, line); + REQUIRE(elf->eimic_real < -0.1); + auto const braking{read(elf, elf_cab)}; + REQUIRE(braking.ed_percent.has_value()); + CHECK(*braking.ed_percent == std::lround(-100.0 * elf->eimic_real)); + CHECK(braking.throttle_first == 0); + CHECK(braking.throttle_second == 0); + CHECK_FALSE(braking.show_local_brake); + + // applied after all (the AI, or the keys), it shows + elf->LocalBrakePosA = 0.3; + auto const applied{read(elf, elf_cab)}; + CHECK(applied.show_local_brake); + CHECK(applied.local_brake == doctest::Approx(3.0)); +} + +TEST_CASE("driving aid: a vehicle without an EIM controller shows what it did") { + vehicle eu07{definition::fiz("4e_v1/4e"), 60.0 /* km/h */, "eu07", 1}; + eu07->MainCtrlPos = 5; + eu07->LocalBrakePosA = 0.2; + auto const readout{read(eu07, lever_cab)}; + CHECK(readout.throttle_first == 5); + CHECK(readout.throttle_second == eu07->ScndCtrlPos); + CHECK(readout.local_brake == doctest::Approx(2.0)); + CHECK(readout.show_local_brake); + CHECK_FALSE(readout.ed_percent.has_value()); + + // the SM42's local brake is the braking range of its joint controller + vehicle sm42{definition::fiz("sm42_v1/6d1"), 0.0, "sm42", 1}; + CHECK(read(sm42, jointctrl_cab).show_local_brake); + CHECK_FALSE(read(sm42, elf_cab).show_local_brake); +} + +TEST_CASE("driving aid: the integrated universal controller shows the ED demand as its brake number, once") { + drivingaid::input input; + input.eim = true; + input.eimctrltype = 3; + input.integratedbrake = true; + input.eimic_real = -0.35; + input.brakectrlpos = 2.0; + auto const readout{drivingaid::compute(input)}; + CHECK(readout.brake_first == doctest::Approx(35.0)); + CHECK_FALSE(readout.ed_percent.has_value()); + CHECK(readout.throttle_first == 0); +} + +TEST_CASE("driving aid: every real vehicle with a local brake control shows the numbers it showed before") { + // with the ED lever of a split ED brake at zero, the change only adds the ED part and leaves out the local brake + // of a cab without a control of it + for (auto const &path : test::real_vehicles()) { + CAPTURE(path); + test::reseed_random(); + vehicle real{definition::fiz(path), 40.0 /* km/h */, "real", 1}; + for (auto const &[mainctrl, localbrake, eimic] : {std::tuple{0, 0.0, 0.0}, std::tuple{1, 0.4, -0.25}, std::tuple{1, 0.0, 0.6}}) { + real->MainCtrlPos = std::min(mainctrl, real->MainCtrlPosNo); + real->LocalBrakePosA = localbrake; + real->eimic_real = eimic; + auto const now{read(real, lever_cab)}; + auto const was{before(real.mover())}; + CHECK(now.throttle_first == was.throttle_first); + CHECK(now.throttle_second == was.throttle_second); + CHECK(now.brake_first == doctest::Approx(was.brake_first)); + CHECK(now.local_brake == doctest::Approx(was.local_brake)); + CHECK(now.show_local_brake); + } + } +} diff --git a/tests/unit/test_dynamic_brake_diesel.cpp b/tests/unit/test_dynamic_brake_diesel.cpp new file mode 100644 index 000000000..fc3f30f27 --- /dev/null +++ b/tests/unit/test_dynamic_brake_diesel.cpp @@ -0,0 +1,264 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scenario.h" +#include "drive.h" +#include "real_vehicles.h" + +#include "McZapkie/hamulce.h" + +// the dynamic brake of the diesel-electric vehicles (Engine: EDBrake=, MaSzyna-EU07/maszyna#82): the traction motors +// brake into resistors while the engine runs, with the force of the definition (EDBrakeFmax, the power limit +// EDBrakePmax, the fade below EDBrakeV1 down to EDBrakeV0), set either by the negative range of the integrated +// controller (EDBrake=Controller, the BR285's TRAXX controller) or by a lever of its own (EDBrake=Lever, the +// SplitEDPneumaticBrake one, with the master controller at zero) + +using test::definition; +using test::scenario; +using namespace test::channels; + +namespace { + +std::vector dynamic_brake() { + return { + {"EDLevel", [](auto const &M) { return M.DEDynamicBrake.level; }}, + {"EDForce", [](auto const &M) { return M.DEDynamicBrake.force; }}, + {"DynamicBrakeFlag", [](auto const &M) { return M.DynamicBrakeFlag ? 1.0 : 0.0; }}, + {"eimic_real", [](auto const &M) { return M.eimic_real; }}, + {"DynamicBrakeCtrlPos", [](auto const &M) { return M.DynamicBrakeCtrlPos; }}, + }; +} + +// the BR285 with its dynamic brake: 150 kN up to the power limit of 2000 kW (48 km/h), fading out under 6 km/h +definition br285_braking() { + return definition::fiz("br285_v1/br285") + .set("Engine", "EDBrake", "Controller") + .set("Engine", "EDBrakeFmax", 150) + .set("Engine", "EDBrakePmax", 2000) + .set("Engine", "EDBrakeV0", 2) + .set("Engine", "EDBrakeV1", 6); +} + +// a resistor brake of a locomotive with direct current motors, on the ST44 (M62): a lever of 8 steps, the force +// growing with the speed up to 120 kN at 40 km/h, the resistors taking 1200 kW +definition st44_braking() { + return definition::fiz("st44_v2/m62-1151") + .set("Cntrl", "DBPN", 8) + .set("Engine", "EDBrake", "Lever") + .set("Engine", "EDBrakeFmax", 120) + .set("Engine", "EDBrakePmax", 1200) + .set("Engine", "EDBrakeV0", 0) + .set("Engine", "EDBrakeV1", 40); +} + +// the force of the brakes above at full effort at the speed of the vehicle +double br285_limit(TMoverParameters const &Vehicle) { + return std::min(150000.0, 2000000.0 / std::abs(Vehicle.V)) * std::clamp((Vehicle.Vel - 2.0) / 4.0, 0.0, 1.0); +} +double st44_limit(TMoverParameters const &Vehicle) { + return std::min(120000.0, 1200000.0 / std::abs(Vehicle.V)) * std::clamp(Vehicle.Vel / 40.0, 0.0, 1.0); +} + +// the controller of the BR285 down to the given position, a step a time +void controller_to(TMoverParameters &Locomotive, int Position) { + while (Locomotive.MainCtrlPos > Position && Locomotive.DecMainCtrl(1)) {} + while (Locomotive.MainCtrlPos < Position && Locomotive.IncMainCtrl(1)) {} +} + +} // namespace + +TEST_CASE("diesel-electric dynamic brake: none without its definition") { + // no game vehicle defines it: the diesel-electric ones load without, the BR285's braking positions brake nothing + for (auto const &path : test::real_vehicles()) { + CAPTURE(path); + test::vehicle vehicle{definition::fiz(path)}; + CHECK(vehicle->DEDynamicBrake.source == TMoverParameters::diesel_electric_dynamic_brake::control::none); + } + scenario scenario{"dynamic brake/diesel electric/br285 without", motion() + traction() + dynamic_brake()}; + scenario.add("br285_v1/br285", 1); + REQUIRE(scenario.start_up()); + auto &locomotive{scenario.cab()}; + scenario.get_going(); + scenario.full_power(40.0); + auto const speed{locomotive.Vel}; + REQUIRE(speed > 30.0); + scenario.act("braking range"); + controller_to(locomotive, 0); + scenario.wait(15.0); + CHECK(locomotive.eimic_real == doctest::Approx(-1.0)); + CHECK(locomotive.Ft == doctest::Approx(0.0)); + CHECK_FALSE(locomotive.DynamicBrakeFlag); + // coasting: braking with the power of the resistors above, it would lose more than 30 km/h + CHECK(locomotive.Vel > speed - 12.0); + scenario.check(); +} + +TEST_CASE("diesel-electric dynamic brake: the BR285's controller") { + // the braking positions of the TRAXX controller: EB+ raises the braking effort, EB holds it, EB- lowers it. + // the force is limited by the power of the resistors at speed, holds below that, fades out at the stop; the + // air brake stays off + scenario scenario{"dynamic brake/diesel electric/br285", motion() + traction() + brakes() + dynamic_brake()}; + scenario.train().add(br285_braking(), 1); + auto &locomotive{scenario.cab()}; + REQUIRE(locomotive.DEDynamicBrake.source == TMoverParameters::diesel_electric_dynamic_brake::control::controller); + CHECK(locomotive.DEDynamicBrake.max_force == doctest::Approx(150000.0)); + CHECK(locomotive.DEDynamicBrake.max_power == doctest::Approx(2000000.0)); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(60.0); + REQUIRE(locomotive.Vel > 60.0); + + scenario.act("EB+"); + controller_to(locomotive, 0); + scenario.wait(10.0); + CHECK(locomotive.eimic_real == doctest::Approx(-1.0)); + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); + CHECK(locomotive.DynamicBrakeFlag); + REQUIRE(locomotive.Vel > 6.0); + CHECK(-locomotive.Ft == doctest::Approx(br285_limit(locomotive)).epsilon(0.01)); + CHECK(locomotive.Im > 0.0); + CHECK(locomotive.EngineVoltage == doctest::Approx(0.0)); + CHECK(locomotive.BrakePress < 0.1); + + scenario.act("EB- to half"); + controller_to(locomotive, 2); + for (int i = 0; i < 20 && locomotive.eimic_real < -0.5; ++i) { + scenario.wait(1.0); + } + scenario.act("EB"); + controller_to(locomotive, 1); + scenario.wait(2.0); + auto const held{locomotive.eimic_real}; + CHECK(held == doctest::Approx(-0.5).epsilon(0.35)); + scenario.wait(5.0); + CHECK(locomotive.eimic_real == doctest::Approx(held)); + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(-held).epsilon(0.01)); + + scenario.act("EB+ to the stop"); + controller_to(locomotive, 0); + for (int i = 0; i < 120 && locomotive.Vel > 20.0; ++i) { + scenario.wait(1.0); + } + // under the power limit the force holds + REQUIRE(locomotive.Vel < 40.0); + REQUIRE(locomotive.Vel > 6.0); + CHECK(-locomotive.Ft == doctest::Approx(150000.0).epsilon(0.01)); + for (int i = 0; i < 120 && locomotive.Vel > 4.0; ++i) { + scenario.wait(1.0); + } + // fading out + CHECK(-locomotive.Ft < 150000.0 * 0.6); + for (int i = 0; i < 120 && locomotive.Vel > 1.5; ++i) { + scenario.wait(1.0); + } + CHECK(locomotive.Ft == doctest::Approx(0.0)); + CHECK_FALSE(locomotive.DynamicBrakeFlag); + // it doesn't hold the train: the air brake does + CHECK(locomotive.Vel > 0.1); + scenario.check(); +} + +TEST_CASE("diesel-electric dynamic brake: a resistor brake with its own lever") { + // on a locomotive with direct current motors the lever sets the excitation of the motors: the force grows with + // the speed, up to the limit of the current, then of the resistors' power. it works only with the master + // controller at zero and the engine running + scenario scenario{"dynamic brake/diesel electric/st44 lever", motion() + traction() + brakes() + dynamic_brake()}; + scenario.train().add(st44_braking(), 1); + auto &locomotive{scenario.cab()}; + REQUIRE(locomotive.DEDynamicBrake.source == TMoverParameters::diesel_electric_dynamic_brake::control::lever); + CHECK(locomotive.SplitEDPneumaticBrake); + CHECK(locomotive.DynamicBrakeCtrlPosNo == 8); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(90.0); + REQUIRE(locomotive.Vel > 50.0); + + scenario.act("lever with power on"); + CHECK(locomotive.DynamicBrakeLevelSet(1.0)); + scenario.wait(5.0); + // the master controller at a power position keeps it off + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(0.0)); + CHECK(locomotive.Ft > 0.0); + CHECK_FALSE(locomotive.DynamicBrakeFlag); + + scenario.act("power off"); + scenario.notch_back(0); + scenario.wait(4.0); + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); + CHECK(locomotive.DynamicBrakeFlag); + CHECK(-locomotive.Ft == doctest::Approx(st44_limit(locomotive)).epsilon(0.01)); + CHECK(locomotive.ShowCurrent(0) > 0.0); + + scenario.act("half the lever"); + locomotive.DecDynamicBrakeLevel(4.0f); + CHECK(locomotive.DynamicBrakeCtrlPos == doctest::Approx(0.5)); + for (int i = 0; i < 300 && locomotive.Vel > 20.0; ++i) { + scenario.wait(1.0); + } + REQUIRE(locomotive.Vel < 21.0); + REQUIRE(locomotive.Vel > 10.0); + // on the rising part, half the excitation + CHECK(-locomotive.Ft == doctest::Approx(0.5 * st44_limit(locomotive)).epsilon(0.01)); + + scenario.act("engine off"); + locomotive.MainSwitch(false); + scenario.wait(1.0); + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(0.0)); + CHECK(locomotive.Ft == doctest::Approx(0.0)); + CHECK_FALSE(locomotive.DynamicBrakeFlag); + scenario.check(); +} + +TEST_CASE("diesel-electric dynamic brake: blended with the locomotive's air brake") { + // EDBrakeBlending: the LSt valve lets the train brake off the locomotive while the dynamic brake takes over + // (Hamulec->SetED with the share of the force it gives); without, both brake + for (auto const blending : {false, true}) { + CAPTURE(blending); + scenario scenario{std::format("dynamic brake/diesel electric/st44 blending {}", blending), motion() + traction() + brakes() + dynamic_brake()}; + scenario.train().add(st44_braking().set("Engine", "EDBrakeBlending", blending ? "Yes" : "No"), 1); + auto &locomotive{scenario.cab()}; + REQUIRE(locomotive.DEDynamicBrake.blending == blending); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(150.0); + scenario.notch_back(0); + scenario.act("dynamic and train brake"); + locomotive.DynamicBrakeLevelSet(1.0); + locomotive.BrakeLevelSet(locomotive.Handle->GetPos(bh_FB)); + scenario.wait(6.0); + REQUIRE(locomotive.Vel > 15.0); + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); + CHECK(locomotive.PipePress < 4.6); + CHECK((locomotive.BrakePress < 0.2) == blending); + scenario.check(); + } +} + +TEST_CASE("diesel-electric dynamic brake: without a fade it brings the vehicle to rest") { + // EDBrakeV0 = EDBrakeV1 = 0 (the defaults): the whole force down to the stop. near it no more than what stops the + // vehicle within the step, or the force turned round each time the speed crossed zero and the vehicle never + // came to rest, the air brake being off + scenario scenario{"dynamic brake/diesel electric/br285 no fade", motion() + traction() + brakes() + dynamic_brake()}; + scenario.train().add(definition::fiz("br285_v1/br285").set("Engine", "EDBrake", "Controller").set("Engine", "EDBrakeFmax", 150), 1); + auto &locomotive{scenario.cab()}; + REQUIRE(locomotive.DEDynamicBrake.fade_low == doctest::Approx(0.0)); + REQUIRE(locomotive.DEDynamicBrake.fade_high == doctest::Approx(0.0)); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(30.0); + REQUIRE(locomotive.Vel > 10.0); + + scenario.act("EB+ to the stop"); + controller_to(locomotive, 0); + for (int i = 0; i < 120 && locomotive.V != 0.0; ++i) { + scenario.wait(1.0); + } + CHECK(locomotive.BrakePress < 0.1); + // at rest, and staying there: no speed either way, no force + for (int i = 0; i < 5; ++i) { + scenario.wait(1.0); + CHECK(locomotive.V == 0.0); + CHECK(locomotive.Ft == doctest::Approx(0.0)); + } + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); + scenario.check(); +} diff --git a/tests/unit/test_editor_http.cpp b/tests/unit/test_editor_http.cpp index ffdfe9959..a3abfc6b7 100644 --- a/tests/unit/test_editor_http.cpp +++ b/tests/unit/test_editor_http.cpp @@ -91,6 +91,21 @@ bool proxied() { } // namespace +TEST_CASE("editor http: a build with an http client has it at run time") { +#if defined(_WIN32) || defined(EU07_WITH_CURL) + // WinHTTP comes with Windows. libcurl isn't linked, it's loaded when first needed: a build made with its headers runs + // on a system that has it, so the tests below don't quietly skip a libcurl that failed to load + CHECK(editor_http::available()); +#else + CHECK_FALSE(editor_http::available()); + editor_http::client client; + std::vector data; + std::string error; + CHECK_FALSE(client.get("http://127.0.0.1/", data, error, []() { return false; })); + CHECK_FALSE(error.empty()); +#endif +} + TEST_CASE("editor http: a request a service doesn't answer is given up as soon as a stop is asked for") { if (false == editor_http::available() || proxied()) return; // a build with no http client, or a proxy in the way diff --git a/tests/unit/test_editor_switch_drives.cpp b/tests/unit/test_editor_switch_drives.cpp new file mode 100644 index 000000000..aeff9c7e2 --- /dev/null +++ b/tests/unit/test_editor_switch_drives.cpp @@ -0,0 +1,171 @@ +#include "stdafx.h" +#include "doctest.h" +#include "editor/editorSwitchDrives.hpp" + +#include +#include +#include +#include +#include + +namespace { + +// a track of the scenery: its name as written, and whether the editor removed it +struct track +{ + std::string name; + bool removed{false}; +}; + +// the scenery as the game finds its tracks: Paths finds a name as written or lower case, the later of two tracks of a name; a track +// deleted takes its name away (editor_track::retire()), Retired lists those names +struct scenery +{ + std::vector tracks; + std::vector retired; + int lookups{0}; // of the whole sequence + + std::optional find(std::string const &Name) const + { + auto const name{switch_drives::game_name(Name)}; + if (std::ranges::find(retired, name) != retired.end()) + return std::nullopt; + std::optional found; + for (auto const &entry : tracks) + if (switch_drives::game_name(entry.name) == name) + found = entry.removed; // the later one + return found; + } + + std::vector standing() + { + ++lookups; + std::vector names; + for (auto const &entry : tracks) + if (false == entry.removed) + names.push_back(entry.name); + return names; + } + + switch_drives::standing_switches lookup() + { + return switch_drives::standing_switches{[this](std::string const &Name) { return find(Name); }, [this] { return standing(); }}; + } + + // deletes the later track of the name, as the editor does + void erase_later(std::string const &Name) + { + auto const name{switch_drives::game_name(Name)}; + for (auto entry{tracks.rbegin()}; entry != tracks.rend(); ++entry) + if (switch_drives::game_name(entry->name) == name && false == entry->removed) + { + entry->removed = true; + retired.push_back(name); + return; + } + } +}; + +} // namespace + +TEST_CASE("switch drives: a name is found as the game finds it") +{ + CHECK(switch_drives::game_name("Zwr\\12A") == "zwr/12a"); + CHECK(switch_drives::game_name("zwr_1") == "zwr_1"); + + scenery line{{{"Zwr1"}, {"zwr2", true}}, {}}; + auto switches{line.lookup()}; + CHECK(switches.stands("Zwr1")); + CHECK(switches.stands("ZWR1")); + // one the name finds, removed, doesn't stand + CHECK_FALSE(switches.stands("zwr2")); + CHECK_FALSE(switches.stands("zwr3")); +} + +TEST_CASE("switch drives: two switches of one name, the later deleted, leave the drive throwing the earlier") +{ + // an older scenery has two tracks of the name; the drive set to it throws the one the game finds + scenery line{{{"zwr7"}, {"other"}, {"Zwr7"}}, {}}; + line.erase_later("zwr7"); + REQUIRE_FALSE(line.find("zwr7").has_value()); // the name went with the track deleted + { + auto switches{line.lookup()}; + // the earlier one still stands: the drive isn't stray, and a hint to delete it would delete a working drive + CHECK(switches.stands("zwr7")); + CHECK(switches.stands("ZWR7")); + CHECK(switches.any_stands({"zwr7"})); + CHECK_FALSE(switches.stands("zwr8")); + // the tracks of the scenery are read once, however many names find none + CHECK(line.lookups == 1); + } + // both deleted: the drive throws nothing now + line.erase_later("zwr7"); + auto switches{line.lookup()}; + CHECK_FALSE(switches.stands("zwr7")); + CHECK_FALSE(switches.any_stands({"zwr7"})); +} + +TEST_CASE("switch drives: the drive of a double switch stands while one of its four switches does") +{ + scenery line{{{"dkw1a"}, {"dkw1b"}, {"dkw1c"}, {"dkw1d"}}, {}}; + std::vector const names{"dkw1a", "dkw1b", "dkw1c", "dkw1d"}; + for (auto const *name : {"dkw1a", "dkw1b", "dkw1c"}) + { + line.erase_later(name); + CHECK(line.lookup().any_stands(names)); + } + line.erase_later("dkw1d"); + CHECK_FALSE(line.lookup().any_stands(names)); +} + +TEST_CASE("switch drives: the switches of a template are read once while the templates stay the same") +{ + switch_drives::template_switches templates; + std::map reads; + std::map> files{{"napedy/naped_l.inc", {""}}, {"napedy/dkw.inc", {"a", "b", "c", "d"}}, {"podsypka.inc", {}}}; + auto const read = [&reads, &files](std::string const &File, std::vector &Suffixes) { + ++reads[File]; + auto const found{files.find(File)}; + if (found == files.end()) + return false; + Suffixes = found->second; + return true; + }; + + SUBCASE("read once in a revision") + { + CHECK(templates.of("napedy/naped_l.inc", 1, 10, read) == std::vector{""}); + CHECK(templates.of("napedy/naped_l.inc", 1, 11, read) == std::vector{""}); + CHECK(templates.of("napedy/dkw.inc", 1, 12, read).size() == 4); + CHECK(templates.of("podsypka.inc", 1, 12, read).empty()); + CHECK(templates.of("podsypka.inc", 1, 13, read).empty()); + CHECK(reads["napedy/naped_l.inc"] == 1); + CHECK(reads["napedy/dkw.inc"] == 1); + CHECK(reads["podsypka.inc"] == 1); + } + + SUBCASE("a template changed is read again in the next revision") + { + CHECK(templates.of("napedy/naped_l.inc", 1, 10, read) == std::vector{""}); + // saved in the editor, or changed on the disk and rescanned: no drive any more + files["napedy/naped_l.inc"] = {}; + CHECK(templates.of("napedy/naped_l.inc", 1, 11, read) == std::vector{""}); + CHECK(templates.of("napedy/naped_l.inc", 2, 11, read).empty()); + CHECK(reads["napedy/naped_l.inc"] == 2); + } + + SUBCASE("a file that can't be read is tried again in a later frame") + { + CHECK(templates.of("napedy/nowy.inc", 1, 10, read).empty()); + // each include of it asks in the same frame: read once + CHECK(templates.of("napedy/nowy.inc", 1, 10, read).empty()); + CHECK(reads["napedy/nowy.inc"] == 1); + CHECK(templates.of("napedy/nowy.inc", 1, 11, read).empty()); + CHECK(reads["napedy/nowy.inc"] == 2); + // there now, with the same revision: no rescan needed + files["napedy/nowy.inc"] = {""}; + CHECK(templates.of("napedy/nowy.inc", 1, 12, read) == std::vector{""}); + CHECK(templates.of("napedy/nowy.inc", 1, 13, read) == std::vector{""}); + CHECK(reads["napedy/nowy.inc"] == 3); + } +} diff --git a/tests/unit/test_elf_controller.cpp b/tests/unit/test_elf_controller.cpp index 212ed51d0..bb7d34b74 100644 --- a/tests/unit/test_elf_controller.cpp +++ b/tests/unit/test_elf_controller.cpp @@ -5,7 +5,9 @@ #include "McZapkie/hamulce.h" +#include #include +#include #include // the master controller of the Elf (EIMCtrlType 2): its positions, and the emergency brake position below @@ -26,10 +28,14 @@ enum class data { plain, emergency, emergency_old_layout }; // controller's eimic is worked out there) struct elf { explicit elf(bool Emergency) : elf({Emergency ? data::emergency : data::plain}) {} - explicit elf(std::initializer_list Units) { + // HoldingBrakeDelay, when given, goes to every car as SBDReleaseDelay + explicit elf(std::initializer_list Units, std::optional HoldingBrakeDelay = std::nullopt) { for (auto const units : Units) { for (auto const *car : {"elf_v1/21we-a", "elf_v1/21we-b", "elf_v1/21we-c"}) { auto cardefinition{definition::fiz(car)}; + if (HoldingBrakeDelay) { + cardefinition.set("Cntrl", "SBDReleaseDelay", *HoldingBrakeDelay); + } if (units != data::plain) { cardefinition.set("Cntrl", "EIMCtrlMainEmergency", "Yes"); } @@ -254,3 +260,277 @@ TEST_CASE("elf controller: EIMCtrlMainEmergency leaves the other controllers alo impuls->MainCtrlPos = 0; CHECK_FALSE(impuls->IsMainCtrlEmergencyPos()); } + +// the holding brake of the Elf (SBD) lets go only once power has been demanded for SBDReleaseDelay (eu07/maszyna#556): +// the release waits the initial delay of the controller (IniCDelay) instead of going at the first percent of the +// demand. TDynamicObject::Update() works the holding brake out, its MED isn't in the tests, so they do here what it +// does with it: TMoverParameters::UpdateStopBrakeRelease() of the cab with its demand after every step and, where the +// brake matters, the brake's share of every car on its cylinders (LocalBrakePosAEIM) + +namespace { + +constexpr double step_time{0.01}; // of a step of the tests, see test::consist::step() +constexpr double elf_delay{1.0}; // IniCDelay of the Elf with a cab + +// the time from the start to the first step with the holding brake let go, the brake worked out after every step; +// Act runs before every step with the time so far. negative when it holds all the time +template double release_time(elf &Unit, double Seconds, Action Act) { + auto &cab{Unit.cab()}; + auto const steps{std::lround(Seconds / step_time)}; + for (long i = 0; i < steps; ++i) { + auto const time{i * step_time}; + Act(time); + Unit.unit.step(Unit.line); + if (cab.UpdateStopBrakeRelease(cab.eimic_real, step_time)) { + return time; + } + } + return -1.0; +} + +// the holding brake of TDynamicObject::Update() at standstill: StopBrakeDecc times the mass of the train, shared out +// by the axles, each car's share made a position of its brake valve (LocalBrakePosAEIM) as there. at standstill the +// electric brake makes no part of it +void hold(elf &Unit, bool Hold) { + auto mass{0.0}; + auto axles{0}; + for (std::size_t i = 0; i < Unit.unit.size(); ++i) { + mass += Unit.car(i).TotalMass; + axles += Unit.car(i).NAxles; + } + auto const force{Unit.cab().StopBrakeDecc * mass}; + for (std::size_t i = 0; i < Unit.unit.size(); ++i) { + auto &car{Unit.car(i)}; + auto const nmax{((car.P2FTrans * car.MaxBrakePress[0] - car.BrakeCylSpring) * car.BrakeCylMult[0] - car.BrakeSlckAdj) * car.BrakeCylNo * car.BrakeRigEff}; + auto const fmax{nmax * car.Hamulec->GetFC(nmax / (car.NAxles * car.NBpA), car.MED_Vref) * 1000}; + auto position{Hold ? force * car.NAxles / axles / fmax : 0.0}; + if (position > 0.009) { + auto const slack{(car.BrakeSlckAdj / car.BrakeCylMult[0] + car.BrakeCylSpring) / (car.P2FTrans * car.MaxBrakePress[0])}; + position = slack + (1 - slack) * position; + } + else { + position = 0.0; + } + car.LocalBrakePosAEIM = position; + } +} + +// how a start of the Elf goes with its holding brake +struct start { + double release{-1.0}; // the time the holding brake let go + double moving{-1.0}; // the time the train got above 0.5 km/h + double running{-1.0}; // the time it got above 10 km/h + double demand{0.0}; // of the controller when the brake let go + double pressure{0.0}; // in the brake cylinders of the cab car then +}; + +// the brake applied at standstill, then Act before every step with the time from the start; the brake let go as +// TDynamicObject::Update() lets it go (in ShuntMode, until above 1 km/h) +template start start_off(elf &Unit, double Seconds, Action Act) { + auto &cab{Unit.cab()}; + // the train stands held, its cylinders filled + hold(Unit, true); + Unit.wait(10.0); + start result; + result.pressure = cab.BrakePress; + auto shuntmode{true}; + auto const steps{std::lround(Seconds / step_time)}; + for (long i = 0; i < steps && result.running < 0.0; ++i) { + auto const time{i * step_time}; + Act(time); + Unit.unit.step(Unit.line); + auto const released{cab.UpdateStopBrakeRelease(cab.eimic_real, step_time)}; + if (cab.Vel > 1.0) { + shuntmode = false; + } + hold(Unit, shuntmode && false == released); + if (released && result.release < 0.0) { + result.release = time; + result.demand = cab.eimic_real; + } + if (cab.Vel > 0.5 && result.moving < 0.0) { + result.moving = time; + } + if (cab.Vel > 10.0) { + result.running = time; + } + } + return result; +} + +void flick(elf &Unit, double Time) { + Unit.set_controller(Time < 0.5 * step_time ? 4 : 3); +} + +} // namespace + +TEST_CASE("elf holding brake: without SBDReleaseDelay it lets go at the first demand, as it always did") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + CHECK(car->StopBrakeDecc == doctest::Approx(0.6)); + CHECK(car->StopBrakeReleaseDelay == 0.0); + CHECK_FALSE(car->UpdateStopBrakeRelease(0.0, step_time)); + CHECK_FALSE(car->UpdateStopBrakeRelease(-0.5, step_time)); + CHECK(car->UpdateStopBrakeRelease(0.001, step_time)); + CHECK(car->UpdateStopBrakeRelease(0.01, step_time)); + // and holds again at no demand + CHECK_FALSE(car->UpdateStopBrakeRelease(0.0, step_time)); +} + +TEST_CASE("elf holding brake: SBDReleaseDelay holds it for that long of a demand") { + vehicle car{definition::fiz("elf_v1/21we-a").set("Cntrl", "SBDReleaseDelay", 1.0)}; + REQUIRE(car->StopBrakeReleaseDelay == doctest::Approx(1.0)); + // the demand rises above 0 in the step of time 0 + long held{0}; + while (held < 500 && false == car->UpdateStopBrakeRelease(0.01, step_time)) { + ++held; + } + CHECK(held * step_time == doctest::Approx(1.0).epsilon(0.015)); + // it holds again once there's no demand, and waits the whole delay again for the next one + CHECK_FALSE(car->UpdateStopBrakeRelease(0.0, step_time)); + CHECK(car->StopBrakeReleaseTimer == 0.0); + CHECK_FALSE(car->UpdateStopBrakeRelease(0.01, step_time)); +} + +TEST_CASE("elf holding brake: the controller held at power") { + SUBCASE("without SBDReleaseDelay the brake lets go at the first step of the power position, at 1%") { + elf unit{{data::plain}}; + REQUIRE(unit.ready); + auto const release{release_time(unit, 5.0, [&unit](double) { unit.set_controller(4); })}; + CHECK(release == doctest::Approx(0.0)); + CHECK(unit.cab().eimic_real == doctest::Approx(0.01)); + } + SUBCASE("with SBDReleaseDelay=1.0 it lets go as the demand starts to ramp up, about 1 s on") { + elf unit{{data::plain}, elf_delay}; + REQUIRE(unit.ready); + auto &cab{unit.cab()}; + auto const release{release_time(unit, 5.0, [&unit](double) { unit.set_controller(4); })}; + // the 1% of the first step is all there is until then + auto const demand{cab.eimic_real}; + // the step the ramp of the demand starts at + auto rampstart{release}; + while (cab.eimic_real < 0.0101 && rampstart < 5.0) { + rampstart += step_time; + unit.unit.step(unit.line); + } + MESSAGE("held: release " << release << " s at " << demand << ", ramp from " << rampstart << " s"); + CHECK(release == doctest::Approx(1.0).epsilon(0.015)); + CHECK(demand == doctest::Approx(0.01).epsilon(0.02)); + // it lets go within a step of the ramp's start + CHECK(std::abs(release - rampstart) <= 1.5 * step_time); + } +} + +TEST_CASE("elf holding brake: the controller flicked to power once and back to holding the power") { + elf unit{{data::plain}, elf_delay}; + REQUIRE(unit.ready); + auto &cab{unit.cab()}; + auto const release{release_time(unit, 5.0, [&unit](double Time) { flick(unit, Time); })}; + MESSAGE("flick: release " << release << " s, demand " << cab.eimic_real); + CHECK(release == doctest::Approx(1.0).epsilon(0.015)); + // the demand stays at the 1% of the flick + CHECK(cab.eimic_real == doctest::Approx(0.01).epsilon(0.02)); +} + +TEST_CASE("elf holding brake: a demand dropped to zero before the delay starts the count again") { + elf unit{{data::plain}, elf_delay}; + REQUIRE(unit.ready); + auto &cab{unit.cab()}; + // power for 0.5 s, the braking position for 0.2 s (no demand), then power again + auto const release{release_time(unit, 5.0, [&unit](double Time) { unit.set_controller(Time > 0.495 && Time < 0.695 ? 2 : 4); })}; + MESSAGE("restart: release " << release << " s"); + CHECK(release == doctest::Approx(1.7).epsilon(0.01)); + CHECK(cab.eimic_real > 0.0); +} + +TEST_CASE("elf holding brake: it comes back when the demand drops to zero at standstill") { + elf unit{{data::plain}, elf_delay}; + REQUIRE(unit.ready); + auto &cab{unit.cab()}; + auto const release{release_time(unit, 5.0, [&unit](double) { unit.set_controller(4); })}; + REQUIRE(release > 0.0); + // the braking position takes the demand off: the brake holds from the next step + unit.set_controller(2); + unit.unit.step(unit.line); + CHECK(cab.eimic_real <= 0.0); + CHECK_FALSE(cab.UpdateStopBrakeRelease(cab.eimic_real, step_time)); + // and power demanded again waits the delay again + auto const again{release_time(unit, 5.0, [&unit](double) { unit.set_controller(4); })}; + CHECK(again == doctest::Approx(1.0).epsilon(0.015)); +} + +TEST_CASE("elf holding brake: two Elfs coupled let it go as one does") { + elf one{{data::plain}, elf_delay}; + elf two{{data::plain, data::plain}, elf_delay}; + REQUIRE(one.ready); + REQUIRE(two.ready); + REQUIRE(two.unit.size() == 6); + auto const oneheld{release_time(one, 5.0, [&one](double) { one.set_controller(4); })}; + auto const twoheld{release_time(two, 5.0, [&two](double) { two.set_controller(4); })}; + CHECK(oneheld == doctest::Approx(1.0).epsilon(0.015)); + CHECK(twoheld == doctest::Approx(oneheld)); + // no demand for a while, which holds the brake, then the flick + CHECK(release_time(one, 5.0, [&one](double) { one.set_controller(2); }) < 0.0); + CHECK(release_time(two, 5.0, [&two](double) { two.set_controller(2); }) < 0.0); + auto const oneflicked{release_time(one, 5.0, [&one](double Time) { flick(one, Time); })}; + auto const twoflicked{release_time(two, 5.0, [&two](double Time) { flick(two, Time); })}; + CHECK(oneflicked == doctest::Approx(1.0).epsilon(0.015)); + CHECK(twoflicked == doctest::Approx(oneflicked)); +} + +TEST_CASE("elf holding brake: the train doesn't move before the brake lets go, and starts off after it") { + // the driver and the AI both put the controller to power and keep it there: TController::CheckTimeControllers() + // drops it to holding the power once there's a demand, but IncSpeedEIM() puts it back to power in the same update + // of the AI, so the physics sees it held + elf now{{data::plain}}; + elf delayed{{data::plain}, elf_delay}; + REQUIRE(now.ready); + REQUIRE(delayed.ready); + auto const before{start_off(now, 60.0, [&now](double) { now.set_controller(4); })}; + auto const after{start_off(delayed, 60.0, [&delayed](double) { delayed.set_controller(4); })}; + MESSAGE("held brake " << before.pressure << " bar in the cab car"); + MESSAGE("without the delay: release " << before.release << " s at " << before.demand << ", moving " << before.moving << " s, 10 km/h " << before.running << " s"); + MESSAGE("with the delay: release " << after.release << " s at " << after.demand << ", moving " << after.moving << " s, 10 km/h " << after.running << " s"); + CHECK(before.pressure > 1.0); + CHECK(before.release == doctest::Approx(0.0)); + CHECK(after.release == doctest::Approx(1.0).epsilon(0.015)); + // held until then, at the 1% of the first step + CHECK(after.demand == doctest::Approx(0.01).epsilon(0.05)); + CHECK(after.moving > after.release); + // both start off, the delayed one at most the delay later + REQUIRE(before.running > 0.0); + REQUIRE(after.running > 0.0); + CHECK(after.running >= before.running); + CHECK(after.running <= before.running + elf_delay + 0.05); +} + +TEST_CASE("elf holding brake: the flick to power doesn't move the train before the brake lets go") { + elf unit{{data::plain}, elf_delay}; + REQUIRE(unit.ready); + auto const flicked{start_off(unit, 10.0, [&unit](double Time) { flick(unit, Time); })}; + MESSAGE("flick: release " << flicked.release << " s, moving " << flicked.moving << " s, speed " << unit.cab().Vel << " km/h after 10 s"); + CHECK(flicked.release == doctest::Approx(1.0).epsilon(0.015)); + CHECK((flicked.moving < 0.0 || flicked.moving > flicked.release)); +} + +TEST_CASE("elf holding brake: the force of the motors at 1% against the holding brake") { + // the numbers for the report: the holding force of the train (SBD times its mass), and what the motors of the cab + // car make at the 1% of the first step of the controller with no brake holding them back + elf unit{{data::plain}}; + REQUIRE(unit.ready); + auto &cab{unit.cab()}; + auto mass{0.0}; + auto powered{0}; + for (std::size_t i = 0; i < unit.unit.size(); ++i) { + mass += unit.car(i).TotalMass; + powered += unit.car(i).NPoweredAxles > 0 ? 1 : 0; + } + unit.set_controller(4); + unit.unit.step(unit.line); + unit.set_controller(3); + unit.wait(5.0); + auto const holding{cab.StopBrakeDecc * mass}; + MESSAGE("mass " << mass << " kg, holding " << holding << " N, cars with motors " << powered << ", demand " << cab.eimic_real << ", cab car Ft " << cab.Ft + << " N, Fful " << cab.eimv[eimv_Fful] << " kN, speed " << cab.Vel << " km/h after 5 s"); + CHECK(cab.eimic_real == doctest::Approx(0.01).epsilon(0.02)); + CHECK(cab.Ft * powered < 0.1 * holding); +} diff --git a/tests/unit/test_est3al2_relay.cpp b/tests/unit/test_est3al2_relay.cpp new file mode 100644 index 000000000..63296901b --- /dev/null +++ b/tests/unit/test_est3al2_relay.cpp @@ -0,0 +1,145 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +#include "McZapkie/hamulce.h" + +#include +#include + +using test::definition; +using test::vehicle; + +// the fill and release times of the brake cylinder of an ESt3 distributor with the AL2 load relay (TNESt3 with +// TPrzekCiagly), in G and in P, with the empty/loaded lever in each of its three positions. bb43f559e made the +// relay's impulse chamber 1 l and scaled the cylinder nozzles to the times of table 3-9 of the ESt3 data; before it +// they were set by eye. this pins what the valve does today, so a change of the relay or of the nozzles shows + +namespace { + +// a Fas 413S four-axle freight wagon (pkp/413s_v1/413s.fiz of the game data): ESt3AL2, 100 l reservoir, one +// 16" cylinder, the empty/medium/loaded lever at 1.5/2.6/3.8 bar, brake delays G and P. not among the converted +// real vehicles of tests/unit/data/fiz, so its lines are set over the test wagon +definition fas_413s() { + return definition::load("wagon") + .set("Param", "M", 25300) + .set("Param", "Vmax", 100) + .set("Load", "MaxLoad", 56) + .set("Load", "LoadQ", "tonns") + .set("Load", "LoadAccepted", "coal,gravel") + .set("Dimensions", "L", 14.4) + .set("Wheels", "D", 0.92) + .set("Wheels", "Axle", "2'2'") + .set("Wheels", "Ad", 2.0) + .set("Wheels", "Bd", 8.5) + .set("Brake", "BrakeValve", "ESt3AL2") + .set("Brake", "Size", 100) + .set("Brake", "MBF", 144) + .set("Brake", "MaxBP", 3.8) + .set("Brake", "TareMaxBP", 1.5) + .set("Brake", "MedMaxBP", 2.6) + .set("Brake", "BCN", 1) + .set("Brake", "BCR", 0.2032) + .set("Brake", "BCD", 0.14) + .set("Brake", "BCM", 11.75) + .set("Brake", "NBpA", 4) + .set("Brake", "BM", "P10-Bg") + .set("Brake", "BCS", 2.7) + .set("Brake", "BSA", 16.0) + .set("Brake", "BVV", 100) + .set("Brake", "BRE", 0.8) + .set("Cntrl", "BrakeDelays", "GP") + .remove("Cntrl", "MaxBPMass"); +} + +struct times { + double charged; // in the cylinder after charging [bar] + double applied; // in the cylinder 60 s after the emergency application [bar] + double fill; // from the pipe emptied to 95% of applied [s] + double release; // from the pipe back at 5 bar to 0.4 bar in the cylinder [s] +}; + +// charges the wagon, empties the pipe at once (an emergency application) and fills it again at once, stepping +// the physics in 0.01 s steps as the game does +times measure(int const Delay, int const Lever) { + test::reseed_random(); + vehicle wagon{fas_413s()}; + REQUIRE(wagon->BrakeValve == TBrakeValve::ESt3AL2); + if (wagon->BrakeDelayFlag != Delay) { + REQUIRE(wagon->BrakeDelaySwitch(Delay)); + } + // an empty wagon starts with the lever at empty (TMoverParameters::CheckLocomotiveParameters) + REQUIRE(wagon->LoadFlag == 1); + while (wagon->LoadFlag < Lever) { + REQUIRE(wagon->IncBrakeMult()); + } + REQUIRE(wagon->LoadFlag == Lever); + + times result{}; + wagon.hold_brake_pipe(5.0); + wagon.run(180.0); + result.charged = wagon->BrakePress; + + double constexpr step{0.01}; + std::vector cylinder; + wagon.hold_brake_pipe(0.0); + for (int i = 0; i < 6000; ++i) { + wagon.step(); + cylinder.push_back(wagon->BrakePress); + } + result.applied = cylinder.back(); + result.fill = -1.0; + for (std::size_t i = 0; i < cylinder.size(); ++i) { + if (cylinder[i] >= 0.95 * result.applied) { + result.fill = static_cast(i + 1) * step; + break; + } + } + + wagon.hold_brake_pipe(5.0); + result.release = -1.0; + for (int i = 0; i < 18000; ++i) { + wagon.step(); + if (wagon->BrakePress <= 0.4) { + result.release = static_cast(i + 1) * step; + break; + } + } + return result; +} + +} // namespace + +TEST_CASE("ESt3AL2: fill and release times of the cylinder of a 413S wagon, G and P, empty, medium and loaded") { + struct expected { + char const *name; + int delay; + int lever; // LoadFlag: 1 empty, 2 medium, 3 loaded + double applied; // [bar] + double fill; // [s] + double release; // [s] + }; + // measured on staging 5a24a1048, held to 1% (the pressure) and 5% (the times). the fill time is to 95% of the + // pressure 60 s after the pipe was emptied, the release time down to 0.4 bar. both count from a step of the pipe, + // 5 to 0 bar and back at once, not from the rate of a driver's brake valve or of a test bench. for comparison only, + // UIC 540 asks for G fill 18-30 s, release 45-60 s, P fill 3-5 s, release 15-20 s: the fill times are within, the + // release times shorter. the emergency application gives the cylinder 0.19-0.27 bar more than the lever's + // TareMaxBP, MedMaxBP and MaxBP (1.5, 2.6, 3.8 bar) + for (auto const &[name, delay, lever, applied, fill, release] : { + expected{"G empty", bdelay_G, 1, 1.736, 22.81, 33.89}, + expected{"G medium", bdelay_G, 2, 2.870, 21.98, 40.82}, + expected{"G loaded", bdelay_G, 3, 3.991, 21.15, 43.98}, + expected{"P empty", bdelay_P, 1, 1.737, 3.84, 10.98}, + expected{"P medium", bdelay_P, 2, 2.871, 3.71, 13.18}, + expected{"P loaded", bdelay_P, 3, 3.995, 3.62, 14.19}, + }) { + CAPTURE(name); + auto const measured{measure(delay, lever)}; + INFO(std::format("{}: charged {:.3f} bar, applied {:.3f} bar, fill {:.2f} s, release {:.2f} s", name, measured.charged, measured.applied, measured.fill, + measured.release)); + CHECK(measured.charged < 0.05); + CHECK(measured.applied == doctest::Approx(applied).epsilon(0.01)); + CHECK(measured.fill == doctest::Approx(fill).epsilon(0.05)); + CHECK(measured.release == doctest::Approx(release).epsilon(0.05)); + } +} diff --git a/tests/unit/test_event_conditions.cpp b/tests/unit/test_event_conditions.cpp new file mode 100644 index 000000000..81a55201b --- /dev/null +++ b/tests/unit/test_event_conditions.cpp @@ -0,0 +1,130 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "utilities/comparison.h" +#include "utilities/parser.h" +#include "world/Event.h" + +#include + +// the condition block of the multiple and updatevalues events (world/eventconditions.cpp): the scenery editor writes +// the conditions of the events back with export_as_text(), and what it writes has to read back as the same conditions + +namespace { + +// the conditions are a part of the event, open to its kinds only +struct event_kind : basic_event { + using basic_event::event_conditions; +}; +using conditions = event_kind::event_conditions; + +// the conditions of an event text, read the way the events read them: the parser stands on the word 'condition' +conditions read(std::string const &Text) { + cParser parser(Text, cParser::buffer_TEXT); + parser.getTokens(); + REQUIRE(parser.peek() == "condition"); + conditions result; + result.deserialize(parser); + // the reading stops at the next keyword of the event and leaves it for the event + CHECK(parser.peek() == "endevent"); + return result; +} + +std::string write(conditions const &Conditions) { + std::ostringstream output; + Conditions.export_as_text(output); + return output.str(); +} + +// the conditions written and read again +conditions write_and_read(conditions const &Conditions) { + return read(write(Conditions) + "endevent"); +} + +void check_same(conditions const &Read, conditions const &Expected) { + CHECK(Read.flags == Expected.flags); + CHECK(Read.probability == Expected.probability); + CHECK(Read.memcompare_pass == Expected.memcompare_pass); + CHECK(Read.memcompare_text == Expected.memcompare_text); + CHECK(Read.memcompare_text_operator == Expected.memcompare_text_operator); + CHECK(Read.memcompare_value1 == Expected.memcompare_value1); + CHECK(Read.memcompare_value1_operator == Expected.memcompare_value1_operator); + CHECK(Read.memcompare_value2 == Expected.memcompare_value2); + CHECK(Read.memcompare_value2_operator == Expected.memcompare_value2_operator); +} + +comparison_operator const operators[]{comparison_operator::equal, comparison_operator::not_equal, comparison_operator::lt, + comparison_operator::gt, comparison_operator::lt_eq, comparison_operator::gt_eq}; +comparison_pass const passes[]{comparison_pass::all, comparison_pass::any, comparison_pass::none}; + +} // namespace + +TEST_CASE("event conditions: each comparison operator and pass is written as the word that reads back as it") { + for (auto const op : operators) { + CAPTURE(to_string(op)); + CHECK(comparison_operator_from_string(to_string(op)) == op); + } + CHECK(to_string(comparison_operator::gt_eq) == ">="); + for (auto const pass : passes) { + CAPTURE(to_string(pass)); + CHECK(comparison_pass_from_string(to_string(pass)) == pass); + } +} + +TEST_CASE("event conditions: memcompareex is written as the pass, then the operator before each compared value") { + auto const conditions{read("condition memcompareex any != Blokada >= 1 < 2.5 endevent")}; + CHECK(conditions.memcompare_pass == comparison_pass::any); + CHECK(conditions.memcompare_text == "Blokada"); + CHECK(conditions.memcompare_text_operator == comparison_operator::not_equal); + CHECK(conditions.memcompare_value1_operator == comparison_operator::gt_eq); + CHECK(conditions.memcompare_value2_operator == comparison_operator::lt); + CHECK(write(conditions) == "condition memcompareex any != Blokada >= 1.000000 < 2.500000 "); + check_same(write_and_read(conditions), conditions); +} + +TEST_CASE("event conditions: memcompareex reads back the same for every pass, operator and left out value") { + for (auto const pass : passes) { + for (auto const op : operators) { + for (unsigned int used{0}; used < 8; ++used) { + std::string text{"condition memcompareex " + to_string(pass)}; + text += (used & 1) ? " " + to_string(op) + " Zajety_tor" : std::string{" *"}; + text += (used & 2) ? " " + to_string(op) + " -3.25" : std::string{" *"}; + text += (used & 4) ? " " + to_string(op) + " 1250" : std::string{" *"}; + text += " endevent"; + CAPTURE(text); + auto const conditions{read(text)}; + CHECK(conditions.flags == used); + if (used == 0) { + // nothing compared is no condition, and no condition is written + CHECK(write(conditions).empty()); + continue; + } + check_same(write_and_read(conditions), conditions); + } + } + } +} + +TEST_CASE("event conditions: the old memcompare is written as memcompareex all with == and reads back the same") { + auto const conditions{read("condition memcompare Wolny * 3 endevent")}; + CHECK(write(conditions) == "condition memcompareex all == Wolny * == 3.000000 "); + check_same(write_and_read(conditions), conditions); + + auto const all{read("condition memcompare Wolny 1 0 endevent")}; + check_same(write_and_read(all), all); +} + +TEST_CASE("event conditions: the track and probability conditions read back along with the comparison") { + auto const conditions{read("condition trackoccupied trackfree probability 0.25 memcompareex none <= 3 * > -1.5 endevent")}; + CHECK(conditions.flags == (basic_event::flags::track_busy | basic_event::flags::track_free | basic_event::flags::probability | + basic_event::flags::text | basic_event::flags::value2)); + check_same(write_and_read(conditions), conditions); + + auto const probability{read("condition probability 0.5 endevent")}; + CHECK(write(probability) == "condition probability 0.5 "); + check_same(write_and_read(probability), probability); +} + +TEST_CASE("event conditions: an event without conditions writes none") { + CHECK(write(conditions{}).empty()); +} diff --git a/tests/unit/test_fcfuh_default.cpp b/tests/unit/test_fcfuh_default.cpp new file mode 100644 index 000000000..437164060 --- /dev/null +++ b/tests/unit/test_fcfuh_default.cpp @@ -0,0 +1,153 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "utilities/utilities.h" + +#include +#include +#include +#include +#include +#include + +using test::definition; +using test::vehicle; + +// the figure of the voltage by the frequency of an induction motor drive in the dynamic brake (fcfuH) takes the +// one of the traction (fcfu) when the definition has none. the loader took it by writing fcfu out with +// std::to_string() and reading the text back as the default of fcfuH (eu07/maszyna#99); it assigns it now + +namespace { + +// a figure read from a line the way TMoverParameters::LoadFIZ_EngineInductionMotor() reads fcfu +double read_fcfu(std::string const &Text) { + double fcfu{0.0}; + extract_value(fcfu, "fcfu", "fcfu=" + Text, ""); + return fcfu; +} + +// fcfuH missing, the way the loader took it before: the figure written out with six decimals in the C locale +// (the game never sets another) and read back +double fcfuh_before(double const Fcfu) { + double fcfuh{-1.0}; + extract_value(fcfuh, "fcfuH", "", std::to_string(Fcfu)); + return fcfuh; +} + +// the bits of the value, which tell -0.0 from 0.0 too +std::uint64_t bits(double const Value) { + std::uint64_t result; + std::memcpy(&result, &Value, sizeof(result)); + return result; +} + +// the value with all its digits, for the message +std::string exact(double const Value) { + char text[64]; + std::snprintf(text, sizeof(text), "%.17g", Value); + return text; +} + +// a generator of its own (splitmix64), for the same numbers on every platform +struct numbers { + std::uint64_t state{0x2545f4914f6cdd1dull}; + std::uint64_t next() { + auto value{state += 0x9e3779b97f4a7c15ull}; + value = (value ^ (value >> 30)) * 0xbf58476d1ce4e5b9ull; + value = (value ^ (value >> 27)) * 0x94d049bb133111ebull; + return value ^ (value >> 31); + } +}; + +// the decimal text of Integer / 10^Decimals, as a definition could hold it +std::string decimal(std::uint64_t const Integer, int const Decimals, bool const Negative) { + auto digits{std::to_string(Integer)}; + if (Decimals > 0) { + if (digits.size() <= static_cast(Decimals)) { + digits.insert(0, Decimals + 1 - digits.size(), '0'); + } + digits.insert(digits.size() - Decimals, "."); + } + return (Negative ? "-" : "") + digits; +} + +} // namespace + +TEST_CASE("fcfuH: the figure of the traction is the same, assigned or written out and read back, for every figure of up to six decimals") { + // any decimal figure of up to six decimals: the value read from it lies within half a millionth of it, so + // std::to_string() writes the figure itself and the text reads back to the very same value. checked over the + // figures the game's definitions use (33.5 to 81.5) and the ones around them, and over many others, of up + // to six decimals and up to 18 digits, of either sign + auto compared{0}; + auto const check{[&](std::string const &Text) { + auto const fcfu{read_fcfu(Text)}; + auto const before{fcfuh_before(fcfu)}; + if (bits(before) != bits(fcfu)) { + FAIL_CHECK("fcfu=" << Text << " was " << exact(before) << " as fcfuH, now " << exact(fcfu)); + } + ++compared; + }}; + // every figure of up to two decimals, from -10 to 200 + for (auto hundredths{-1000}; hundredths <= 20000; ++hundredths) { + check(decimal(static_cast(std::abs(hundredths)), 2, hundredths < 0)); + } + // every figure of up to six decimals around the ones of the game's definitions + for (auto const figure : {33.5, 40.1, 43.7, 45.18, 46.8, 47.6, 48.9, 49.0, 81.5}) { + auto const millionths{static_cast(figure * 1e6 + 0.5)}; + for (auto offset{-2000}; offset <= 2000; ++offset) { + check(decimal(static_cast(millionths + offset), 6, false)); + } + } + // figures of 0 to 6 decimals and 1 to 18 digits + numbers random; + for (auto decimals{0}; decimals <= 6; ++decimals) { + for (auto digits{1}; digits <= 18; ++digits) { + std::uint64_t limit{1}; + for (auto digit{0}; digit < digits; ++digit) { + limit *= 10; + } + for (auto sample{0}; sample < 400; ++sample) { + check(decimal(random.next() % limit, decimals, (sample & 1) != 0)); + } + } + } + // the way of writing it doesn't matter, only the value + for (auto const text : {"4.76e1", "47.60", "+47.6", "0047.6", "476e-1", "0", "-0", "1e15", "-1e-6", "1e300"}) { + check(text); + } + // nor does a figure the stream can't read, which reads as 0 + for (auto const text : {"abc", "-", "x47.6"}) { + check(text); + } + CHECK(compared > 70000); +} + +TEST_CASE("fcfuH: where the two ways part, figures no definition has") { + // no definition of the game has such a figure (they have one or two decimals, from 33.5 to 81.5). more than + // six decimals: std::to_string() rounded the value to six, the figure is taken as it's written now + CHECK(fcfuh_before(read_fcfu("0.1234567")) == read_fcfu("0.123457")); + CHECK(fcfuh_before(read_fcfu("1e-7")) == 0.0); + CHECK(read_fcfu("1e-7") == 1e-7); + // a figure past the largest value reads as infinite (with MSVC; the largest value with GCC): written out it + // was "inf", which the stream doesn't read, so the dynamic brake got 0 where it gets the traction's figure now + auto const huge{read_fcfu("1e999")}; + CHECK(huge > 1e300); + if (std::isinf(huge)) { + CHECK(fcfuh_before(huge) == 0.0); + } +} + +TEST_CASE("fcfuH: the loader gives the dynamic brake the traction's figure when the definition has none") { + for (auto const fcfu : {"43.7", "45.18", "49", "0.000001", "1e2"}) { + CAPTURE(fcfu); + // the EU47's definition has fcfu only + vehicle eu47{definition::fiz("e186_v2/eu47").set("Engine", "fcfu", fcfu)}; + CHECK(eu47->eimc[eimc_f_cfu] == read_fcfu(fcfu)); + CHECK(bits(eu47->eimc[eimc_f_cfuH]) == bits(eu47->eimc[eimc_f_cfu])); + CHECK(bits(eu47->eimc[eimc_f_cfuH]) == bits(fcfuh_before(read_fcfu(fcfu)))); + // its own figure is kept + vehicle own{definition::fiz("e186_v2/eu47").set("Engine", "fcfu", fcfu).set("Engine", "fcfuH", "40.1")}; + CHECK(own->eimc[eimc_f_cfu] == read_fcfu(fcfu)); + CHECK(own->eimc[eimc_f_cfuH] == read_fcfu("40.1")); + } +} diff --git a/tests/unit/test_feed_pipe.cpp b/tests/unit/test_feed_pipe.cpp new file mode 100644 index 000000000..55816af43 --- /dev/null +++ b/tests/unit/test_feed_pipe.cpp @@ -0,0 +1,175 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "McZapkie/MOVER.h" +#include "McZapkie/hamulce.h" +#include "consist.h" +#include "vehicle.h" + +// the air exchange through the main reservoir hoses between the vehicles of a train (TMoverParameters::UpdatePipeCouplers()). +// taken in one explicit step of 0.01 s, a hose carried about 1.5 times the air which evens out the pipes on its ends, +// and the vehicles' own main reservoirs fed the pipe in the same step: the pipes of the middle vehicles of a multiple +// unit, or of locomotives in multiple traction, kept jumping 0.8 bar to and fro between the steps, with the main +// reservoirs all at the same pressure + +namespace { + +using test::definition; + +// an EN57 of Units units, driven from the front cab +void en57(test::consist &Train, int const Units) { + for (int i = 0; i < Units; ++i) { + Train.add(definition::fiz("en57_v1/5bgb"), i == 0 ? 1 : 0); + Train.add(definition::fiz("en57_v1/6ba_840")); + Train.add(definition::fiz("en57_v1/5bgb")); + } +} + +// Count SM40 shunters in multiple traction, driven from the first +void sm40(test::consist &Train, int const Count) { + for (int i = 0; i < Count; ++i) { + Train.add(definition::fiz("sm40_v1/sm40"), i == 0 ? 1 : 0); + } +} + +// a locomotive and Cars passenger cars, whose main reservoir pipe only the locomotive feeds +void passenger_train(test::consist &Train, int const Cars) { + Train.add(definition::fiz("ep09_v2/104e")); + for (int i = 0; i < Cars; ++i) { + Train.add(definition::fiz("11xa_v2/93a")); + } + Train[0].hold_brake_pipe(5.0); +} + +// the largest difference [bar] of a main reservoir pipe of the train from Pressure, over Seconds of steps of Dt +double off_pressure(test::consist &Train, double const Pressure, double const Seconds, double const Dt = 0.01) { + auto off{0.0}; + auto const steps{static_cast(std::lround(Seconds / Dt))}; + for (int step = 0; step < steps; ++step) { + Train.step({}, Dt); + for (std::size_t i = 0; i < Train.size(); ++i) { + off = std::max(off, std::abs(Train[i]->ScndPipePress - Pressure)); + } + } + return off; +} + +struct evening_out { + double time{60.0}; // [s] until the main reservoirs of the train's ends are within 0.05 bar + double zigzag{0.0}; // [bar] the largest step of a main reservoir pipe back and forth, between steps the other way +}; + +// the train standing, the main reservoir of its first vehicle Pressure [bar], those of the rest 1 bar below, stepping +// by Dt until they even out through the main reservoir pipe +template +evening_out even_out(Builder Train, int const Count, double const Pressure, double const Dt) { + test::consist train; + Train(train, Count); + for (std::size_t i = 0; i < train.size(); ++i) { + auto &mover{train[i].mover()}; + REQUIRE(mover.VeselVolume > 0.0); + auto const pressure{i == 0 ? Pressure : Pressure - 1.0}; + mover.CompressedVolume = pressure * mover.VeselVolume; + mover.Compressor = pressure; + mover.Pipe2->CreatePress(pressure); + mover.Pipe2->Act(); + mover.ScndPipePress = pressure; + } + evening_out result; + auto const &first{train[0].mover()}; + auto const &last{train[train.size() - 1].mover()}; + std::vector previous(train.size()); + std::vector change(train.size()); + for (std::size_t i = 0; i < train.size(); ++i) { + previous[i] = train[i]->ScndPipePress; + } + auto time{0.0}; + while (time < 60.0) { + train.step({}, Dt); + time += Dt; + for (std::size_t i = 0; i < train.size(); ++i) { + auto const step{train[i]->ScndPipePress - previous[i]}; + if (step * change[i] < 0.0) { + // turned back + result.zigzag = std::max(result.zigzag, std::min(std::abs(step), std::abs(change[i]))); + } + change[i] = step; + previous[i] = train[i]->ScndPipePress; + } + if (std::abs(first.Compressor - last.Compressor) < 0.05) { + result.time = time; + break; + } + } + return result; +} + +// the time [s] until the main reservoir pipe of the train's last vehicle, emptied with all the others which have no +// main reservoir of their own, is within 0.2 bar of the first vehicle's, which holds its main reservoir at Pressure [bar] +template +double charging_time(Builder Train, int const Count, double const Pressure, double const Dt) { + test::consist train; + Train(train, Count); + train[0].hold_main_reservoir(Pressure); + for (std::size_t i = 1; i < train.size(); ++i) { + auto &mover{train[i].mover()}; + REQUIRE(mover.VeselVolume == 0.0); + mover.Pipe2->CreatePress(0.0); + mover.Pipe2->Act(); + mover.ScndPipePress = 0.0; + } + auto const &first{train[0].mover()}; + auto const &last{train[train.size() - 1].mover()}; + auto time{0.0}; + while ((last.ScndPipePress < 1.0 || std::abs(last.ScndPipePress - first.ScndPipePress) > 0.2) && time < 60.0) { + train.step({}, Dt); + time += Dt; + } + return time; +} + +} // namespace + +TEST_CASE("main reservoir pipe: the pipes of a three unit EN57 stand at the pressure of its main reservoirs") { + test::consist train; + en57(train, 3); + for (std::size_t i = 0; i < train.size(); ++i) { + train[i].hold_main_reservoir(7.0); + } + // the pipes filling up from the reservoirs + train.run(60.0); + CHECK(off_pressure(train, 7.0, 1.0) < 0.01); + // the exchange through the hoses of the 21 m cars takes 2 sub-steps of a step of 0.01 s + CHECK(train[1]->ScndPipeCouplersSubsteps(0.01) == 2); +} + +TEST_CASE("main reservoir pipe: the pipes of locomotives in multiple traction stand at the pressure of their main reservoirs") { + test::consist train; + sm40(train, 3); + for (std::size_t i = 0; i < train.size(); ++i) { + train[i].hold_main_reservoir(7.5); + } + train.run(60.0); + CHECK(off_pressure(train, 7.5, 1.0) < 0.01); +} + +TEST_CASE("main reservoir pipe: the main reservoirs of a multiple unit even out as with a short step") { + auto const converged{even_out(en57, 3, 7.0, 0.001)}; + auto const usual{even_out(en57, 3, 7.0, 0.01)}; + CAPTURE(converged.time); + CAPTURE(usual.time); + CAPTURE(usual.zigzag); + CHECK(converged.time < 60.0); + CHECK(usual.time == doctest::Approx(converged.time).epsilon(0.1)); + // the pipes go along with the reservoirs, without jumping to and fro between the steps + CHECK(usual.zigzag < 0.05); +} + +TEST_CASE("main reservoir pipe: a passenger train, whose exchange was stable in one step, fills its pipe as with a short step") { + auto const converged{charging_time(passenger_train, 10, 9.0, 0.001)}; + auto const usual{charging_time(passenger_train, 10, 9.0, 0.01)}; + CAPTURE(converged); + CAPTURE(usual); + CHECK(converged < 60.0); + CHECK(usual == doctest::Approx(converged).epsilon(0.05)); +} diff --git a/tests/unit/test_field_shunting.cpp b/tests/unit/test_field_shunting.cpp new file mode 100644 index 000000000..e61783b0e --- /dev/null +++ b/tests/unit/test_field_shunting.cpp @@ -0,0 +1,99 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scenario.h" + +#include "vehicle/fieldshunting.h" + +// the field shunting of the diesel-electric locomotives, set by the driver or by the shunting relays, and the switch +// of the SU45 and the SP45 that lets the relays shunt the field ("załączenie bocznikowania", eu07/maszyna#167) + +using test::definition; +using test::scenario; +using namespace test::channels; + +TEST_CASE("field shunting: who shunts the field of a diesel-electric, by AutoRelay, FieldShuntSwitch and the switch") { + using enum fieldshunting::control; + struct setting { + int type; // AutoRelay: 0 No, 1 Yes, 2 Optional + bool fieldshuntswitch; // FieldShuntSwitch + bool flag; // the switch, AutoRelayFlag + fieldshunting::control expected; + }; + for (auto const &[type, fieldshuntswitch, flag, expected] : + {setting{0, false, false, manual}, setting{1, false, true, automatic}, + // AutoRelay=Optional alone, as before: off, the driver shunts by hand + setting{2, false, true, automatic}, setting{2, false, false, manual}, + // with FieldShuntSwitch=Yes the switch of the field shunting: off, nobody + setting{2, true, true, automatic}, setting{2, true, false, off}, + // FieldShuntSwitch=Yes without the switch (AutoRelay=Yes or No) changes nothing + setting{1, true, true, automatic}, setting{0, true, false, manual}, + // AutoRelaySwitch from a coupled vehicle turns the flag of every one off, as before + setting{1, false, false, manual}, setting{1, true, false, manual}}) { + CAPTURE(type); + CAPTURE(fieldshuntswitch); + CAPTURE(flag); + CHECK(fieldshunting::diesel_electric(type, fieldshuntswitch, flag) == expected); + CHECK(fieldshunting::has_switch(type, fieldshuntswitch) == (type == 2 && fieldshuntswitch)); + } +} + +TEST_CASE("field shunting: the SU45 with its switch, off at full power and switched on and off on the move") { + // the SU45 (RelayType 45) given the switch (AutoRelay=Optional, FieldShuntSwitch=Yes) its cab has, with a coach: + // off, the field stays full and the second controller can't shunt it; on, the relays shunt it as they do with + // AutoRelay=Yes; off again, the shunting drops + scenario scenario{"traction/field shunting switch/su45", motion() + traction()}; + scenario.train().add(definition::fiz("su45_v2/301d").set("Cntrl", "AutoRelay", "Optional").set("Cntrl", "FieldShuntSwitch", "Yes"), 1); + scenario.add("bdhpumn_v3/bdhpumn"); + REQUIRE(scenario.start_up()); + auto &su45{scenario.driver().controlling}; + REQUIRE(su45.AutoRelayType == 2); + REQUIRE(su45.FieldShuntSwitch); + // the driver switches it on as the AI does, getting the locomotive ready + CHECK(su45.AutoRelayFlag); + scenario.act("field shunting off"); + CHECK(su45.AutoRelaySwitch(false)); + scenario.get_going(); + scenario.full_power(120.0); + CHECK(su45.IsMainCtrlMaxPowerPos()); + CHECK(su45.StLinFlag); + CHECK(su45.ScndCtrlPos == 0); + CHECK_FALSE(su45.IncScndCtrl(1)); + scenario.wait(1.0); + CHECK(su45.ScndCtrlPos == 0); + // over 50 km/h, where the relays of the SU45 let the third stage in + CHECK(su45.Vel > 50.0); + scenario.act("field shunting on"); + CHECK(su45.AutoRelaySwitch(true)); + scenario.wait(30.0); + CHECK(su45.ScndCtrlPos == su45.ScndCtrlPosNo); + scenario.act("field shunting off on the move"); + CHECK(su45.AutoRelaySwitch(false)); + scenario.wait(1.0); + CHECK(su45.ScndCtrlPos == 0); + scenario.check(); +} + +TEST_CASE("field shunting: a diesel-electric with AutoRelay=Optional alone shunts by hand with the switch off, as before") { + // the SU45 with AutoRelay=Optional but no FieldShuntSwitch: the switch is the old one, off hands the shunting to the + // second controller, and the start-up (as the AI) leaves it off + scenario scenario{"traction/field shunting switch/su45 optional alone", motion() + traction()}; + scenario.train().add(definition::fiz("su45_v2/301d").set("Cntrl", "AutoRelay", "Optional"), 1); + scenario.add("bdhpumn_v3/bdhpumn"); + REQUIRE(scenario.start_up()); + auto &su45{scenario.driver().controlling}; + REQUIRE(su45.AutoRelayType == 2); + REQUIRE_FALSE(su45.FieldShuntSwitch); + CHECK_FALSE(su45.AutoRelayFlag); + scenario.get_going(); + scenario.full_power(120.0); + CHECK(su45.IsMainCtrlMaxPowerPos()); + CHECK(su45.StLinFlag); + // over 50 km/h: the relays don't shunt, the driver does + CHECK(su45.Vel > 50.0); + CHECK(su45.ScndCtrlPos == 0); + scenario.act("field shunting by hand"); + CHECK(su45.IncScndCtrl(1)); + scenario.wait(1.0); + CHECK(su45.ScndCtrlPos == 1); + scenario.check(); +} diff --git a/tests/unit/test_gauge_wrap.cpp b/tests/unit/test_gauge_wrap.cpp new file mode 100644 index 000000000..629183369 --- /dev/null +++ b/tests/unit/test_gauge_wrap.cpp @@ -0,0 +1,55 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/gaugewrap.h" +#include "vehicle/gaugepositions.h" + +#include +#include + +// a light preset selector with Wrap=Yes turned on past its last position to the first one, or back past the first one +// to the last (eu07/maszyna#464): the EN57AKM selector has 0 as its first position and A1 as its last one, and the +// knob, rather than jump between them with no sound, turns on to the next position as it does between any two others + +TEST_CASE("gauge wrap: a knob whose positions make a full turn turns on past its end") { + CHECK(gauge_wrap::full_turn(-0.08333f, 12) == 12); // E186, BR285: 12 positions, 30 degrees each + CHECK(gauge_wrap::full_turn(-0.0625f, 16) == 16); // E189: 16 positions + CHECK(gauge_wrap::full_turn(-0.167f, 6) == 6); // EN57AL Zachodniopomorskie: a sixth given as 0.167 +} + +TEST_CASE("gauge wrap: a knob with a free position in its turn turns on across it (eu07/maszyna#464)") { + // EN57AKM: 7 positions, 45 degrees each, A1 at 270 degrees, 0 at 0 degrees: 90 degrees on from A1 to 0 + CHECK(gauge_wrap::full_turn(0.125f, 7) == 8); + // the way on is half a turn at most + CHECK(gauge_wrap::full_turn(0.25f, 3) == 4); + CHECK_FALSE(gauge_wrap::full_turn(0.125f, 4).has_value()); +} + +TEST_CASE("gauge wrap: a switch whose positions don't make a full turn doesn't turn on past its end") { + CHECK_FALSE(gauge_wrap::full_turn(0.1f, 12).has_value()); // the positions would overlap in a turn + CHECK_FALSE(gauge_wrap::full_turn(0.15f, 6).has_value()); // 6.67 positions in a turn + CHECK_FALSE(gauge_wrap::full_turn(0.f, 6).has_value()); // no motion + CHECK_FALSE(gauge_wrap::full_turn(0.5f, 1).has_value()); // nothing to turn to +} + +TEST_CASE("gauge wrap: turned round, the knob stands the same one turn earlier or later") { + // EN57AKM, from A1 (value 6) on to 0: from -2 up to 0, 90 degrees the way it was turned + CHECK(gauge_wrap::turned_round(6.f, 8, true) == doctest::Approx(-2.f)); + // from 0 back to A1 (value 6): from 8 down to 6 + CHECK(gauge_wrap::turned_round(0.f, 8, false) == doctest::Approx(8.f)); + // the angle stays: value * scale differs by one full turn + CHECK((6.f - gauge_wrap::turned_round(6.f, 8, true)) * 0.125f == doctest::Approx(1.f)); +} + +TEST_CASE("gauge wrap: turned round, the knob sounds the position it reaches (eu07/maszyna#464)") { + // the EN57AKM selector has a sound for each position 0-7, as values of the gauge + std::map sounds{{0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}, {7, 7}}; + auto const reached{[&sounds](float const From, float const To) { + auto const position{gauge_positions::last_reached(sounds, static_cast(std::round(100.f * From)), static_cast(std::round(100.f * To)))}; + return position != sounds.end() ? position->second : -1; + }}; + // A1 (6) on to 0 + CHECK(reached(gauge_wrap::turned_round(6.f, 8, true), 0.f) == 0); + // 0 back to A1 (6) + CHECK(reached(gauge_wrap::turned_round(0.f, 8, false), 6.f) == 6); +} diff --git a/tests/unit/test_genset.cpp b/tests/unit/test_genset.cpp new file mode 100644 index 000000000..c3b4f3015 --- /dev/null +++ b/tests/unit/test_genset.cpp @@ -0,0 +1,662 @@ +#include "stdafx.h" +#include "doctest.h" +#include "consist.h" +#include "drive.h" +#include "golden.h" + +#include "McZapkie/hamulce.h" + +// the genset of a dual-mode vehicle (eu07/maszyna#536): a second source of the traction circuit of an induction +// motor vehicle next to its pantographs, which the traction selector picks. the vehicle is the game's E6ACT +// (Dragon 2) with the genset of the E6ACTad "last mile" set in the test: 520 kW, the rest assumed + +using test::consist; +using test::definition; +using test::track; +using test::vehicle; +using traction_mode = TMoverParameters::traction_mode; + +namespace { + +definition dragon() { + return definition::fiz("e6act_v2/e6acta"); +} + +definition dragon_genset() { + return dragon() + .set("Power", "GensetPower", 520) + .set("Power", "GensetVoltage", 3000) + .set("Power", "GensetIdleRPM", 700) + .set("Power", "GensetMaxRPM", 1800) + .set("Power", "GensetStartTime", 8) + .set("Power", "GensetSpinUpTime", 3) + .set("Power", "GensetPmaxRatio", 0.85); +} + +// the power the traction of dragon_genset() may take at full revolutions [kW] +double const genset_traction_power{520.0 * 0.85}; + +track const no_wire{0.15, 0.0, 0.0}; +track const wire{0.15, 0.0, test::catenary_3kv}; + +// the battery, the cab and a direction, as the driver begins +void wake(TMoverParameters &Cab) { + Cab.BatterySwitch(true); + Cab.CabActivisation(); + for (int i = 0; i < 3 && Cab.DirActive <= 0; ++i) { + Cab.DirectionForward(); + } +} + +// the vigilance and the cab signalling acknowledged, as test::drive() does once a second +void attend(TMoverParameters &Cab) { + if (Cab.SecuritySystem.is_cabsignal_blinking() && Cab.SecuritySystem.has_separate_acknowledge()) { + Cab.SecuritySystem.cabsignal_reset(); + } + if (Cab.SecuritySystem.is_blinking()) { + Cab.SecuritySystemReset(); + } +} + +void run(vehicle &Vehicle, double const Seconds, track const &Track = no_wire) { + test::drive(test::driving(Vehicle), Track, Seconds); +} + +// the line breaker closed, which it does only with the controller at zero, and after the relays are reset +void close_line_breaker(TMoverParameters &Cab) { + while (Cab.DecMainCtrl(2)) { + // down to zero + } + Cab.RelayReset(relay_t::maincircuitground | relay_t::tractionnmotoroverload | relay_t::primaryconverteroverload); + Cab.MainSwitch(true); +} + +// gets the vehicle ready to run on its genset, as test::start_up() does on the pantographs: the selector on the +// genset, the genset started, the line breaker closed once it runs, the converter and the compressor, the air, the +// brakes released. one round of the driver's actions a second; returns whether the vehicle got ready +bool start_on_genset(vehicle &Vehicle, track const &Track = no_wire, double const Seconds = 300.0) { + auto &cab{Vehicle.mover()}; + for (auto second = 0; second < Seconds; ++second) { + wake(cab); + cab.TractionModeSwitch(traction_mode::genset); + cab.GensetSwitch(true); + if (false == cab.Mains) { + if (cab.MainSwitchCheck()) { + close_line_breaker(cab); + } + } + else { + cab.ConverterSwitch(true); + cab.CompressorSwitch(true); + } + run(Vehicle, 1.0, Track); + if (cab.Mains && cab.ConverterFlag && cab.ScndPipePress >= 4.5) { + // and the brakes let go + test::release_brakes(cab); + for (auto wait = 0; wait < 120 && cab.BrakePress > 0.05; ++wait) { + run(Vehicle, 1.0, Track); + } + return cab.BrakePress <= 0.05; + } + } + return false; +} + +// the main controller to its full power position +void notch_up(TMoverParameters &Cab) { + for (int i = 0; i < 60 && false == Cab.IsMainCtrlMaxPowerPos(); ++i) { + Cab.IncMainCtrl(1); + } +} + +// the power at the wheels [kW] +double wheel_power(TMoverParameters const &Vehicle) { + return std::abs(Vehicle.Ft * Vehicle.V) / 1000.0; +} + +// one step of 0.01 s, acknowledging the vigilance once a second +void step(vehicle &Vehicle, long const Step, track const &Track = no_wire) { + if (Step % 100 == 0) { + attend(Vehicle.mover()); + } + Vehicle.step(Track); +} + +} // namespace + +TEST_CASE("genset: a vehicle without the keys has none and stays on the catenary") { + vehicle dragon6{dragon(), 0.0, "plain", 1}; + auto &cab{dragon6.mover()}; + CHECK(cab.Genset.power == 0.0); + CHECK_FALSE(cab.Genset.fitted()); + CHECK_FALSE(cab.TractionModeSwitch(traction_mode::genset)); + CHECK(cab.TractionMode == traction_mode::catenary); + CHECK_FALSE(cab.GensetSelected()); + REQUIRE(test::start_up(test::driving(dragon6), wire)); + CHECK(cab.PantographVoltage > 2900.0); + CHECK(cab.TractionSupplyVoltage() == std::max(cab.GetTrainsetHighVoltage(), cab.PantographVoltage)); + CHECK(cab.TractionSupplyMinVoltage() == cab.EnginePowerSource.CollectorParameters.MinV); + CHECK(cab.GensetTractionPowerLimit() == std::numeric_limits::max()); + // a start request does nothing without a genset + cab.GensetSwitch(true); + run(dragon6, 20.0, wire); + CHECK_FALSE(cab.Genset.is_active); + CHECK(cab.Genset.voltage == 0.0); + CHECK(cab.TractionMode == traction_mode::catenary); +} + +TEST_CASE("genset: the keys reach the vehicle") { + vehicle dragon6{dragon_genset()}; + auto const &genset{dragon6->Genset}; + CHECK(genset.fitted()); + CHECK(genset.power == 520.0); + CHECK(genset.voltage_nominal == 3000.0); + CHECK(genset.revolutions_idle == doctest::Approx(700.0 / 60.0)); + CHECK(genset.revolutions_max == doctest::Approx(30.0)); + CHECK(genset.start_time == 8.0); + CHECK(genset.spinup_time == 3.0); + CHECK(genset.traction_share == 0.85); + CHECK(genset.start_type == start_t::manual); + CHECK(dragon6->TractionMode == traction_mode::catenary); + // the pantographs stay what they were + CHECK(dragon6->EnginePowerSource.SourceType == TPowerSource::CurrentCollector); + CHECK(dragon6->EnginePowerSource.CollectorParameters.MinV == 2000.0); + + SUBCASE("started on its own") { + vehicle automatic{dragon_genset().set("Cntrl", "GensetStart", "Automatic")}; + CHECK(automatic->Genset.start_type == start_t::automatic); + } + SUBCASE("the defaults") { + vehicle defaults{dragon().set("Power", "GensetPower", 520)}; + auto const &plain{defaults->Genset}; + CHECK(plain.fitted()); + CHECK(plain.voltage_nominal == doctest::Approx(0.65 * 4600.0)); // of the pantographs' MaxVoltage + CHECK(plain.revolutions_idle == doctest::Approx(10.0)); + CHECK(plain.revolutions_max == doctest::Approx(30.0)); + CHECK(plain.start_time == 8.0); + CHECK(plain.spinup_time == 3.0); + CHECK(plain.traction_share == 1.0); + } +} + +TEST_CASE("genset: the keys are ignored on other than induction motor vehicles") { + for (auto const *path : {"4e_v1/4e", "br285_v1/br285"}) { + CAPTURE(path); + vehicle other{definition::fiz(path).set("Power", "GensetPower", 520)}; + CHECK_FALSE(other->Genset.fitted()); + CHECK_FALSE(other->TractionModeSwitch(traction_mode::genset)); + CHECK(other->TractionMode == traction_mode::catenary); + } +} + +TEST_CASE("genset: the selector moves only with the line breaker open") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + REQUIRE(test::start_up(test::driving(dragon6), wire)); + REQUIRE(cab.Mains); + CHECK_FALSE(cab.TractionModeSwitch(traction_mode::genset)); + CHECK(cab.TractionMode == traction_mode::catenary); + run(dragon6, 2.0, wire); + CHECK(cab.Mains); + cab.MainSwitch(false); + REQUIRE_FALSE(cab.Mains); + CHECK(cab.TractionModeSwitch(traction_mode::genset)); + CHECK(cab.GensetSelected()); + CHECK(cab.TractionModeSwitch(traction_mode::catenary)); + CHECK(cab.TractionMode == traction_mode::catenary); +} + +TEST_CASE("genset: started, it closes the line breaker without a catenary") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + wake(cab); + REQUIRE(cab.TractionModeSwitch(traction_mode::genset)); + cab.GensetSwitch(true); + run(dragon6, 7.0); + CHECK(cab.Genset.is_cranking); + CHECK_FALSE(cab.Genset.is_active); + CHECK(cab.Genset.voltage == 0.0); + CHECK_FALSE(cab.MainSwitchCheck()); + run(dragon6, 2.0); + CHECK(cab.Genset.is_active); + CHECK_FALSE(cab.Genset.is_cranking); + CHECK(cab.Genset.revolutions == cab.Genset.revolutions_idle); + CHECK(cab.Genset.voltage == 3000.0); + // the line breaker gets ready MainInitTime after the voltage came + for (auto second = 0; second < 10 && false == cab.Mains; ++second) { + if (cab.MainSwitchCheck()) { + close_line_breaker(cab); + } + run(dragon6, 1.0); + } + REQUIRE(cab.Mains); + CHECK(cab.PantographVoltage == 0.0); + dragon6.step(no_wire); + CHECK(cab.EngineVoltage == 3000.0); + CHECK(cab.MainCircuitPowered()); + run(dragon6, 5.0); + CHECK(cab.Mains); +} + +TEST_CASE("genset: on the catenary position the genset feeds nothing") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + wake(cab); + cab.GensetSwitch(true); + run(dragon6, 20.0); + REQUIRE(cab.Genset.is_active); + CHECK(cab.TractionMode == traction_mode::catenary); + CHECK_FALSE(cab.MainSwitchCheck()); + close_line_breaker(cab); + CHECK_FALSE(cab.Mains); + dragon6.step(no_wire); + CHECK(cab.EngineVoltage == 0.0); + CHECK(cab.TractionSupplyVoltage() == 0.0); + // running isolated, at idle + CHECK(cab.Genset.revolutions == cab.Genset.revolutions_idle); +} + +TEST_CASE("genset: on the genset position the catenary feeds nothing") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + wake(cab); + REQUIRE(cab.TractionModeSwitch(traction_mode::genset)); + // the pantographs up under the wire, the genset stopped: the line breaker never closes + CHECK_FALSE(test::start_up(test::driving(dragon6), wire, 120.0)); + REQUIRE(cab.PantographVoltage > 2900.0); + CHECK_FALSE(cab.Mains); + CHECK_FALSE(cab.MainSwitchCheck()); + dragon6.step(wire); + CHECK(cab.EngineVoltage == 0.0); + CHECK(cab.TractionSupplyVoltage() == 0.0); +} + +TEST_CASE("genset: the power at the wheels stays within the genset's") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + REQUIRE(start_on_genset(dragon6)); + notch_up(cab); + auto peak{0.0}; + auto revolutions{0.0}; + auto over{0L}; + auto step_count{0L}; + for (; step_count < 60000 && cab.Vel < 80.0 && cab.Mains; ++step_count) { + step(dragon6, step_count); + auto const power{wheel_power(cab)}; + peak = std::max(peak, power); + revolutions = std::max(revolutions, cab.Genset.revolutions); + if (power > genset_traction_power * 1.02) { + ++over; + } + } + CAPTURE(step_count); + CAPTURE(peak); + CHECK(cab.Mains); + CHECK(cab.Vel >= 80.0); + CHECK(over == 0); + CHECK(peak <= genset_traction_power * 1.02); + CHECK(peak >= genset_traction_power * 0.95); // the limit bites + CHECK(revolutions >= 0.95 * cab.Genset.revolutions_max); +} + +TEST_CASE("genset: the revolutions follow the demand, so the power builds up") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + REQUIRE(start_on_genset(dragon6)); + // at idle with nothing asked of it + CHECK(cab.Genset.revolutions == doctest::Approx(cab.Genset.revolutions_idle)); + CHECK(cab.GensetTractionPowerLimit() == doctest::Approx(genset_traction_power * 700.0 / 1800.0).epsilon(0.001)); + notch_up(cab); + // the demand of the traction builds up at the pace of the inverters, the revolutions follow it + auto step_count{0L}; + for (; step_count < 3000 && cab.eimv_pr < 0.99; ++step_count) { + step(dragon6, step_count); + } + CAPTURE(step_count); + REQUIRE(cab.eimv_pr >= 0.99); + run(dragon6, 3.0); + auto const after3{cab.Genset.available_power()}; + CAPTURE(after3); + // first order: 1 - exp(-1) of the way from idle to full in the time constant at the least + CHECK(after3 > 520.0 * 0.75); + run(dragon6, 9.0); + CHECK(cab.Genset.available_power() > 520.0 * 0.95); + CHECK(cab.GensetTractionPowerLimit() == doctest::Approx(cab.Genset.available_power() * 0.85)); + // notched down it goes back to idle + while (cab.DecMainCtrl(2)) { + // down to zero + } + run(dragon6, 20.0); + CHECK(cab.Genset.revolutions == doctest::Approx(cab.Genset.revolutions_idle).epsilon(0.01)); +} + +TEST_CASE("genset: running from the catenary is the same with the keys") { + // the values of a run of each one, every step + struct values { + std::vector force; + std::vector speed; + std::vector voltage; + std::vector current; + std::vector demand; + }; + auto const record = [](values &Values) { + return std::vector{ + {"Ft", [&Values](TMoverParameters const &Vehicle) { Values.force.push_back(Vehicle.Ft); return Vehicle.Ft; }}, + {"V", [&Values](TMoverParameters const &Vehicle) { Values.speed.push_back(Vehicle.V); return Vehicle.V; }}, + {"EngineVoltage", [&Values](TMoverParameters const &Vehicle) { Values.voltage.push_back(Vehicle.EngineVoltage); return Vehicle.EngineVoltage; }}, + {"Itot", [&Values](TMoverParameters const &Vehicle) { Values.current.push_back(Vehicle.Itot); return Vehicle.Itot; }}, + {"eimv_pr", [&Values](TMoverParameters const &Vehicle) { Values.demand.push_back(Vehicle.eimv_pr); return Vehicle.eimv_pr; }}, + }; + }; + auto const drive = [&record](definition const &Definition, values &Values) { + test::reseed_random(); + vehicle dragon6{Definition, 0.0, "test", 1}; + // not checked against a recorded one: the runs are compared with each other + test::trace trace{"genset/catenary", record(Values), 1, false}; + dragon6.record(trace); + test::drive_cycle(test::driving(dragon6), wire, trace); + }; + values plain; + values genset; + drive(dragon(), plain); + drive(dragon_genset(), genset); + REQUIRE(plain.speed.size() > 10000); + REQUIRE(genset.speed.size() == plain.speed.size()); + CHECK(*std::ranges::max_element(plain.speed) > 10.0); + // the first step they differ in, if any + auto const first_difference = [](std::vector const &Left, std::vector const &Right) { + return std::ranges::mismatch(Left, Right).in1 - Left.begin(); + }; + auto const size{static_cast(plain.speed.size())}; + CHECK(first_difference(plain.force, genset.force) == size); + CHECK(first_difference(plain.speed, genset.speed) == size); + CHECK(first_difference(plain.voltage, genset.voltage) == size); + CHECK(first_difference(plain.current, genset.current) == size); + CHECK(first_difference(plain.demand, genset.demand) == size); +} + +TEST_CASE("genset: stopped, it opens the line breaker") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + REQUIRE(start_on_genset(dragon6)); + REQUIRE(cab.Genset.revolutions == doctest::Approx(cab.Genset.revolutions_idle)); + cab.GensetSwitch(false); + auto step_count{0L}; + for (; step_count < 1000 && cab.Mains; ++step_count) { + step(dragon6, step_count); + } + // coasting down from idle, the voltage falls to half, the undervoltage limit, in spinup_time * ln 2 + auto const seconds{step_count * 0.01}; + CAPTURE(seconds); + CHECK_FALSE(cab.Mains); + CHECK(seconds == doctest::Approx(3.0 * std::log(2.0)).epsilon(0.05)); + CHECK_FALSE(cab.Genset.is_active); + // and it doesn't close again + for (auto second = 0; second < 20; ++second) { + close_line_breaker(cab); + run(dragon6, 1.0); + } + CHECK_FALSE(cab.Mains); + // coasting down to a stop, with the time constant spinup_time + CHECK(cab.Genset.revolutions < 0.01 * cab.Genset.revolutions_idle); + CHECK(cab.Genset.voltage < 0.01 * cab.Genset.voltage_nominal); +} + +TEST_CASE("genset: automatic start follows the selector") { + vehicle dragon6{dragon_genset().set("Cntrl", "GensetStart", "Automatic"), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + wake(cab); + run(dragon6, 10.0); + CHECK_FALSE(cab.Genset.is_cranking); + CHECK_FALSE(cab.Genset.is_active); + REQUIRE(cab.TractionModeSwitch(traction_mode::genset)); + run(dragon6, 1.0); + CHECK(cab.Genset.is_cranking); + run(dragon6, 8.0); + CHECK(cab.Genset.is_active); + // the start switch does nothing to it + CHECK_FALSE(cab.GensetSwitch(false)); + run(dragon6, 1.0); + CHECK(cab.Genset.is_active); + REQUIRE(cab.TractionModeSwitch(traction_mode::catenary)); + dragon6.step(no_wire); + CHECK_FALSE(cab.Genset.is_active); +} + +TEST_CASE("genset: no battery, no start") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + cab.BatterySwitch(false); + REQUIRE(cab.TractionModeSwitch(traction_mode::genset)); + cab.GensetSwitch(true); + run(dragon6, 20.0); + CHECK_FALSE(cab.Power24vIsAvailable); + CHECK_FALSE(cab.Genset.is_cranking); + CHECK_FALSE(cab.Genset.is_active); + CHECK(cab.Genset.revolutions == 0.0); + // and with it, it starts + wake(cab); + run(dragon6, 10.0); + CHECK(cab.Genset.is_active); +} + +TEST_CASE("genset: the pantographs' pressure switch leaves the genset's line breaker alone") { + SUBCASE("on the genset") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + REQUIRE(start_on_genset(dragon6)); + cab.PantPressSwitchActive = true; + cab.PantPress = 0.0; + cab.PantPressureSwitchCheck(); + CHECK(cab.Mains); + } + SUBCASE("on the pantographs it opens the line breaker, the check the genset is spared") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + REQUIRE(test::start_up(test::driving(dragon6), wire)); + REQUIRE(cab.Mains); + // the pressure switch looks at the voltage through the couplers, not the pantographs' + cab.PantPressSwitchActive = true; + cab.PantPress = 0.0; + cab.PantPressureSwitchCheck(); + CHECK_FALSE(cab.Mains); + } +} + +namespace { + +// what braking showed of the current of the traction circuit +struct braking { + double lowest_current{0.0}; // [A], negative going back to the source + bool electrodynamic{false}; // whether the electrodynamic brake took part + double speed_lost{0.0}; // [km/h] in the 20 s of braking +}; + +// up to 60 km/h at full power, then braking with the train brake for 20 s, which the E6ACT blends with the +// electrodynamic one +braking brake_from_60(vehicle &Dragon, track const &Track) { + auto &cab{Dragon.mover()}; + notch_up(cab); + for (auto step_count = 0L; step_count < 60000 && cab.Vel < 60.0; ++step_count) { + step(Dragon, step_count, Track); + } + REQUIRE(cab.Vel >= 60.0); + while (cab.DecMainCtrl(2)) { + // down to zero + } + run(Dragon, 2.0, Track); + cab.DynamicBrakeSwitch(true); + cab.BrakeLevelSet(cab.Handle->GetPos(bh_FB)); + braking result; + auto const speed{cab.Vel}; + for (auto step_count = 0L; step_count < 2000; ++step_count) { + step(Dragon, step_count, Track); + result.lowest_current = std::min(result.lowest_current, cab.Itot); + result.electrodynamic |= cab.eimv_pr < 0.0 && cab.eimv[eimv_Ipoj] < 0.0; + } + result.speed_lost = speed - cab.Vel; + return result; +} + +} // namespace + +TEST_CASE("genset: braking electrodynamically on the genset sends nothing back") { + SUBCASE("on the genset") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + REQUIRE(start_on_genset(dragon6)); + auto const braked{brake_from_60(dragon6, no_wire)}; + REQUIRE(braked.electrodynamic); + CHECK(braked.lowest_current >= -1e-6); + CHECK(braked.speed_lost > 5.0); + CHECK(dragon6->Mains); + } + SUBCASE("on the catenary the same braking feeds the line, the check the genset is spared") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + REQUIRE(test::start_up(test::driving(dragon6), wire)); + test::release_brakes(dragon6.mover()); + run(dragon6, 5.0, wire); + auto const braked{brake_from_60(dragon6, wire)}; + REQUIRE(braked.electrodynamic); + CHECK(braked.lowest_current < -10.0); + CHECK(braked.speed_lost > 5.0); + } +} + +TEST_CASE("genset: one genset feeds the next car through the high voltage coupling") { + // both able to join the control and the high voltage lines: 35 of the E6ACT, + control 4 + high voltage 8 + consist train; + auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 1).mover()}; + auto &second{train.add(dragon().set("BuffCoupl", "AllowedFlag", 47)).mover()}; + REQUIRE((first.Couplers[end::rear].CouplingFlag & coupling::highvoltage) != 0); + wake(first); + REQUIRE(first.TractionModeSwitch(traction_mode::genset)); + first.GensetSwitch(true); + train.run(5.0, no_wire); + CHECK(second.GetTrainsetHighVoltage() == 0.0); + train.run(10.0, no_wire); + REQUIRE(first.Genset.is_active); + CHECK(second.GetTrainsetHighVoltage() > 2900.0); + CHECK(second.PantographVoltage == 0.0); + // the second one, on its catenary position with the pantographs down, takes it as the catenary's + second.BatterySwitch(true); + train.run(10.0, no_wire); + second.RelayReset(relay_t::maincircuitground | relay_t::tractionnmotoroverload | relay_t::primaryconverteroverload, range_t::local); + CHECK(second.MainSwitchCheck()); + second.MainSwitch(true, range_t::local); + CHECK(second.Mains); + // stopped, the genset takes the voltage away + first.GensetSwitch(false); + train.run(30.0, no_wire); + CHECK(second.GetTrainsetHighVoltage() < 1.0); + CHECK_FALSE(second.Mains); +} + +TEST_CASE("genset: the selector command travels along the train") { + // two locomotives in multiple: the control line, no permanent coupling + auto const coupling{coupling::coupler | coupling::brakehose | coupling::mainhose | coupling::control}; + consist train; + auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 1).mover()}; + auto &second{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 0, coupling).mover()}; + REQUIRE((first.Couplers[end::rear].CouplingFlag & coupling::control) != 0); + wake(first); + train.run(1.0, no_wire); + CHECK(first.TractionModeSwitch(traction_mode::genset, range_t::consist)); + CHECK(first.GensetSelected()); + CHECK(second.GensetSelected()); + first.GensetSwitch(true, range_t::consist); + CHECK(first.Genset.is_enabled); + CHECK(second.Genset.is_enabled); + first.TractionModeSwitch(traction_mode::catenary, range_t::consist); + CHECK_FALSE(second.GensetSelected()); + // the unit range keeps to the permanent couplings, which locomotives in multiple don't have + first.TractionModeSwitch(traction_mode::genset, range_t::unit); + CHECK(first.GensetSelected()); + CHECK_FALSE(second.GensetSelected()); +} + +TEST_CASE("genset: a selector command refused with the line breaker closed isn't passed on") { + auto const coupling{coupling::coupler | coupling::brakehose | coupling::mainhose | coupling::control}; + consist train; + auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 1).mover()}; + auto &second{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 0, coupling).mover()}; + REQUIRE(test::start_up(test::driving(train), wire)); + REQUIRE(first.Mains); + // the second one's line breaker opened by itself, the lead's is closed + second.MainSwitch(false, range_t::local); + REQUIRE_FALSE(second.Mains); + CHECK_FALSE(first.TractionModeSwitch(traction_mode::genset, range_t::consist)); + CHECK_FALSE(first.GensetSelected()); + CHECK_FALSE(second.GensetSelected()); + // with the lead's open it goes along + first.MainSwitch(false, range_t::local); + CHECK(first.TractionModeSwitch(traction_mode::genset, range_t::consist)); + CHECK(first.GensetSelected()); + CHECK(second.GensetSelected()); +} + +TEST_CASE("genset: a lead which starts its genset on its own passes the start switch on") { + auto const coupling{coupling::coupler | coupling::brakehose | coupling::mainhose | coupling::control}; + consist train; + auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47).set("Cntrl", "GensetStart", "Automatic"), 1).mover()}; + auto &second{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 0, coupling).mover()}; + wake(first); + train.run(1.0, no_wire); + // ignored by the lead, so its cab switch doesn't move, but the car behind starts on it + CHECK_FALSE(first.GensetSwitch(true, range_t::consist)); + CHECK_FALSE(first.Genset.is_enabled); + CHECK(second.Genset.is_enabled); + CHECK_FALSE(first.GensetSwitch(false, range_t::consist)); + CHECK_FALSE(second.Genset.is_enabled); +} + +TEST_CASE("genset: on the genset the pantographs carry no traction current") { + SUBCASE("on the genset") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + REQUIRE(start_on_genset(dragon6)); + notch_up(cab); + run(dragon6, 10.0); + REQUIRE(cab.Itot > 50.0); + CHECK(cab.CatenaryCurrent() == 0.0); + // only a heating fed straight from the pantographs takes from the wire + cab.TotalCurrent = 40.0; + cab.HeatingPowerSource.SourceType = TPowerSource::CurrentCollector; + CHECK(cab.CatenaryCurrent() == 40.0); + cab.HeatingPowerSource.SourceType = TPowerSource::Main; + CHECK(cab.CatenaryCurrent() == 0.0); + } + SUBCASE("on the catenary the traction current goes through them, the check the genset is spared") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + REQUIRE(test::start_up(test::driving(dragon6), wire)); + test::release_brakes(cab); + run(dragon6, 5.0, wire); + notch_up(cab); + for (auto step_count = 0L; step_count < 60000 && cab.Vel < 30.0; ++step_count) { + step(dragon6, step_count, wire); + } + CAPTURE(cab.Vel); + REQUIRE(cab.Itot > 50.0); + CHECK(cab.CatenaryCurrent() == std::abs(cab.Itot) * cab.IsVehicleEIMBrakingFactor() + cab.TotalCurrent); + CHECK(cab.CatenaryCurrent() > 50.0); + } +} + +TEST_CASE("genset: a scenery command reaches the selector") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.mover()}; + wake(cab); + // as a scenery's PutValues event gives it, one at a time + cab.PutCommand("TractionMode", 1, 0, cab.Loc); + dragon6.step(no_wire); + CHECK(cab.GensetSelected()); + CHECK(cab.CommandIn.Command.empty()); + cab.PutCommand("GensetSwitch", 1, 0, cab.Loc); + dragon6.step(no_wire); + CHECK(cab.Genset.is_enabled); + run(dragon6, 10.0); + CHECK(cab.Genset.is_active); + cab.PutCommand("TractionMode", 0, 0, cab.Loc); + dragon6.step(no_wire); + CHECK_FALSE(cab.GensetSelected()); +} diff --git a/tests/unit/test_hardware_info.cpp b/tests/unit/test_hardware_info.cpp new file mode 100644 index 000000000..73023ca23 --- /dev/null +++ b/tests/unit/test_hardware_info.cpp @@ -0,0 +1,236 @@ +#include "stdafx.h" +#include "doctest.h" +#include "utilities/hardwareinfo.h" + +// what the log says of the machine at startup (utilities/hardwareinfo.h): the names of real GPUs, as DXGI and the +// OpenGL drivers give them, and the text of /proc on Linux +using namespace hardware; + +TEST_CASE("hardware info: NVIDIA GPUs are discrete") +{ + CHECK(classify_gpu(vendor_nvidia, "NVIDIA GeForce RTX 3060") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_nvidia, "NVIDIA GeForce MX150") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_nvidia, "NVIDIA RTX A2000 Laptop GPU") == gpu_kind::discrete); +} + +TEST_CASE("hardware info: Intel GPUs are integrated, except the Arc cards and Iris Xe MAX") +{ + CHECK(classify_gpu(vendor_intel, "Intel(R) UHD Graphics 630") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_intel, "Intel(R) HD Graphics 4600") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_intel, "Intel(R) Iris(R) Xe Graphics") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) Graphics") == gpu_kind::integrated); // Meteor Lake + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) 140V GPU (16GB)") == gpu_kind::integrated); // Lunar Lake + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) B390 GPU") == gpu_kind::integrated); // Panther Lake + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) B370 GPU") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) A310 Graphics") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) A380 Graphics") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) A370M Graphics") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) B570 Graphics") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) A770 Graphics") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) B580 Graphics") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) Pro A60 Graphics") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_intel, "Intel(R) Iris(R) Xe MAX Graphics") == gpu_kind::discrete); +} + +TEST_CASE("hardware info: AMD cards are discrete, the APUs integrated, the rest unknown") +{ + CHECK(classify_gpu(vendor_amd, "AMD Radeon RX 6600") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_amd, "Radeon RX 580 Series") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_amd, "AMD Radeon Pro W6600") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_amd, "AMD Radeon VII") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_amd, "AMD FirePro W5100") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_amd, "AMD Radeon(TM) Graphics") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_amd, "AMD Radeon(TM) Vega 8 Graphics") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_amd, "AMD Radeon 780M Graphics") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_amd, "AMD Radeon(TM) R7 Graphics") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_amd, "AMD Radeon(TM) RX Vega 11 Graphics") == gpu_kind::integrated); // Raven Ridge + CHECK(classify_gpu(vendor_amd, "AMD Radeon(TM) RX Vega 10 Graphics") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_amd, "Radeon RX Vega") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_amd, "AMD Radeon RX Vega 56") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_amd, "Radeon RX Vega M GH Graphics") == gpu_kind::discrete); // Kaby Lake G, own memory + CHECK(classify_gpu(vendor_amd, "AMD Radeon R7 370") == gpu_kind::unknown); + CHECK(classify_gpu(vendor_amd, "AMD Radeon HD 7850") == gpu_kind::unknown); + CHECK(classify_gpu(vendor_amd_alt, "AMD Radeon(TM) Graphics") == gpu_kind::integrated); +} + +TEST_CASE("hardware info: other vendors are unknown, software renderers software") +{ + CHECK(classify_gpu(0x15ad, "VMware SVGA 3D") == gpu_kind::unknown); + CHECK(classify_gpu(0x5143, "Qualcomm(R) Adreno(TM) X1-85 GPU") == gpu_kind::unknown); + CHECK(classify_gpu(vendor_microsoft, "Microsoft Basic Render Driver") == gpu_kind::software); +} + +TEST_CASE("hardware info: the OpenGL vendor and renderer strings") +{ + // Windows drivers + CHECK(vendor_from_gl("NVIDIA Corporation", "NVIDIA GeForce RTX 3060/PCIe/SSE2") == vendor_nvidia); + CHECK(vendor_from_gl("ATI Technologies Inc.", "AMD Radeon RX 6600") == vendor_amd); + CHECK(vendor_from_gl("Intel", "Intel(R) UHD Graphics 630") == vendor_intel); + // Mesa names the maker in the renderer + CHECK(vendor_from_gl("Mesa", "Mesa Intel(R) UHD Graphics 620 (KBL GT2)") == vendor_intel); + CHECK(vendor_from_gl("X.Org", "AMD Radeon Graphics (radeonsi, renoir, LLVM 15.0.7, DRM 3.49)") == vendor_amd); + CHECK(vendor_from_gl("Mesa", "llvmpipe (LLVM 15.0.7, 256 bits)") == 0); + + CHECK(classify_gl("NVIDIA Corporation", "NVIDIA GeForce RTX 3060/PCIe/SSE2") == gpu_kind::discrete); + CHECK(classify_gl("Intel", "Intel(R) UHD Graphics 630") == gpu_kind::integrated); + CHECK(classify_gl("ATI Technologies Inc.", "AMD Radeon(TM) Graphics") == gpu_kind::integrated); + CHECK(classify_gl("X.Org", "AMD Radeon Graphics (radeonsi, renoir, LLVM 15.0.7, DRM 3.49)") == gpu_kind::integrated); + CHECK(classify_gl("AMD", "AMD Radeon RX 6600 (radeonsi, navi23, LLVM 17.0.6, DRM 3.57)") == gpu_kind::discrete); + CHECK(classify_gl("Intel", "Mesa Intel(R) Arc(tm) A770 Graphics (DG2)") == gpu_kind::discrete); + CHECK(classify_gl("Mesa", "llvmpipe (LLVM 15.0.7, 256 bits)") == gpu_kind::software); + CHECK(classify_gl("Microsoft Corporation", "GDI Generic") == gpu_kind::software); + CHECK(classify_gl("nouveau", "NV138") == gpu_kind::unknown); +} + +namespace { +gpu_adapter adapter(std::string Description, std::uint32_t const VendorId, bool const Software = false) +{ + gpu_adapter result; + result.description = std::move(Description); + result.vendor_id = VendorId; + result.software = Software; + return result; +} +} // namespace + +TEST_CASE("hardware info: a warning when OpenGL runs on the integrated GPU beside a dedicated one") +{ + std::vector const laptop{adapter("Intel(R) UHD Graphics 630", vendor_intel), adapter("NVIDIA GeForce GTX 1650", vendor_nvidia)}; + + auto const warnings{gl_warnings(laptop, "Intel", "Intel(R) UHD Graphics 630")}; + REQUIRE(warnings.size() == 1); + CHECK(warnings.front().starts_with("hardware: warning: ")); + CHECK(warnings.front().find("Intel(R) UHD Graphics 630") != std::string::npos); + CHECK(warnings.front().find("NVIDIA GeForce GTX 1650") != std::string::npos); + + // on the dedicated one all is well + CHECK(gl_warnings(laptop, "NVIDIA Corporation", "NVIDIA GeForce GTX 1650/PCIe/SSE2").empty()); + // a desktop with the integrated GPU only, or a GPU that can't be told, says nothing + CHECK(gl_warnings({adapter("Intel(R) UHD Graphics 630", vendor_intel)}, "Intel", "Intel(R) UHD Graphics 630").empty()); + CHECK(gl_warnings({adapter("AMD Radeon HD 7850", vendor_amd), adapter("Intel(R) HD Graphics 4600", vendor_intel)}, "Intel", "Intel(R) HD Graphics 4600").empty()); + // Linux lists no adapters + CHECK(gl_warnings({}, "Intel", "Mesa Intel(R) UHD Graphics 620 (KBL GT2)").empty()); + // an AMD APU beside an AMD card + CHECK(gl_warnings({adapter("AMD Radeon(TM) Graphics", vendor_amd), adapter("AMD Radeon RX 6600M", vendor_amd)}, "ATI Technologies Inc.", "AMD Radeon(TM) Graphics").size() == 1); + // a Ryzen 2400G with the monitor on the motherboard beside a GeForce, a Panther Lake laptop running GL on the B390 + CHECK(gl_warnings({adapter("AMD Radeon(TM) RX Vega 11 Graphics", vendor_amd), adapter("NVIDIA GeForce GTX 1650", vendor_nvidia)}, "ATI Technologies Inc.", "AMD Radeon(TM) RX Vega 11 Graphics").size() == 1); + CHECK(gl_warnings({adapter("Intel(R) Arc(TM) B390 GPU", vendor_intel), adapter("NVIDIA GeForce RTX 5060 Laptop GPU", vendor_nvidia)}, "Intel", "Intel(R) Arc(TM) B390 GPU").size() == 1); +} + +TEST_CASE("hardware info: a warning when OpenGL draws on the cpu") +{ + auto const warnings{gl_warnings({adapter("NVIDIA GeForce GTX 1650", vendor_nvidia)}, "Microsoft Corporation", "GDI Generic")}; + REQUIRE(warnings.size() == 1); + CHECK(warnings.front().find("GDI Generic") != std::string::npos); +} + +TEST_CASE("hardware info: a warning for a cpu without AVX2 only when the build needs it") +{ + cpu_info cpu; + cpu.avx2 = 0; + CHECK(cpu_warnings(cpu, true).size() == 1); + CHECK(cpu_warnings(cpu, false).empty()); + cpu.avx2 = 1; + CHECK(cpu_warnings(cpu, true).empty()); + cpu.avx2 = -1; // can't tell: no warning + CHECK(cpu_warnings(cpu, true).empty()); +} + +TEST_CASE("hardware info: sizes") +{ + CHECK(format_size(0) == "0 MiB"); + CHECK(format_size(128ULL * 1024 * 1024) == "128 MiB"); + CHECK(format_size(1023ULL * 1024 * 1024) == "1023 MiB"); + CHECK(format_size(1024ULL * 1024 * 1024) == "1.0 GiB"); + CHECK(format_size(12ULL * 1024 * 1024 * 1024) == "12.0 GiB"); + CHECK(format_size(17'058'000'000ULL) == "15.9 GiB"); +} + +TEST_CASE("hardware info: names") +{ + CHECK(tidy_name(" Intel(R) Core(TM) i5-4430 CPU @ 3.00GHz") == "Intel(R) Core(TM) i5-4430 CPU @ 3.00GHz"); + CHECK(tidy_name("AMD Ryzen 5 5600X 6-Core Processor ") == "AMD Ryzen 5 5600X 6-Core Processor"); + CHECK(tidy_name("") == ""); +} + +TEST_CASE("hardware info: /proc/cpuinfo") +{ + // two cores with two threads each, one package; the flags of the first processor count + auto const cpu{parse_cpuinfo("processor\t: 0\n" + "model name\t: Intel(R) Core(TM) i3-7100U CPU @ 2.40GHz\n" + "physical id\t: 0\n" + "core id\t\t: 0\n" + "cpu cores\t: 2\n" + "flags\t\t: fpu vme sse sse2 avx avx2 bmi2\n" + "\n" + "processor\t: 1\n" + "model name\t: Intel(R) Core(TM) i3-7100U CPU @ 2.40GHz\n" + "physical id\t: 0\n" + "core id\t\t: 1\n" + "\n" + "processor\t: 2\n" + "physical id\t: 0\n" + "core id\t\t: 0\n" + "\n" + "processor\t: 3\n" + "physical id\t: 0\n" + "core id\t\t: 1\n")}; + CHECK(cpu.model == "Intel(R) Core(TM) i3-7100U CPU @ 2.40GHz"); + CHECK(cpu.logical_cores == 4); + CHECK(cpu.physical_cores == 2); + CHECK(cpu.avx2 == 1); + + // no core ids (some virtual machines): the cores of the package; no avx2 in the flags + auto const vm{parse_cpuinfo("processor : 0\nmodel name : Some CPU\ncpu cores : 4\nflags : sse sse2 avx\n")}; + CHECK(vm.physical_cores == 4); + CHECK(vm.avx2 == 0); + + // nothing known + auto const empty{parse_cpuinfo("")}; + CHECK(empty.model.empty()); + CHECK(empty.logical_cores == 0); + CHECK(empty.physical_cores == 0); + CHECK(empty.avx2 == -1); +} + +TEST_CASE("hardware info: /proc/meminfo") +{ + auto const memory{parse_meminfo("MemTotal: 16303064 kB\nMemFree: 1234567 kB\nMemAvailable: 8151532 kB\n")}; + CHECK(memory.total == 16303064ULL * 1024); + CHECK(memory.available == 8151532ULL * 1024); + CHECK(parse_meminfo("").total == 0); +} + +TEST_CASE("hardware info: the lines of the log") +{ + cpu_info cpu; + cpu.model = "AMD Ryzen 5 5600X 6-Core Processor"; + cpu.physical_cores = 6; + cpu.logical_cores = 12; + cpu.avx2 = 1; + CHECK(format_cpu(cpu) == "hardware: cpu: AMD Ryzen 5 5600X 6-Core Processor, 6 cores, 12 threads, avx2 yes"); + CHECK(format_cpu(cpu_info{}) == "hardware: cpu: unknown, avx2 unknown"); + + memory_info memory; + memory.total = 16ULL * 1024 * 1024 * 1024; + memory.available = 7ULL * 1024 * 1024 * 1024; + CHECK(format_memory(memory) == "hardware: ram: 16.0 GiB total, 7.0 GiB available"); + CHECK(format_memory(memory_info{}) == "hardware: ram: unknown total"); + + gpu_adapter gpu{adapter("NVIDIA GeForce GTX 1650", vendor_nvidia)}; + gpu.device_id = 0x1f82; + gpu.dedicated_video_memory = 4ULL * 1024 * 1024 * 1024; + gpu.shared_system_memory = 8ULL * 1024 * 1024 * 1024; + gpu.outputs = 1; + CHECK(format_adapter(1, gpu) == "hardware: gpu 1: NVIDIA GeForce GTX 1650 (vendor 0x10de, device 0x1f82), 4.0 GiB dedicated, 8.0 GiB shared, 1 outputs, discrete"); + + CHECK(format_gl("Intel", "Intel(R) UHD Graphics 630") == "hardware: opengl gpu: Intel(R) UHD Graphics 630 (Intel), integrated"); + + gl_memory_info gl; + gl.dedicated = 4ULL * 1024 * 1024 * 1024; + gl.available = 3ULL * 1024 * 1024 * 1024; + CHECK(format_gl_memory(gl) == "hardware: opengl gpu memory: 4.0 GiB dedicated, 3.0 GiB free"); + gl.dedicated = 0; + CHECK(format_gl_memory(gl) == "hardware: opengl gpu memory: 3.0 GiB free"); + CHECK(format_gl_memory(gl_memory_info{}) == "hardware: opengl gpu memory: unknown"); +} diff --git a/tests/unit/test_ini_only_settings.cpp b/tests/unit/test_ini_only_settings.cpp new file mode 100644 index 000000000..83303aad4 --- /dev/null +++ b/tests/unit/test_ini_only_settings.cpp @@ -0,0 +1,154 @@ +#include "stdafx.h" +#include "doctest.h" + +// the settings only eu07.ini sets (utilities/inionlysettings.h): a config block of a scenery is read by the parser of +// eu07.ini (global_settings::ConfigParse with config_source::scenery), which keeps these as eu07.ini set them, and puts +// them back before FinalizeConfig() acts on any. here the keeping, as ConfigParse does it around the keys of a scenery + +#include "utilities/Globals.h" +#include "utilities/inionlysettings.h" + +#include +#include +#include +#include +#include + +namespace { + +bool listed(std::vector const &Keys, std::string_view const Key) { + return std::ranges::find(Keys, Key) != Keys.end(); +} + +} // namespace + +TEST_CASE("ini only settings: a scenery's config block doesn't give its scripts all libraries") { + auto const settings{std::make_unique()}; + settings->lua_fulllibraries = false; + ini_only_settings const ini{*settings}; + // "config lua.fulllibraries yes endconfig" in the .scn + settings->lua_fulllibraries = true; + auto const changed{ini.restore(*settings)}; + CHECK_FALSE(settings->lua_fulllibraries); + CHECK(changed == std::vector{"lua.fulllibraries"}); +} + +TEST_CASE("ini only settings: a scenery switches a runtime off, but not on") { + auto const python{[](global_settings &Settings) -> bool & { return Settings.python_enabled; }}; + auto const luascreens{[](global_settings &Settings) -> bool & { return Settings.luascreens_enabled; }}; + auto const wasm{[](global_settings &Settings) -> bool & { return Settings.wasm_enabled; }}; + auto const fulllibraries{[](global_settings &Settings) -> bool & { return Settings.lua_fulllibraries; }}; + using setting = bool &(*)(global_settings &); + for (auto const &[key, switched] : {std::pair{"python.enabled", python}, {"luascreens.enabled", luascreens}, + {"wasm.enabled", wasm}, {"lua.fulllibraries", fulllibraries}}) { + CAPTURE(key); + { + // on in eu07.ini, off in the scenery: off, and nothing in the log + auto const settings{std::make_unique()}; + switched(*settings) = true; + ini_only_settings const ini{*settings}; + // "config python.enabled no endconfig" in the .scn, as the release honoured it + switched(*settings) = false; + CHECK(ini.restore(*settings).empty()); + CHECK_FALSE(switched(*settings)); + } + { + // off in eu07.ini, on in the scenery: back off, and told + auto const settings{std::make_unique()}; + switched(*settings) = false; + ini_only_settings const ini{*settings}; + switched(*settings) = true; + CHECK(ini.restore(*settings) == std::vector{key}); + CHECK_FALSE(switched(*settings)); + } + // as eu07.ini set it: kept, nothing told + for (auto const value : {false, true}) { + auto const settings{std::make_unique()}; + switched(*settings) = value; + ini_only_settings const ini{*settings}; + CHECK(ini.restore(*settings).empty()); + CHECK(switched(*settings) == value); + } + } +} + +TEST_CASE("ini only settings: a scenery runs no program, opens no connection and switches no runtime back on") { + auto const settings{std::make_unique()}; + settings->luascreens_enabled = false; + settings->wasm_enabled = false; + settings->python_enabled = false; + ini_only_settings const ini{*settings}; + + settings->exec_on_exit = "cmd /c del something"; + settings->extcam_cmd = "evil.exe"; + settings->extcam_rec = "evil.exe"; + settings->screenshot_dir = "C:/Users/Public"; + settings->network_servers.emplace_back("tcp", "0.0.0.0:7424"); + settings->network_client.emplace("tcp", "example.com:7424"); + settings->motiontelemetry_conf.enable = true; + settings->motiontelemetry_conf.address = "example.com"; + settings->iFeedbackMode = 4; + settings->iFeedbackPort = 0x378; + settings->luascreens_enabled = true; + settings->wasm_enabled = true; + settings->python_enabled = true; +#ifdef WITH_UART + settings->uart_conf.enable = true; + settings->uart_conf.port = "COM1"; +#endif +#ifdef WITH_ZMQ + settings->zmq_address = "tcp://*:5555"; +#endif + // and a key a scenery may set + settings->fFriction = 0.5; + + auto const changed{ini.restore(*settings)}; + CHECK(settings->exec_on_exit.empty()); + CHECK(settings->extcam_cmd.empty()); + CHECK(settings->extcam_rec.empty()); + CHECK(settings->screenshot_dir.empty()); + CHECK(settings->network_servers.empty()); + CHECK_FALSE(settings->network_client.has_value()); + CHECK_FALSE(settings->motiontelemetry_conf.enable); + CHECK(settings->motiontelemetry_conf.address.empty()); + CHECK(settings->iFeedbackMode == 1); + CHECK(settings->iFeedbackPort == 0); + CHECK_FALSE(settings->luascreens_enabled); + CHECK_FALSE(settings->wasm_enabled); + CHECK_FALSE(settings->python_enabled); + for (auto const *key : {"execonexit", "extcam.cmd", "extcam.rec", "screenshotsdir", "network.server", "network.client", "motiontelemetry", + "feedbackmode", "feedbackport", "luascreens.enabled", "wasm.enabled", "python.enabled"}) { + CAPTURE(key); + CHECK(listed(changed, key)); + } +#ifdef WITH_UART + CHECK_FALSE(settings->uart_conf.enable); + CHECK(settings->uart_conf.port.empty()); + CHECK(listed(changed, "uart")); +#endif +#ifdef WITH_ZMQ + CHECK(settings->zmq_address.empty()); + CHECK(listed(changed, "zmq.address")); +#endif + // the rest is the scenery's to set + CHECK(settings->fFriction == doctest::Approx(0.5)); +} + +TEST_CASE("ini only settings: nothing changed, nothing to tell") { + auto const settings{std::make_unique()}; + settings->exec_on_exit = "notify.exe"; + ini_only_settings const ini{*settings}; + CHECK(ini.restore(*settings).empty()); + CHECK(settings->exec_on_exit == "notify.exe"); +} + +TEST_CASE("ini only settings: a scenery's config block doesn't change the period of the odometer states") { + auto const settings{std::make_unique()}; + settings->odometer_expiry = 730; + ini_only_settings const ini{*settings}; + // "config odometer.expiry 1 endconfig" in the .scn would drop the states of the vehicles not run yesterday + settings->odometer_expiry = 1; + auto const changed{ini.restore(*settings)}; + CHECK(settings->odometer_expiry == 730); + CHECK(changed == std::vector{"odometer.expiry"}); +} diff --git a/tests/unit/test_linebreaker.cpp b/tests/unit/test_linebreaker.cpp index 126e3307c..9b36b817f 100644 --- a/tests/unit/test_linebreaker.cpp +++ b/tests/unit/test_linebreaker.cpp @@ -9,6 +9,7 @@ using test::consist; using test::definition; +using linebreaker::state; namespace { @@ -16,7 +17,7 @@ namespace { // the cab keeps of the line breaker follows the vehicle, the breaker closes while the lever is on and can close struct lever { TMoverParameters &mover; - int breaker{0}; // as TTrain::m_linebreakerstate: 0 open, 1 closed + state breaker{state::open}; // as TTrain::m_linebreakerstate bool on{false}; void press() { @@ -26,8 +27,8 @@ struct lever { break; case linebreaker::toggle::open: on = false; - if (breaker == 1 && mover.MainSwitch(false)) { - breaker = 0; + if (breaker == state::closed && mover.MainSwitch(false)) { + breaker = state::open; } break; default: @@ -36,14 +37,14 @@ struct lever { } // TTrain::Update() void update() { - if (breaker == 0 && mover.Mains) { - breaker = 1; + if (breaker == state::open && mover.Mains) { + breaker = state::closed; } - if (breaker == 1 && false == mover.Mains) { - breaker = 0; + if (breaker == state::closed && false == mover.Mains) { + breaker = state::open; } - if (on && breaker == 0 && mover.MainSwitchCheck()) { - breaker = mover.MainSwitch(true) ? 1 : 0; + if (on && breaker == state::open && mover.MainSwitchCheck()) { + breaker = mover.MainSwitch(true) ? state::closed : state::open; } } }; @@ -53,15 +54,15 @@ struct lever { TEST_CASE("line breaker: a press of the toggle closes an open breaker and opens a closed one") { using enum linebreaker::toggle; for (auto const latching : {false, true}) { - CHECK(linebreaker::pressed(0, latching, false) == close); - CHECK(linebreaker::pressed(1, latching, true) == open); - CHECK(linebreaker::pressed(1, latching, false) == open); + CHECK(linebreaker::pressed(state::open, latching, false) == close); + CHECK(linebreaker::pressed(state::closed, latching, true) == open); + CHECK(linebreaker::pressed(state::closed, latching, false) == open); // freshly closed, the cab finishes closing it first - CHECK(linebreaker::pressed(2, latching, true) == none); + CHECK(linebreaker::pressed(state::closing, latching, true) == none); } // a lever left on over an open breaker goes off; push buttons have no position to keep - CHECK(linebreaker::pressed(0, true, true) == open); - CHECK(linebreaker::pressed(0, false, true) == close); + CHECK(linebreaker::pressed(state::open, true, true) == open); + CHECK(linebreaker::pressed(state::open, false, true) == close); } TEST_CASE("line breaker: the EP05's lever goes off with the converter overload relay tripped (eu07/maszyna#394)") { @@ -72,7 +73,7 @@ TEST_CASE("line breaker: the EP05's lever goes off with the converter overload r REQUIRE(test::start_up(driver, line)); REQUIRE(ep05.Mains); REQUIRE(ep05.ConverterFlag); - lever ws{ep05, 1, true}; + lever ws{ep05, state::closed, true}; // the converter overload relay knocks the line breaker out, as the cab does it when the converter is // switched on together with the compressor; the lever stays on @@ -80,7 +81,7 @@ TEST_CASE("line breaker: the EP05's lever goes off with the converter overload r ep05.MainSwitch(false, range_t::local); ws.update(); REQUIRE_FALSE(ep05.Mains); - REQUIRE(ws.breaker == 0); + REQUIRE(ws.breaker == state::open); CHECK(ws.on); // with the relay tripped the breaker doesn't close test::drive(driver, line, 5.0); @@ -106,7 +107,7 @@ TEST_CASE("line breaker: the EP05's lever goes off with the converter overload r ws.press(); ws.update(); CHECK(ep05.Mains); - CHECK(ws.breaker == 1); + CHECK(ws.breaker == state::closed); // and the next press opens it ws.press(); CHECK_FALSE(ws.on); diff --git a/tests/unit/test_log_files.cpp b/tests/unit/test_log_files.cpp new file mode 100644 index 000000000..8a0aac6f3 --- /dev/null +++ b/tests/unit/test_log_files.cpp @@ -0,0 +1,35 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "utilities/logfiles.h" + +#include + +// the files the log is written to, and which of them a run deletes when it starts + +TEST_CASE("log files: without multiplelogs the run writes the shared log.txt and errors.txt") +{ + CHECK(log_file_name(log_file::log, false, "td", "20261112_1200123") == "log.txt"); + CHECK(log_file_name(log_file::errors, false, "td", "20261112_1200123") == "errors.txt"); +} + +TEST_CASE("log files: with multiplelogs the run writes its own in logs/, named after the scenery and the time") +{ + CHECK(log_file_name(log_file::log, true, "autotest_case", "20261112_1200123") == "logs/log (autotest_case) 20261112_1200123.txt"); + CHECK(log_file_name(log_file::errors, true, "autotest_case", "20261112_1200123") == "logs/errors (autotest_case) 20261112_1200123.txt"); +} + +TEST_CASE("log files: without multiplelogs the start deletes the shared files it is going to write") +{ + // errors.txt is made at the first error only: one of the run before must not stay behind a run without errors + auto const stale{stale_log_files(false)}; + CHECK(stale.size() == 2); + for (auto const kind : {log_file::log, log_file::errors}) + CHECK(std::ranges::count(stale, log_file_name(kind, false, "td", "20261112_1200123")) == 1); +} + +TEST_CASE("log files: with multiplelogs the start keeps the shared log.txt and errors.txt of the last ordinary run") +{ + // the scenario tests run with multiplelogs; the logs of the player's last game in the game folder stay + CHECK(stale_log_files(true).empty()); +} diff --git a/tests/unit/test_lua_sandbox.cpp b/tests/unit/test_lua_sandbox.cpp new file mode 100644 index 000000000..bc0753162 --- /dev/null +++ b/tests/unit/test_lua_sandbox.cpp @@ -0,0 +1,535 @@ +#include "stdafx.h" +#include "doctest.h" + +// the sandbox the Lua states of the game share (scripting/luasandbox.cpp): the scenery scripts (lua in the .scn, +// scripting/lua.cpp) and the script screens (scripting/luaprogram.cpp, tested with the screens in +// test_script_screen_host.cpp). a script gets base, table, string, math and bit, and of os only the clock; it reaches +// no files, no programs, no ffi, loads no code of its own and no precompiled chunk, and a scenery reads its scripts +// only from its own folder + +#ifdef WITH_LUA + +#include "scripting/luasandbox.h" +#include "scratch.h" + +#include +#include +#include +#include +#include + +namespace { + +// a state with the libraries of the scenery scripts +class sandboxed_state { + public: + sandboxed_state() : m_state{luaL_newstate()} { + lua_sandbox::open_safe_libraries(m_state); + lua_sandbox::open_clock_library(m_state); + } + ~sandboxed_state() { lua_close(m_state); } + sandboxed_state(sandboxed_state const &) = delete; + sandboxed_state &operator=(sandboxed_state const &) = delete; + + lua_State *get() const { return m_state; } + + // runs the code, which returns one value, and gives that value as text ("nil", "true", a number, a string), or + // "error: " and the message + std::string run(std::string_view const Code) const { + auto const top{lua_gettop(m_state)}; + std::string result; + if (false == lua_sandbox::load_text_chunk(m_state, Code, "test") || 0 != lua_pcall(m_state, 0, 1, 0)) { + result = std::string{"error: "} + lua_tostring(m_state, -1); + } else if (lua_isnil(m_state, -1)) { + result = "nil"; + } else if (lua_isboolean(m_state, -1)) { + result = lua_toboolean(m_state, -1) ? "true" : "false"; + } else { + auto const *text{lua_tostring(m_state, -1)}; + result = text != nullptr ? text : "?"; + } + lua_settop(m_state, top); + return result; + } + + private: + lua_State *m_state; +}; + +bool contains(std::string_view const Text, std::string_view const Part) { + return Text.find(Part) != std::string_view::npos; +} + +} // namespace + +TEST_CASE("lua sandbox: no library that reaches files, programs, ffi or the debugger, and nothing that loads code") { + sandboxed_state const lua; + for (auto const *name : {"io", "ffi", "debug", "package", "jit", "require", "module", "dofile", "loadfile", "load", "loadstring", + "newproxy", "string.dump", "os.execute", "os.exit", "os.remove", "os.rename", "os.getenv", "os.tmpname", + "os.setlocale"}) { + CAPTURE(name); + CHECK(lua.run(std::format("return {}", name)) == "nil"); + } + // what the scripts did with them fails, as a Lua error + CHECK(contains(lua.run("return io.open('eu07.ini')"), "attempt to index global 'io' (a nil value)")); + CHECK(contains(lua.run("return os.execute('cmd')"), "attempt to call field 'execute' (a nil value)")); + CHECK(contains(lua.run("return require('ffi')"), "attempt to call global 'require' (a nil value)")); +} + +TEST_CASE("lua sandbox: the libraries a script gets work") { + sandboxed_state const lua; + CHECK(lua.run("return math.floor(2.5) + #string.rep('a', 3) + bit.band(7, 4) + #table.concat({ 'a', 'b' })") == "11"); + CHECK(lua.run("return ('%d-%s'):format(7, 'x')") == "7-x"); + CHECK(lua.run("local ok, error = pcall(function() error('boom') end) return (not ok) and error:find('boom') ~= nil") == "true"); + CHECK(lua.run("local n = 0 for _, v in ipairs({ 1, 2, 3 }) do n = n + v end return n") == "6"); + CHECK(lua.run("return tostring(tonumber('12') + select('#', 1, 2))") == "14"); +} + +TEST_CASE("lua sandbox: os reads the clock, and nothing else") { + sandboxed_state const lua; + CHECK(lua.run("return type(os.time()) == 'number' and os.time() > 0") == "true"); + CHECK(lua.run("return type(os.clock()) == 'number'") == "true"); + CHECK(lua.run("return os.difftime(10, 4)") == "6"); + CHECK(lua.run("return os.time({ year = 2020, month = 1, day = 2, hour = 12 }) > 0") == "true"); + CHECK(lua.run("return os.date('!%Y-%m-%d', 0)") == "1970-01-01"); + CHECK(lua.run("return os.date('!*t', 86400 * 365).year") == "1971"); + CHECK(lua.run("return #os.date()") != "0"); + // a lone % at the end and %% are text + CHECK(lua.run("return os.date('!100%%', 0)") == "100%"); + CHECK(lua.run("return os.date('!100%', 0)") == "100%"); + // conversions the Microsoft C library doesn't know end the program there: refused before + CHECK(contains(lua.run("return os.date('%Q')"), "os.date: unknown conversion '%Q'")); + CHECK(contains(lua.run("return os.date('%#c')"), "os.date: unknown conversion '%#'")); + CHECK(contains(lua.run("return os.date('%Ey')"), "os.date: unknown conversion '%E'")); + // the table holds only the clock + CHECK(lua.run("local n = 0 for _ in pairs(os) do n = n + 1 end return n") == "4"); +} + +TEST_CASE("lua sandbox: all libraries opened over the sandbox are whole again (lua.fulllibraries)") { + sandboxed_state const lua; + luaL_openlibs(lua.get()); + for (auto const *name : {"io.open", "os.execute", "os.getenv", "os.date", "require", "loadstring", "dofile", "string.dump", "debug.traceback"}) { + CAPTURE(name); + CHECK(lua.run(std::format("return type({})", name)) == "function"); + } + CHECK(lua.run("return type(require('ffi'))") == "table"); + CHECK(lua.run("return rawequal(os, package.loaded.os)") == "true"); +} + +TEST_CASE("lua sandbox: precompiled code isn't loaded") { + // real LuaJIT bytecode, from a state with all libraries + auto *full{luaL_newstate()}; + luaL_openlibs(full); + // luaL_dostring is a || of two calls, a bool in C++ + REQUIRE_FALSE(luaL_dostring(full, "return string.dump(function() return 42 end)")); + std::size_t length{0}; + auto const *bytes{lua_tolstring(full, -1, &length)}; + std::string const bytecode{bytes, length}; + lua_close(full); + REQUIRE(false == bytecode.empty()); + CHECK(bytecode.front() == '\x1b'); + + sandboxed_state const lua; + auto const top{lua_gettop(lua.get())}; + CHECK_FALSE(lua_sandbox::load_text_chunk(lua.get(), bytecode, "compiled.lua")); + CHECK(contains(lua_tostring(lua.get(), -1), "compiled.lua: precompiled scripts aren't loaded")); + lua_settop(lua.get(), top); + // nor in a text that only starts with the marker + CHECK_FALSE(lua_sandbox::load_text_chunk(lua.get(), std::string_view{"\x1bLJ\x02 return 1"}, "fake.lua")); + lua_settop(lua.get(), top); +} + +TEST_CASE("lua sandbox: a scenery reads its scripts only from its own folder") { + test::scratch_folder const root{"lua_sandbox_paths"}; + root.write("outside.lua", "return 1"); + root.write("scenery/test.lua", "return 2"); + root.write("scenery/scripts/module.lua", "return 3"); + root.write("scenery/folder.lua/inner.lua", "return 4"); + auto const folder{root.path("scenery") + "/"}; + + CHECK(lua_sandbox::read_script_file(folder, "test.lua") == std::optional{"return 2"}); + CHECK(lua_sandbox::read_script_file(folder, "scripts/module.lua") == std::optional{"return 3"}); + // '\' separates the folders on Linux too, as in the rest of the scenery's paths + CHECK(lua_sandbox::with_forward_slashes("a\\b/c\\d.lua") == "a/b/c/d.lua"); + CHECK(lua_sandbox::read_script_file(folder, "scripts\\module.lua") == std::optional{"return 3"}); + for (auto const &path : {std::string{"../outside.lua"}, std::string{"scripts/../../outside.lua"}, std::string{"..\\outside.lua"}, + std::string{"scripts\\..\\..\\outside.lua"}, std::string{"scripts/..\\../outside.lua"}, + root.path("outside.lua"), std::string{"/outside.lua"}, std::string{"\\outside.lua"}, std::string{"C:outside.lua"}, + std::string{"missing.lua"}, std::string{"folder.lua"}, std::string{"scripts"}, std::string{}}) { + CAPTURE(path); + CHECK_FALSE(lua_sandbox::read_script_file(folder, path).has_value()); + } +} + +TEST_CASE("lua sandbox: a script larger than the limit isn't read") { + test::scratch_folder const root{"lua_sandbox_size"}; + root.write("scenery/limit.lua", std::string(static_cast(lua_sandbox::max_script_file), ' ')); + root.write("scenery/over.lua", std::string(static_cast(lua_sandbox::max_script_file) + 1, ' ')); + auto const folder{root.path("scenery") + "/"}; + CHECK(lua_sandbox::read_script_file(folder, "limit.lua").has_value()); + CHECK_FALSE(lua_sandbox::read_script_file(folder, "over.lua").has_value()); +} + +TEST_CASE("lua sandbox: a scenery script runs in protected mode, and its errors name the file") { + test::scratch_folder const root{"lua_sandbox_run"}; + root.write("scenery/good.lua", "ran = (ran or 0) + 1"); + root.write("scenery/fails.lua", "ran = 10\nlocal x = nil\nx.field = 1\nran = 20"); + root.write("scenery/files.lua", "local f = io.open('eu07.ini')"); + root.write("scenery/system.lua", "os.execute('cmd /c echo pwned')"); + root.write("scenery/syntax.lua", "this is not lua"); + root.write("scenery/compiled.lua", std::string_view{"\x1bLJ\x02 bytes"}); + auto const folder{root.path("scenery") + "/"}; + + sandboxed_state const lua; + auto *L{lua.get()}; + auto const top{lua_gettop(L)}; + + CHECK_FALSE(lua_sandbox::run_script_file(L, folder, "good.lua").has_value()); + CHECK(lua.run("return ran") == "1"); + + auto const fails{lua_sandbox::run_script_file(L, folder, "fails.lua")}; + REQUIRE(fails.has_value()); + CHECK(contains(*fails, "fails.lua:3:")); + // it stopped at the error + CHECK(lua.run("return ran") == "10"); + + auto const files{lua_sandbox::run_script_file(L, folder, "files.lua")}; + REQUIRE(files.has_value()); + CHECK(contains(*files, "files.lua:1: attempt to index global 'io' (a nil value)")); + + auto const system{lua_sandbox::run_script_file(L, folder, "system.lua")}; + REQUIRE(system.has_value()); + CHECK(contains(*system, "system.lua:1: attempt to call field 'execute' (a nil value)")); + + auto const syntax{lua_sandbox::run_script_file(L, folder, "syntax.lua")}; + REQUIRE(syntax.has_value()); + CHECK(contains(*syntax, "syntax.lua:1:")); + + auto const compiled{lua_sandbox::run_script_file(L, folder, "compiled.lua")}; + REQUIRE(compiled.has_value()); + CHECK(contains(*compiled, "compiled.lua: precompiled scripts aren't loaded")); + + auto const outside{lua_sandbox::run_script_file(L, folder, "../good.lua")}; + REQUIRE(outside.has_value()); + CHECK(contains(*outside, "outside the folder")); + + // nothing left on the stack, and the state still works + CHECK(lua_gettop(L) == top); + CHECK_FALSE(lua_sandbox::run_script_file(L, folder, "good.lua").has_value()); + CHECK(lua.run("return ran") == "11"); +} + +TEST_CASE("lua sandbox: eu07.read_file reads a file of the scenery folder, and nothing outside it") { + test::scratch_folder const root{"lua_sandbox_read"}; + root.write("outside.txt", "secret"); + root.write("scenery/data.txt", "line 1\nline 2"); + root.write("scenery/sub/more.txt", "more"); + root.write("scenery/folder/inner.txt", "inner"); + auto const folder{std::filesystem::path{root.path("scenery")}}; + + CHECK(lua_sandbox::read_file(folder, "data.txt", 100) == std::optional{"line 1\nline 2"}); + CHECK(lua_sandbox::read_file(folder, "sub/more.txt", 100) == std::optional{"more"}); + CHECK(lua_sandbox::read_file(folder, "sub\\more.txt", 100) == std::optional{"more"}); + // the limit is the caller's + CHECK(lua_sandbox::read_file(folder, "sub/more.txt", 4).has_value()); + CHECK_FALSE(lua_sandbox::read_file(folder, "sub/more.txt", 3).has_value()); + for (auto const &path : {std::string{"../outside.txt"}, std::string{"sub/../../outside.txt"}, std::string{"..\\outside.txt"}, + std::string{"sub\\..\\..\\outside.txt"}, root.path("outside.txt"), std::string{"/outside.txt"}, + std::string{"\\outside.txt"}, std::string{"C:outside.txt"}, std::string{"missing.txt"}, + std::string{"folder"}, std::string{}, std::string{"data.txt\0x", 10}}) { + CAPTURE(path); + CHECK_FALSE(lua_sandbox::read_file(folder, path, 100).has_value()); + } +} + +TEST_CASE("lua sandbox: the paths a script may write to") { + for (auto const *path : {"state.txt", "saves/state.txt", "saves\\state.txt", "a/b/c/d/e/f/g/h/file.txt", "con_log.txt", "comx.txt", + "com10.txt", "nul_state", ".hidden", "stan poci\xc4\x85gu.txt", "a..b"}) { + CAPTURE(path); + CHECK(lua_sandbox::is_safe_write_path(path)); + } + for (auto const &path : {std::string{}, std::string{".."}, std::string{"../x.txt"}, std::string{"a/../../x.txt"}, std::string{"..\\x.txt"}, + std::string{"/x.txt"}, std::string{"\\x.txt"}, std::string{"C:x.txt"}, std::string{"C:\\x.txt"}, + std::string{"x.txt:stream"}, std::string{"a//b.txt"}, std::string{"a/"}, std::string{"./x.txt"}, + std::string{"a/./x.txt"}, std::string{"con"}, std::string{"CON.txt"}, std::string{"saves/nul.dat"}, + std::string{"Com1"}, std::string{"lpt9.log"}, std::string{"aux"}, std::string{"prn.x.y"}, + std::string{"conin$"}, std::string{"CONOUT$.txt"}, std::string{"con .txt"}, std::string{"ab"}, std::string{"a\"b"}, std::string{"a|b"}, std::string{"a?b"}, std::string{"a*b"}, + std::string{"x."}, std::string{"x "}, std::string{"dir./x"}, std::string{"a\tb"}, std::string{"a\nb"}, + std::string{"a\0b", 3}, std::string{"a/b/c/d/e/f/g/h/i/file.txt"}, + std::string(lua_sandbox::max_data_path + 1, 'x')}) { + CAPTURE(path); + CHECK_FALSE(lua_sandbox::is_safe_write_path(path)); + } + CHECK(lua_sandbox::is_safe_write_path(std::string(lua_sandbox::max_data_path, 'x'))); +} + +TEST_CASE("lua sandbox: a script writes into its data folder only, and reads back what it wrote") { + test::scratch_folder const root{"lua_sandbox_write"}; + root.write("outside.txt", "kept"); + auto const data{root.root() / "data" / "td"}; + + // the folder is made with the first file + CHECK_FALSE(lua_sandbox::write_data_file(data, "state.txt", "runs=1").has_value()); + CHECK(lua_sandbox::read_file(data, "state.txt", lua_sandbox::max_data_file) == std::optional{"runs=1"}); + // replaced, not appended + CHECK_FALSE(lua_sandbox::write_data_file(data, "state.txt", "runs=2").has_value()); + CHECK(lua_sandbox::read_file(data, "state.txt", lua_sandbox::max_data_file) == std::optional{"runs=2"}); + // any bytes, and the folders of the path + std::string const bytes{"a\0b\r\n\xff", 6}; + CHECK_FALSE(lua_sandbox::write_data_file(data, "saves\\day 1/bin.dat", bytes).has_value()); + CHECK(lua_sandbox::read_file(data, "saves/day 1/bin.dat", lua_sandbox::max_data_file) == std::optional{bytes}); + CHECK_FALSE(lua_sandbox::write_data_file(data, "empty.txt", "").has_value()); + CHECK(lua_sandbox::read_file(data, "empty.txt", lua_sandbox::max_data_file) == std::optional{""}); + + // nothing outside the folder + for (auto const *path : {"../outside.txt", "../../outside.txt", "..\\outside.txt", "saves/../../outside.txt", "nul", "con.txt", "x:y"}) { + CAPTURE(path); + auto const error{lua_sandbox::write_data_file(data, path, "overwritten")}; + REQUIRE(error.has_value()); + CHECK(contains(*error, "not a path to write to")); + } + CHECK(lua_sandbox::write_data_file(data, root.path("outside.txt"), "overwritten").has_value()); + CHECK(lua_sandbox::read_file(root.root(), "outside.txt", 100) == std::optional{"kept"}); + // a folder isn't replaced by a file + auto const folder{lua_sandbox::write_data_file(data, "saves", "x")}; + REQUIRE(folder.has_value()); + CHECK(contains(*folder, "not a file")); + CHECK(std::filesystem::is_directory(data / "saves")); + // no folder (the game knows no folder of the player), nothing written + CHECK(lua_sandbox::write_data_file(std::filesystem::path{}, "state.txt", "x").has_value()); +} + +TEST_CASE("lua sandbox: the limits of a data folder") { + test::scratch_folder const root{"lua_sandbox_limits"}; + auto const data{root.root() / "data"}; + std::string const full(static_cast(lua_sandbox::max_data_file), 'x'); + + SUBCASE("a file") { + CHECK_FALSE(lua_sandbox::write_data_file(data, "full.txt", full).has_value()); + CHECK(lua_sandbox::read_file(data, "full.txt", lua_sandbox::max_data_file).has_value()); + auto const over{lua_sandbox::write_data_file(data, "full.txt", full + "x")}; + REQUIRE(over.has_value()); + CHECK(contains(*over, "larger than")); + // the file stays as it was + CHECK(std::filesystem::file_size(data / "full.txt") == lua_sandbox::max_data_file); + } + SUBCASE("the bytes of the folder") { + auto const files{static_cast(lua_sandbox::max_data_folder / lua_sandbox::max_data_file)}; + for (int idx = 0; idx < files; ++idx) { + REQUIRE_FALSE(lua_sandbox::write_data_file(data, std::format("part{}.dat", idx), full).has_value()); + } + auto const over{lua_sandbox::write_data_file(data, "one_more.dat", "x")}; + REQUIRE(over.has_value()); + CHECK(contains(*over, "more than")); + CHECK_FALSE(std::filesystem::exists(data / "one_more.dat")); + // a file replaced counts with its new size: as large again fits, and a smaller one makes room + CHECK_FALSE(lua_sandbox::write_data_file(data, "part0.dat", full).has_value()); + CHECK_FALSE(lua_sandbox::write_data_file(data, "part0.dat", "small").has_value()); + CHECK_FALSE(lua_sandbox::write_data_file(data, "one_more.dat", "x").has_value()); + } + SUBCASE("the files of the folder") { + for (std::size_t idx = 0; idx < lua_sandbox::max_data_files; ++idx) { + REQUIRE_FALSE(lua_sandbox::write_data_file(data, std::format("sub{}/file{}.txt", idx % 4, idx), "x").has_value()); + } + auto const over{lua_sandbox::write_data_file(data, "one_more.txt", "x")}; + REQUIRE(over.has_value()); + CHECK(contains(*over, "files already")); + CHECK_FALSE(std::filesystem::exists(data / "one_more.txt")); + // one that is there is still replaced + CHECK_FALSE(lua_sandbox::write_data_file(data, "sub0/file0.txt", "y").has_value()); + } +} + +TEST_CASE("lua sandbox: a link in the data folder doesn't lead a write out of it") { + test::scratch_folder const root{"lua_sandbox_link"}; + root.write("outside/kept.txt", "kept"); + auto const data{root.root() / "data"}; + std::filesystem::create_directories(data); + std::error_code error; + std::filesystem::create_directory_symlink(root.root() / "outside", data / "link", error); + if (error) { + // Windows makes links only for an administrator or in developer mode + MESSAGE("no folder link made (" << error.message() << "), not tested"); + return; + } + auto const written{lua_sandbox::write_data_file(data, "link/kept.txt", "overwritten")}; + REQUIRE(written.has_value()); + CHECK(contains(*written, "outside the data folder")); + CHECK(lua_sandbox::read_file(root.root(), "outside/kept.txt", 100) == std::optional{"kept"}); +} + +TEST_CASE("lua sandbox: the data folder of a scenery") { + std::filesystem::path const root{"user/scenery_data"}; + CHECK(lua_sandbox::scenery_data_folder(root, "td.scn") == root / "td"); + CHECK(lua_sandbox::scenery_data_folder(root, "Td.SCN") == root / "Td"); + CHECK(lua_sandbox::scenery_data_folder(root, "lines\\l107.scn") == root / "lines/l107"); + CHECK(lua_sandbox::scenery_data_folder(root, "test.scm") == root / "test.scm"); + for (auto const *scenery : {"", ".scn", "../td.scn", "/td.scn", "C:td.scn", "con.scn"}) { + CAPTURE(scenery); + CHECK(lua_sandbox::scenery_data_folder(root, scenery).empty()); + } + CHECK(lua_sandbox::scenery_data_folder(std::filesystem::path{}, "td.scn").empty()); +} + +TEST_CASE("lua sandbox: the file functions of a scenery script") { + test::scratch_folder const root{"lua_sandbox_api"}; + root.write("outside.txt", "secret"); + root.write("scenery/settings.txt", "speed=40"); + lua_sandbox::file_folders folders{root.path("scenery") + "/", root.root() / "data" / "td"}; + + sandboxed_state const lua; + // next to eu07.events, as the scenery state has it + REQUIRE_FALSE(luaL_dostring(lua.get(), "eu07 = { events = { marker = 1 } }")); + lua_sandbox::open_file_library(lua.get(), &folders); + auto const top{lua_gettop(lua.get())}; + + CHECK(lua.run("return eu07.events.marker") == "1"); + CHECK(lua.run("return eu07.read_file('settings.txt')") == "speed=40"); + CHECK(lua.run("return eu07.read_file('../outside.txt')") == "nil"); + CHECK(lua.run("return eu07.read_file('missing.txt')") == "nil"); + CHECK(lua.run("return eu07.read_data_file('state.txt')") == "nil"); + CHECK(lua.run("return eu07.write_file('state.txt', 'runs=' .. 1)") == "true"); + CHECK(lua.run("return eu07.read_data_file('state.txt')") == "runs=1"); + // the scenery folder and the data folder are apart + CHECK(lua.run("return eu07.read_file('state.txt')") == "nil"); + CHECK(lua.run("return eu07.read_data_file('../../scenery/settings.txt')") == "nil"); + // a number is written as its text + CHECK(lua.run("return eu07.write_file('number.txt', 42)") == "true"); + CHECK(lua.run("return eu07.read_data_file('number.txt')") == "42"); + // a refused write gives nil and the reason + CHECK(lua.run("local ok, reason = eu07.write_file('../outside.txt', 'x') return tostring(ok) .. ' ' .. reason") == + "nil ../outside.txt: not a path to write to (a relative path of portable names, at most 200 bytes and 8 folders deep, without '..')"); + CHECK(lua.run("local ok, reason = eu07.write_file('big.txt', string.rep('x', 1024 * 1024 + 1)) return reason") == + "big.txt: larger than 1048576 bytes"); + CHECK(lua_sandbox::read_file(root.root(), "outside.txt", 100) == std::optional{"secret"}); + // the arguments are checked + CHECK(contains(lua.run("return eu07.write_file('x.txt')"), "bad argument #2")); + CHECK(contains(lua.run("return eu07.read_file()"), "bad argument #1")); + CHECK(contains(lua.run("return eu07.write_file({}, 'x')"), "bad argument #1")); + + // the folders are read on every call: without a data folder nothing is written or read there + folders.data.clear(); + CHECK(lua.run("local ok, reason = eu07.write_file('state.txt', 'x') return tostring(ok) .. ' ' .. reason") == + "nil state.txt: no folder to write to (the game knows no folder of the player)"); + CHECK(lua.run("return eu07.read_data_file('state.txt')") == "nil"); + CHECK(lua_gettop(lua.get()) == top); +} + +TEST_CASE("lua sandbox: the file functions make eu07 when there is none") { + lua_sandbox::file_folders const folders; + sandboxed_state const lua; + lua_sandbox::open_file_library(lua.get(), &folders); + CHECK(lua.run("return type(eu07.read_file) .. type(eu07.write_file) .. type(eu07.read_data_file)") == "functionfunctionfunction"); + CHECK(lua.run("return eu07.read_file('x.txt')") == "nil"); +} + +TEST_CASE("lua sandbox: no userdata of the script's own, whose __gc would run without the hooks") { + sandboxed_state const lua; + CHECK(lua.run("return newproxy") == "nil"); + // a table's __gc isn't called (Lua 5.1, LuaJIT): no other way to a finalizer of the script's own + CHECK(lua.run("collected = false setmetatable({}, { __gc = function() collected = true end }) collectgarbage() collectgarbage() return collected") == + "false"); +} + +namespace { + +// two objects of the simulation, of which a script holds handles +int memcell_object{1}; +int track_object{2}; + +// eu07.test_memcell(handle): the number of the memcell object, nil for none; eu07.test_track(handle) likewise +int test_memcell(lua_State *L) { + auto const *object{lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::memcell)}; + if (object == nullptr) { + lua_pushnil(L); + } else { + lua_pushnumber(L, *object); + } + return 1; +} + +int test_track(lua_State *L) { + auto const *object{lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::track)}; + if (object == nullptr) { + lua_pushnil(L); + } else { + lua_pushnumber(L, *object); + } + return 1; +} + +// a state with the handles, the functions above, and the globals memcell, track (handles), memcell2 (the memcell's +// handle pushed again) and light (a light userdata, which a script can't make, as the game gave them before) +class handle_state : public sandboxed_state { + public: + handle_state() { + auto *L{get()}; + lua_sandbox::open_handles(L); + lua_register(L, "test_memcell", test_memcell); + lua_register(L, "test_track", test_track); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::memcell, &memcell_object); + lua_setglobal(L, "memcell"); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::memcell, &memcell_object); + lua_setglobal(L, "memcell2"); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::track, &track_object); + lua_setglobal(L, "track"); + // the address of the memcell as a handle of another kind: told apart all the same + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::track, &memcell_object); + lua_setglobal(L, "memcell_as_track"); + lua_pushlightuserdata(L, &memcell_object); + lua_setglobal(L, "light"); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::event, nullptr); + lua_setglobal(L, "none"); + } +}; + +} // namespace + +TEST_CASE("lua sandbox: a handle of the scenery api reaches the object of its kind") { + handle_state const lua; + CHECK(lua.run("return test_memcell(memcell)") == "1"); + CHECK(lua.run("return test_track(track)") == "2"); + CHECK(lua.run("return type(memcell)") == "userdata"); + // what the find functions give for a missing object, and what the functions take as no object + CHECK(lua.run("return none") == "nil"); + CHECK(lua.run("return test_memcell(nil)") == "nil"); + CHECK(lua.run("return test_memcell()") == "nil"); + // one object, one handle: equal, and the same key of a table + CHECK(lua.run("return rawequal(memcell, memcell2)") == "true"); + CHECK(lua.run("local t = { [memcell] = 'cell' } return t[memcell2]") == "cell"); + CHECK(lua.run("return rawequal(memcell, memcell_as_track)") == "false"); + // the handle of a dropped handle is made again + REQUIRE_FALSE(luaL_dostring(lua.get(), "memcell = nil memcell2 = nil collectgarbage() collectgarbage()")); + lua_sandbox::push_handle(lua.get(), lua_sandbox::handle_kind::memcell, &memcell_object); + lua_setglobal(lua.get(), "memcell"); + CHECK(lua.run("return test_memcell(memcell)") == "1"); +} + +TEST_CASE("lua sandbox: a handle of another kind, or anything else, is a Lua error and not an object") { + handle_state const lua; + // a track where a memcell goes (memcell_update(track_find(...)) once wrote into a track as a memcell). not a tail + // call, which LuaJIT gives no function name in the message + CHECK(contains(lua.run("local r = test_memcell(track) return r"), "bad argument #1 to 'test_memcell' (eu07.memcell expected, got userdata)")); + CHECK(contains(lua.run("local r = test_track(memcell) return r"), "bad argument #1 to 'test_track' (eu07.track expected, got userdata)")); + CHECK(contains(lua.run("return test_memcell(memcell_as_track)"), "eu07.memcell expected")); + CHECK(contains(lua.run("return test_memcell(light)"), "eu07.memcell expected, got userdata")); + for (auto const *value : {"1", "'memcell'", "{}", "true", "false", "print", "coroutine.create(function() end)"}) { + CAPTURE(value); + CHECK(contains(lua.run(std::format("return test_memcell({})", value)), "eu07.memcell expected")); + } + // the error is the script's: caught by pcall, and the state goes on + CHECK(lua.run("return (pcall(test_memcell, track))") == "false"); + CHECK(lua.run("return test_memcell(memcell)") == "1"); +} + +TEST_CASE("lua sandbox: a script can't reach the metatable of a handle") { + handle_state const lua; + CHECK(lua.run("return getmetatable(memcell)") == "false"); + CHECK(contains(lua.run("local r = setmetatable(memcell, {}) return r"), "bad argument #1 to 'setmetatable' (table expected, got userdata)")); + // no field to read or write + CHECK(contains(lua.run("return memcell.x"), "attempt to index")); + CHECK(contains(lua.run("memcell.x = 1"), "attempt to index")); +} + +#endif diff --git a/tests/unit/test_motor_param_bounds.cpp b/tests/unit/test_motor_param_bounds.cpp new file mode 100644 index 000000000..5d44c7331 --- /dev/null +++ b/tests/unit/test_motor_param_bounds.cpp @@ -0,0 +1,57 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +#include + +#include + +using test::definition; +using test::vehicle; + +// the field shunting step a position of the master controller selects (RList, its sixth column ScndAct) indexes the +// motor parameter table, MotorParam, which has MotorParametersArraySize + 1 entries. The loader takes ScndAct from the +// .fiz as it is, so the readers of the table (TMoverParameters::Momentum(), MomentumF(), TController::ESMVelocity()) +// go through motor_param(), which keeps the index inside the table + +namespace { + +// the RList rows of the EP09 with the ScndAct of the first position replaced +nlohmann::ordered_json ep09_rlist_with_scndact(std::string const &Scndact) { + std::ifstream file{std::string{EU07_UNIT_TESTS_DATA} + "/fiz/ep09_v2/104e.json"}; + REQUIRE(file.good()); + // '=' rather than braces: GCC takes a json in braces for an initializer list, an array holding it + auto const ep09 = nlohmann::ordered_json::parse(file); + auto rows = ep09.at("RList").at("rows"); + REQUIRE(rows.size() > 1); + rows[1][5] = Scndact; + return rows; +} + +} // namespace + +TEST_CASE("motor parameters: the ScndAct of an RList row is read from the .fiz as it is") { + vehicle ep09{definition::fiz("ep09_v2/104e")}; + // the first position of the EP09 runs on field shunting step 2 + CHECK(ep09->RList[1].ScndAct == 2); + CHECK(&ep09->motor_param(ep09->RList[1].ScndAct) == &ep09->MotorParam[2]); + + // a .fiz giving a step beyond the table: nothing checks it on loading + vehicle broken{definition::fiz("ep09_v2/104e").set("RList", "rows", ep09_rlist_with_scndact("20"))}; + CHECK(broken->RList[1].ScndAct == 20); + CHECK(broken->RList[1].ScndAct > MotorParametersArraySize); +} + +TEST_CASE("motor parameters: motor_param() keeps a step from the .fiz inside the table") { + vehicle broken{definition::fiz("ep09_v2/104e").set("RList", "rows", ep09_rlist_with_scndact("20"))}; + auto const &table{broken->MotorParam}; + // past the end: the last entry, rather than memory beyond the table + CHECK(&broken->motor_param(broken->RList[1].ScndAct) == &table[MotorParametersArraySize]); + CHECK(&broken->motor_param(MotorParametersArraySize + 1) == &table[MotorParametersArraySize]); + // below the start: the first entry + CHECK(&broken->motor_param(-1) == &table[0]); + // inside the table: the entry itself + for (int step = 0; step <= MotorParametersArraySize; ++step) { + CHECK(&broken->motor_param(step) == &table[step]); + } +} diff --git a/tests/unit/test_odometer.cpp b/tests/unit/test_odometer.cpp index 067e31037..b3da8d792 100644 --- a/tests/unit/test_odometer.cpp +++ b/tests/unit/test_odometer.cpp @@ -4,9 +4,23 @@ #include "utilities/Globals.h" #include "vehicle/odometer.h" +#include +#include +#include #include #include +#include +#include +#include #include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif // the odometer of a vehicle, kept between the sessions (eu07/maszyna#72): one state the cab's counters and the // python screens show, saved in one store, taking over the states the python screens kept in their own files @@ -355,13 +369,146 @@ TEST_CASE("odometer: two simulations saving one file keep each other's states") } CHECK(files == 1); } - SUBCASE("a store with nothing recorded since doesn't write") { + SUBCASE("a store with nothing recorded since doesn't write, once the file showed what it saved") { + REQUIRE(odometer::save(second, path)); write_file(path, "1 replaced by hand\n"); REQUIRE(odometer::save(second, path)); CHECK(load().size() == 1); } } +namespace { + +odometer::store load_store(std::filesystem::path const &Path) { + odometer::store store; + std::ifstream input{Path, std::ios::binary}; + store.read(input); + return store; +} + +// a comment line added to the file; a save that writes the file drops it +void mark(std::filesystem::path const &Path) { + std::ofstream{Path, std::ios::binary | std::ios::app} << "# not written since\n"; +} + +bool marked(std::filesystem::path const &Path) { + std::ifstream input{Path, std::ios::binary}; + std::stringstream content; + content << input.rdbuf(); + return content.str().find("# not written since") != std::string::npos; +} + +// the save of Late reads the file before the save of Early writes it, and puts its own file in place after: Late +// writes the file as it was before Early's save, Early's states are gone from it +void interleave(odometer::store &Early, odometer::store &Late, std::filesystem::path const &Path) { + auto const view{Path.parent_path() / "late_view" / Path.filename()}; + std::filesystem::create_directories(view.parent_path()); + std::filesystem::copy_file(Path, view, std::filesystem::copy_options::overwrite_existing); + REQUIRE(odometer::save(Early, Path)); + REQUIRE(odometer::save(Late, view)); + std::filesystem::rename(view, Path); +} + +} // namespace + +TEST_CASE("odometer: a save another simulation's save put its file over is written again") { + scratch_directory directory{"odometer_lost_save"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, "1000 shared\n"); + auto first{load_store(path)}; + auto second{load_store(path)}; + first.record("first only", run(70.0, 1000.0)); + second.record("second only", run(80.0, 1000.0)); + + interleave(second, first, path); + // the race of the two saves: the second one's state is gone from the file + REQUIRE_FALSE(load_store(path).find("second only").has_value()); + REQUIRE(load_store(path).find("first only").has_value()); + + // the second one's next save, nothing recorded since, finds the file without its state and writes it again + CHECK_FALSE(second.modified()); + REQUIRE(odometer::save(second, path)); + auto const saved{load_store(path)}; + CHECK(saved.size() == 3); + CHECK(saved.find("second only").value_or(0.0) == doctest::Approx(81.0)); + CHECK(saved.find("first only").value_or(0.0) == doctest::Approx(71.0)); + CHECK(saved.find("shared").value_or(0.0) == 1000.0); + + // both find their states in the file now: their next saves don't write it + mark(path); + for (auto round{0}; round < 3; ++round) { + REQUIRE(odometer::save(first, path)); + REQUIRE(odometer::save(second, path)); + } + CHECK(marked(path)); + CHECK(load_store(path).size() == 3); +} + +TEST_CASE("odometer: two simulations with different states of a vehicle settle on the newer one") { + scratch_directory directory{"odometer_lost_save_conflict"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, "1000 shared\n~20000 guessed by both\n"); + auto first{load_store(path)}; + auto second{load_store(path)}; + // the first one ran the shared vehicle further, and the made up one further from its made up state; the second + // one has a known state of the made up one, from a cab's counter + first.record("shared", run(1000.0, 10000.0)); + second.record("shared", run(1000.0, 5000.0)); + odometer::reading guessed; + guessed.begin(20000.0, odometer::origin::guessed); + guessed.run(9000.0); + first.record("guessed by both", guessed); + odometer::reading seeded; + seeded.begin(300.0, odometer::origin::counter); + second.record("guessed by both", seeded); + + // the second one's save is lost to the first one's, which holds the made up state + interleave(second, first, path); + REQUIRE(load_store(path).guessed("guessed by both")); + + // the second one writes its known state again. the first one takes it, and the second one the larger state of + // the shared vehicle the first one saved + REQUIRE(odometer::save(second, path)); + REQUIRE(odometer::save(first, path)); + auto const settled{load_store(path)}; + CHECK(settled.find("shared").value_or(0.0) == doctest::Approx(1010.0)); + CHECK(settled.find("guessed by both").value_or(0.0) == 300.0); + CHECK_FALSE(settled.guessed("guessed by both")); + CHECK(first.find("guessed by both").value_or(0.0) == 300.0); + CHECK(second.find("shared").value_or(0.0) == doctest::Approx(1010.0)); + + // neither one keeps writing the file over to have its own state there + mark(path); + for (auto round{0}; round < 3; ++round) { + REQUIRE(odometer::save(first, path)); + REQUIRE(odometer::save(second, path)); + } + CHECK(marked(path)); +} + +TEST_CASE("odometer: a save with nothing recorded since doesn't write the file again") { + scratch_directory directory{"odometer_saved_once"}; + auto const path{directory.path / "eu07_odometers.txt"}; + odometer::store store; + // states the file holds rounded to its digits + store.record("known", run(1000.0, 1234.56789)); + odometer::reading guessed; + guessed.begin(12345.678912, odometer::origin::guessed); + guessed.run(98.76543); + store.record("guessed", guessed); + REQUIRE(odometer::save(store, path)); + CHECK_FALSE(store.modified()); + + // the next save finds the file holding the states, rounded as they are: it doesn't write it + mark(path); + REQUIRE(odometer::save(store, path)); + CHECK(marked(path)); + // and the saves after it don't look at the file any more + std::filesystem::remove(path); + REQUIRE(odometer::save(store, path)); + CHECK_FALSE(std::filesystem::exists(path)); +} + TEST_CASE("odometer: a test run neither reads nor saves the player's store") { if (false == Global.test.enabled) CHECK(odometer::persistent()); @@ -532,3 +679,467 @@ TEST_CASE("odometer: the files of both kinds of python screens are read, by the CHECK_FALSE(odometer::legacy_state(vehicles, "EU07-425", scripts).has_value()); CHECK_FALSE(odometer::legacy_state(vehicles, "", scripts).has_value()); } + +// the day a state was last updated, kept in the file so the vehicles not run for long are dropped from it (review of +// eu07/maszyna#283: the file grew with every vehicle ever run). the tests give the day, the clock of the machine +// doesn't matter + +namespace { + +constexpr odometer::day today{std::chrono::year{2026} / 11 / 21}; + +odometer::day days_ago(int const Days) { + return today - std::chrono::days{Days}; +} + +odometer::day days_on(int const Days) { + return today + std::chrono::days{Days}; +} + +odometer::store read_text(std::string const &Text, odometer::day const Today = today) { + std::stringstream file{Text}; + odometer::store store; + store.read(file, Today); + return store; +} + +std::string read_file(std::filesystem::path const &Path) { + std::ifstream input{Path, std::ios::binary}; + std::stringstream content; + content << input.rdbuf(); + return content.str(); +} + +std::string written(odometer::store const &Store) { + std::stringstream text; + Store.write(text); + return text.str(); +} + +// the reader of the builds before the stamps, as it was (2f127688, odometer::store::read): the states it gets +struct old_state { + double km; + bool guessed; +}; + +std::optional old_line(std::string const &Line, std::string &Name) { + auto const separator{Line.find_first_of(" \t")}; + if (separator == std::string::npos) + return std::nullopt; + auto number{Line.substr(0, separator)}; + auto const guessed{false == number.empty() && number.front() == '~'}; + if (guessed) + number.erase(0, 1); + std::size_t used{0}; + double km{0.0}; + try { + km = std::stod(number, &used); + } catch (std::exception const &) { + return std::nullopt; + } + Name = Line.substr(separator + 1); + if (used != number.size() || false == std::isfinite(km) || km < 0.0 || Name.empty()) + return std::nullopt; + return old_state{km, guessed}; +} + +std::map old_read(std::string const &Text) { + std::map states; + std::stringstream input{Text}; + std::string line; + while (std::getline(input, line)) { + if (false == line.empty() && line.back() == '\r') + line.pop_back(); + if (line.empty() || line.front() == '#') + continue; + std::string name; + if (auto const state{old_line(line, name)}; state.has_value()) + states[name] = *state; + } + return states; +} + +odometer::reading guessed_run(double const Km, double const Metres) { + odometer::reading reading; + reading.begin(Km, odometer::origin::guessed); + reading.run(Metres); + return reading; +} + +} // namespace + +TEST_CASE("odometer: a file of the builds before the stamps is read whole, its states updated the day it's read") { + std::string const unstamped{"# odometer states of the vehicles: , ~ for one counted from a made up state\n" + "1000.0000 EU07-424\n" + "~20000.0000 SM42-001\n" + "42.5000 loco with spaces\n"}; + auto const store{read_text(unstamped)}; + REQUIRE(store.size() == 3); + CHECK(store.find("EU07-424").value() == 1000.0); + CHECK(store.guessed("SM42-001")); + CHECK(store.find("loco with spaces").value() == 42.5); + for (auto const *name : {"EU07-424", "SM42-001", "loco with spaces"}) { + CAPTURE(name); + CHECK(store.updated(name) == today); + } + CHECK_FALSE(store.updated("EU07-425").has_value()); + + // saved, all of them are written with the day they were read, none dropped + scratch_directory directory{"odometer_unstamped"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, unstamped); + auto loaded{read_text(read_file(path))}; + loaded.record("EU07-424", run(1000.0, 1000.0), today); + REQUIRE(odometer::save(loaded, path, today)); + auto const text{read_file(path)}; + CHECK(text.find("# updated 2026-11-21\n") != std::string::npos); + auto const after{read_text(text, days_on(10))}; + CHECK(after.size() == 3); + CHECK(after.find("EU07-424").value() == doctest::Approx(1001.0)); + CHECK(after.find("SM42-001").value() == 20000.0); + CHECK(after.updated("SM42-001") == today); +} + +TEST_CASE("odometer: the day a state was last updated is written with it and read back") { + odometer::store store; + store.record("EU07-424", run(1000.0, 1000.0), days_ago(10)); + store.record("loco with spaces", run(42.0, 500.0), today); + store.record("SM42-001", guessed_run(20000.0, 1000.0), days_ago(10)); + store.record("ET22-001", run(5.0, 1000.0), days_ago(400)); + auto const text{written(store)}; + // grouped by the day, the oldest first, by the name in a group + CHECK(text.find("# updated 2025-10-17\n6.0000 ET22-001\n" + "# updated 2026-11-11\n1001.0000 EU07-424\n~20001.0000 SM42-001\n" + "# updated 2026-11-21\n42.5000 loco with spaces\n") + != std::string::npos); + + auto const read{read_text(text)}; + CHECK(read.size() == 4); + CHECK(read.updated("EU07-424") == days_ago(10)); + CHECK(read.updated("SM42-001") == days_ago(10)); + CHECK(read.guessed("SM42-001")); + CHECK(read.updated("loco with spaces") == today); + CHECK(read.updated("ET22-001") == days_ago(400)); + CHECK(read.find("loco with spaces").value() == doctest::Approx(42.5)); + // the store read writes the same file again + CHECK(written(read) == text); +} + +TEST_CASE("odometer: a build before the stamps reads the file with them as it read its own") { + odometer::store store; + store.record("EU07-424", run(1000.0, 1000.0), days_ago(10)); + store.record("loco with spaces", run(42.0, 500.0), today); + store.record("SM42-001", guessed_run(20000.0, 1000.0), days_ago(300)); + auto const old{old_read(written(store))}; + REQUIRE(old.size() == 3); + CHECK(old.at("EU07-424").km == doctest::Approx(1001.0)); + CHECK_FALSE(old.at("EU07-424").guessed); + CHECK(old.at("loco with spaces").km == doctest::Approx(42.5)); + CHECK(old.at("SM42-001").km == doctest::Approx(20001.0)); + CHECK(old.at("SM42-001").guessed); +} + +TEST_CASE("odometer: a stamp later than the day is kept as written, a malformed one doesn't make a state expire") { + auto const store{read_text("# updated 2099-01-01\n1 future\n" + "# updated 2025-01-01\n2 dated\n" + "# a comment between\n3 after a comment\n" + "# updated nonsense\n4 malformed\n" + "# updated 2026-02-30\n5 no such day\n" + "# updated 2025-1-01\n6 short\n" + "# updated 2025-01-01 \r\n7 trailing space\n" + "#updated 2024-01-01\n8 not a stamp\n")}; + odometer::day const newyear{std::chrono::year{2025} / 1 / 1}; + CHECK(store.size() == 8); + // a clock set back doesn't move it back (review of #435: the next session with the right clock dropped them all) + CHECK(store.updated("future") == odometer::day{std::chrono::year{2099} / 1 / 1}); + CHECK(store.updated("dated") == newyear); + CHECK(store.updated("after a comment") == newyear); + CHECK(store.updated("malformed") == today); + CHECK(store.updated("no such day") == today); + CHECK(store.updated("short") == today); + CHECK(store.updated("trailing space") == newyear); + CHECK(store.updated("not a stamp") == newyear); +} + +TEST_CASE("odometer: a state is updated the day it's recorded, one left as it was keeps its day") { + auto store{read_text("# updated 2026-08-13\n300 known\n")}; + REQUIRE(store.updated("known") == days_ago(100)); + store.record("known", started(300.0), today); + CHECK(store.updated("known") == days_ago(100)); + store.record("known", run(300.0, 1000.0), today); + CHECK(store.updated("known") == today); +} + +TEST_CASE("odometer: of two stores merged, the later day of a state is kept, whichever state is newer") { + auto const other{read_text("# updated 2026-11-01\n100 known\n# updated 2026-11-20\n200 other\n")}; + auto mine{read_text("# updated 2026-11-10\n150 known\n# updated 2026-11-15\n250 other\n")}; + mine.merge(other); + CHECK(mine.find("known").value() == 150.0); + CHECK(mine.updated("known") == days_ago(11)); + CHECK(mine.find("other").value() == 250.0); + CHECK(mine.updated("other") == days_ago(1)); + auto const newer{read_text("# updated 2026-11-01\n500 known\n")}; + mine.merge(newer); + CHECK(mine.find("known").value() == 500.0); + CHECK(mine.updated("known") == days_ago(11)); +} + +TEST_CASE("odometer: a save drops the states not updated for longer than a year, the other simulations' too") { + CHECK(odometer::expiry() == std::chrono::days{365}); + scratch_directory directory{"odometer_expiry"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, "# updated 2025-11-20\n100 over a year\n" + "# updated 2025-11-21\n200 a year\n" + "# updated 2026-11-21\n300 fresh\n"); + auto store{read_text(read_file(path))}; + // another simulation saved meanwhile, with a state as old as one of this one's + write_file(path, "# updated 2025-11-20\n100 over a year\n" + "# updated 2025-11-21\n200 a year\n" + "# updated 2025-06-01\n5 old of another\n" + "# updated 2026-11-21\n300 fresh\n6 fresh of another\n"); + store.record("run today", run(70.0, 1000.0), today); + REQUIRE(odometer::save(store, path, today)); + + auto const saved{read_text(read_file(path))}; + CHECK(saved.size() == 4); + CHECK_FALSE(saved.find("over a year").has_value()); + CHECK_FALSE(saved.find("old of another").has_value()); + CHECK(saved.find("a year").value() == 200.0); + CHECK(saved.updated("a year") == days_ago(365)); + CHECK(saved.find("fresh").value() == 300.0); + CHECK(saved.find("fresh of another").value() == 6.0); + CHECK(saved.find("run today").value() == doctest::Approx(71.0)); + // gone from the store of the simulation too + CHECK_FALSE(store.find("over a year").has_value()); + CHECK(store.size() == 4); + + SUBCASE("the one of a year drops too once the file was updated a day later, in the session that reads it") { + // the session goes on the next day: measured from the day the file had when the session read it + store.record("run today", run(71.0, 1000.0), days_on(1)); + REQUIRE(odometer::save(store, path, days_on(1))); + CHECK(read_text(read_file(path), days_on(1)).find("a year").has_value()); + // the next session + auto next{read_text(read_file(path), days_on(1))}; + next.record("run today", run(72.0, 1000.0), days_on(1)); + REQUIRE(odometer::save(next, path, days_on(1))); + auto const later{read_text(read_file(path), days_on(1))}; + CHECK(later.size() == 3); + CHECK_FALSE(later.find("a year").has_value()); + CHECK(later.updated("run today") == days_on(1)); + } + SUBCASE("a store with nothing recorded since doesn't write the file only to drop them") { + REQUIRE(odometer::save(store, path, today)); + mark(path); + REQUIRE(odometer::save(store, path, days_on(1))); + CHECK(marked(path)); + CHECK(read_text(read_file(path), days_on(1)).find("a year").has_value()); + } +} + +TEST_CASE("odometer: a save lost to another simulation's save is written again with its stamps") { + scratch_directory directory{"odometer_lost_save_stamps"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, "# updated 2026-06-01\n1000 shared\n"); + auto first{read_text(read_file(path))}; + auto second{read_text(read_file(path))}; + first.record("shared", run(1000.0, 5000.0), today); + first.record("first only", run(70.0, 1000.0), today); + second.record("second only", run(80.0, 1000.0), days_ago(1)); + + // the second one reads the file before the first one writes it, and puts its own in place after + auto const view{directory.path / "late_view" / path.filename()}; + std::filesystem::create_directories(view.parent_path()); + std::filesystem::copy_file(path, view); + REQUIRE(odometer::save(first, path, today)); + REQUIRE(odometer::save(second, view, today)); + std::filesystem::rename(view, path); + REQUIRE_FALSE(read_text(read_file(path)).find("first only").has_value()); + + REQUIRE(odometer::save(first, path, today)); + REQUIRE(odometer::save(second, path, today)); + auto const saved{read_text(read_file(path))}; + CHECK(saved.size() == 3); + CHECK(saved.find("shared").value() == doctest::Approx(1005.0)); + CHECK(saved.updated("shared") == today); + CHECK(saved.find("first only").value() == doctest::Approx(71.0)); + CHECK(saved.updated("first only") == today); + CHECK(saved.find("second only").value() == doctest::Approx(81.0)); + CHECK(saved.updated("second only") == days_ago(1)); +} + +// a wrong clock, the period of eu07.ini (odometer.expiry) and the log of what's dropped (review of eu07/maszyna#435) + +// the lines logged while the object lives, kept by the engine stubs (engine_stubs.cpp) +void unit_tests_log_capture(bool Enabled); +std::vector unit_tests_logged_lines(); + +namespace { + +odometer::day const backintime{std::chrono::year{2000} / 1 / 1}; + +int process_id() { +#ifdef _WIN32 + return _getpid(); +#else + return static_cast(getpid()); +#endif +} + +class log_capture { +public: + log_capture() { unit_tests_log_capture(true); } + ~log_capture() { unit_tests_log_capture(false); } + log_capture(log_capture const &) = delete; + log_capture &operator=(log_capture const &) = delete; + + std::size_t count(std::string_view const Text) const { + auto const lines{unit_tests_logged_lines()}; + return static_cast(std::ranges::count_if(lines, [Text](std::string const &Line) { return Line.find(Text) != std::string::npos; })); + } +}; + +std::string const stamped_file{"# updated 2025-12-01\n100 a year ago\n" + "# updated 2026-11-11\n200 driven\n" + "# updated 2026-11-21\n300 fresh\n"}; + +} // namespace + +TEST_CASE("odometer: a clock set back doesn't move the days of the states back, nor drops them then") { + scratch_directory directory{"odometer_clock_back"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, stamped_file); + // a dead battery of the clock: the session starts on 2000-01-01 + auto back{read_text(read_file(path), backintime)}; + CHECK(back.updated("a year ago") == days_ago(355)); + back.record("driven", run(200.0, 1000.0), backintime); + CHECK(back.updated("driven") == days_ago(10)); + REQUIRE(odometer::save(back, path, backintime)); + auto const written{read_file(path)}; + CHECK(written.find("# updated 2000-01-01") == std::string::npos); + CHECK(read_text(written).size() == 3); + + // the next session with the right clock drops none of them + auto right{read_text(written, days_on(1))}; + right.record("fresh", run(300.0, 1000.0), days_on(1)); + REQUIRE(odometer::save(right, path, days_on(1))); + auto const after{read_text(read_file(path), days_on(1))}; + CHECK(after.size() == 3); + CHECK(after.updated("a year ago") == days_ago(355)); + CHECK(after.updated("driven") == days_ago(10)); + CHECK(after.find("driven").value() == doctest::Approx(201.0)); +} + +TEST_CASE("odometer: a clock set forward doesn't drop the states not run in that session") { + scratch_directory directory{"odometer_clock_forward"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, stamped_file); + // two years ahead: measured from the day the file had when the session read it + auto ahead{read_text(read_file(path), days_on(730))}; + ahead.record("driven", run(200.0, 1000.0), days_on(730)); + REQUIRE(odometer::save(ahead, path, days_on(730))); + // the later saves of the session too, which find its own states of that day in the file + ahead.record("driven", run(201.0, 1000.0), days_on(730)); + REQUIRE(odometer::save(ahead, path, days_on(730))); + CHECK(read_text(read_file(path), days_on(730)).size() == 3); + + // the next session with the right clock: the day ahead is kept as written, nothing drops + auto right{read_text(read_file(path), days_on(1))}; + CHECK(right.updated("driven") == days_on(730)); + right.record("fresh", run(300.0, 1000.0), days_on(1)); + REQUIRE(odometer::save(right, path, days_on(1))); + auto const after{read_text(read_file(path), days_on(1))}; + CHECK(after.size() == 3); + CHECK(after.updated("a year ago") == days_ago(355)); + CHECK(after.updated("driven") == days_on(730)); +} + +TEST_CASE("odometer: a player back after a break keeps the states in the session he comes back in") { + scratch_directory directory{"odometer_break"}; + auto const path{directory.path / "eu07_odometers.txt"}; + // the last session was 500 days ago + write_file(path, "# updated 2024-05-19\n10 too old\n" + "# updated 2025-01-31\n20 older\n" + "# updated 2025-07-09\n30 last run\n40 not run since\n"); + REQUIRE(odometer::day{std::chrono::year{2025} / 7 / 9} == days_ago(500)); + auto back{read_text(read_file(path))}; + back.record("last run", run(30.0, 1000.0), today); + REQUIRE(odometer::save(back, path, today)); + auto const first{read_text(read_file(path))}; + // more than a year before the last session: gone, as that session would have dropped it the next day + CHECK_FALSE(first.find("too old").has_value()); + CHECK(first.find("older").has_value()); + CHECK(first.find("not run since").has_value()); + CHECK(first.updated("last run") == today); + + // the session after: not run for a year before the last one, they drop + auto next{read_text(read_file(path), days_on(1))}; + next.record("last run", run(31.0, 1000.0), days_on(1)); + REQUIRE(odometer::save(next, path, days_on(1))); + auto const second{read_text(read_file(path), days_on(1))}; + CHECK(second.size() == 1); + CHECK(second.find("last run").has_value()); +} + +TEST_CASE("odometer: the period is the one eu07.ini gives, 0 keeps every state") { + auto const text{"# updated 2000-01-01\n1 long ago\n# updated 2026-10-21\n2 a month ago\n# updated 2026-11-21\n3 fresh\n"}; + { + auto store{read_text(text)}; + CHECK(store.expire(today, std::chrono::days{0}) == 0); + CHECK(store.size() == 3); + } + { + auto store{read_text(text)}; + CHECK(store.expire(today, std::chrono::days{30}) == 2); + CHECK(store.find("fresh").has_value()); + } + { + // and a save with it + scratch_directory directory{"odometer_never"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, text); + auto store{read_text(read_file(path))}; + store.record("fresh", run(3.0, 1000.0), today); + REQUIRE(odometer::save(store, path, today, std::chrono::days{0})); + CHECK(read_text(read_file(path)).size() == 3); + } + + // odometer.expiry in eu07.ini, a year unless set (the parser of eu07.ini, Globals.cpp, isn't in the build of + // the unit tests) + CHECK(std::make_unique()->odometer_expiry == 365); + // the store of the simulation takes it from the settings, a negative one as 0 + auto const kept{Global.odometer_expiry}; + Global.odometer_expiry = 90; + CHECK(odometer::expiry() == std::chrono::days{90}); + Global.odometer_expiry = 0; + CHECK(odometer::expiry() == std::chrono::days{0}); + Global.odometer_expiry = -5; + CHECK(odometer::expiry() == std::chrono::days{0}); + Global.odometer_expiry = kept; +} + +TEST_CASE("odometer: the states dropped are logged once, by the save that writes the file without them") { + scratch_directory directory{"odometer_dropped_log"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, "# updated 2025-01-01\n1 long ago\n# updated 2026-11-21\n2 fresh\n"); + auto store{read_text(read_file(path))}; + store.record("fresh", run(2.0, 1000.0), today); + constexpr std::string_view dropped{"not updated for 365 days dropped"}; + log_capture const log; + + // the file aside can't be written: each save fails, none logs the states dropped + auto temporary{path}; + temporary += "." + std::to_string(process_id()) + ".tmp"; + std::filesystem::create_directories(temporary / "blocked"); + CHECK_FALSE(odometer::save(store, path, today, std::chrono::days{365})); + CHECK_FALSE(odometer::save(store, path, today, std::chrono::days{365})); + CHECK(log.count(dropped) == 0); + CHECK(read_text(read_file(path)).find("long ago").has_value()); + + std::filesystem::remove_all(temporary); + REQUIRE(odometer::save(store, path, today, std::chrono::days{365})); + CHECK(log.count(dropped) == 1); + CHECK_FALSE(read_text(read_file(path)).find("long ago").has_value()); + // the save after, which finds the file as written, doesn't log them again + REQUIRE(odometer::save(store, path, today, std::chrono::days{365})); + CHECK(log.count(dropped) == 1); +} diff --git a/tests/unit/test_parser.cpp b/tests/unit/test_parser.cpp index 2584218d0..ee82aca9a 100644 --- a/tests/unit/test_parser.cpp +++ b/tests/unit/test_parser.cpp @@ -696,6 +696,70 @@ TEST_CASE("parser: read line by line, a line starting with include is the direct CHECK(rest(word, false, "\n\r") == "one|two"); } +namespace { + +// the lines of a file, read the way the vehicle's .fiz is (TMoverParameters::LoadFIZ_Parse): line by line while the +// parser is ok +std::string fiz_lines(cParser &Parser) { + std::string joined; + while (Parser.ok()) { + auto const line{Parser.getToken(false, "\n\r")}; + if (line.empty()) { + continue; + } + if (false == joined.empty()) { + joined += '|'; + } + joined += line; + } + return joined; +} + +} // namespace + +TEST_CASE("parser: a file which ends right after the end of an include is read through, the included file too") { + // the shape of the .fiz files of the wagons (pkp/yb_v1/b84_pl_1.fiz): the directive, the file and its parameters + // each on a line of their own, and no line break after the end. the change of MaSzyna-EU07/maszyna#100 broke on these + test::scratch_folder const folder{"parser_include_at_end"}; + folder.write("yb.fiz.inc", "Mass=(p1)\r\nVmax=(p2)\r\nLength=20\r\n"); + folder.write("ended.fiz", "include\r\nyb.fiz.inc\r\n160\r\n80\r\nend"); + folder.write("newline.fiz", "include\r\nyb.fiz.inc\r\n160\r\n80\r\nend\r\n"); + + cParser ended("ended.fiz", cParser::buffer_FILE, folder.path()); + CHECK(fiz_lines(ended) == "Mass=160|Vmax=80|Length=20"); + cParser newline("newline.fiz", cParser::buffer_FILE, folder.path()); + CHECK(fiz_lines(newline) == "Mass=160|Vmax=80|Length=20"); + + SUBCASE("the end of the data shows once the included file is read through, not when its directive is") { + folder.write("pair.inc", "x y"); + cParser parser("include pair.inc end", cParser::buffer_TEXT, folder.path()); + CHECK(parser.getToken() == "x"); + CHECK_FALSE(parser.eof()); + CHECK(parser.getToken() == "y"); + CHECK(parser.eof()); + CHECK(parser.ok()); + CHECK(parser.getToken().empty()); + CHECK_FALSE(parser.ok()); + // the same as for a text with the included tokens in place of the directive + cParser same("x y", cParser::buffer_TEXT); + CHECK(same.getToken() == "x"); + CHECK_FALSE(same.eof()); + CHECK(same.getToken() == "y"); + CHECK(same.eof()); + } + SUBCASE("a reader which stops at the end of the data reads the whole included file") { + folder.write("map.inc", "alpha One\nbeta Two"); + for (auto const *const text : {"include map.inc end", "include map.inc end\n"}) { + CAPTURE(text); + cParser parser(text, cParser::buffer_TEXT, folder.path()); + std::map map; + deserialize_map(map, parser); + CHECK(map["alpha"] == "One"); + CHECK(map["beta"] == "Two"); + } + } +} + TEST_CASE("parser: an include can name several files to pick one from at random") { test::scratch_folder const folder{"parser_random_include"}; folder.write("only.inc", "chosen"); diff --git a/tests/unit/test_pressure_switch.cpp b/tests/unit/test_pressure_switch.cpp new file mode 100644 index 000000000..65672b252 --- /dev/null +++ b/tests/unit/test_pressure_switch.cpp @@ -0,0 +1,295 @@ +#include "stdafx.h" +#include "doctest.h" +#include "drive.h" + +#include "McZapkie/hamulce.h" + +// the pressure switch of the EP05 (git.eu07.pl eu07/maszyna#48). the pressure switch of the simulator is two +// conditions in one: it cuts the traction motors off above 2 bar in the brake cylinders and below 3.6 bar in the +// brake pipe. the EP05 takes current whatever the pressure in its brake cylinders (Engine: PressureSwitchBrakeCylinder=No +// leaves the brake pipe half alone), and an emergency brake application made with the master controller on a power +// position opens its line breaker (Cntrl. EmergencyBrakeMainOff=), which on this locomotive +// drops the pantographs too, as they stay up only through the closed line breaker (Cntrl. PantRequiresMain) + +namespace { + +constexpr test::track line{0.15, 0.0, test::catenary_3kv}; + +// the brake pipe pressure taken for an emergency application in these tests [bar]: below the 2.8 bar the FV4a +// gives on its last service position, above what is left in the pipe once it's vented +constexpr double emergency_pressure{2.5}; + +struct keys { + bool brakecylinder{true}; // Engine: PressureSwitchBrakeCylinder + bool mainoff{false}; // Cntrl. EmergencyBrakeMainOff + bool mainsfirst{true}; // Cntrl. PantRequiresMain, which the game's EP05 has +}; + +test::definition ep05(keys const &Keys) { + auto definition{test::definition::fiz("ep05_v2/ep05")}; + if (Keys.mainsfirst) { + // the game's definition got it after the one of the tests was converted + definition.set("Cntrl", "PantRequiresMain", "Yes"); + } + if (false == Keys.brakecylinder) { + definition.set("Engine", "PressureSwitchBrakeCylinder", "No"); + } + if (Keys.mainoff) { + definition.set("Cntrl", "EmergencyBrakeMainOff", emergency_pressure); + } + return definition; +} + +// the locomotive started up the way the driver does it and its brakes released, until the pressure switch lets go +void get_ready(test::vehicle &Loco, test::driven const &Driven) { + REQUIRE(test::start_up(Driven, line)); + test::release_brakes(Driven.cab); + test::drive(Driven, line, 20.0); + for (int i = 0; i < 120 && Loco->ControlPressureSwitch; ++i) { + test::drive(Driven, line, 1.0); + } + REQUIRE_FALSE(Loco->ControlPressureSwitch); + REQUIRE(Loco->Mains); + REQUIRE(Loco->Pantographs[end::rear].is_active); +} + +// the master controller taken to the given position a notch a second +void notch_up(test::vehicle &Loco, test::driven const &Driven, int const Position) { + while (Loco->MainCtrlPos < Position && Loco->IncMainCtrl(1)) { + test::drive(Driven, line, 1.0); + } + test::drive(Driven, line, 2.0); + REQUIRE(Loco->MainCtrlPos == Position); +} + +void get_under_power(test::vehicle &Loco, test::driven const &Driven, int const Position) { + get_ready(Loco, Driven); + notch_up(Loco, Driven, Position); + REQUIRE(Loco->StLinFlag); + REQUIRE(std::abs(Loco->Im) > 10.0); +} + +// the independent brake applied in full: 3.8 bar in the brake cylinders of the locomotive (Brake: MaxBP) +void apply_independent_brake(test::vehicle &Loco, test::driven const &Driven) { + Loco->IncLocalBrakeLevel(LocalBrakePosNo); + test::drive(Driven, line, 20.0); + REQUIRE(Loco->BrakePress == doctest::Approx(3.8).epsilon(0.03)); + REQUIRE(Loco->PipePress > 4.8); +} + +void emergency_application(test::vehicle &Loco, test::driven const &Driven) { + Loco->BrakeLevelSet(Loco->Handle->GetPos(bh_EB)); + test::drive(Driven, line, 10.0); + REQUIRE(Loco->PipePress < 1.0); +} + +} // namespace + +TEST_CASE("pressure switch: the keys are off by default") { + test::vehicle loco{ep05({}), 0.0, "test", 1}; + CHECK(loco->HasControlPressureSwitch); + CHECK(loco->PressureSwitchBrakeCylinder); + CHECK(loco->EmergencyBrakeMainOffPressure == 0.0); + + test::vehicle changed{ep05({.brakecylinder = false, .mainoff = true}), 0.0, "test", 1}; + CHECK(changed->HasControlPressureSwitch); + CHECK_FALSE(changed->PressureSwitchBrakeCylinder); + CHECK(changed->EmergencyBrakeMainOffPressure == doctest::Approx(emergency_pressure)); +} + +TEST_CASE("pressure switch: with the brake cylinders at 3.8 bar the EP05 takes no current, as before") { + test::vehicle loco{ep05({}), 0.0, "test", 1}; + auto driven{test::driving(loco)}; + get_ready(loco, driven); + apply_independent_brake(loco, driven); + CHECK(loco->ControlPressureSwitch); + CHECK_FALSE(loco->MainCircuitLampsEnabled()); + + notch_up(loco, driven, 3); + CHECK_FALSE(loco->StLinFlag); + CHECK(loco->Im == 0.0); + CHECK(loco->Mains); + CHECK(loco->Pantographs[end::rear].is_active); +} + +TEST_CASE("pressure switch: without its brake cylinder half the EP05 takes current with the brake cylinders at 3.8 bar") { + test::vehicle loco{ep05({.brakecylinder = false}), 0.0, "test", 1}; + auto driven{test::driving(loco)}; + get_ready(loco, driven); + apply_independent_brake(loco, driven); + CHECK_FALSE(loco->ControlPressureSwitch); + // the lamps of the main circuit tell the start can be made + CHECK(loco->MainCircuitLampsEnabled()); + CHECK(loco->LineContactorsLampLit()); + + notch_up(loco, driven, 3); + CHECK(loco->StLinFlag); + CHECK(loco->MainCtrlActualPos == 3); + CHECK(std::abs(loco->Im) > 100.0); + CHECK(loco->BrakePress == doctest::Approx(3.8).epsilon(0.03)); + MESSAGE("current with 3.8 bar in the brake cylinders, position 3: " << std::abs(loco->Im) << " A"); +} + +TEST_CASE("pressure switch: without its brake cylinder half the brake pipe still cuts the traction motors off") { + test::vehicle loco{ep05({.brakecylinder = false}), 0.0, "test", 1}; + auto driven{test::driving(loco)}; + get_under_power(loco, driven, 5); + + SUBCASE("a service application") { + loco->BrakeLevelSet(loco->Handle->GetPos(bh_FB)); + test::drive(driven, line, 15.0); + REQUIRE(loco->PipePress < 3.6); + REQUIRE(loco->PipePress > 3.0); + } + SUBCASE("an emergency application") { + emergency_application(loco, driven); + } + CHECK(loco->ControlPressureSwitch); + CHECK_FALSE(loco->StLinFlag); + CHECK(loco->Im == 0.0); + // nothing else lets go without the other key + CHECK(loco->Mains); + CHECK(loco->Pantographs[end::rear].is_active); +} + +TEST_CASE("pressure switch: an emergency application with the master controller on a power position opens the line breaker and drops the pantographs") { + test::vehicle loco{ep05({.brakecylinder = false, .mainoff = true}), 0.0, "test", 1}; + auto driven{test::driving(loco)}; + get_under_power(loco, driven, 5); + + SUBCASE("made with the brake handle") { + loco->BrakeLevelSet(loco->Handle->GetPos(bh_EB)); + } + SUBCASE("made with the emergency brake of the train") { + loco->AlarmChainSwitch(true); + } + test::drive(driven, line, 10.0); + REQUIRE(loco->PipePress < emergency_pressure); + REQUIRE(loco->MainCtrlPos == 5); + CHECK_FALSE(loco->Mains); + CHECK_FALSE(loco->Pantographs[end::front].is_active); + CHECK_FALSE(loco->Pantographs[end::rear].is_active); + CHECK(loco->PantographVoltage == 0.0); + CHECK_FALSE(loco->StLinFlag); + CHECK(loco->Im == 0.0); + + // the line breaker doesn't close again while the master controller is where it was + loco->MainSwitch(true); + test::drive(driven, line, 2.0); + CHECK_FALSE(loco->Mains); + CHECK_FALSE(loco->Pantographs[end::rear].is_active); +} + +TEST_CASE("pressure switch: an emergency application with the master controller at zero leaves the line breaker and the pantographs alone") { + test::vehicle loco{ep05({.brakecylinder = false, .mainoff = true}), 0.0, "test", 1}; + auto driven{test::driving(loco)}; + get_under_power(loco, driven, 5); + while (loco->DecMainCtrl(1)) { + // down to zero + } + test::drive(driven, line, 2.0); + REQUIRE(loco->MainCtrlPos == 0); + + emergency_application(loco, driven); + CHECK(loco->Mains); + CHECK(loco->Pantographs[end::rear].is_active); + CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); + CHECK(loco->Im == 0.0); + + // and the master controller moved with the pipe empty is the same as the application made with it moved + loco->IncMainCtrl(1); + test::drive(driven, line, 2.0); + CHECK_FALSE(loco->Mains); + CHECK_FALSE(loco->Pantographs[end::rear].is_active); +} + +TEST_CASE("pressure switch: a service application with the master controller on a power position doesn't open the line breaker") { + test::vehicle loco{ep05({.brakecylinder = false, .mainoff = true}), 0.0, "test", 1}; + auto driven{test::driving(loco)}; + get_under_power(loco, driven, 5); + + // the last service position of the FV4a, 2.8 bar in the pipe + loco->BrakeLevelSet(5.0); + auto lowest{loco->PipePress}; + for (int second = 0; second < 60; ++second) { + test::drive(driven, line, 1.0); + lowest = std::min(lowest, loco->PipePress); + } + MESSAGE("the lowest brake pipe pressure of the service application: " << lowest << " bar"); + REQUIRE(lowest < 3.0); + CHECK(lowest > emergency_pressure); + CHECK(loco->Mains); + CHECK(loco->Pantographs[end::rear].is_active); + // the pressure switch has cut the motors off + CHECK_FALSE(loco->StLinFlag); + CHECK(loco->Im == 0.0); +} + +TEST_CASE("pressure switch: without the key an emergency application leaves the line breaker closed and the pantographs up, as before") { + test::vehicle loco{ep05({}), 0.0, "test", 1}; + auto driven{test::driving(loco)}; + get_under_power(loco, driven, 5); + + emergency_application(loco, driven); + REQUIRE(loco->MainCtrlPos == 5); + CHECK(loco->Mains); + CHECK(loco->Pantographs[end::rear].is_active); + CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); + // the pressure switch cuts the motors off + CHECK(loco->ControlPressureSwitch); + CHECK_FALSE(loco->StLinFlag); + CHECK(loco->Im == 0.0); +} + +TEST_CASE("pressure switch: where the pantographs don't hang on the line breaker the emergency application opens only the line breaker") { + test::vehicle loco{ep05({.brakecylinder = false, .mainoff = true, .mainsfirst = false}), 0.0, "test", 1}; + REQUIRE_FALSE(loco->PantographsRequireMains); + auto driven{test::driving(loco)}; + get_under_power(loco, driven, 5); + + emergency_application(loco, driven); + CHECK_FALSE(loco->Mains); + CHECK(loco->Pantographs[end::rear].is_active); + CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); + CHECK_FALSE(loco->StLinFlag); + CHECK(loco->Im == 0.0); +} + +TEST_CASE("pressure switch: after the emergency application the driver's start-up gets the locomotive going again") { + // test::start_up() takes the AI's steps of TController::PrepareEngine(): the master controller to zero, the relays + // reset, the line breaker closed. the pantograph switches stay as they were, so the pantograph rises with the line + // breaker + test::vehicle loco{ep05({.brakecylinder = false, .mainoff = true}), 0.0, "test", 1}; + auto driven{test::driving(loco)}; + get_under_power(loco, driven, 5); + emergency_application(loco, driven); + REQUIRE_FALSE(loco->Mains); + REQUIRE_FALSE(loco->Pantographs[end::rear].is_active); + REQUIRE(loco->Pantographs[end::rear].valve.is_enabled); + + // with the brake pipe still empty + REQUIRE(test::start_up(driven, line, 60.0)); + CHECK(loco->MainCtrlPos == 0); + CHECK(loco->Mains); + CHECK(loco->Pantographs[end::rear].is_active); + CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); + REQUIRE(loco->PipePress < emergency_pressure); + // and it stays so + test::drive(driven, line, 30.0); + CHECK(loco->Mains); + CHECK(loco->Pantographs[end::rear].is_active); + + // the brakes released (the AI fills an emptied pipe with the releaser held, TController::control_releaser()), + // the pressure switch lets the start be made + test::release_brakes(driven.cab); + for (int i = 0; i < 180 && loco->ControlPressureSwitch; ++i) { + loco->BrakeReleaser(loco->PipePress < 3.0 ? 1 : 0); + test::drive(driven, line, 1.0); + } + loco->BrakeReleaser(0); + REQUIRE_FALSE(loco->ControlPressureSwitch); + notch_up(loco, driven, 3); + CHECK(loco->Mains); + CHECK(loco->StLinFlag); + CHECK(std::abs(loco->Im) > 10.0); +} diff --git a/tests/unit/test_pullee.cpp b/tests/unit/test_pullee.cpp new file mode 100644 index 000000000..7e2742f7a --- /dev/null +++ b/tests/unit/test_pullee.cpp @@ -0,0 +1,449 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "consist.h" +#include "drive.h" +#include "real_vehicles.h" + +#include "vehicle/pulleemode.h" + +using test::definition; +using test::vehicle; + +// the pullee mode ("jazda ciągniona", MaSzyna-EU07/maszyna#64): a vehicle prepared for being hauled dead in a +// train, TMoverParameters::PulleeModeSwitch(). the trains here are an EU07 and the vehicle behind it, coupled with +// the hook and the brake hose alone, as with coupling 3 of a scenery. every test has both sides: what the vehicle +// does as it is (unchanged by the mode being there), and what it does prepared for hauling. +// pressures in bar, the brake pipe runs at 5.0 + +namespace { + +constexpr int hook_and_brake_hose{coupling::coupler | coupling::brakehose}; + +// an EU07 with nobody in it, its brake pipe held by the test the way a driver's valve would hold it, and the +// vehicle it hauls. Velocity as of a trainset of a scenery [km/h]: not 0, the vehicles are ready to depart, +// 0, they stand braked (brake pipe at 3.5, hand and spring brakes on, batteries off) +struct hauled_train { + test::consist train; + vehicle &locomotive; + vehicle &hauled; + + hauled_train(definition const &Hauled, double const Velocity, bool const Pullee) + : locomotive{train.add(definition::fiz("4e_v1/4e"), 0, test::consist::full_coupling, Velocity)}, hauled{train.add(Hauled, 0, hook_and_brake_hose, Velocity)} { + if (Pullee) { + REQUIRE(hauled->PulleeModeSwitch(true)); + } + locomotive.hold_brake_pipe(5.0); + } + + void run(double const Seconds) { train.run(Seconds); } +}; + +// no air in the main reservoir and the feed pipe, as after standing dead for some hours +void drain_feed_air(TMoverParameters &Vehicle) { + Vehicle.Pipe2->CreatePress(0.0); + Vehicle.Pipe2->Act(); + Vehicle.CompressedVolume = 0.0; +} + +// whether the real vehicle can go in a train at all: the road vehicles can't, nor can the draisine, which has no coupler +bool can_be_hauled(std::string const &Path) { + vehicle probe{definition::fiz(Path)}; + return (probe->CategoryFlag & 1) != 0 && probe->Couplers[end::front].CouplerType != TCouplerType::NoCoupler; +} + +} // namespace + +TEST_CASE("pullee: the parameter H among the ones after the coupling of a vehicle asks for the mode") { + CHECK(pullee_mode::requested("H")); + CHECK(pullee_mode::requested("h")); + CHECK(pullee_mode::requested("BG.H")); + CHECK(pullee_mode::requested("H.BG")); + CHECK(pullee_mode::requested("BP.WF10.h.TA")); + CHECK(pullee_mode::requested("HX")); // letters after it are for later + // the parameters the sceneries have: brakes, wheels (their H is the hunting of a bogie), temperatures, load + CHECK_FALSE(pullee_mode::requested("")); + CHECK_FALSE(pullee_mode::requested("BG")); + CHECK_FALSE(pullee_mode::requested("WH25")); + CHECK_FALSE(pullee_mode::requested("BR.WF5R10P50H25.TA.L50")); + CHECK_FALSE(pullee_mode::requested("0")); +} + +TEST_CASE("pullee: a dead Vectron vents the brake pipe of the train hauling it, prepared for hauling it doesn't") { + // the Vectron applies the emergency brake while none of its cabs is active (InactiveCabFlag bit 1), which a + // vehicle hauled with the hook and the brake hose never has + auto const vectron{definition::fiz("vectron_v1/wariant_7w")}; + SUBCASE("as it is") { + hauled_train train{vectron, 60.0, false}; + REQUIRE((train.hauled->InactiveCabFlag & activation::emergencybrake) != 0); + REQUIRE_FALSE(train.hauled->PulleeMode); + train.run(120.0); + CHECK(train.hauled->EmergencyValveFlow > 0.0); + CHECK(train.locomotive->PipePress < 4.95); // the pipe sags although the locomotive keeps feeding it + CHECK(train.hauled->BrakePress > 0.4); + CHECK(train.hauled.speed() < 30.0); + } + SUBCASE("prepared for hauling") { + hauled_train train{vectron, 60.0, true}; + train.run(120.0); + CHECK(train.hauled->EmergencyValveFlow == 0.0); + CHECK(train.locomotive->PipePress > 4.99); + CHECK(train.hauled->BrakePress < 0.1); + CHECK(train.hauled->Fb < 1.0); + CHECK(train.hauled.speed() > 40.0); // running resistance alone + } +} + +TEST_CASE("pullee: an EU07 with a driver can't release the brakes of a dead Vectron, and hauls one prepared for hauling") { + for (auto const pullee : {false, true}) { + CAPTURE(pullee); + test::reseed_random(); + test::consist train; + // a trainset ready to depart, as with velocity 0.1 in a scenery + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 1, test::consist::full_coupling, 0.1)}; + auto &hauled{train.add(definition::fiz("vectron_v1/wariant_7w"), 0, hook_and_brake_hose, 0.1)}; + if (pullee) { + REQUIRE(hauled->PulleeModeSwitch(true)); + } + test::track const track{0.15, 0.0, test::catenary_3kv}; + auto driven{test::driving(train)}; + REQUIRE(test::start_up(driven, track, 600.0)); + test::release_brakes(driven.cab); + // the driver of a train switches on the batteries of the vehicles not controlled from the cab, TController::CheckVehicles() + hauled->BatterySwitch(true); + test::drive(driven, track, 60.0); + if (false == pullee) { + // the Vectron has emptied the brake pipe, and both locomotives stand on an emergency application + CHECK(hauled->Battery); + CHECK(locomotive->PipePress < 1.0); + CHECK(locomotive->BrakePress > 3.0); + CHECK(hauled->BrakePress > 3.0); + continue; + } + CHECK_FALSE(hauled->Battery); + CHECK(locomotive->PipePress > 4.9); + CHECK(locomotive->BrakePress < 0.1); + CHECK(hauled->BrakePress < 0.1); + // the driver notches up watching the ammeter + for (int i = 0; i < 3 && driven.cab.DirActive <= 0; ++i) { + driven.cab.DirectionForward(); + } + for (int second = 0; second < 60; second += 5) { + if (std::abs(driven.controlling.Im) < 350.0 && false == driven.controlling.IsMainCtrlMaxPowerPos()) { + driven.controlling.IncMainCtrl(1); + } + test::drive(driven, track, 5.0); + } + CHECK(hauled.speed() > 20.0); + } +} + +TEST_CASE("pullee: the spring brake of a dead locomotive without air stops the train, prepared for hauling it gives no force") { + // the spring brake is held off by the air of the feed pipe, which on a dead locomotive is what its main + // reservoir has left. the EU47 and the EP09 have the spring brake alone, the Vectron the emergency brake too + for (auto const *path : {"e186_v2/eu47", "ep09_v2/104e", "vectron_v1/wariant_7w"}) { + for (auto const pullee : {false, true}) { + CAPTURE(path); + CAPTURE(pullee); + test::reseed_random(); + hauled_train train{definition::fiz(path), 60.0, pullee}; + auto const &hauled{train.hauled.mover()}; + REQUIRE(hauled.SpringBrake.MaxBrakeForce > 0.0); + drain_feed_air(train.hauled.mover()); + train.run(60.0); + // no air came from anywhere: the cylinder of the spring brake is empty either way + REQUIRE(hauled.SpringBrake.SBP < 0.1); + if (pullee) { + CHECK(hauled.Fb < 1.0); + CHECK(train.hauled.speed() > 45.0); + } + else { + CHECK(hauled.Fb > 30000.0); + CHECK(std::abs(train.hauled.speed()) < 1.0); + } + } + } +} + +TEST_CASE("pullee: a dead EU47 starts to drag once its main reservoir has leaked down, prepared for hauling it never does") { + // from a standing start the reservoir has 4.4 bar, and the spring brake comes on below 3.5 (MinFP) + for (auto const pullee : {false, true}) { + CAPTURE(pullee); + test::reseed_random(); + hauled_train train{definition::fiz("e186_v2/eu47"), 0.0, pullee}; + auto &hauled{train.hauled.mover()}; + // what the driver of the train does on its inspection, TController::AutoRewident() + hauled.DecManualBrakeLevel(ManualBrakePosNo); + hauled.SpringBrake.Activate = false; + train.run(180.0); + // charged and released: nothing holds it yet + CHECK(hauled.BrakePress < 0.1); + CHECK(hauled.Fb < 1.0); + train.run(1020.0); // 20 minutes since the start + CHECK(hauled.ScndPipePress < hauled.SpringBrake.MinForcePressure); + if (pullee) { + CHECK(hauled.Fb < 1.0); + } + else { + CHECK(hauled.Fb > 5000.0); + } + } +} + +TEST_CASE("pullee: a vehicle prepared for hauling brakes and releases with the train, and its spring brake stays off after") { + // the distributor stays on the brake pipe. with air in the feed pipe and without: the cylinders fill from the + // auxiliary reservoir, and the spring brake, with no air to hold it off, still gives nothing after the release + for (auto const *path : {"vectron_v1/wariant_7w", "e6act_v2/e6acta", "ep09_v2/104e", "e186_v2/eu47"}) { + for (auto const feedair : {true, false}) { + CAPTURE(path); + CAPTURE(feedair); + test::reseed_random(); + hauled_train train{definition::fiz(path), 60.0, true}; + auto const &hauled{train.hauled.mover()}; + if (false == feedair) { + drain_feed_air(train.hauled.mover()); + } + train.run(30.0); + CHECK(hauled.BrakePress < 0.1); + // a full service application + train.locomotive.hold_brake_pipe(3.5); + train.run(20.0); + CHECK(hauled.BrakePress > 2.0); + CHECK(hauled.Fb > 30000.0); + train.locomotive.hold_brake_pipe(5.0); + train.run(90.0); + CHECK(hauled.BrakePress < 0.1); + CHECK(hauled.Fb < 1.0); + CHECK(hauled.EmergencyValveFlow == 0.0); + } + } +} + +TEST_CASE("pullee: the spring brake of an Impuls prepared for hauling doesn't call the emergency brake") { + // SpringBrakeDriveEmergencyVel=2: above 2 km/h an applied spring brake vents the brake pipe. the emergency + // brake of the inactive cab (InactiveCabFlag) is taken out of the definition, so that it's the spring brake's + auto const impuls{definition::fiz("impuls_v1/31we-a_pr").set("Cntrl", "InactiveCabFlag", 0)}; + for (auto const pullee : {false, true}) { + CAPTURE(pullee); + test::reseed_random(); + hauled_train train{impuls, 60.0, pullee}; + auto const &hauled{train.hauled.mover()}; + REQUIRE(hauled.InactiveCabFlag == 0); + REQUIRE(hauled.SpringBrakeDriveEmergencyVel == doctest::Approx(2.0)); + drain_feed_air(train.hauled.mover()); + train.run(10.0); + REQUIRE(hauled.Vel > 2.0); + REQUIRE(hauled.SpringBrake.IsActive); + if (pullee) { + CHECK(hauled.EmergencyValveFlow == 0.0); + CHECK(hauled.BrakePress < 0.1); + } + else { + CHECK(hauled.EmergencyValveFlow > 0.0); + } + } +} + +TEST_CASE("pullee: the brake valves in the cab of a vehicle prepared for hauling move no air") { + // with somebody in the cab: nobody is put there by a scenery, but the valves are cut out whoever sits down. + // the Elf has the MHZ_K5P driver's valve, the EU47 the MHZ_6P, the Vectron the MHZ_K8P, the EP09 and the EU07 the FV4a + for (auto const *path : {"elf_v1/21we-a", "e186_v2/eu47", "vectron_v1/wariant_7w", "ep09_v2/104e", "4e_v1/4e"}) { + for (auto const pullee : {false, true}) { + CAPTURE(path); + CAPTURE(pullee); + test::reseed_random(); + vehicle driven{definition::fiz(path), 0.1, "test", 1}; + // the emergency brake of the inactive cab is another matter, see above + driven->InactiveCabFlag = 0; + if (pullee) { + REQUIRE(driven->PulleeModeSwitch(true)); + } + // the local brake a driver keeps a standing vehicle on is let go + driven->DecLocalBrakeLevel(LocalBrakePosNo); + driven.run(20.0); + REQUIRE(driven->BrakePress < 0.1); + auto const charged{driven->PipePress}; + // full service braking with the driver's valve + driven->BrakeLevelSet(driven->Handle->GetPos(bh_FB)); + driven.run(10.0); + if (pullee) { + CHECK(driven->dpMainValve == 0.0); + CHECK(driven->PipePress > charged - 0.1); + CHECK(driven->BrakePress < 0.1); + } + else { + CHECK(driven->PipePress < charged - 0.5); + CHECK(driven->BrakePress > 1.0); + } + // and the emergency position + driven->BrakeLevelSet(driven->Handle->GetPos(bh_EB)); + driven.run(10.0); + if (pullee) { + CHECK(driven->dpMainValve == 0.0); + CHECK(driven->PipePress > charged - 0.1); + } + else { + CHECK(driven->PipePress < 1.0); + } + } + } +} + +TEST_CASE("pullee: the local brake of a vehicle prepared for hauling stays released") { + for (auto const *path : {"vectron_v1/wariant_7w", "4e_v1/4e", "ep09_v2/104e"}) { + for (auto const pullee : {false, true}) { + CAPTURE(path); + CAPTURE(pullee); + test::reseed_random(); + vehicle driven{definition::fiz(path), 0.1, "test", 1}; + driven->InactiveCabFlag = 0; + driven.hold_brake_pipe(5.0); + if (pullee) { + REQUIRE(driven->PulleeModeSwitch(true)); + } + // applied with the lever, as on a vehicle left on standby, and asked for by the brake computer of a unit + // (what the MED of TDynamicObject writes; the lever of a Vectron does nothing without it) + driven->IncLocalBrakeLevel(LocalBrakePosNo); + driven->LocalBrakePosAEIM = 1.0; + driven.run(20.0); + if (pullee) { + CHECK(driven->BrakePress < 0.1); + } + else { + CHECK(driven->BrakePress > 1.0); + } + } + } +} + +TEST_CASE("pullee: entering the mode lets go of the hand brake and the spring brake switch, and switches the battery off") { + SUBCASE("a locomotive standing braked, its spring brake switched on") { + vehicle vectron{definition::fiz("vectron_v1/wariant_7w")}; + REQUIRE(vectron->SpringBrake.Activate); + REQUIRE_FALSE(vectron->PulleeMode); + CHECK(vectron->PulleeModeSwitch(true)); + CHECK(vectron->PulleeMode); + CHECK_FALSE(vectron->SpringBrake.Activate); + // already in it + CHECK_FALSE(vectron->PulleeModeSwitch(true)); + } + SUBCASE("a unit standing with its hand brake on") { + vehicle en57{definition::fiz("en57_v1/5bgb")}; + REQUIRE(en57->ManualBrakePos > 0); + CHECK(en57->PulleeModeSwitch(true)); + CHECK(en57->ManualBrakePos == 0); + } + SUBCASE("a locomotive ready to depart, its battery on") { + vehicle vectron{definition::fiz("vectron_v1/wariant_7w"), 0.1}; + REQUIRE(vectron->Battery); + CHECK(vectron->PulleeModeSwitch(true)); + CHECK_FALSE(vectron->Battery); + } +} + +TEST_CASE("pullee: the battery and the cabs of a vehicle prepared for hauling stay off, until it leaves the mode") { + vehicle vectron{definition::fiz("vectron_v1/wariant_7w"), 0.0, "test", 1}; + REQUIRE(vectron->PulleeModeSwitch(true)); + CHECK_FALSE(vectron->BatterySwitch(true)); + CHECK_FALSE(vectron->Battery); + CHECK_FALSE(vectron->CabActivisation()); + CHECK_FALSE(vectron->CabActivisation(true)); + CHECK(vectron->CabActive == 0); + vectron.run(5.0); + // the vigilance device and the cab signalling of a cab never activated stay out of it + CHECK_FALSE(vectron->SecuritySystem.is_braking()); + CHECK(vectron->EmergencyValveFlow == 0.0); + + REQUIRE(vectron->PulleeModeSwitch(false)); + CHECK_FALSE(vectron->PulleeMode); + CHECK(vectron->BatterySwitch(true)); + CHECK(vectron->Battery); + CHECK(vectron->CabActivisation()); + CHECK(vectron->CabActive == 1); + // a vehicle driven from isn't one to haul + CHECK_FALSE(vectron->PulleeModeSwitch(true)); + CHECK_FALSE(vectron->PulleeMode); +} + +TEST_CASE("pullee: a cab activated on a dead battery calls the emergency brake, which the mode keeps from happening") { + // the vigilance device of an activated cab brakes when it has no power + for (auto const pullee : {false, true}) { + CAPTURE(pullee); + test::reseed_random(); + vehicle vectron{definition::fiz("vectron_v1/wariant_7w"), 0.0, "test", 1}; + vectron->InactiveCabFlag = 0; + if (pullee) { + REQUIRE(vectron->PulleeModeSwitch(true)); + } + CHECK(vectron->CabActivisation() == (false == pullee)); + vectron.run(0.5); + CHECK(vectron->SecuritySystem.is_braking() == (false == pullee)); + CHECK((vectron->EmergencyValveFlow > 0.0) == (false == pullee)); + } +} + +TEST_CASE("pullee: the battery and cab commands of the train's driver pass a vehicle prepared for hauling by") { + // coupled with the control cable too, which a hauled vehicle normally isn't + for (auto const pullee : {false, true}) { + CAPTURE(pullee); + test::reseed_random(); + test::consist train; + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 1)}; + auto &hauled{train.add(definition::fiz("4e_v1/4e"))}; + auto &last{train.add(definition::fiz("4e_v1/4e"))}; + if (pullee) { + REQUIRE(hauled->PulleeModeSwitch(true)); + } + REQUIRE_FALSE(hauled->Battery); + locomotive->BatterySwitch(true); + locomotive->CabActivisation(); + train.run(2.0); + CHECK(hauled->Battery == (false == pullee)); + CHECK(hauled->CabActive == (pullee ? 0 : 1)); + // the vehicle behind it gets them either way + CHECK(last->Battery); + CHECK(last->CabActive == 1); + } +} + +TEST_CASE("pullee: every real vehicle prepared for hauling runs free behind a locomotive, with no air of its own") { + for (auto const &path : test::real_vehicles()) { + CAPTURE(path); + test::reseed_random(); + if (false == can_be_hauled(path)) { + continue; + } + test::reseed_random(); + hauled_train train{definition::fiz(path), 60.0, true}; + auto const &hauled{train.hauled.mover()}; + drain_feed_air(train.hauled.mover()); + train.run(60.0); + CHECK(hauled.EmergencyValveFlow == 0.0); + CHECK(hauled.BrakePress < 0.1); + CHECK(hauled.Fb < 1.0); + CHECK(train.locomotive->PipePress > 4.99); + CHECK(train.hauled.speed() > 40.0); + } +} + +TEST_CASE("pullee: every real vehicle standing braked releases once prepared for hauling and charged") { + for (auto const &path : test::real_vehicles()) { + CAPTURE(path); + test::reseed_random(); + if (false == can_be_hauled(path)) { + continue; + } + test::reseed_random(); + // hand brakes on, spring brakes switched on, cylinders half full, the pipe at 3.5 + hauled_train train{definition::fiz(path), 0.0, true}; + auto const &hauled{train.hauled.mover()}; + CHECK(hauled.ManualBrakePos == 0); + CHECK_FALSE(hauled.SpringBrake.Activate); + CHECK_FALSE(hauled.Battery); + train.run(180.0); + CHECK(hauled.EmergencyValveFlow == 0.0); + CHECK(hauled.BrakePress < 0.1); + // the cylinders of a few are still letting out the last of their air (6Dg, SM42, 810: 15-72 N) + CHECK(hauled.Fb < 500.0); + } +} diff --git a/tests/unit/test_region_file.cpp b/tests/unit/test_region_file.cpp new file mode 100644 index 000000000..346823ae3 --- /dev/null +++ b/tests/unit/test_region_file.cpp @@ -0,0 +1,207 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scratch.h" +#include "scene/regionfile.h" +#include "scene/sn_utils.h" + +#include +#include +#include +#include + +// the region file (.sbt), the static geometry of a scenery the game caches beside it: a file cut short or +// damaged is turned down before any of it is used, and the game writes it so that it is never left cut short + +namespace { + +std::uint32_t constexpr header{0x37305545}; // EU07 +std::uint32_t constexpr version{0x32544253}; // SBT2 +std::uint32_t constexpr sectionlimit{500 * 500}; + +struct section { + std::uint32_t index; + std::string data; +}; + +// the file as basic_region::serialize() lays it out: the section size covers the index, the size and the data +std::string region(std::vector
const &Sections, std::uint32_t const Header = header, std::uint32_t const Version = version) { + std::ostringstream output; + sn_utils::ls_uint32(output, Header); + sn_utils::ls_uint32(output, Version); + sn_utils::ls_uint32(output, static_cast(Sections.size())); + for (auto const §ion : Sections) { + sn_utils::ls_uint32(output, section.index); + sn_utils::ls_uint32(output, static_cast(scene::region_file::section_header_size + section.data.size())); + output << section.data; + } + return output.str(); +} + +std::string check(std::string const &File) { + std::istringstream input{File}; + return scene::region_file::check_layout(input, header, version, sectionlimit); +} + +// what a writer throws when it gives up +class writer_failure : public std::runtime_error { + public: + using std::runtime_error::runtime_error; +}; + +std::string read(std::filesystem::path const &Path) { + std::ifstream input{Path, std::ios::binary}; + return {std::istreambuf_iterator{input}, std::istreambuf_iterator{}}; +} + +} // namespace + +TEST_CASE("region file: a file laid out whole is accepted, with no sections or with many") { + CHECK(check(region({})) == ""); + CHECK(check(region({{0, ""}, {7, std::string(100, 'x')}, {sectionlimit - 1, std::string(3, '\0')}})) == ""); +} + +TEST_CASE("region file: a file cut short anywhere is turned down") { + auto const file{region({{12, std::string(40, 'a')}, {13, std::string(7, 'b')}, {250, std::string(64, 'c')}})}; + REQUIRE(check(file) == ""); + for (std::size_t length{0}; length < file.size(); ++length) { + CAPTURE(length); + CHECK(check(file.substr(0, length)) != ""); + } + // the count of the sections is checked against those present, and the length against where the last one ends + CHECK(check(file.substr(0, file.size() - 64 - 8)).find("ends after 2 of its 3 sections") != std::string::npos); + CHECK(check(file.substr(0, file.size() / 2)).find("ends inside section") != std::string::npos); +} + +TEST_CASE("region file: a file of another type or version is turned down") { + CHECK(check(region({{1, "x"}}, header, version + 1)).find("unrecognized type or version") != std::string::npos); + CHECK(check(region({{1, "x"}}, header + 1, version)).find("unrecognized type or version") != std::string::npos); + CHECK(check("EU0").find("unrecognized type or version") != std::string::npos); +} + +TEST_CASE("region file: sections the region can't hold, held twice, or of impossible sizes are turned down") { + CHECK(check(region({{sectionlimit, "x"}})).find("out of the 250000") != std::string::npos); + CHECK(check(region({{0xffffffffu, "x"}})).find("out of the 250000") != std::string::npos); + CHECK(check(region({{5, "x"}, {5, "y"}})).find("more than once") != std::string::npos); + + // a size smaller than the header of the section + auto file{region({{5, "abcd"}})}; + file[16] = 7; + file[17] = 0; + file[18] = 0; + file[19] = 0; + CHECK(check(file).find("less than its header takes") != std::string::npos); + // a size reaching past the end of the file + file[16] = 13; + CHECK(check(file).find("ends inside section 5") != std::string::npos); + // a size falling short of it + file[16] = 11; + CHECK(check(file).find("bytes past its last section") != std::string::npos); + // more sections than a region has + auto many{region({})}; + for (std::size_t byte{8}; byte < 12; ++byte) { + many[byte] = static_cast(0xff); + } + CHECK(check(many).find("more than the 250000") != std::string::npos); +} + +TEST_CASE("region file: the header of a section is read and checked") { + std::uint32_t index{0}; + std::uint32_t size{0}; + { + std::istringstream input{region({{42, "abc"}}).substr(12)}; + CHECK(scene::region_file::read_section_header(input, sectionlimit, index, size) == ""); + CHECK(index == 42); + CHECK(size == 11); + } + { + std::istringstream input{region({{42, "abc"}}).substr(12, 6)}; + CHECK(scene::region_file::read_section_header(input, sectionlimit, index, size).find("ends inside a section header") != std::string::npos); + } + { + std::istringstream input{region({{42, "abc"}}).substr(12)}; + CHECK(scene::region_file::read_section_header(input, 42, index, size).find("out of the 42") != std::string::npos); + } +} + +TEST_CASE("region file: a string cut short by the end of the data ends there, rather than being read on forever") { + std::istringstream input{std::string{"abc"}}; + CHECK(sn_utils::d_str(input) == "abc"); + CHECK(input.fail()); + CHECK(sn_utils::d_str(input) == ""); + + std::istringstream whole{std::string{"abc\0def", 7}}; + CHECK(sn_utils::d_str(whole) == "abc"); + CHECK(whole.good()); +} + +TEST_CASE("region file: the bytes left in the data are known, so a count it can't hold is turned down before anything is made for it") { + std::istringstream input{std::string(100, 'x')}; + CHECK(sn_utils::remaining(input) == 100); + sn_utils::ld_uint32(input); + CHECK(sn_utils::remaining(input) == 96); + // asking doesn't move the reading on + CHECK(sn_utils::ld_uint32(input) == 0x78787878); + input.seekg(0, std::ios::end); + CHECK(sn_utils::remaining(input) == 0); + sn_utils::ld_uint32(input); + CHECK(input.fail()); + CHECK(sn_utils::remaining(input) == 0); +} + +TEST_CASE("region file: the file is written through a temporary one, which replaces the previous file when complete") { + test::scratch_folder folder{"region_file"}; + auto const file{folder.root() / "scenery.sbt"}; + auto const temporary{folder.root() / "scenery.sbt.tmp"}; + auto const write = [&file](std::string const &Content) { + return scene::region_file::write_through_temporary(file.string(), [&Content](std::ostream &Output) { Output << Content; }); + }; + + SUBCASE("a new file") { + CHECK(write("first") == ""); + CHECK(read(file) == "first"); + CHECK_FALSE(std::filesystem::exists(temporary)); + } + SUBCASE("a previous file is replaced, a longer one entirely") { + REQUIRE(write("a much longer first version") == ""); + CHECK(write("second") == ""); + CHECK(read(file) == "second"); + CHECK_FALSE(std::filesystem::exists(temporary)); + } + SUBCASE("a temporary file left by a write cut short earlier is written over") { + folder.write("scenery.sbt.tmp", "left over from a crash, longer than what follows"); + CHECK(write("third") == ""); + CHECK(read(file) == "third"); + CHECK_FALSE(std::filesystem::exists(temporary)); + } +} + +TEST_CASE("region file: a write which fails leaves the previous file, or none, and no temporary file") { + test::scratch_folder folder{"region_file_failed"}; + auto const file{folder.root() / "scenery.sbt"}; + auto const temporary{folder.root() / "scenery.sbt.tmp"}; + folder.write("scenery.sbt", "previous"); + + SUBCASE("the writer gives up half way") { + auto const error{scene::region_file::write_through_temporary(file.string(), [](std::ostream &Output) { + Output << "half of the"; + throw writer_failure("out of memory"); + })}; + CHECK(error.find("out of memory") != std::string::npos); + } + SUBCASE("the stream fails") { + auto const error{scene::region_file::write_through_temporary(file.string(), [](std::ostream &Output) { + Output << "half of the"; + Output.setstate(std::ios::badbit); + })}; + CHECK(error.find("can't write to file") != std::string::npos); + } + CHECK(read(file) == "previous"); + CHECK_FALSE(std::filesystem::exists(temporary)); + + SUBCASE("the temporary file can't be made") { + auto const missing{folder.root() / "no such folder" / "scenery.sbt"}; + auto const error{scene::region_file::write_through_temporary(missing.string(), [](std::ostream &Output) { Output << "x"; })}; + CHECK(error.find("can't write to file") != std::string::npos); + CHECK_FALSE(std::filesystem::exists(missing)); + } +} diff --git a/tests/unit/test_ring_room.cpp b/tests/unit/test_ring_room.cpp new file mode 100644 index 000000000..835072f75 --- /dev/null +++ b/tests/unit/test_ring_room.cpp @@ -0,0 +1,143 @@ +#include "stdafx.h" +#include "doctest.h" +#include "editor/editorRingRoom.hpp" + +#include + +// the room a road leaving the side of a roundabout takes of the ring (eu07/maszyna GH#349): with the ring's bend +// counted, as many roads fit on a small roundabout as there's room for between their edges +namespace { + +double constexpr pi{3.14159265358979323846}; +// as the road editor has them: a junction takes the road it's made on past where the edges meet by the corner room, +// and between two junctions there's at least the shortest road left +double constexpr kCornerRoom{4.0}; +double constexpr kShortestRoad{2.0}; +// the roads the editor builds unless told otherwise: a lane each way, 3.5 m each, and a roundabout of a single lane +double constexpr kRoadHalfwidth{3.5}; +double constexpr kRingHalfwidth{1.75}; + +glm::dvec2 at(double const Radius, double const Angle) { return glm::dvec2{std::cos(Angle), std::sin(Angle)} * Radius; } +glm::dvec2 ahead(double const Angle) { return {-std::sin(Angle), std::cos(Angle)}; } + +// room of a road leaving the ring of the radius at the angle, turned from the way straight out by the slant (to the way ahead) +double room(double const Radius, double const Slant, bool const Ahead, double const Halfwidth = kRingHalfwidth, double const Branchhalfwidth = kRoadHalfwidth) { + double const angle{0.3}; + auto const outwards{at(1.0, angle)}; + auto const direction{outwards * std::cos(Slant) + ahead(angle) * std::sin(Slant)}; + return editor_ring::edge_room(glm::dvec2{0.0}, Radius, at(Radius, angle), direction, Ahead ? ahead(angle) : -ahead(angle), Halfwidth, Branchhalfwidth); +} + +// where the edges of two straight roads meet, measured along the first one, as the editor has it for a road leaving a straight road. +// Lean: the second one leans towards the side measured (the angle between them there is the acute one) +double straight_reach(double const Halfwidth, double const Branchhalfwidth, double const Angle, bool const Lean) { + return (Branchhalfwidth + (Lean ? 1.0 : -1.0) * Halfwidth * std::cos(Angle)) / std::sin(Angle); +} + +// whether the roads leaving straight out, evenly all around the ring, each get a junction: the junctions with what's left between them. +// Bend: the room measured on the ring, rather than as on a straight road; Shortest: the shortest piece left between two junctions. +// Arcs: a junction next to the end of an arc of the ring takes the rest of the arc when less than the shortest piece would be left +// of it, so in the worst case it grows by as much +bool fit(double const Radius, int const Roads, bool const Bend, double const Shortest, bool const Arcs) { + auto const side{Bend ? room(Radius, 0.0, true) : straight_reach(kRingHalfwidth, kRoadHalfwidth, pi / 2.0, true)}; + auto const junction{2.0 * (side + kCornerRoom)}; + return Roads * (junction + Shortest + (Arcs ? Shortest : 0.0)) <= 2.0 * pi * Radius; +} +bool fit(double const Radius, int const Roads, bool const Bend) { return fit(Radius, Roads, Bend, kShortestRoad, false); } +// as the editor has it now, wherever the roads join the ring +bool fits(double const Radius, int const Roads) { return fit(Radius, Roads, true, editor_ring::shortest_piece, true); } + +} // namespace + +TEST_CASE("ring room: on a very large ring the room is the one of a straight road") { + for (double const slant : {0.0, pi / 12.0, pi / 6.0, pi / 4.0, pi / 3.0}) { + CAPTURE(slant); + double const angle{pi / 2.0 - slant}; + CHECK(room(1.0e6, slant, true) == doctest::Approx(straight_reach(kRingHalfwidth, kRoadHalfwidth, angle, true)).epsilon(1e-4)); + CHECK(room(1.0e6, slant, false) == doctest::Approx(straight_reach(kRingHalfwidth, kRoadHalfwidth, angle, false)).epsilon(1e-4)); + } +} + +TEST_CASE("ring room: a road leaving straight out meets the outer edge where the circle reaches its edge") { + for (double const radius : {8.0, 15.0, 40.0}) { + CAPTURE(radius); + double const expected{radius * std::asin(kRoadHalfwidth / (radius + kRingHalfwidth))}; + CHECK(room(radius, 0.0, true) == doctest::Approx(expected)); + CHECK(room(radius, 0.0, false) == doctest::Approx(expected)); + // never more than on a straight road + CHECK(room(radius, 0.0, true) < kRoadHalfwidth); + } +} + +TEST_CASE("ring room: a slanted road takes less on the side it leans away from") { + for (double const radius : {8.0, 15.0, 50.0}) { + for (double const slant : {pi / 6.0, pi / 4.0}) { + CAPTURE(radius); + CAPTURE(slant); + auto const towards{room(radius, slant, true)}; + auto const away{room(radius, slant, false)}; + CHECK(away >= 0.0); + CHECK(away < towards); + // the editor took the room of the acute corner on both sides + CHECK(towards < straight_reach(kRingHalfwidth, kRoadHalfwidth, pi / 2.0 - slant, true)); + } + } + // on a straight road the obtuse corner takes less than the acute one too + CHECK(room(1.0e6, pi / 4.0, false) < room(1.0e6, pi / 4.0, true)); + // leaving the smallest ring as sharply as the editor allows, 30 degrees off it, the edge on the side the road leans away from + // is outside the ring all along: there's no point to measure to, and the editor keeps the room it took before + CHECK(room(8.0, pi / 3.0, false) < 0.0); + CHECK(room(8.0, pi / 3.0, true) > 0.0); + CHECK(room(15.0, pi / 3.0, false) >= 0.0); +} + +TEST_CASE("ring room: none for a road going inwards") { + CHECK(room(15.0, pi * 0.75, true) < 0.0); + CHECK(room(15.0, pi, true) < 0.0); + CHECK(editor_ring::edge_room(glm::dvec2{0.0}, 0.0, glm::dvec2{1.0, 0.0}, glm::dvec2{1.0, 0.0}, glm::dvec2{0.0, 1.0}, 1.0, 1.0) < 0.0); +} + +TEST_CASE("ring room: a road wider than the ring is round still meets its edge, sooner than on a straight road") { + // two lanes each way on the smallest roundabout: the edge of the road starts outside the ring + double const halfwidth{7.0}; + double const radius{8.0}; + double const expected{radius * std::atan2(halfwidth, std::sqrt((radius + kRingHalfwidth) * (radius + kRingHalfwidth) - halfwidth * halfwidth))}; + CHECK(room(radius, 0.0, true, kRingHalfwidth, halfwidth) == doctest::Approx(expected)); + CHECK(room(radius, 0.0, true, kRingHalfwidth, halfwidth) < halfwidth); +} + +TEST_CASE("ring room: roads joined to roundabouts of the radii the editor allows") { + // the smallest roundabout took two roads; three were too many for it + CHECK(fit(8.0, 2, false)); + CHECK_FALSE(fit(8.0, 3, false)); + CHECK(fit(8.0, 3, true)); + // four roads from 11 m + CHECK(fit(11.0, 4, true)); + CHECK(fit(15.0, 4, true)); + // six from 16 m, where they took 17 m before + CHECK_FALSE(fit(16.0, 6, false)); + CHECK(fit(16.0, 6, true)); + CHECK(fit(25.0, 6, true)); + // and more on the large ones + CHECK(fit(50.0, 8, true)); + CHECK(fit(200.0, 30, true)); +} + +TEST_CASE("ring room: a short piece of the ring is left between junctions, so small roundabouts take three or four roads") { + // the ring goes on past a piece of it, which can be much shorter than a road of its own + CHECK(editor_ring::shortest_piece < kShortestRoad); + CHECK(editor_ring::shortest_piece > 0.25); // further apart than ends taken for joined + // with the shortest road left between them, and a junction growing by as much next to the end of an arc, three roads + // didn't always fit on the smallest roundabout, nor four on one of 10 m + CHECK_FALSE(fit(8.0, 3, true, kShortestRoad, true)); + CHECK_FALSE(fit(10.0, 4, true, kShortestRoad, false)); + // they do now, wherever they join the ring + CHECK(fits(8.0, 3)); + CHECK(fits(10.0, 4)); + CHECK(fits(9.6, 4)); + // four on the smallest one would take smaller corners + CHECK_FALSE(fits(8.0, 4)); + // and the larger ones take more + CHECK(fits(15.0, 6)); + CHECK(fits(25.0, 8)); +} diff --git a/tests/unit/test_road_escape.cpp b/tests/unit/test_road_escape.cpp new file mode 100644 index 000000000..31fbc1a21 --- /dev/null +++ b/tests/unit/test_road_escape.cpp @@ -0,0 +1,44 @@ +// Esc in the road window (GH#348): the first one gives up what is going on, the next one goes back to the selection + +#include "stdafx.h" +#include "doctest.h" +#include "editor/editorRoad.hpp" + +namespace { + +constexpr int select_tool{0}; +constexpr int build_tool{1}; +constexpr int place_tool{2}; + +} // namespace + +TEST_CASE("Esc with the build tool and no road being drawn goes back to the selection") { + CHECK(editor_road::tool_after_escape(build_tool, false, false) == select_tool); +} + +TEST_CASE("Esc while a road is being drawn or led out of a road or a junction keeps the build tool") { + CHECK(editor_road::tool_after_escape(build_tool, true, false) == build_tool); +} + +TEST_CASE("Esc with the place tool goes back to the selection, the tool has nothing being drawn") { + CHECK(editor_road::tool_after_escape(place_tool, false, false) == select_tool); +} + +TEST_CASE("Esc while the selected points are dragged up or down keeps the tool, the drag is given up") { + CHECK(editor_road::tool_after_escape(select_tool, false, true) == select_tool); + CHECK(editor_road::tool_after_escape(build_tool, false, true) == build_tool); +} + +TEST_CASE("Esc with the selection tool stays with it") { + CHECK(editor_road::tool_after_escape(select_tool, false, false) == select_tool); +} + +TEST_CASE("two Esc presses from the build tool in the middle of a road: the road given up, then the selection") { + auto tool{build_tool}; + bool drawing{true}; + tool = editor_road::tool_after_escape(tool, drawing, false); + drawing = false; // what the first Esc gives up + CHECK(tool == build_tool); + tool = editor_road::tool_after_escape(tool, drawing, false); + CHECK(tool == select_tool); +} diff --git a/tests/unit/test_road_surface_type.cpp b/tests/unit/test_road_surface_type.cpp new file mode 100644 index 000000000..dfe7e14a1 --- /dev/null +++ b/tests/unit/test_road_surface_type.cpp @@ -0,0 +1,161 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "editor/editorRoadLimits.hpp" +#include "utilities/parser.h" + +#include +#include + +// the type of a road's surface (eu07/maszyna GH#347): a dirt road, a track between fields, can be laid out tighter than +// a paved one; the type is saved with the road, and the roads made before the types load and save as they did + +namespace { + +// what the scenery entry of a road says about its surface, read the way road_node::import_from() reads it: +// a road which doesn't say what it's made of is paved +struct surface_read +{ + std::string material{"asphaltdark1"}; + road_surface_type type{road_surface_type::paved}; + float texturelength{4.f}; + bool bad{false}; // an unknown type was named + std::string next; // the token which follows the read properties +}; + +surface_read read(std::string const &Entry) { + surface_read result; + cParser parser(Entry, cParser::buffer_TEXT); + auto token{parser.getToken()}; + while (false == token.empty() && token != "endroad") { + if (token == "surface") { + result.material = parser.getToken(); + } + else if (token == "surfacetype") { + if (false == road_surface::from_name(parser.getToken(), result.type)) + result.bad = true; + } + else if (token == "texlength") { + parser.getTokens(); + parser >> result.texturelength; + } + else { + result.next = token; + break; + } + token = parser.getToken(); + } + return result; +} + +// the appearance part of the scenery entry, written the way road_node::export_as_text_() writes it +std::string write(std::string const &Material, road_surface_type const Type, float const Texturelength) { + std::ostringstream output; + output << "surface " << Material << ' ' << "texlength " << Texturelength << ' '; + output << road_surface::entry(Type); + output << "side left shoulder 1.5 grass "; + return output.str(); +} + +} // namespace + +TEST_CASE("road surface type: a paved road keeps the limits every road had before the types") { + // the values editorRoad.cpp had as kTightestRadius, kShortestRoad, kSharpestBranch and in editor_road::plan() + auto const paved{road_limits_for(road_surface_type::paved)}; + CHECK(paved.tightest_radius == doctest::Approx(6.0)); + CHECK(paved.shortest_road == doctest::Approx(2.0)); + CHECK(paved.sharpest_branch == doctest::Approx(glm::radians(30.0))); + CHECK(paved.tied_lead == doctest::Approx(0.1)); + CHECK(paved.widest_turn == doctest::Approx(glm::radians(170.0))); +} + +TEST_CASE("road surface type: a dirt road is laid out more freely in every respect") { + auto const paved{road_limits_for(road_surface_type::paved)}; + auto const dirt{road_limits_for(road_surface_type::dirt)}; + // a bend a tractor makes on a single lane track + CHECK(dirt.tightest_radius < paved.tightest_radius); + CHECK(dirt.tightest_radius > 0.0); + CHECK(dirt.shortest_road < paved.shortest_road); + CHECK(dirt.shortest_road > 0.0); + CHECK(dirt.sharpest_branch < paved.sharpest_branch); + CHECK(dirt.sharpest_branch > 0.0); + // an end may lead off square to the way to the other end, but not away from it + CHECK(dirt.tied_lead < paved.tied_lead); + CHECK(dirt.tied_lead >= 0.0); + // a hairpin: the arc may turn past a half circle + CHECK(dirt.widest_turn > glm::radians(180.0)); + CHECK(dirt.widest_turn < glm::radians(360.0)); +} + +TEST_CASE("road surface type: no bend is tighter than the road is wide") { + auto const paved{road_limits_for(road_surface_type::paved)}; + auto const dirt{road_limits_for(road_surface_type::dirt)}; + // a single 3 m lane: the limit of the type + CHECK(editor_road_limits::tightest_bend(dirt, 1.5) == doctest::Approx(dirt.tightest_radius)); + // the layout the tool starts with, a 3.5 m lane each way: the inner edge 3.5 m from the axis keeps its room from the centre + CHECK(editor_road_limits::tightest_bend(dirt, 3.5) == doctest::Approx(3.5 + editor_road_limits::inner_edge_room)); + CHECK(editor_road_limits::tightest_bend(dirt, 3.5) > dirt.tightest_radius); + // a paved road of that layout keeps the limit it had + CHECK(editor_road_limits::tightest_bend(paved, 3.5) == doctest::Approx(paved.tightest_radius)); + // and a wide one is held to its width + CHECK(editor_road_limits::tightest_bend(paved, 7.0) == doctest::Approx(7.0 + editor_road_limits::inner_edge_room)); +} + +TEST_CASE("road surface type: the types go by their scenery names") { + for (auto const type : {road_surface_type::paved, road_surface_type::dirt}) { + CAPTURE(road_surface::name(type)); + road_surface_type read{type == road_surface_type::paved ? road_surface_type::dirt : road_surface_type::paved}; + CHECK(road_surface::from_name(road_surface::name(type), read)); + CHECK(read == type); + } + CHECK(std::string{road_surface::name(road_surface_type::paved)} == "paved"); + CHECK(std::string{road_surface::name(road_surface_type::dirt)} == "dirt"); + // an unknown name changes nothing + road_surface_type type{road_surface_type::dirt}; + CHECK_FALSE(road_surface::from_name("gravel", type)); + CHECK(type == road_surface_type::dirt); + CHECK_FALSE(road_surface::from_name("", type)); + CHECK(type == road_surface_type::dirt); +} + +TEST_CASE("road surface type: a paved road is saved as the roads were before the types") { + CHECK(road_surface::entry(road_surface_type::paved).empty()); + CHECK(write("asphaltdark1", road_surface_type::paved, 4.f) == "surface asphaltdark1 texlength 4 side left shoulder 1.5 grass "); + // and an entry of a road made before the types reads paved, with what follows read as before + auto const old{read("surface asphalt2 texlength 6 side left shoulder 1.5 grass endroad")}; + CHECK(old.type == road_surface_type::paved); + CHECK(old.material == "asphalt2"); + CHECK(old.texturelength == doctest::Approx(6.f)); + CHECK(old.next == "side"); + CHECK_FALSE(old.bad); +} + +TEST_CASE("road surface type: a dirt road is saved with its type and read back") { + auto const text{write(road_surface::default_material(road_surface_type::dirt), road_surface_type::dirt, 5.f)}; + CHECK(text == "surface droga_polna texlength 5 surfacetype dirt side left shoulder 1.5 grass "); + auto const back{read(text)}; + CHECK(back.type == road_surface_type::dirt); + CHECK(back.material == "droga_polna"); + CHECK(back.texturelength == doctest::Approx(5.f)); + CHECK(back.next == "side"); + CHECK_FALSE(back.bad); + // and written again it's the same + CHECK(write(back.material, back.type, back.texturelength) == text); + // the type is read wherever it stands among the properties, and an explicit paved reads as the default + CHECK(read("surfacetype dirt surface droga_polna endroad").type == road_surface_type::dirt); + CHECK(read("surface asphaltdark1 surfacetype paved endroad").type == road_surface_type::paved); +} + +TEST_CASE("road surface type: an unknown type leaves the road paved") { + auto const back{read("surface asphaltdark1 surfacetype cobbles texlength 4 side")}; + CHECK(back.bad); + CHECK(back.type == road_surface_type::paved); + // the unknown name is taken as the value of the type, not as the next property + CHECK(back.texturelength == doctest::Approx(4.f)); + CHECK(back.next == "side"); +} + +TEST_CASE("road surface type: a road made dirt or paved gets the surface of the type") { + CHECK(std::string{road_surface::default_material(road_surface_type::paved)} == "asphaltdark1"); + CHECK(std::string{road_surface::default_material(road_surface_type::dirt)} == "droga_polna"); +} diff --git a/tests/unit/test_script_screen_drawing.cpp b/tests/unit/test_script_screen_drawing.cpp index ff822b02d..a68857ebe 100644 --- a/tests/unit/test_script_screen_drawing.cpp +++ b/tests/unit/test_script_screen_drawing.cpp @@ -5,6 +5,7 @@ #include #include +#include #include // the drawing the Lua screens get from the game: fonts read as scripts/led_util.py reads them, text and images @@ -85,6 +86,44 @@ TEST_CASE("script screen drawing: a description without glyphs, or one wider tha CHECK_FALSE(font->find(U'w').lit(4, 0)); } +TEST_CASE("script screen drawing: a glyph wider than the largest image is skipped") { + auto const pixels{image(2, 1, {})}; + auto const font{bitmap_font::parse(pixels, 2, 1, "//\nw5000\nv1\nx2147483647\n")}; + REQUIRE(font.has_value()); + // not in the font: the fallback, its first glyph + CHECK(font->find(U'w').width() == 1); + CHECK(font->find(U'x').width() == 1); + CHECK(font->find(U'v').width() == 1); + // the largest one is taken + auto const widest{bitmap_font::parse(pixels, 2, 1, "//\nw4096\n")}; + REQUIRE(widest.has_value()); + CHECK(widest->find(U'w').width() == 4096); +} + +TEST_CASE("script screen drawing: a font of too many glyphs, too many columns or too large an image is refused") { + auto const pixels{image(2, 1, {})}; + // more glyphs than any font has + std::string many{"//\n"}; + for (char32_t character = 0x100; character < 0x100 + 5000; ++character) { + // the character in UTF-8 (two bytes up to 0x7FF, three above), then its width + if (character < 0x800) { + many += static_cast(0xC0 | (character >> 6)); + } + else { + many += static_cast(0xE0 | (character >> 12)); + many += static_cast(0x80 | ((character >> 6) & 0x3F)); + } + many += static_cast(0x80 | (character & 0x3F)); + many += "0\n"; + } + CHECK_FALSE(bitmap_font::parse(pixels, 2, 1, many).has_value()); + // glyphs side by side much wider than the largest image + CHECK_FALSE(bitmap_font::parse(pixels, 2, 1, "//\na4000\nb4000\nc4000\n").has_value()); + // an image taller than the largest one + std::vector const tall(static_cast(1) * 5000 * 4, 255); + CHECK_FALSE(bitmap_font::parse(tall, 1, 5000, "//\na1\n").has_value()); +} + TEST_CASE("script screen drawing: text is drawn from x rightwards and returns where it ends") { auto const pixels{image(4, 1, {{0, 0}, {1, 0}, {3, 0}})}; auto const font{bitmap_font::parse(pixels, 4, 1, "//\na2\nb1\n")}; diff --git a/tests/unit/test_script_screen_host.cpp b/tests/unit/test_script_screen_host.cpp index 355b9b9e8..519e928de 100644 --- a/tests/unit/test_script_screen_host.cpp +++ b/tests/unit/test_script_screen_host.cpp @@ -2,23 +2,27 @@ #include "doctest.h" // the script screen host (scripting/scriptscreens.cpp) with the real runtimes: a script reads its input, draws an -// image that goes to the screen's texture, bottom row first, and sends a command; a script stuck in a loop is stopped; -// a Lua script can't reach files, the system or precompiled code. the Lua cases need WITH_LUA, the WebAssembly ones -// WITH_WASM +// image that goes to the screen's texture, bottom row first, and sends a command; a script stuck in a loop is stopped, +// even when it catches the error; a Lua script can't reach files, the system, precompiled code or the metatables of the +// api; what a call may send, log, read or make is capped. the Lua cases need WITH_LUA, the WebAssembly ones WITH_WASM #include "scripting/scriptscreens.h" +#include "scripting/scriptscreenprogram.h" #include "input/command.h" #include "interfaces/ITexture.h" #include "utilities/Globals.h" #include "utilities/dictionary.h" +#include #include #include #include #include #include #include +#include #include +#include #include #include #include @@ -142,6 +146,47 @@ void refresh(script_screen_queue &Queue, std::shared_ptr const &S Queue.submit(Screen, std::move(Input), Vehicle); } +// runs frames for a while: long enough for the worker to load and run a screen that was submitted +void run_frames(script_screen_queue &Queue) { + for (int frame = 0; frame < 40; ++frame) { + Queue.update(); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } +} + +// the limits of the sandbox (scripting/scriptscreenprogram.h), as the tests expect them +constexpr std::size_t commands_per_call{64}; +constexpr std::size_t log_lines_per_call{32}; +constexpr std::size_t log_line_length{1024}; +constexpr std::size_t screen_file_size{16 * 1024 * 1024}; + +} // namespace + +// the lines logged while the object lives, kept by the engine stubs (engine_stubs.cpp) +void unit_tests_log_capture(bool Enabled); +std::vector unit_tests_logged_lines(); + +namespace { + +class log_capture { + public: + log_capture() { unit_tests_log_capture(true); } + ~log_capture() { unit_tests_log_capture(false); } + log_capture(log_capture const &) = delete; + log_capture &operator=(log_capture const &) = delete; + + // the lines logged so far with the text in them + std::vector lines_with(std::string_view const Text) const { + std::vector result; + for (auto &line : unit_tests_logged_lines()) { + if (line.find(Text) != std::string::npos) { + result.push_back(std::move(line)); + } + } + return result; + } +}; + } // namespace TEST_CASE("script screens: a language that doesn't run gets no screens") { @@ -202,21 +247,54 @@ constexpr std::array spin_module{ 0x64, 0x65, 0x72, 0x00, 0x02, 0x0a, 0x15, 0x03, 0x04, 0x00, 0x41, 0x02, 0x0b, 0x04, 0x00, 0x41, 0x02, 0x0b, 0x09, 0x00, 0x03, 0x40, 0x0c, 0x00, 0x0b, 0x41, 0x00, 0x0b}; +// "flood": screen_render sends the command "cmdtest" 1000 times (with the parameters (i, 0)), then logs a line of +// 4000 'a' 100 times, and returns 0: +// (import "eu07" "command" (func $command (param i32 i32 i32 i32))) +// (import "eu07" "log" (func $log (param i32 i32))) +// (memory (export "memory") 1) +// (data (i32.const 0) "cmdtest") +// (func (export "screen_width") (result i32) i32.const 2) +// (func (export "screen_height") (result i32) i32.const 2) +// (func (export "screen_render") (result i32) (local $i i32) +// ;; for i in 0..1000: (call $command (i32.const 0) (i32.const 7) (local.get $i) (i32.const 0)) +// ;; for i in 0..4000: (i32.store8 (i32.add (local.get $i) (i32.const 64)) (i32.const 97)) +// ;; for i in 0..100: (call $log (i32.const 64) (i32.const 4000)) +// (i32.const 0)) +constexpr std::array flood_module{ + 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x11, 0x03, 0x60, 0x04, 0x7f, 0x7f, 0x7f, + 0x7f, 0x00, 0x60, 0x02, 0x7f, 0x7f, 0x00, 0x60, 0x00, 0x01, 0x7f, 0x02, 0x1b, 0x02, 0x04, 0x65, + 0x75, 0x30, 0x37, 0x07, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x00, 0x00, 0x04, 0x65, 0x75, + 0x30, 0x37, 0x03, 0x6c, 0x6f, 0x67, 0x00, 0x01, 0x03, 0x04, 0x03, 0x02, 0x02, 0x02, 0x05, 0x03, + 0x01, 0x00, 0x01, 0x07, 0x39, 0x04, 0x06, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x02, 0x00, 0x0c, + 0x73, 0x63, 0x72, 0x65, 0x65, 0x6e, 0x5f, 0x77, 0x69, 0x64, 0x74, 0x68, 0x00, 0x02, 0x0d, 0x73, + 0x63, 0x72, 0x65, 0x65, 0x6e, 0x5f, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x00, 0x03, 0x0d, 0x73, + 0x63, 0x72, 0x65, 0x65, 0x6e, 0x5f, 0x72, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x00, 0x04, 0x0a, 0x81, + 0x01, 0x03, 0x04, 0x00, 0x41, 0x02, 0x0b, 0x04, 0x00, 0x41, 0x02, 0x0b, 0x75, 0x01, 0x01, 0x7f, + 0x41, 0x00, 0x21, 0x00, 0x02, 0x40, 0x03, 0x40, 0x20, 0x00, 0x41, 0xe8, 0x07, 0x4e, 0x0d, 0x01, + 0x41, 0x00, 0x41, 0x07, 0x20, 0x00, 0x41, 0x00, 0x10, 0x00, 0x20, 0x00, 0x41, 0x01, 0x6a, 0x21, + 0x00, 0x0c, 0x00, 0x0b, 0x0b, 0x41, 0x00, 0x21, 0x00, 0x02, 0x40, 0x03, 0x40, 0x20, 0x00, 0x41, + 0xa0, 0x1f, 0x4e, 0x0d, 0x01, 0x20, 0x00, 0x41, 0xc0, 0x00, 0x6a, 0x41, 0xe1, 0x00, 0x3a, 0x00, + 0x00, 0x20, 0x00, 0x41, 0x01, 0x6a, 0x21, 0x00, 0x0c, 0x00, 0x0b, 0x0b, 0x41, 0x00, 0x21, 0x00, + 0x02, 0x40, 0x03, 0x40, 0x20, 0x00, 0x41, 0xe4, 0x00, 0x4e, 0x0d, 0x01, 0x41, 0xc0, 0x00, 0x41, + 0xa0, 0x1f, 0x10, 0x01, 0x20, 0x00, 0x41, 0x01, 0x6a, 0x21, 0x00, 0x0c, 0x00, 0x0b, 0x0b, 0x41, + 0x00, 0x0b, 0x0b, 0x0d, 0x01, 0x00, 0x41, 0x00, 0x0b, 0x07, 0x63, 0x6d, 0x64, 0x74, 0x65, 0x73, + 0x74}; + } // namespace TEST_CASE("wasm screens: a cab screen draws from its input and sends commands to its vehicle") { sent_commands().clear(); script_folder const folder{"wasm_paint"}; - auto const module{folder.write("paint.wasm", paint_module)}; + auto const module_path{folder.write("paint.wasm", paint_module)}; script_screen_queue queue; REQUIRE(queue.init()); REQUIRE(queue.runs(script_language::wasm)); recording_texture texture; - auto const screen{queue.acquire(request(script_language::wasm, module, "cab", &texture))}; + auto const screen{queue.acquire(request(script_language::wasm, module_path, "cab", &texture))}; REQUIRE(screen != nullptr); // the same key, the same screen - CHECK(queue.acquire(request(script_language::wasm, module, "cab", &texture)) == screen); + CHECK(queue.acquire(request(script_language::wasm, module_path, "cab", &texture)) == screen); refresh(queue, screen, speed(5.0), 42); REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0 && false == sent_commands().empty(); })); @@ -243,13 +321,13 @@ TEST_CASE("wasm screens: a cab screen draws from its input and sends commands to TEST_CASE("wasm screens: the image goes up again when the texture is made anew, and waits while it isn't there") { sent_commands().clear(); script_folder const folder{"wasm_reupload"}; - auto const module{folder.write("paint.wasm", paint_module)}; + auto const module_path{folder.write("paint.wasm", paint_module)}; script_screen_queue queue; REQUIRE(queue.init()); recording_texture texture; texture.ready = false; - auto const screen{queue.acquire(request(script_language::wasm, module, "cab", &texture))}; + auto const screen{queue.acquire(request(script_language::wasm, module_path, "cab", &texture))}; refresh(queue, screen, speed(9.0), 1); REQUIRE(run_until(queue, [] { return false == sent_commands().empty(); })); queue.update(); @@ -272,12 +350,12 @@ TEST_CASE("wasm screens: the image goes up again when the texture is made anew, TEST_CASE("wasm screens: a screen outside the cab draws, but its commands are dropped") { sent_commands().clear(); script_folder const folder{"wasm_sign"}; - auto const module{folder.write("paint.wasm", paint_module)}; + auto const module_path{folder.write("paint.wasm", paint_module)}; script_screen_queue queue; REQUIRE(queue.init()); recording_texture texture; - auto const screen{queue.acquire(request(script_language::wasm, module, "sign", &texture, script_screen_kind::external))}; + auto const screen{queue.acquire(request(script_language::wasm, module_path, "sign", &texture, script_screen_kind::external))}; refresh(queue, screen, speed(3.0), 0); REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0; })); queue.update(); @@ -310,13 +388,13 @@ TEST_CASE("wasm screens: a screen stuck in a loop is stopped, and the others kee TEST_CASE("wasm screens: the screens outlive the queue without harm") { script_folder const folder{"wasm_outlive"}; - auto const module{folder.write("paint.wasm", paint_module)}; + auto const module_path{folder.write("paint.wasm", paint_module)}; std::shared_ptr screen; recording_texture texture; { script_screen_queue queue; REQUIRE(queue.init()); - screen = queue.acquire(request(script_language::wasm, module, "cab", &texture)); + screen = queue.acquire(request(script_language::wasm, module_path, "cab", &texture)); refresh(queue, screen, speed(4.0), 1); REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0; })); } @@ -325,6 +403,60 @@ TEST_CASE("wasm screens: the screens outlive the queue without harm") { screen.reset(); } +TEST_CASE("wasm screens: the commands and the log lines of one call are capped") { + sent_commands().clear(); + log_capture const log; + script_folder const folder{"wasm_flood"}; + auto const module{folder.write("flood.wasm", flood_module)}; + script_screen_queue queue; + REQUIRE(queue.init()); + + recording_texture texture; + auto const screen{queue.acquire(request(script_language::wasm, module, "flood", &texture))}; + refresh(queue, screen, speed(0.0), 3); + REQUIRE(run_until(queue, [] { return false == sent_commands().empty(); })); + queue.update(); + // the first ones go, the rest is dropped + CHECK(sent_commands().size() == commands_per_call); + CHECK(sent_commands().back().first.param1 == static_cast(commands_per_call - 1)); + + auto const lines{log.lines_with("aaaaaaaaaa")}; + REQUIRE(false == lines.empty()); + CHECK(lines.size() <= log_lines_per_call); + auto const longest{std::ranges::max(lines, {}, [](std::string const &Line) { return Line.size(); })}; + CHECK(longest.size() < module.size() + log_line_length + 100); + queue.exit(); +} + +TEST_CASE("wasm screens: a module larger than the limit isn't loaded") { + // the screen of "paint", with a custom section that makes the file larger than a screen may read + std::vector bytes(paint_module.begin(), paint_module.end()); + auto const payload{screen_file_size}; + auto size{static_cast(payload + 2)}; // the name: its length and one letter + bytes.push_back(0x00); + do { + auto const low{static_cast(size & 0x7f)}; + size >>= 7; + bytes.push_back(size != 0 ? static_cast(low | 0x80) : low); + } while (size != 0); + bytes.push_back(0x01); + bytes.push_back('x'); + bytes.resize(bytes.size() + payload, 0); + + script_folder const folder{"wasm_large"}; + auto const module{folder.write("large.wasm", bytes)}; + script_screen_queue queue; + REQUIRE(queue.init()); + + recording_texture texture; + auto const screen{queue.acquire(request(script_language::wasm, module, "large", &texture))}; + refresh(queue, screen, speed(1.0), 1); + run_frames(queue); + CHECK_FALSE(queue.due(*screen)); + CHECK(texture.uploads == 0); + queue.exit(); +} + #endif #ifdef WITH_LUA @@ -750,4 +882,558 @@ TEST_CASE("lua screens: an image read after led_post has its post-processing don queue.exit(); } +namespace { + +// scripts that catch the error of the instruction limit and go on looping +constexpr std::string_view pcall_spin_script{R"( +local function spin() while true do end end +return { render = function(state) while true do pcall(spin) end end } +)"}; + +constexpr std::string_view nested_pcall_spin_script{R"( +local function spin() while true do end end +return { render = function(state) while true do pcall(function() while true do pcall(spin) end end) end end } +)"}; + +constexpr std::string_view xpcall_spin_script{R"( +local function spin() while true do end end +local function handler() while true do end end +return { render = function(state) while true do xpcall(spin, handler) end end } +)"}; + +constexpr std::string_view coroutine_spin_script{R"( +local function spin() while true do end end +return { render = function(state) while true do coroutine.resume(coroutine.create(spin)) end end } +)"}; + +// white when the metatable of an image can't be reached, and its __gc can't be called +constexpr std::string_view metatable_script{R"( +local image = eu07.image(1, 1) +local metatable = getmetatable(image) +local locked = type(metatable) ~= "table" +-- only where the metatable is locked: an unlocked one would destroy the image twice +local collected = locked and pcall(function() return metatable.__gc(image) end) +local usable = image:width() == 1 +return { + render = function(state) + return eu07.image(1, 1, (locked and not collected and usable) and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// white when string.rep refuses a result over the limit and makes the ones under it +constexpr std::string_view repeat_script{R"( +local huge = pcall(string.rep, "x", 64 * 1024 * 1024) +local method = pcall(function() return ("ab"):rep(16 * 1024 * 1024) end) +local endless = pcall(string.rep, "x", 1e300) +local fits = #string.rep("x", 1024 * 1024) == 1024 * 1024 and ("ab"):rep(3) == "ababab" and ("x"):rep(0) == "" and ("x"):rep(-1) == "" +return { + render = function(state) + return eu07.image(1, 1, (not huge and not method and not endless and fits) and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// white when an image larger than a screen can be isn't decoded, and a small one is +constexpr std::string_view large_png_script{R"( +local sprite = pcall(eu07.sprite, "large") +local font = pcall(eu07.font, "large") +local small = pcall(eu07.sprite, "small") +return { + render = function(state) + return eu07.image(1, 1, (not sprite and not font and small) and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// a long command name first, then too many commands and log lines for one call +constexpr std::string_view flood_script{R"( +return { + render = function(state) + eu07.command("cmdtest" .. ("q"):rep(100), 1, 0) + for i = 0, 999 do eu07.command("cmdtest", i, 0) end + for i = 1, 100 do eu07.log(("y"):rep(5000)) end + return eu07.image(1, 1) + end +} +)"}; + +// white when a file larger than a screen may read, and a folder, read as nothing +constexpr std::string_view large_file_script{R"( +local large = eu07.read_file("large.bin") +local folder = eu07.read_file("data") +local small = eu07.read_file("data/small.txt") +return { + render = function(state) + return eu07.image(1, 1, (large == nil and folder == nil and small == "small") and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// a white image of the size, as a .png +std::vector white_png(int const Width, int const Height) { + std::vector const pixels(static_cast(Width) * Height * 4, 255); + std::vector result; + auto const append{[](void *Target, void *Data, int const Size) { + auto *bytes{static_cast(Data)}; + static_cast *>(Target)->insert(static_cast *>(Target)->end(), bytes, bytes + Size); + }}; + stbi_write_png_to_func(append, &result, Width, Height, 4, pixels.data(), Width * 4); + return result; +} + +// runs the script of a screen once; the first pixel of what it drew, or -1 when it drew nothing (after a wait) +int first_pixel(std::string const &Script, std::string const &Key) { + script_screen_queue queue; + REQUIRE(queue.init()); + recording_texture texture; + auto const screen{queue.acquire(request(script_language::lua, Script, Key, &texture))}; + refresh(queue, screen, speed(0.0), 1); + auto const drawn{run_until(queue, [&texture] { return texture.uploads > 0; })}; + queue.exit(); + return drawn && false == texture.pixels.empty() ? texture.pixels[0] : -1; +} + +} // namespace + +TEST_CASE("lua screens: a script catching the instruction limit with pcall, xpcall or a coroutine is stopped all the same") { + script_folder const folder{"lua_pcall_spin"}; + auto const painting{folder.write("paint.lua", paint_script)}; + for (auto const &[name, code] : {std::pair{"pcall.lua", pcall_spin_script}, std::pair{"nested.lua", nested_pcall_spin_script}, + std::pair{"xpcall.lua", xpcall_spin_script}, std::pair{"coroutine.lua", coroutine_spin_script}}) { + CAPTURE(name); + auto const spinning{folder.write(name, code)}; + // a worker stuck for good would keep the queue's destructor waiting: such a queue is left behind, so the test + // fails instead of hanging the run + auto *queue{new script_screen_queue}; // NOSONAR see above + REQUIRE(queue->init()); + + recording_texture stuck; + recording_texture working; + auto const first{queue->acquire(request(script_language::lua, spinning, "spin", &stuck))}; + auto const second{queue->acquire(request(script_language::lua, painting, "paint", &working))}; + refresh(*queue, first, speed(1.0), 1); + refresh(*queue, second, speed(2.0), 1); + + auto const stopped{run_until(*queue, [&working] { return working.uploads > 0; })}; + CHECK(stopped); + if (false == stopped) { + // the stuck worker doesn't touch the textures, and nothing uploads to them any more + continue; + } + CHECK(stuck.uploads == 0); + CHECK_FALSE(queue->due(*first)); + queue->exit(); + delete queue; // NOSONAR see above + } +} + +TEST_CASE("lua screens: xpcall passes the arguments, and the error to its handler") { + script_folder const folder{"lua_xpcall"}; + constexpr std::string_view script{R"( +local ok1, sum = xpcall(function(a, b) return a + b end, function(e) return "handled" end, 2, 3) +local ok2, handled = xpcall(function() error("boom") end, function(e) return "handled: " .. tostring(e) end) +local ok3 = xpcall(function() error("boom") end, function(e) error("again") end) +local good = ok1 and sum == 5 and not ok2 and handled:find("handled: .*boom") ~= nil and not ok3 +return { + render = function(state) + return eu07.image(1, 1, good and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + CHECK(first_pixel(folder.write("xpcall.lua", script), "xpcall") == 255); +} + +TEST_CASE("lua screens: the metatables of the api objects can't be reached from a script") { + script_folder const folder{"lua_metatable"}; + CHECK(first_pixel(folder.write("metatable.lua", metatable_script), "metatable") == 255); +} + +TEST_CASE("lua screens: string.rep makes no string over the limit") { + script_folder const folder{"lua_rep"}; + CHECK(first_pixel(folder.write("rep.lua", repeat_script), "rep") == 255); +} + +TEST_CASE("lua screens: a .png larger than a screen image isn't decoded") { + script_folder const folder{"lua_large_png"}; + folder.write("large.png", white_png(5000, 1)); + folder.write("large.txt", std::string_view{"//\na1\n"}); + folder.write("small.png", white_png(2, 2)); + CHECK(first_pixel(folder.write("png.lua", large_png_script), "png") == 255); +} + +TEST_CASE("lua screens: the commands and the log lines of one call are capped") { + sent_commands().clear(); + log_capture const log; + script_folder const folder{"lua_flood"}; + auto const script{folder.write("flood.lua", flood_script)}; + script_screen_queue queue; + REQUIRE(queue.init()); + + recording_texture texture; + auto const screen{queue.acquire(request(script_language::lua, script, "flood", &texture))}; + refresh(queue, screen, speed(0.0), 3); + REQUIRE(run_until(queue, [] { return false == sent_commands().empty(); })); + queue.update(); + // the long name is dropped, of the rest the first ones go + CHECK(sent_commands().size() == commands_per_call); + CHECK(sent_commands().front().first.param1 == 0.0); + CHECK(sent_commands().back().first.param1 == static_cast(commands_per_call - 1)); + // the command of the long name didn't get as far as the engine's command names + CHECK(log.lines_with("not found").empty()); + + auto const lines{log.lines_with("yyyyyyyyyy")}; + REQUIRE(false == lines.empty()); + CHECK(lines.size() <= log_lines_per_call); + auto const longest{std::ranges::max(lines, {}, [](std::string const &Line) { return Line.size(); })}; + CHECK(longest.size() < script.size() + log_line_length + 100); + queue.exit(); +} + +TEST_CASE("lua screens: a file larger than the limit, or a folder, reads as nothing") { + script_folder const folder{"lua_large_file"}; + folder.write("large.bin", std::string(screen_file_size + 1, 'x')); + folder.write("data/small.txt", std::string_view{"small"}); + CHECK(first_pixel(folder.write("file.lua", large_file_script), "file") == 255); +} + +TEST_CASE("lua screens: a script larger than the limit isn't loaded") { + script_folder const folder{"lua_large_script"}; + std::string code{"return { render = function(state) return eu07.image(1, 1, { 255, 255, 255 }) end }\n--"}; + code.append(screen_file_size, 'x'); + auto const script{folder.write("large.lua", code)}; + script_screen_queue queue; + REQUIRE(queue.init()); + + recording_texture texture; + auto const screen{queue.acquire(request(script_language::lua, script, "large", &texture))}; + refresh(queue, screen, speed(0.0), 1); + run_frames(queue); + CHECK_FALSE(queue.due(*screen)); + CHECK(texture.uploads == 0); + queue.exit(); +} + +namespace { + +// white when the script gets no userdata of its own (newproxy), and a table's __gc isn't called: no finalizer of the +// script's, which LuaJIT would run without the hook +constexpr std::string_view finalizer_script{R"( +local collected = false +setmetatable({}, { __gc = function() collected = true end }) +collectgarbage() +collectgarbage() +local good = newproxy == nil and ffi == nil and require == nil and not collected +return { + render = function(state) + return eu07.image(1, 1, good and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// a table whose metatable fails, loops, or gives render: the game reads the table in protected mode +constexpr std::string_view failing_index_script{R"( +return setmetatable({}, { __index = function() error("x") end }) +)"}; + +constexpr std::string_view looping_index_script{R"( +return setmetatable({}, { __index = function() while true do end end }) +)"}; + +constexpr std::string_view inherited_render_script{R"( +local base = { render = function(state) return eu07.image(1, 1, { 255, 255, 255 }) end } +return setmetatable({}, { __index = base }) +)"}; + +// starts, then fails when render is read for a refresh +constexpr std::string_view failing_later_script{R"( +local started = false +return setmetatable({}, { __index = function(t, key) + if key == "init" then return function() started = true end end + if key == "render" then + if started then error("render can't be read any more") end + return function() end + end +end }) +)"}; + +// white when the pattern functions refuse what may take too long, and do what doesn't +constexpr std::string_view pattern_script{R"( +local long = ("a"):rep(1000000) +local function refused(...) + local ok, message = pcall(...) + return not ok and message:find("may take too long", 1, true) ~= nil +end +local slow = refused(string.find, long, ".-b") + and refused(function() return long:find(".-b") end) + and refused(string.match, long, "(a*)b") + and refused(string.gsub, long, "a-b", "") + and refused(function() for x in long:gmatch("a-b") do end end) + and refused(string.find, ("a"):rep(1000), "a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?aaaaaaaaaaaaaaaaaaaaaaaaaaaaaab") + and refused(string.find, long, ("a"):rep(1000) .. "b", 1, true) +-- %b walks to the end of the subject from each opening character that nothing closes +local open = ("("):rep(1000000) +slow = slow and refused(string.find, open, '%b()') + and refused(string.gsub, open, '%b()', "") + and refused(function() for x in open:gmatch('%b()') do end end) +-- what a screen does: lines of a file, fields of a line, a plain search, short subjects +local text = ("key=value\n"):rep(10000) +local lines = 0 +for line in text:gmatch("[^\n]+") do lines = lines + 1 end +local key, value = ("speed=120"):match("^(%w+)=(%d+)$") +local spaced = select(2, (("a b c "):rep(100)):gsub("%s+", " ")) +local found = long:find("aaab", 1, true) == nil and (long .. "b"):find("ab", 1, true) == 1000000 +local calls = select(2, (("call(a, b) "):rep(10000)):gsub('%b()', "")) +local fast = lines == 10000 and key == "speed" and value == "120" and spaced == 300 and found and calls == 10000 + and ("x = 1"):find("=") == 3 and ("abc"):gsub("b", "%0%0") == "abbc" +return { + render = function(state) + return eu07.image(1, 1, (slow and fast) and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// white when what makes a large string in one call is refused past the memory of a screen +constexpr std::string_view large_result_script{R"( +local mega = ("x"):rep(1024 * 1024) +local function refused(...) + local ok, message = pcall(...) + return not ok and message:find("over the memory of a screen", 1, true) ~= nil +end +local parts = {} +for i = 1, 200 do parts[i] = mega end +local format = refused(string.format, ("%s"):rep(200), unpack(parts)) +local concat = refused(table.concat, parts) +local gsub = refused(string.gsub, mega, "", ("y"):rep(1000)) +local gsub_table = refused(string.gsub, mega, ".", { x = ("y"):rep(1000) }) +local fits = #table.concat({ mega, mega }, ",") == 2 * 1024 * 1024 + 1 and #string.format("%s%s", mega, mega) == 2 * 1024 * 1024 + and select(2, mega:gsub("x", "yy")) == 1024 * 1024 +return { + render = function(state) + return eu07.image(1, 1, (format and concat and gsub and gsub_table and fits) and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// white when gsub takes a table with a metatable as Lua does (the metatable doesn't get to the library as an argument), +// and a line is trimmed: with the usual idiom on a long line of words, without a pattern on a long run of spaces +constexpr std::string_view gsub_metatable_trim_script{R"( +local upper = setmetatable({}, { __index = function(_, k) return k:upper() end }) +local replaced, count = ("one two"):gsub("%w+", upper) +local line = ("word next\tone "):rep(700) +local trimmed = (" " .. line .. " "):match("^%s*(.-)%s*$") +local ok, message = pcall(string.match, "x" .. (" "):rep(1000000) .. "x", "^%s*(.-)%s*$") +local refused = not ok and message:find("may take too long", 1, true) ~= nil +local function trim(s) + local first = s:find("%S") + if not first then return "" end + return s:sub(first, #s - s:reverse():find("%S") + 1) +end +local spaced = trim(" x" .. (" "):rep(1000000) .. "x ") +local good = replaced == "ONE TWO" and count == 2 and trimmed == line:sub(1, -2) and refused + and #spaced == 1000002 and trim(" ") == "" and trim(" a b ") == "a b" +return { + render = function(state) + return eu07.image(1, 1, good and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// white when the images a screen holds are held to its memory, and the images it dropped don't count. an image of +// 4096 x 4096 is 64 MB, half the memory of a screen: the second one kept is refused, and the 4 dropped ones (twice +// the memory) would be refused too if the dropped ones counted. no more of them: each is filled pixel by pixel, slowly +// in the coverage build (GCC -O0 --coverage), and with 20 of them the screen sometimes didn't draw in its 20 s there +constexpr std::string_view image_memory_script{R"( +local kept = {} +local ok, message = pcall(function() + for i = 1, 100 do kept[i] = eu07.image(4096, 4096) end +end) +local refused = not ok and message:find("memory limit exceeded", 1, true) ~= nil and #kept < 100 +kept = nil +local dropped = pcall(function() + for i = 1, 4 do local image = eu07.image(4096, 4096) end +end) +return { + render = function(state) + return eu07.image(1, 1, (refused and dropped) and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// holds more and more memory, a little at a time +constexpr std::string_view growing_script{R"( +local kept = {} +for i = 1, 10000000 do kept[i] = ("x"):rep(1000) .. i end +return { render = function(state) return eu07.image(1, 1, { 255, 255, 255 }) end } +)"}; + +// the memory limit of the Lua screens made while it lives, in place of max_screen_memory: a test that fills the memory +// of a screen stays small +class screen_memory_limit { + public: + explicit screen_memory_limit(std::size_t const Bytes) { script_screens::set_lua_screen_memory_limit(Bytes); } + ~screen_memory_limit() { script_screens::set_lua_screen_memory_limit(script_screens::max_screen_memory); } + screen_memory_limit(screen_memory_limit const &) = delete; + screen_memory_limit &operator=(screen_memory_limit const &) = delete; +}; + +constexpr std::size_t small_screen_memory{32 * 1024 * 1024}; + +// with small_screen_memory: a concatenation of 80 MB in one operation, from a string of 8 MB, refused as it is made, in +// the pcall, as the instruction hook would see it only once it is made +constexpr std::string_view one_concatenation_script{R"( +local a = ("x"):rep(1024 * 1024) +for i = 1, 3 do a = a .. a end +local ok, message = pcall(function() return #(a .. a .. a .. a .. a .. a .. a .. a .. a .. a) end) +local refused = #a == 8 * 1024 * 1024 and not ok and message:find("not enough memory", 1, true) ~= nil +a = nil +return { + render = function(state) + return eu07.image(1, 1, refused and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// doubles a string to 2 GB, 64 times small_screen_memory, in some fifty instructions: fewer than the thousand after +// which the instruction hook looks at the heap +constexpr std::string_view doubling_script{R"( +local s = ("x"):rep(1024 * 1024) +for i = 1, 11 do s = s .. s end +return { render = function(state) return eu07.image(1, 1, { 255, 255, 255 }) end } +)"}; + +// white when a coroutine yields across xpcall, and xpcall without a handler is an error +constexpr std::string_view xpcall_yield_script{R"( +local resume = coroutine.wrap(function() + local ok, value = xpcall(function() + coroutine.yield(1) + return 2 + end, function(e) return e end) + coroutine.yield(ok and value) + local caught, handled = xpcall(function() + coroutine.yield(3) + error("boom") + end, function(e) return "handled: " .. e end) + coroutine.yield(not caught and handled:find("handled: .*boom") ~= nil) +end) +local first, second, third, fourth = resume(), resume(), resume(), resume() +local missing = not pcall(xpcall, print) +local good = first == 1 and second == 2 and third == 3 and fourth == true and missing +return { + render = function(state) + return eu07.image(1, 1, good and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// loads the script as a screen next to a working one: the working one draws, the script's screen draws nothing, and +// nothing hangs or ends the program +void check_switched_off(script_folder const &Folder, std::string const &Name, std::string_view const Code) { + auto const painting{Folder.write("paint.lua", paint_script)}; + auto const failing{Folder.write(Name, Code)}; + auto *queue{new script_screen_queue}; // NOSONAR a stuck worker would keep the destructor waiting, see above + REQUIRE(queue->init()); + recording_texture switched_off; + recording_texture working; + auto const first{queue->acquire(request(script_language::lua, failing, Name, &switched_off))}; + auto const second{queue->acquire(request(script_language::lua, painting, "paint", &working))}; + refresh(*queue, first, speed(1.0), 1); + refresh(*queue, second, speed(2.0), 1); + auto const drawn{run_until(*queue, [&working] { return working.uploads > 0; })}; + CHECK(drawn); + if (false == drawn) { + return; + } + run_frames(*queue); + CHECK(switched_off.uploads == 0); + CHECK_FALSE(queue->due(*first)); + queue->exit(); + delete queue; // NOSONAR see above +} + +} // namespace + +TEST_CASE("lua screens: a script makes no finalizer of its own") { + script_folder const folder{"lua_finalizer"}; + CHECK(first_pixel(folder.write("finalizer.lua", finalizer_script), "finalizer") == 255); +} + +TEST_CASE("lua screens: the table of a script is read in protected mode") { + log_capture const log; + script_folder const folder{"lua_index"}; + SUBCASE("a metatable that fails") { + check_switched_off(folder, "failing.lua", failing_index_script); + CHECK_FALSE(log.lines_with("reading render and init failed").empty()); + } + SUBCASE("a metatable that loops") { + check_switched_off(folder, "looping.lua", looping_index_script); + CHECK_FALSE(log.lines_with("instruction limit exceeded").empty()); + } + SUBCASE("a metatable that fails once the screen runs") { + check_switched_off(folder, "later.lua", failing_later_script); + CHECK_FALSE(log.lines_with("render can't be read any more").empty()); + } + SUBCASE("a metatable that gives render") { + CHECK(first_pixel(folder.write("inherited.lua", inherited_render_script), "inherited") == 255); + } +} + +TEST_CASE("lua screens: the pattern functions refuse what may take too long, and do the rest") { + script_folder const folder{"lua_patterns"}; + auto const started{std::chrono::steady_clock::now()}; + CHECK(first_pixel(folder.write("patterns.lua", pattern_script), "patterns") == 255); + // the refused calls take no time, the others little + CHECK(std::chrono::steady_clock::now() - started < std::chrono::seconds(10)); +} + +TEST_CASE("lua screens: what makes a large string in one call is held to the memory of a screen") { + script_folder const folder{"lua_large_result"}; + CHECK(first_pixel(folder.write("large.lua", large_result_script), "large") == 255); +} + +TEST_CASE("lua screens: gsub with a table that has a metatable, and the trim of a long line") { + script_folder const folder{"lua_gsub_metatable_trim"}; + auto const started{std::chrono::steady_clock::now()}; + CHECK(first_pixel(folder.write("trim.lua", gsub_metatable_trim_script), "trim") == 255); + CHECK(std::chrono::steady_clock::now() - started < std::chrono::seconds(10)); +} + +TEST_CASE("lua screens: the images a screen holds are held to its memory") { + script_folder const folder{"lua_image_memory"}; + CHECK(first_pixel(folder.write("images.lua", image_memory_script), "images") == 255); +} + +TEST_CASE("lua screens: a screen holding more than its memory is switched off") { + log_capture const log; + script_folder const folder{"lua_growing"}; + check_switched_off(folder, "growing.lua", growing_script); + CHECK(log.lines_with("memory limit exceeded").size() + log.lines_with("not enough memory").size() > 0); +} + +TEST_CASE("lua screens: a string made over the memory in one operation is refused") { + screen_memory_limit const limit{small_screen_memory}; + script_folder const folder{"lua_one_concatenation"}; + CHECK(first_pixel(folder.write("concatenation.lua", one_concatenation_script), "concatenation") == 255); + CHECK(script_screens::lua_screen_memory_peak() <= 2 * small_screen_memory); +} + +TEST_CASE("lua screens: a string doubled in a loop stops at the memory of the screen, not at LuaJIT's own limit") { + log_capture const log; + screen_memory_limit const limit{small_screen_memory}; + script_folder const folder{"lua_doubling"}; + check_switched_off(folder, "doubling.lua", doubling_script); + CHECK(log.lines_with("not enough memory").size() + log.lines_with("memory limit exceeded").size() > 0); + // past the limit between two checks of the hook, but refused before twice the limit (its garbage included). with + // LuaJIT 2.0 on x64 and no allocator in front of LuaJIT's own, this went on to its own limit, over 1 GB + auto const peak{script_screens::lua_screen_memory_peak()}; + CAPTURE(peak); + CHECK(peak > small_screen_memory); + CHECK(peak <= 2 * small_screen_memory); +} + +TEST_CASE("lua screens: a coroutine yields across xpcall") { + script_folder const folder{"lua_xpcall_yield"}; + CHECK(first_pixel(folder.write("yield.lua", xpcall_yield_script), "yield") == 255); +} + #endif diff --git a/tests/unit/test_script_screens.cpp b/tests/unit/test_script_screens.cpp index 9e0bb7a92..af8678f2e 100644 --- a/tests/unit/test_script_screens.cpp +++ b/tests/unit/test_script_screens.cpp @@ -101,3 +101,146 @@ TEST_CASE("script screens: a screen reads files only below its own folder") { CHECK_FALSE(script_screens::is_safe_relative_path("\\windows")); CHECK_FALSE(script_screens::is_safe_relative_path("c:/windows/win.ini")); } + +TEST_CASE("script screens: the script of a screen is in the vehicle's folder, or from the game's, and not outside it") { + using script_screens::screen_script_path; + std::string const vehicle{"dynamic/pkp/ep07_v1/"}; + CHECK(screen_script_path(vehicle, "screen.lua") == "dynamic/pkp/ep07_v1/screen.lua"); + CHECK(screen_script_path(vehicle, "scripts/screen.lua") == "scripts/screen.lua"); + // a backslash isn't a folder to the game (substr_path), so the name goes in the vehicle's folder + CHECK(screen_script_path(vehicle, "lua\\screen.lua") == "dynamic/pkp/ep07_v1/lua\\screen.lua"); + + CHECK_FALSE(screen_script_path(vehicle, "../../../screen.lua").has_value()); + CHECK_FALSE(screen_script_path(vehicle, "scripts/../../screen.lua").has_value()); + CHECK_FALSE(screen_script_path(vehicle, "..\\..\\screen.lua").has_value()); + CHECK_FALSE(screen_script_path(vehicle, "/screen.lua").has_value()); + CHECK_FALSE(screen_script_path(vehicle, "c:/games/screen.lua").has_value()); + CHECK_FALSE(screen_script_path("../outside/", "screen.lua").has_value()); +} + +TEST_CASE("script screens: the steps a Lua pattern function may take at worst") { + using script_screens::lua_pattern_cost; + using script_screens::max_pattern_cost; + // a plain search: the subject (and one past it) times the pattern + CHECK(lua_pattern_cost("abc", 999, true, true) == doctest::Approx(1000.0 * 3)); + CHECK(lua_pattern_cost(".-b", 999, true, true) == doctest::Approx(1000.0 * 3)); + // a pattern without special characters is searched plainly as well + CHECK(lua_pattern_cost("abc", 999, false, true) == doctest::Approx(1000.0 * 3)); + CHECK(lua_pattern_cost("", 999, false, true) == doctest::Approx(1000.0)); + // from every position, times the subject for each repetition but a last one + CHECK(lua_pattern_cost(".-b", 999, false, true) == doctest::Approx(1000.0 * 1000 * 3)); + CHECK(lua_pattern_cost("a*", 999, false, true) == doctest::Approx(1000.0 * 2)); + CHECK(lua_pattern_cost("(a+)", 999, false, true) == doctest::Approx(1000.0 * 4)); + CHECK(lua_pattern_cost("a+$", 999, false, true) == doctest::Approx(1000.0 * 1000 * 3)); + CHECK(lua_pattern_cost("(%d+):(%d+)", 999, false, true) == doctest::Approx(1000.0 * 1000 * 11)); + CHECK(lua_pattern_cost("[^\n]+", 999, false, false) == doctest::Approx(1000.0 * 5)); + CHECK(lua_pattern_cost("[%]x]*y", 999, false, true) == doctest::Approx(1000.0 * 1000 * 7)); + CHECK(lua_pattern_cost("%bxyz", 999, false, true) == doctest::Approx(1000.0 * 1000 * 5)); + // %b goes along the subject on its own: it counts where it ends the pattern too + CHECK(lua_pattern_cost("%b()", 999, false, true) == doctest::Approx(1000.0 * 1000 * 4)); + CHECK(lua_pattern_cost("(%b())", 999, false, true) == doctest::Approx(1000.0 * 1000 * 6)); + CHECK(lua_pattern_cost("%b().*", 999, false, true) == doctest::Approx(1000.0 * 1000 * 6)); + CHECK(lua_pattern_cost("(a)%1x", 999, false, true) == doctest::Approx(1000.0 * 1000 * 6)); + CHECK(lua_pattern_cost("%f[%w]%w+", 999, false, true) == doctest::Approx(1000.0 * 9)); + // '?' doubles + CHECK(lua_pattern_cost("a?a?b", 999, false, true) == doctest::Approx(1000.0 * 4 * 5)); + // '^' anchors find, match and gsub to the first position; gmatch takes it as a character + CHECK(lua_pattern_cost("^.-b", 999, false, true) == doctest::Approx(1000.0 * 4)); + CHECK(lua_pattern_cost("^.-b", 999, false, false) == doctest::Approx(1000.0 * 1000 * 4)); + // a malformed pattern is the library's to refuse + CHECK(lua_pattern_cost("[a", 999, false, true) > 0.0); + CHECK(lua_pattern_cost("%", 999, false, true) > 0.0); + CHECK(lua_pattern_cost("%b", 999, false, true) > 0.0); + + // the review's case, and what a screen does + CHECK(lua_pattern_cost(".-b", 1'000'000, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("[^\n]+", 1'000'000, false, false) < max_pattern_cost); + CHECK(lua_pattern_cost("^(%w+)=(%d+)$", 1'000, false, true) < max_pattern_cost); + CHECK(lua_pattern_cost("%s+$", 4'000, false, true) < max_pattern_cost); + std::string optional; + for (int idx = 0; idx < 30; ++idx) { + optional += "a?"; + } + CHECK(lua_pattern_cost(optional + std::string(30, 'a'), 100, false, true) > max_pattern_cost); +} + +TEST_CASE("script screens: a repetition followed by what always matches doesn't multiply") { + using script_screens::lua_pattern_cost; + // the first %s* of the trim: past it, (.-)%s*$ matches from wherever it stopped, so it's tried once + CHECK(lua_pattern_cost("^%s*(.-)%s*$", 999, false, true) == doctest::Approx(1000.0 * 1000 * 12)); + CHECK(lua_pattern_cost("^%s*(.*)", 999, false, true) == doctest::Approx(8.0)); + CHECK(lua_pattern_cost("a*.-$", 999, false, true) == doctest::Approx(1000.0 * 1000 * 5)); + // what may not match still multiplies + CHECK(lua_pattern_cost("^%s*(.*%S)", 999, false, true) == doctest::Approx(1000.0 * 1000 * 10)); + CHECK(lua_pattern_cost("^%s*x%s*$", 999, false, true) == doctest::Approx(1000.0 * 1000 * 9)); + // '$' is the end only at the end of the pattern + CHECK(lua_pattern_cost("a*$b", 999, false, true) == doctest::Approx(1000.0 * 1000 * 4)); +} + +TEST_CASE("script screens: %b counts the way from an opening character to the one that closes it") { + using script_screens::lua_pattern_cost; + using script_screens::max_pattern_cost; + // nothing closes: from each character to the end of the subject, the subject squared; whatever follows the %b + auto const open{std::string(1'000'000, '(')}; + CHECK(lua_pattern_cost("%b()", std::string_view{open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b()", std::string_view{open}, false, false) > max_pattern_cost); + CHECK(lua_pattern_cost("(%b())", std::string_view{open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b().*", std::string_view{open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b()x*", std::string_view{open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b()", std::string_view{open + open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b()", std::string_view{open}.substr(0, 10'000), false, true) > max_pattern_cost); + // the same with a hundred thousand of them, more than the openings held at a time + CHECK(lua_pattern_cost("%b()", std::string_view{open}.substr(0, 100'000), false, true) > max_pattern_cost); + // tried once from each position: the positions and the ways from the three openings, 2 + 5 + 2 + std::string_view const calls{"a(b)c(d(e))"}; + CHECK(lua_pattern_cost("%b()", calls, false, true) == doctest::Approx((12.0 + 9.0) * 4)); + CHECK(lua_pattern_cost("(%b())", calls, false, true) == doctest::Approx((12.0 + 9.0) * 6)); + // tried from the first position only, or after a repetition: the longest way of one try, and one + CHECK(lua_pattern_cost("^%b()", calls, false, true) == doctest::Approx(6.0 * 5)); + CHECK(lua_pattern_cost(".-%b()", calls, false, true) == doctest::Approx(12.0 * 12 * 6 * 6)); + // the same character opens and closes: to the next one + CHECK(lua_pattern_cost("%b\"\"", std::string_view{"a\"b\"c\""}, false, true) == doctest::Approx((7.0 + 5.0) * 4)); + // none in the subject: nothing to go along + CHECK(lua_pattern_cost("%b()", std::string_view{"abc"}, false, true) == doctest::Approx(4.0 * 4)); + // a long text of short calls is cheap, and so is one opening left unclosed in it + std::string text; + while (text.size() < 100'000) { + text += "call(a, b) "; + } + CHECK(lua_pattern_cost("%b()", std::string_view{text}, false, true) < max_pattern_cost); + text[9] = ' '; + CHECK(lua_pattern_cost("%b()", std::string_view{text}, false, true) < max_pattern_cost); + // nested deep, the ways add up to the subject squared again + auto const nested{std::string(20'000, '(') + std::string(20'000, ')')}; + CHECK(lua_pattern_cost("%b()x", std::string_view{nested}, false, true) > max_pattern_cost); + // malformed: the function raises its error + CHECK(lua_pattern_cost("%b(", std::string_view{open}, false, true) > 0.0); +} + +TEST_CASE("script screens: a repetition right before the final $ counts its longest run in the subject") { + using script_screens::lua_pattern_cost; + using script_screens::max_pattern_cost; + std::string words; + while (words.size() < 10'000) { + words += "word next\tone "; + } + // a line of 10 KB trimmed: the subject times the longest run of spaces (2), where the length alone gives the + // subject squared + CHECK(lua_pattern_cost("^%s*(.-)%s*$", std::string_view{words}, false, true) == doctest::Approx((words.size() + 1.0) * 3 * 12)); + CHECK(lua_pattern_cost("^%s*(.-)%s*$", std::string_view{words}, false, true) < max_pattern_cost); + CHECK(lua_pattern_cost("^%s*(.-)%s*$", words.size(), false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%s+$", std::string_view{words}, false, true) < max_pattern_cost); + CHECK(lua_pattern_cost("%d*$", std::string_view{words}, false, true) == doctest::Approx((words.size() + 1.0) * 1 * 4)); + CHECK(lua_pattern_cost("x*$", std::string_view{"axxxa"}, false, true) == doctest::Approx(6.0 * 4 * 3)); + CHECK(lua_pattern_cost("%%*$", std::string_view{"a%%%a"}, false, true) == doctest::Approx(6.0 * 4 * 4)); + // a long run is still the subject squared: "x", 10 000 spaces, "x" takes the trim about 10^8 steps, and a + // megabyte of them hours + auto const spaces{"x" + std::string(10'000, ' ') + "x"}; + CHECK(lua_pattern_cost("^%s*(.-)%s*$", std::string_view{spaces}, false, true) > max_pattern_cost); + auto const megabyte{"x" + std::string(1'000'000, ' ') + "x"}; + CHECK(lua_pattern_cost("^%s*(.-)%s*$", std::string_view{megabyte}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%s*$", std::string_view{megabyte}, false, true) > max_pattern_cost); + // a set or '.' isn't gone through: the whole subject + CHECK(lua_pattern_cost("[ ]*$", std::string_view{words}, false, true) == doctest::Approx((words.size() + 1.0) * (words.size() + 1.0) * 5)); + CHECK(lua_pattern_cost(".-b", std::string(1'000'000, 'a'), false, true) > max_pattern_cost); +} diff --git a/tests/unit/test_signal_passing.cpp b/tests/unit/test_signal_passing.cpp new file mode 100644 index 000000000..16d3cd9eb --- /dev/null +++ b/tests/unit/test_signal_passing.cpp @@ -0,0 +1,128 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/signalpassing.h" + +// when a signal in the AI's speed table counts as passed by the train (TController::CheckSignalPassed): the test +// mode reports a signal at stop passed that way as "passed at danger", the blackbox records every passed signal. a +// train set or standing past a signal at the start of a scenario didn't pass it; within 5 m of the signal the test +// mode used to report it all the same. + +namespace { + +// a point of the speed table the way TSpeedPos keeps it: found by the scan of the route, then updated as the head +// moves on (TController::TableCheck: UpdateDistance, Update, CheckSignalPassed) +struct table_point { + double distance; // ahead of the head [m], negative behind it + bool seen_ahead; + bool elapsed{false}; + int passes{0}; // reports of the point passed + + table_point(double const Distance, bool const Standing) + : distance(Distance), seen_ahead(signal_passing::seen_ahead_when_found(Distance, Standing)) { + move(0.0); // the first update comes with the next check of the table, the train hasn't moved yet + } + + // the head moves Metres on, and the table updates the point + void move(double const Metres) { + distance -= Metres; + auto const elapsedbefore{elapsed}; + elapsed = elapsed || distance < 0.0; + seen_ahead = signal_passing::seen_ahead_on_update(distance, seen_ahead); + if (signal_passing::passed_now(elapsedbefore, elapsed, seen_ahead)) { + ++passes; + } + } + + // the head moves Metres on in steps of a metre + void run(double const Metres) { + for (int moved{0}; moved < Metres; ++moved) { + move(1.0); + } + } +}; + +auto constexpr standing{true}; +auto constexpr moving{false}; + +} // namespace + +TEST_CASE("signal passing: a train standing past a signal when its table is traced hasn't passed it") { + auto behind{0.0}; + // 1-4.5 m: reported as passed at danger before; 20 m: the train standing across the signal of #409 + SUBCASE("0.5 m") { behind = 0.5; } + SUBCASE("1 m") { behind = 1.0; } + SUBCASE("2 m") { behind = 2.0; } + SUBCASE("3 m") { behind = 3.0; } + SUBCASE("4 m") { behind = 4.0; } + SUBCASE("4.9 m") { behind = 4.9; } + SUBCASE("20 m") { behind = 20.0; } + CAPTURE(behind); + + table_point signal{-behind, standing}; + CHECK_FALSE(signal.seen_ahead); + // standing there a while, then pulling away from it + for (auto check{0}; check < 10; ++check) { + signal.move(0.0); + } + signal.run(200.0); + CHECK(signal.passes == 0); +} + +TEST_CASE("signal passing: a train standing short of a signal passes it when it moves on") { + auto ahead{0.0}; + SUBCASE("at the signal") { ahead = 0.0; } + SUBCASE("0.5 m") { ahead = 0.5; } + SUBCASE("10 m") { ahead = 10.0; } + SUBCASE("150 m") { ahead = 150.0; } + CAPTURE(ahead); + + table_point signal{ahead, standing}; + CHECK(signal.seen_ahead); + signal.move(0.0); + CHECK(signal.passes == 0); + signal.run(ahead + 50.0); + CHECK(signal.passes == 1); +} + +TEST_CASE("signal passing: a moving train passing a signal its table finds just behind the head passes it") { + // the table traced anew in motion, the head right at the signal: the distance is found in steps of a metre, + // so a signal just ahead may come out a little behind + auto behind{0.0}; + SUBCASE("0.5 m") { behind = 0.5; } + SUBCASE("3 m") { behind = 3.0; } + SUBCASE("at the tolerance") { behind = signal_passing::moving_tolerance; } + CAPTURE(behind); + + table_point signal{-behind, moving}; + CHECK(signal.seen_ahead); + CHECK(signal.passes == 1); + signal.run(100.0); + CHECK(signal.passes == 1); +} + +TEST_CASE("signal passing: a signal found further behind a moving train than the tolerance wasn't passed by it") { + table_point signal{-(signal_passing::moving_tolerance + 0.5), moving}; + CHECK_FALSE(signal.seen_ahead); + signal.run(100.0); + CHECK(signal.passes == 0); +} + +TEST_CASE("signal passing: a train that overruns a signal and stops past it passes it once") { + // the overrun counts while the train moves; a table traced again with the train standing 3 m past the signal + // (a change of direction and back, a new order) doesn't count it again + table_point approach{150.0, moving}; + approach.run(153.0); + CHECK(approach.passes == 1); + + table_point traced_again{-3.0, standing}; + traced_again.run(50.0); + CHECK(traced_again.passes == 0); +} + +TEST_CASE("signal passing: the report of a pass needs the point to become elapsed in this very update") { + CHECK(signal_passing::passed_now(false, true, true)); + CHECK_FALSE(signal_passing::passed_now(true, true, true)); // elapsed before + CHECK_FALSE(signal_passing::passed_now(false, false, true)); // still ahead + CHECK_FALSE(signal_passing::passed_now(false, true, false)); // the head never had it ahead +} diff --git a/tests/unit/test_sleeper_models.cpp b/tests/unit/test_sleeper_models.cpp new file mode 100644 index 000000000..05d90ab32 --- /dev/null +++ b/tests/unit/test_sleeper_models.cpp @@ -0,0 +1,67 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scratch.h" + +#include "world/TrackSleepers.h" + +#include +#include +#include + +// the models of sleepers and timbers the track editor lists (world/TrackSleepers.h), found by the names of the files in a +// folder. a file named with a character the code page lacks is left out, rather than throwing out of the scan (GE#560) + +namespace { + +void write_model(std::filesystem::path const &Path, std::string const &Content) { + std::filesystem::create_directories(Path.parent_path()); + std::ofstream file{Path, std::ios::binary}; + file << Content; +} + +// whether the name can be turned into the narrow names of the code page: on Windows a Chinese character can't be with any +// of the single byte pages, where the narrow names are UTF-8 it can +bool narrow_name(std::filesystem::path const &Path) { + try { + static_cast(Path.generic_string()); + return true; + } catch (std::exception const &) { + return false; + } +} + +} // namespace + +TEST_CASE("sleeper models: a file named outside of the code page is left out, the rest is listed") { + test::scratch_folder const folder{"sleeper_models"}; + auto const root{folder.root()}; + write_model(root / "pkp" / "podklad_a.t3d", "Name: podklad\n"); + write_model(root / "pkp" / "podrozjazd_b.t3d", "Name: begin\nName: main\nName: end\n"); + auto const odd{root / "pkp" / std::filesystem::path{u8"podklad_\u4e2d.t3d"}}; + write_model(odd, "Name: podklad\n"); + // nor any other model of the folder named so, looked at before its name tells it's no sleeper + write_model(root / "drzewa" / std::filesystem::path{u8"drzewo_\u4e2d.e3d"}, ""); + write_model(root / "drzewa" / "drzewo.e3d", ""); + REQUIRE(std::filesystem::exists(odd)); + + std::vector models; + REQUIRE_NOTHROW(models = track_sleepers::pack_models(root)); + + auto const listed{narrow_name(odd)}; + REQUIRE(models.size() == (listed ? 3u : 2u)); + // the timbers first, then by the name + CHECK(models[0].name == "pkp/podrozjazd_b"); + CHECK(models[0].timber); + CHECK(models[1].name == "pkp/podklad_a"); + CHECK_FALSE(models[1].timber); + if (listed) { + CHECK(models[2].name.find("pkp/podklad_") == 0); + } +} + +TEST_CASE("sleeper models: a folder missing lists none") { + test::scratch_folder const folder{"sleeper_models_missing"}; + std::vector models; + REQUIRE_NOTHROW(models = track_sleepers::pack_models(folder.root() / "missing")); + CHECK(models.empty()); +} diff --git a/tests/unit/test_speed_control.cpp b/tests/unit/test_speed_control.cpp new file mode 100644 index 000000000..3f8a9a9ec --- /dev/null +++ b/tests/unit/test_speed_control.cpp @@ -0,0 +1,401 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scenario.h" +#include "drive.h" + +#include + +// the cruise control (tempomat, SpeedCtrl) and the secondary controller (ScndCtrl) of the vehicles which have one +// of them or both (eu07/maszyna#69). on the vehicles with the cruise control alone the secondary controller is +// its switch, as it always was; on those whose secondary controller shunts the field of the traction motors +// (the 6Dg, the ST45 and the BR285 among them) the cruise control has a switch of its own, apart from it + +using test::scenario; +using namespace test::channels; + +namespace { + +std::vector cruise() { + return { + {"SpeedCtrlActive", [](auto const &M) { return M.SpeedCtrlUnit.IsActive ? 1.0 : 0.0; }}, + {"SpeedCtrlStandby", [](auto const &M) { return M.SpeedCtrlUnit.Standby ? 1.0 : 0.0; }}, + {"SpeedCtrlValue", [](auto const &M) { return M.SpeedCtrlValue; }}, + {"eimic", [](auto const &M) { return M.eimic; }}, + {"eimicSpeedCtrl", [](auto const &M) { return M.eimicSpeedCtrl; }}, + {"eimic_real", [](auto const &M) { return M.eimic_real; }}, + }; +} + +// the universal controller (EIMCtrlType 3) of the 6Dg: 3 no power, 4 lowers the demand, 5 holds it, 6 raises it +constexpr int dg_no_power{3}; +constexpr int dg_lower{4}; +constexpr int dg_hold{5}; +constexpr int dg_raise{6}; + +void move_to(TMoverParameters &Vehicle, int const Position) { + while (Vehicle.MainCtrlPos < Position && Vehicle.IncMainCtrl(1)) { + // all the work is done in the condition + } + while (Vehicle.MainCtrlPos > Position && Vehicle.DecMainCtrl(1)) { + // all the work is done in the condition + } + REQUIRE(Vehicle.MainCtrlPos == Position); +} + +// the 6Dg started up, its brakes released, its controller through the no power and lowering positions to holding, +// for the line contactors to close +void get_6dg_going(scenario &Scenario) { + auto &loco{Scenario.cab()}; + REQUIRE(Scenario.start_up()); + Scenario.get_going(); + move_to(loco, dg_no_power); + for (int second = 0; second < 180 && loco.BrakePress > 0.1; ++second) { + Scenario.wait(1.0); + } + REQUIRE(loco.BrakePress <= 0.1); + move_to(loco, dg_lower); + Scenario.wait(1.0); + move_to(loco, dg_hold); + Scenario.wait(5.0); + REQUIRE(loco.StLinFlag); +} + +} // namespace + +// the vehicles with the field shunting alone, and those with the cruise control alone: as before the split + +TEST_CASE("speed control: the field shunting of the vehicles without a cruise control, as before") { + // the EU07's and the SM42's shunting by hand, the SU45's by itself (RelayType 45, from position 11 of its + // controller on); none has a cruise control, and the secondary controller shunts the field + SUBCASE("EU07 and SM42, by hand") { + for (auto const *path : {"4e_v1/4e", "sm42_v1/6d1"}) { + CAPTURE(path); + scenario scenario{std::string{"speed control/shunting/"} + path, motion() + traction() + cruise()}; + scenario.add(path, 1); + auto &loco{scenario.cab()}; + REQUIRE_FALSE(loco.SpeedCtrl); + REQUIRE_FALSE(loco.AutoRelayFlag); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(60.0); + auto const speed{loco.Vel}; + scenario.act("shunt"); + CHECK(loco.IncScndCtrl(1)); + CHECK(loco.ScndCtrlPos == 1); + scenario.wait(10.0); + CHECK(loco.Vel > speed); + CHECK(loco.ScndCtrlPos == 1); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + CHECK(loco.SpeedCtrlValue == 0.0); + scenario.act("shunt off"); + CHECK(loco.DecScndCtrl(2)); + CHECK(loco.ScndCtrlPos == 0); + scenario.wait(5.0); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + scenario.check(); + } + } + SUBCASE("SU45, by itself") { + scenario scenario{"speed control/shunting/su45_v2/301d", motion() + traction() + cruise()}; + scenario.add("su45_v2/301d", 1); + auto &loco{scenario.cab()}; + REQUIRE_FALSE(loco.SpeedCtrl); + REQUIRE(loco.AutoRelayFlag); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(5.0); + auto most{0}; + for (int i = 0; i < 18; ++i) { + scenario.wait(10.0); + most = std::max(most, loco.ScndCtrlPos); + } + CHECK(most == loco.ScndCtrlPosNo); + // the driver can't move it + CHECK_FALSE(loco.DecScndCtrl(2)); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + scenario.act("notch back"); + scenario.notch_back(0); + scenario.wait(5.0); + CHECK(loco.ScndCtrlPos == 0); + scenario.check(); + } +} + +TEST_CASE("speed control: the vehicles whose secondary controller is the cruise control's switch, as before") { + SUBCASE("Impuls: on at the speed of the moment, off by the controller") { + scenario scenario{"speed control/cruise/impuls_v1/31we-a_pr", motion() + traction() + cruise()}; + scenario.add("impuls_v1/31we-a_pr", 1).add("impuls_v1/31we-b_pr").add("impuls_v1/31we-c_pr").add("impuls_v1/31we-d_pr"); + auto &unit{scenario.cab()}; + REQUIRE(unit.SpeedCtrl); + REQUIRE(unit.ScndCtrlPosNo == 1); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(40.0); + scenario.act("cruise control on"); + CHECK(unit.IncScndCtrl(1)); + CHECK(unit.ScndCtrlPos == 1); + CHECK(unit.SpeedCtrlUnit.IsActive); + CHECK(unit.SpeedCtrlValue == doctest::Approx(unit.Vel)); + auto const held{unit.SpeedCtrlValue}; + scenario.wait(60.0); + CHECK(unit.Vel == doctest::Approx(held).epsilon(0.05)); + scenario.act("cruise control off"); + CHECK(unit.DecScndCtrl(2)); + CHECK(unit.ScndCtrlPos == 0); + CHECK_FALSE(unit.SpeedCtrlUnit.IsActive); + CHECK(unit.SpeedCtrlValue == 0.0); + scenario.wait(5.0); + scenario.check(); + } + SUBCASE("EU47: the speed raised by tens while the controller is held up, set when it's let go") { + scenario scenario{"speed control/cruise/e186_v2/eu47", motion() + traction() + cruise()}; + scenario.add("e186_v2/eu47", 1); + auto &loco{scenario.cab()}; + REQUIRE(loco.SpeedCtrl); + REQUIRE(loco.SpeedCtrlTypeTime); + REQUIRE(loco.ScndCtrlPosNo == 4); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.act("raise"); + while (loco.ScndCtrlPos < 3 && loco.IncScndCtrl(1)) { + // all the work is done in the condition + } + REQUIRE(loco.ScndCtrlPos == 3); + scenario.wait(10.0); + CHECK(loco.NewSpeed > 0.0); + scenario.act("set"); + CHECK(loco.DecScndCtrl(1)); + scenario.wait(1.0); + CHECK(loco.SpeedCtrlValue == doctest::Approx(loco.NewSpeed)); + CHECK(loco.SpeedCtrlUnit.IsActive); + scenario.full_power(60.0); + CHECK(loco.Vel == doctest::Approx(loco.SpeedCtrlValue).epsilon(0.1)); + scenario.act("off"); + CHECK(loco.DecScndCtrl(2)); + scenario.wait(1.0); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + scenario.check(); + } +} + +// the vehicles with both: the field shunting as before, the cruise control on a switch of its own + +TEST_CASE("speed control: the field shunting of the vehicles with a cruise control besides, as before") { + SUBCASE("6Dg") { + scenario scenario{"speed control/both/6dg_v1/6dg", motion() + traction() + cruise(), test::track{}}; + scenario.add("6dg_v1/6dg", 1); + auto &loco{scenario.cab()}; + REQUIRE(loco.SpeedCtrl); + REQUIRE(loco.AutoRelayFlag); + REQUIRE(loco.ScndCtrlPosNo == 1); + get_6dg_going(scenario); + scenario.act("raise"); + move_to(loco, dg_raise); + // the shunt engages by itself at about 40 km/h (RelayType 0, by the current of the motors) + scenario.wait(10.0); + CHECK(loco.Vel < 35.0); + CHECK(loco.ScndCtrlPos == 0); + scenario.wait(110.0); + CHECK(loco.Vel > 100.0); + CHECK(loco.ScndCtrlPos == 1); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + CHECK(loco.eimic_real == doctest::Approx(loco.eimic)); + // the driver can't move the shunt + CHECK_FALSE(loco.IncScndCtrl(1)); + CHECK_FALSE(loco.DecScndCtrl(2)); + scenario.check(); + } + SUBCASE("ST45") { + scenario scenario{"speed control/both/st45_v2/301dd", motion() + traction() + cruise(), test::track{}}; + scenario.add("st45_v2/301dd", 1); + auto &loco{scenario.cab()}; + REQUIRE(loco.SpeedCtrl); + REQUIRE(loco.AutoRelayFlag); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(5.0); + // its relays (RelayType 45) engage the shunt from position 11 of the controller on, which the universal + // controller of the ST45, of 4 positions, never gets to: the shunt stays off + auto most{0}; + for (int i = 0; i < 9; ++i) { + scenario.wait(10.0); + most = std::max(most, loco.ScndCtrlPos); + } + CHECK(loco.Vel > 130.0); + CHECK(most == 0); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + CHECK(loco.eimic_real == doctest::Approx(loco.eimic)); + // the speed buttons do nothing with the cruise control off + loco.SpeedCtrlButton(4); + loco.SpeedCtrlInc(); + CHECK(loco.SpeedCtrlValue == 0.0); + CHECK_FALSE(loco.IncScndCtrl(1)); + scenario.check(); + } +} + +TEST_CASE("speed control apart: which vehicles' cruise control has a switch of its own") { + struct kind { + char const *path; + bool separate; + }; + for (auto const &[path, separate] : { + // the secondary controller shunts the field: a switch of its own + kind{"6dg_v1/6dg", true}, kind{"st45_v2/301dd", true}, kind{"br285_v1/br285", true}, + // the secondary controller is the switch, the speed setter or the gears' selector of the automatic gearbox + kind{"21xm_v1/214ma", false}, kind{"21xm_v1/218ma_a_kd", false}, kind{"sa134_v1/218mc_a", false}, kind{"impuls_v1/31we-a_pr", false}, + kind{"elf_v1/21we-a", false}, kind{"e186_v2/eu47", false}, kind{"e6act_v2/e6acta", false}, kind{"en57akl_v1/akl_ra", false}, + // no cruise control + kind{"4e_v1/4e", false}, kind{"sm42_v1/6d1", false}, kind{"su45_v2/301d", false}, kind{"ep09_v2/104e", false}}) { + CAPTURE(path); + test::vehicle vehicle{test::definition::fiz(path)}; + CHECK(vehicle->IsSpeedCtrlSeparate() == separate); + CHECK_FALSE(vehicle->IsSpeedCtrlEngaged()); + } + // with a cruise control and no secondary controller, the switch is its own too + test::vehicle eu07{test::definition::fiz("4e_v1/4e").set("Cntrl", "SCPN", 0).set("SpeedControl", "SpeedCtrl", "Yes")}; + CHECK(eu07->IsSpeedCtrlSeparate()); +} + +namespace { + +// Seconds of the scenario going on, a second at a time, counting the seconds with the field shunted and not +void count_shunting(scenario &Scenario, TMoverParameters const &Vehicle, int const Seconds, int &Shunted, int &Unshunted) { + for (int second = 0; second < Seconds; ++second) { + Scenario.wait(1.0); + ++(Vehicle.ScndCtrlPos > 0 ? Shunted : Unshunted); + } +} + +} // namespace + +TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the field shunting going on by itself") { + scenario scenario{"speed control apart/6dg_v1/6dg", motion() + traction() + cruise(), test::track{}}; + scenario.add("6dg_v1/6dg", 1); + auto &loco{scenario.cab()}; + get_6dg_going(scenario); + scenario.act("raise"); + move_to(loco, dg_raise); + scenario.wait(30.0); + REQUIRE(loco.Vel > 50.0); + REQUIRE(loco.ScndCtrlPos == 1); // the shunt in + // the shunt is no cruise control: its buttons do nothing yet, the secondary controller can't switch it on + CHECK_FALSE(loco.IsSpeedCtrlEngaged()); + loco.SpeedCtrlButton(2); + CHECK(loco.SpeedCtrlValue == 0.0); + CHECK_FALSE(loco.IncScndCtrl(1)); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + + scenario.act("cruise control on"); + CHECK(loco.SpeedCtrlSwitch(true)); + CHECK_FALSE(loco.SpeedCtrlSwitch(true)); // on already + CHECK(loco.SpeedCtrlUnit.IsActive); + CHECK(loco.IsSpeedCtrlEngaged()); + CHECK(loco.SpeedCtrlValue == doctest::Approx(std::round(loco.Vel)).epsilon(0.02)); + CHECK(loco.ScndCtrlPos == 1); // the shunt as it was + auto const held{loco.SpeedCtrlValue}; + // the shunt goes by itself all the while, by the current of the motors, which the cruise control's demand sets + auto shunted{0}; + auto unshunted{0}; + count_shunting(scenario, loco, 60, shunted, unshunted); + CHECK(loco.Vel == doctest::Approx(held).epsilon(0.03)); + CHECK_FALSE(loco.SpeedCtrlUnit.Standby); + CHECK(loco.eimic_real < loco.eimic); // the cruise control holding the power back + + scenario.act("two steps up"); + loco.SpeedCtrlInc(); + loco.SpeedCtrlInc(); + auto const higher{loco.SpeedCtrlValue}; + CHECK(higher == doctest::Approx(held + 10.0).epsilon(0.1)); + count_shunting(scenario, loco, 60, shunted, unshunted); + CHECK(loco.Vel == doctest::Approx(higher).epsilon(0.03)); + CHECK(loco.StLinFlag); + CHECK(shunted > 0); + CHECK(unshunted > 0); + CHECK_FALSE(loco.IncScndCtrl(1)); // still not the driver's + + scenario.act("button 30"); + loco.SpeedCtrlButton(0); + CHECK(loco.SpeedCtrlValue == doctest::Approx(30.0)); + scenario.wait(60.0); + // it brakes down with the air (BrakeIntervention), which opens the line contactors (the pressure switch), and + // they close again only through the first power position of the controller, as without the cruise control + CHECK(loco.Vel < 35.0); + CHECK_FALSE(loco.StLinFlag); + scenario.act("controller to the first power position and back up"); + move_to(loco, dg_lower); + scenario.wait(2.0); + move_to(loco, dg_raise); + scenario.wait(60.0); + CHECK(loco.StLinFlag); + CHECK(loco.Vel == doctest::Approx(30.0).epsilon(0.05)); + CHECK(loco.ScndCtrlPos == 0); // out at this speed + + scenario.act("cruise control off"); + CHECK(loco.SpeedCtrlSwitch(false)); + CHECK_FALSE(loco.SpeedCtrlSwitch(false)); // off already + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + CHECK(loco.SpeedCtrlValue == 0.0); + scenario.wait(5.0); + CHECK(loco.eimic_real == doctest::Approx(loco.eimic)); // the controller's demand again + scenario.check(); +} + +TEST_CASE("speed control apart: the ST45's cruise control on its own switch, with its buttons and the power limit") { + scenario scenario{"speed control apart/st45_v2/301dd", motion() + traction() + cruise(), test::track{}}; + scenario.add("st45_v2/301dd", 1); + auto &loco{scenario.cab()}; + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(0.0); + REQUIRE(loco.Vel < 50.0); + scenario.act("cruise control on, button 60"); + CHECK(loco.SpeedCtrlSwitch(true)); + CHECK(loco.SpeedCtrlUnit.IsActive); + loco.SpeedCtrlButton(4); + CHECK(loco.SpeedCtrlValue == doctest::Approx(60.0)); + scenario.wait(90.0); + CHECK(loco.Vel == doctest::Approx(60.0).epsilon(0.03)); + CHECK(loco.StLinFlag); + scenario.act("step up, power down"); + loco.SpeedCtrlInc(); + CHECK(loco.SpeedCtrlValue == doctest::Approx(65.0)); + CHECK(loco.SpeedCtrlPowerDec()); + CHECK(loco.SpeedCtrlUnit.DesiredPower == doctest::Approx(0.9)); + scenario.wait(60.0); + CHECK(loco.Vel == doctest::Approx(65.0).epsilon(0.03)); + CHECK(loco.eimic_real <= 0.9 + 1e-9); + scenario.act("cruise control off"); + CHECK(loco.SpeedCtrlSwitch(false)); + // off, its buttons do nothing + loco.SpeedCtrlButton(6); + loco.SpeedCtrlInc(); + CHECK_FALSE(loco.SpeedCtrlPowerInc()); + CHECK(loco.SpeedCtrlValue == 0.0); + scenario.wait(5.0); + CHECK(loco.ScndCtrlPos == 0); + scenario.check(); +} + +TEST_CASE("speed control apart: the switch of a cruise control without one of its own is the secondary controller, as before") { + // the 214M railbus: on, its first position; off, back to zero + scenario scenario{"speed control apart/21xm_v1/214ma", motion() + traction() + cruise(), test::track{}}; + scenario.add("21xm_v1/214ma", 1); + auto &railbus{scenario.cab()}; + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(20.0); + scenario.act("cruise control on"); + CHECK(railbus.SpeedCtrlSwitch(true)); + CHECK(railbus.ScndCtrlPos == 1); + CHECK(railbus.SpeedCtrlUnit.IsActive); + CHECK(railbus.IsSpeedCtrlEngaged()); + scenario.wait(10.0); + scenario.act("cruise control off"); + CHECK(railbus.SpeedCtrlSwitch(false)); + CHECK(railbus.ScndCtrlPos == 0); + CHECK_FALSE(railbus.SpeedCtrlUnit.IsActive); + CHECK_FALSE(railbus.IsSpeedCtrlEngaged()); + scenario.wait(5.0); + scenario.check(); +} diff --git a/tests/unit/test_start_sample.cpp b/tests/unit/test_start_sample.cpp new file mode 100644 index 000000000..00e7fc781 --- /dev/null +++ b/tests/unit/test_start_sample.cpp @@ -0,0 +1,34 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "audio/startsample.h" + +#include + +// the sample a sound with a start offset (startoffset:, or the random one of motors, motor blowers and +// the running noise) begins to play from, in the 16 bit mono buffers the sound files are loaded into + +TEST_CASE("start_sample: a fraction of the samples of the buffer, two bytes each") { + CHECK(audio::start_sample(0.5f, 1000) == 250); + CHECK(audio::start_sample(0.25f, 88200) == 11025); + CHECK(audio::start_sample(0.999f, 1000) == 499); +} + +TEST_CASE("start_sample: no offset starts at the first sample") { + CHECK(audio::start_sample(0.f, 1000) == 0); + CHECK(audio::start_sample(-0.5f, 1000) == 0); + CHECK(audio::start_sample(std::numeric_limits::quiet_NaN(), 1000) == 0); +} + +TEST_CASE("start_sample: the end of the buffer is its last sample, not past it") { + // OpenAL takes an offset at or past the end of the buffer for AL_INVALID_VALUE + CHECK(audio::start_sample(1.f, 1000) == 499); + CHECK(audio::start_sample(1.5f, 1000) == 499); + CHECK(audio::start_sample(1.f, 2) == 0); +} + +TEST_CASE("start_sample: a buffer of unknown or no size starts at 0") { + CHECK(audio::start_sample(0.5f, 0) == 0); + CHECK(audio::start_sample(0.5f, 1) == 0); + CHECK(audio::start_sample(0.5f, -4) == 0); +} diff --git a/tests/unit/test_station_names.cpp b/tests/unit/test_station_names.cpp new file mode 100644 index 000000000..0bcc7953a --- /dev/null +++ b/tests/unit/test_station_names.cpp @@ -0,0 +1,295 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "utilities/utilities.h" +#include "world/stationnames.h" +#include "world/timetablereader.h" + +#include +#include +#include + +// the names of the stations (MaSzyna-EU07/maszyna#94): the timetable keeps a name as its file spells it, with its polish +// letters, for showing; the W4 stop points of the scenery, spelled in their own files, still find their station whatever +// the spelling; the form the announcement files, the scenery events and the scripts get stays the ascii one. +// the texts are windows-1250, written as bytes: the build reads the sources in any code page + +using timetable::same_station; +using timetable::station_ascii; +using timetable::station_caption; +using timetable::station_key; +using timetable::stop_point_is_for; + +namespace { + +// Biała_Podlaska, Łódź_Żabieniec, Częstochowa_Osobowa in windows-1250 +std::string const biala{"Bia\xB3" "a_Podlaska"}; +std::string const lodz{"\xA3\xF3" "d\x9F_\xAF" "abieniec"}; +std::string const czestochowa{"Cz\xEAstochowa_Osobowa"}; +// the 18 polish letters in windows-1250, as in test_win1250.cpp +std::string const letters1250{"\xA5\xC6\xCA\xA3\xD1\xD3\x8C\x8F\xAF\xB9\xE6\xEA\xB3\xF1\xF3\x9C\x9F\xBF"}; + +// a timetable with polish letters in the relation and in the names of the stations +std::string const timetable_text{ + " ___________________________________________________________________\n" + "[ Rodzaj i numer pociagu | Os1234 ]\n" + "[ Kategoria | Os ]\n" + "[________________________________________________|__________________]\n" + "[ | Bia\xB3" "a_Podlaska ]\n" + "[ Relacja pociagu | \xA3\xF3" "d\x9F_\xAF" "abieniec ]\n" + "[________________________________________________|__________________]\n" + "[ Wymagany % ciezaru hamujacego | 60% ]\n" + "[________________________________________________|__________________]\n" + "[ Seria i obciazenie lokomotywy | EN57 120 ]\n" + "[________________________________________________|__________________]\n" + "[ 1.13 | 60 | Bia\xB3" "a_Podlaska 1 | | ]\n" + "[ | | R2,H 1 12.47 | ]\n" + "[ | |----------------------------------1---------|--------]\n" + "[ 5.06 |_____| Cz\xEAstochowa_Osobowa 1 12.54 | 7 ]\n" + "[ | 40 | po 1 12.55 | ]\n" + "[ | |----------------------------------1---------|--------]\n" + "[ 9.16 | | \xA3\xF3" "d\x9F_\xAF" "abieniec 2 13.01 | 6 ]\n" + "[ | | R3 2 | | ]\n" + "[_______|_____|__________________________________2_________|________]\n"}; + +Mtable::timetable_data read(std::string const &Text) { + std::istringstream input{Text}; + Mtable::timetable_data data; + data.TrainName = "file"; + REQUIRE(Mtable::read_timetable(input, data) == 0); + return data; +} + +// the text of a W4 as the driver gets it: a putvalues event cuts what follows # when the scenery is read +// (putvalues_event::deserialize_), a memory cell keeps the whole of its text +std::string text_seen(std::string Text, bool const Event) { + if (auto const hash{Text.find('#')}; Event && hash != std::string::npos) { + Text.erase(hash); + } + return Text; +} + +// the comparison of a W4 text with the next stop of the timetable as TController::TableUpdateStopPoint() made it before +// the names kept their letters: the text of a putvalues event lost its polish letters too when the scenery was read; +// 32 is the sizeof( std::string ) the code had for the length +bool matched_before(std::string const &Text, bool const Event, std::string const &Nextstop) { + auto text{text_seen(Text, Event)}; + if (Event) { + win1250_to_ascii(text); + } + return ToLower(text).compare(19, 32, ToLower(Nextstop)) == 0; +} + +bool matched_now(std::string const &Text, bool const Event, std::string const &Nextstop) { + return stop_point_is_for(text_seen(Text, Event), Nextstop); +} + +} // namespace + +TEST_CASE("station names: the ascii form takes the marks off the polish letters and nothing else") { + CHECK(station_ascii(biala) == "Biala_Podlaska"); + CHECK(station_ascii(lodz) == "Lodz_Zabieniec"); + CHECK(station_ascii(czestochowa) == "Czestochowa_Osobowa"); + CHECK(station_ascii(letters1250) == "ACELNOSZZacelnoszz"); + // a name without them stays, the case, the underscores and the spaces included + CHECK(station_ascii("Warszawa_Zachodnia") == "Warszawa_Zachodnia"); + CHECK(station_ascii("Nowy Targ") == "Nowy Targ"); + // what win1250_to_ascii() always made of a name: letters of other languages stay as they are + auto ostrava{std::string{"Ostrava_hl.n\xE1" "dra\x9E\xED"}}; + auto const expected{ostrava}; + CHECK(station_ascii(ostrava) == expected); + win1250_to_ascii(ostrava); + CHECK(ostrava == expected); +} + +TEST_CASE("station names: the file names of a station come from the ascii form, as before") { + // the announcement of a stop is /.ogg or sounds/sip/.ogg, of the name the timetable entry has + // as StationName; the files have no polish letters in their names + auto const data{read(timetable_text)}; + CHECK(data.TimeTable[2].StationName + ".ogg" == "Czestochowa_Osobowa.ogg"); + CHECK(data.TimeTable[3].StationName + ".ogg" == "Lodz_Zabieniec.ogg"); + // the destination board is looked up by the last station of the relation, through Bezogonkow() + CHECK(Bezogonkow(data.Relation2) == "Lodz_Zabieniec"); +} + +TEST_CASE("station names: a timetable with polish letters keeps them for showing") { + auto const data{read(timetable_text)}; + REQUIRE(data.StationCount == 3); + // as written + CHECK(data.RelationLabel1 == biala); + CHECK(data.RelationLabel2 == lodz); + CHECK(data.TimeTable[1].StationLabel == biala); + CHECK(data.TimeTable[2].StationLabel == czestochowa); + CHECK(data.TimeTable[3].StationLabel == lodz); + // what the player sees: utf-8, spaces for the underscores + CHECK(station_caption(data.TimeTable[1].StationLabel) == "Bia\xC5\x82" "a Podlaska"); + CHECK(station_caption(data.TimeTable[2].StationLabel) == "Cz\xC4\x99stochowa Osobowa"); + CHECK(station_caption(data.TimeTable[3].StationLabel) == "\xC5\x81\xC3\xB3" "d\xC5\xBA \xC5\xBB" "abieniec"); + CHECK(station_caption(data.RelationLabel2) == "\xC5\x81\xC3\xB3" "d\xC5\xBA \xC5\xBB" "abieniec"); + // the rest of the row reads as it did + CHECK(data.TimeTable[2].StationWare == "po"); + CHECK(data.TimeTable[2].Ah == 12); + CHECK(data.TimeTable[3].TrackNo == 2); +} + +TEST_CASE("station names: the name a timetable is matched and handed over by stays the ascii one") { + auto const data{read(timetable_text)}; + // TMTableEntry::StationName and the relation: what the W4 comparison, the announcement files, the scenery events + // (WhoIs) and the python screens get + CHECK(data.Relation1 == "Biala_Podlaska"); + CHECK(data.Relation2 == "Lodz_Zabieniec"); + CHECK(data.TimeTable[1].StationName == "Biala_Podlaska"); + CHECK(data.TimeTable[2].StationName == "Czestochowa_Osobowa"); + CHECK(data.TimeTable[3].StationName == "Lodz_Zabieniec"); + // the first station is still told to be the start of the relation by the two names being the same + CHECK(data.TimeTable[1].StationName == data.Relation1); +} + +TEST_CASE("station names: a timetable without polish letters has the same name in both forms") { + auto const plain{station_ascii(timetable_text)}; + auto const data{read(plain)}; + REQUIRE(data.StationCount == 3); + CHECK(data.RelationLabel1 == data.Relation1); + CHECK(data.RelationLabel2 == data.Relation2); + for (auto i{1}; i <= data.StationCount; ++i) { + CAPTURE(i); + CHECK(data.TimeTable[i].StationLabel == data.TimeTable[i].StationName); + } + // and reads the same as the one with the letters, but for the labels + auto const lettered{read(timetable_text)}; + for (auto i{0}; i <= data.StationCount; ++i) { + CAPTURE(i); + CHECK(data.TimeTable[i].StationName == lettered.TimeTable[i].StationName); + CHECK(data.TimeTable[i].Dh == lettered.TimeTable[i].Dh); + CHECK(data.TimeTable[i].Dm == lettered.TimeTable[i].Dm); + } + // the entry before the first station is the technical one in both forms + CHECK(data.TimeTable[0].StationName == "nowhere"); + CHECK(data.TimeTable[0].StationLabel == "nowhere"); +} + +TEST_CASE("station names: two spellings of a station have one key") { + // with and without the letters + CHECK(same_station(biala, "Biala_Podlaska")); + CHECK(same_station("Biala_Podlaska", biala)); + CHECK(same_station(lodz, "Lodz_Zabieniec")); + // some of the letters only (linia 107 has the W4 of Rzepedz spelled so) + CHECK(same_station("Rzep\xEA" "d\x9F", "Rzeped\x9F")); + // in any case, the letters with marks included (baltyk has BALTYK_GLOWNY in capitals in a timetable) + CHECK(same_station("BA\xA3TYK_G\xA3\xD3WNY", "Ba\xB3tyk_G\xB3\xF3wny")); + CHECK(same_station("BA\xA3TYK_G\xA3\xD3WNY", "baltyk_glowny")); + CHECK(same_station("ZAG\xD3RZ", "Zag\xF3rz")); + // with spaces or underscores + CHECK(same_station("Bia\xB3" "a Podlaska", biala)); + CHECK(same_station("Biala Podlaska", biala)); + CHECK(same_station("Biala Podlaska", "biala_podlaska")); + // the key itself + CHECK(station_key(biala) == "biala_podlaska"); + CHECK(station_key("Bia\xB3" "a Podlaska") == "biala_podlaska"); + CHECK(station_key(letters1250) == "acelnoszzacelnoszz"); + CHECK(station_key("").empty()); +} + +TEST_CASE("station names: different stations have different keys") { + CHECK_FALSE(same_station(biala, "Biala")); + CHECK_FALSE(same_station("Biala_Podlaska", "Biala_Podlaska_po")); + CHECK_FALSE(same_station("Lodz_Zabieniec", "Lodz_Kaliska")); + CHECK_FALSE(same_station("Gorna", "Dolna")); + CHECK_FALSE(same_station("Gorna", "")); + // no other separator stands for a space + CHECK_FALSE(same_station("Biala-Podlaska", "Biala_Podlaska")); + CHECK_FALSE(same_station("BialaPodlaska", "Biala_Podlaska")); + // letters of other languages aren't folded, as they never were + CHECK_FALSE(same_station("Ostrava_hl.n\xE1" "dra\x9E\xED", "Ostrava_hl.nadrazi")); + CHECK(same_station("Ostrava_hl.n\xE1" "dra\x9E\xED", "ostrava_hl.n\xE1" "dra\x9E\xED")); +} + +TEST_CASE("station names: a W4 finds the station of the timetable whatever the two spellings") { + auto const data{read(timetable_text)}; + // the next stop of the driver is the StationName of the entry + auto const &nextstop{data.TimeTable[1].StationName}; + // the W4 spelled with the letters, without them, in another case, with a space + CHECK(stop_point_is_for("PassengerStopPoint:" + biala, nextstop)); + CHECK(stop_point_is_for("PassengerStopPoint:Biala_Podlaska", nextstop)); + CHECK(stop_point_is_for("PassengerStopPoint:BIA\xA3" "A_PODLASKA", nextstop)); + CHECK(stop_point_is_for("PassengerStopPoint:biala_podlaska", nextstop)); + CHECK(stop_point_is_for("PassengerStopPoint:Bia\xB3" "a Podlaska", nextstop)); + CHECK(stop_point_is_for("PassengerStopPoint:Biala Podlaska", nextstop)); + // the usual W4 of a scenery, with the part which makes its event unique: the event cuts it as it's read + CHECK(matched_now("PassengerStopPoint:" + biala + "#W4-P1-T2-1", true, nextstop)); + CHECK(matched_now("PassengerStopPoint:Biala_Podlaska#W4-1", true, nextstop)); + // and the other way round: the timetable name as written against a W4 without the letters + CHECK(stop_point_is_for("PassengerStopPoint:Biala_Podlaska", data.TimeTable[1].StationLabel)); + CHECK(stop_point_is_for("PassengerStopPoint:Lodz_Zabieniec", data.TimeTable[3].StationLabel)); + // another station, a text which isn't a W4 one + CHECK_FALSE(stop_point_is_for("PassengerStopPoint:Biala", nextstop)); + CHECK_FALSE(stop_point_is_for("PassengerStopPoint:Biala_Podlaska_po", nextstop)); + CHECK_FALSE(stop_point_is_for("PassengerStopPoint:" + lodz, nextstop)); + CHECK_FALSE(stop_point_is_for("Biala_Podlaska", nextstop)); + CHECK_FALSE(stop_point_is_for("passengerstoppoint:Biala_Podlaska", nextstop)); + CHECK_FALSE(stop_point_is_for("SetVelocity", nextstop)); + CHECK_FALSE(stop_point_is_for("", nextstop)); + // a memory cell keeps what follows the #: as before, it is a W4 only of a station which has that in its name + CHECK_FALSE(matched_now("PassengerStopPoint:Biala_Podlaska#W4-1", false, nextstop)); + CHECK(matched_now("PassengerStopPoint:Gorna#1", false, "Gorna#1")); + CHECK_FALSE(matched_now("PassengerStopPoint:Gorna", false, "Gorna#1")); + // a W4 without a name is for the end of the timetable, where the next stop has none either + CHECK(stop_point_is_for("PassengerStopPoint:", "")); + CHECK_FALSE(stop_point_is_for("PassengerStopPoint:", nextstop)); + CHECK_FALSE(stop_point_is_for("PassengerStopPoint:Biala_Podlaska", "")); +} + +TEST_CASE("station names: every W4 the driver matched before is matched now") { + // the next stops as the timetable gives them (ascii), and the special ones the driver has when there's no station + std::vector const nextstops{"Biala_Podlaska", "Lodz_Zabieniec", "Czestochowa_Osobowa", "BALTYK_GLOWNY", "Gorna", "Gorna#1", "Rzepedz", "", "nowhere", "[End of route]", + "Ostrava_hl.n\xE1" "dra\x9E\xED"}; + std::vector const names{biala, "Biala_Podlaska", "biala_podlaska", "BIA\xA3" "A_PODLASKA", "Bia\xB3" "a Podlaska", lodz, "Lodz_Zabieniec", czestochowa, + "Ba\xB3tyk_G\xB3\xF3wny", "Rzeped\x9F", "Rzep\xEA" "d\x9F", "Gorna", "Gorna#1", "Dolna", "", "nowhere", "Ostrava_hl.n\xE1" "dra\x9E\xED", + "Ostrava_hl.nadrazi", "Biala", "Biala_Podlaska_po"}; + auto matches{0}; + auto gained{0}; + for (auto const &nextstop : nextstops) { + for (auto const &name : names) { + for (auto const *suffix : {"", "#W4-1"}) { + auto const text{"PassengerStopPoint:" + name + suffix}; + for (auto const event : {true, false}) { + CAPTURE(nextstop); + CAPTURE(text); + CAPTURE(event); + auto const before{matched_before(text, event, nextstop)}; + auto const now{matched_now(text, event, nextstop)}; + // nothing is lost + CHECK((false == before || now)); + // and nothing changes for the spellings the comparison never told apart: a name without polish letters + // and without spaces + if (name == station_ascii(name) && name.find(' ') == std::string::npos) { + CHECK(before == now); + } + matches += (now ? 1 : 0); + gained += (now && false == before ? 1 : 0); + } + } + } + } + CHECK(matches > 0); + // what is new: a memory cell spelled with the polish letters, a space for an underscore + CHECK(gained > 0); + CHECK(matched_now("PassengerStopPoint:" + biala, false, "Biala_Podlaska")); + CHECK_FALSE(matched_before("PassengerStopPoint:" + biala, false, "Biala_Podlaska")); + CHECK(matched_now("PassengerStopPoint:Biala Podlaska", true, "Biala_Podlaska")); + CHECK_FALSE(matched_before("PassengerStopPoint:Biala Podlaska", true, "Biala_Podlaska")); + // and a name longer than the 32 characters the old comparison took of it + std::string const longname{"Bardzo_Dluga_Nazwa_Stacji_Wezlowej_Osobowej"}; + CHECK(matched_now("PassengerStopPoint:" + longname, true, longname)); + CHECK_FALSE(matched_before("PassengerStopPoint:" + longname, true, longname)); +} + +TEST_CASE("station names: the caption of a station is its name as written, in utf-8, with spaces") { + CHECK(station_caption(biala) == "Bia\xC5\x82" "a Podlaska"); + CHECK(station_caption(lodz) == "\xC5\x81\xC3\xB3" "d\xC5\xBA \xC5\xBB" "abieniec"); + CHECK(station_caption("Warszawa_Zachodnia") == "Warszawa Zachodnia"); + CHECK(station_caption("[End of route]") == "[End of route]"); + CHECK(station_caption("").empty()); + // a name already in utf-8 stays + CHECK(station_caption("Bia\xC5\x82" "a_Podlaska") == "Bia\xC5\x82" "a Podlaska"); +} diff --git a/tests/unit/test_timetable.cpp b/tests/unit/test_timetable.cpp new file mode 100644 index 000000000..a41aafcce --- /dev/null +++ b/tests/unit/test_timetable.cpp @@ -0,0 +1,339 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +#include "McZapkie/MOVER.h" +#include "utilities/utilities.h" +#include "vehicle/timetableservice.h" +#include "world/timetablereader.h" + +#include +#include +#include +#include +#include + +// the timetables of the trains (.txt next to the scenery, world/timetablereader.cpp) and the service flags they +// give the AI driver (eu07/maszyna#95): the reader as it was, the flags of the header and of the stations, and what +// the driver does with them + +using timetable::service_flags; +using timetable::tristate; + +namespace { + +// a timetable the way the game's sceneries have them: the header, three stations, a speed change at the second one +std::string const timetable_text{ + " ___________________________________________________________________\n" + "[ Rodzaj i numer pociagu | Os1234 ]\n" + "[ Kategoria | Os ]\n" + "%FLAGS%" + "[________________________________________________|__________________]\n" + "[ | Gorna ]\n" + "[ Relacja pociagu | Dolna ]\n" + "[________________________________________________|__________________]\n" + "[ Wymagany % ciezaru hamujacego | 60% ]\n" + "[________________________________________________|__________________]\n" + "[ Seria i obciazenie lokomotywy | EN57 120 ]\n" + "[________________________________________________|__________________]\n" + "[ 1.13 | 60 | Gorna 1 | | ]\n" + "[ | | %WARE1% 1 12.47 | ]\n" + "[ | |----------------------------------1---------|--------]\n" + "[ 5.06 |_____| Srodkowa 1 12.54 | 7 ]\n" + "[ | 40 | %WARE2% 1 12.55 | ]\n" + "[ | |----------------------------------1---------|--------]\n" + "[ 9.16 | | Dolna 2 13.01 | 6 ]\n" + "[ | | %WARE3% 2 | | ]\n" + "[_______|_____|__________________________________2_________|________]\n"}; + +std::string replaced(std::string Text, std::string const &Key, std::string const &Value) { + for (auto at{Text.find(Key)}; at != std::string::npos; at = Text.find(Key, at + Value.size())) { + Text.replace(at, Key.size(), Value); + } + return Text; +} + +std::string timetable_with(std::string const &Flags, std::string const &Ware1, std::string const &Ware2, std::string const &Ware3) { + return replaced(replaced(replaced(replaced(timetable_text, "%FLAGS%", Flags), "%WARE1%", Ware1), "%WARE2%", Ware2), "%WARE3%", Ware3); +} + +struct read_result { + int error; + Mtable::timetable_data data; +}; + +read_result read(std::string const &Text) { + std::istringstream input{Text}; + read_result result; + result.data.TrainName = "file"; + result.error = Mtable::read_timetable(input, result.data); + return result; +} + +service_flags flags(tristate const Doors, tristate const Doorstep, tristate const Conductor, tristate const Braketest) { + return {Doors, Doorstep, Conductor, Braketest}; +} + +auto const unset{tristate::unset}; +auto const yes{tristate::yes}; +auto const no{tristate::no}; + +// what the timetable gives, but for the service flags: to compare a timetable with flags to one without +std::string contents(Mtable::timetable_data const &Data) { + auto text{std::format("{}|{}|{}|{}|{}|{}|{}|{}|{}\n", Data.TrainName, Data.TrainCategory, Data.TrainLabel, Data.Relation1, Data.Relation2, Data.BrakeRatio, + Data.LocSeries, Data.LocLoad, Data.StationCount)}; + for (auto i{0}; i <= Data.StationCount; ++i) { + auto const &row{Data.TimeTable[i]}; + text += std::format("{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}\n", i, row.km, row.vmax, row.StationName, row.StationWare, row.TrackNo, row.Ah, row.Am, row.Dh, row.Dm, + row.tm, row.is_maintenance, row.radio_channel); + } + return text; +} + +std::string flags_text(service_flags const &Flags) { + auto const one{[](tristate const Flag) { return Flag == tristate::unset ? '-' : Flag == tristate::yes ? 'y' : 'n'; }}; + return {one(Flags.central_doors), one(Flags.doorstep), one(Flags.conductor), one(Flags.brake_test)}; +} + +} // namespace + +TEST_CASE("timetable: the reader reads a timetable the way it always did") { + auto const [error, data]{read(timetable_with("", "R2,H", "po", "R3"))}; + + CHECK(error == 0); + CHECK(data.TrainName == "Os1234"); + CHECK(data.TrainCategory == "Os"); + CHECK(data.Relation1 == "Gorna"); + CHECK(data.Relation2 == "Dolna"); + CHECK(data.BrakeRatio == 60.0); + CHECK(data.LocSeries == "EN57"); + CHECK(data.LocLoad == 120.0); + REQUIRE(data.StationCount == 3); + + auto const &first{data.TimeTable[1]}; + CHECK(first.StationName == "Gorna"); + CHECK(first.km == doctest::Approx(1.13)); + CHECK(first.Ah == -1); // no arrival: LoadTTfile makes it a stop, the first station being the start of the relation + CHECK(first.Dh == 12); + CHECK(first.Dm == 47.f); + CHECK(first.StationWare == "R2,H"); + CHECK(first.radio_channel == 2); + + auto const &second{data.TimeTable[2]}; + CHECK(second.StationName == "Srodkowa"); + CHECK(second.Ah == 12); + CHECK(second.Am == 54.f); + CHECK(second.Dm == 55.f); + CHECK(second.tm == 7.f); + CHECK(second.StationWare == "po"); + CHECK(second.radio_channel == -1); + + auto const &last{data.TimeTable[3]}; + CHECK(last.StationName == "Dolna"); + CHECK(last.TrackNo == 2); + CHECK(last.Ah == 13); + CHECK(last.Dh == 13); // departure as the arrival, for the delay + CHECK(last.radio_channel == 3); + // 60 km/h up to the change at the second station, 40 km/h after it + CHECK(data.TimeTable[1].vmax == 60.f); + CHECK(data.TimeTable[2].vmax == 60.f); + CHECK(data.TimeTable[3].vmax == 40.f); + // a timetable without flags leaves all of them to the vehicles + CHECK(data.Flags.empty()); + for (auto i{0}; i <= data.StationCount; ++i) { + CHECK(data.TimeTable[i].flags.empty()); + } +} + +TEST_CASE("timetable: the row Flagi of the header sets the flags of the whole train") { + auto const [error, data]{read(timetable_with("[ Flagi AI | kierownik=nie, proba_hamulca=nie ]\n", "R2,H", "po", "R3"))}; + + CHECK(error == 0); + CHECK(data.Flags == flags(unset, unset, no, no)); + // every station has them + for (auto i{0}; i <= data.StationCount; ++i) { + CAPTURE(i); + CHECK(data.TimeTable[i].flags == data.Flags); + } + // and the rest of the header reads as before + CHECK(data.TrainName == "Os1234"); + CHECK(data.TrainCategory == "Os"); + CHECK(data.Relation1 == "Gorna"); + CHECK(data.StationCount == 3); +} + +TEST_CASE("timetable: a station's flags hold from that station on") { + auto const [error, data]{read(timetable_with("[ Flagi AI | proba_hamulca=nie ]\n", "R2,H", "po,stopien=nie,drzwi_centralne=tak", "R3,stopien=tak"))}; + + CHECK(error == 0); + CHECK(data.TimeTable[1].flags == flags(unset, unset, unset, no)); + CHECK(data.TimeTable[2].flags == flags(yes, no, unset, no)); + CHECK(data.TimeTable[3].flags == flags(yes, yes, unset, no)); + // the flags are taken out of the station ware, the rest of it stays + CHECK(data.TimeTable[2].StationWare == "po"); + CHECK(data.TimeTable[3].StationWare == "R3"); + CHECK(data.TimeTable[3].radio_channel == 3); +} + +TEST_CASE("timetable: the flags change nothing else the timetable gives") { + auto const plain{read(timetable_with("", "R2,H", "po", "R3"))}; + auto const flagged{read(timetable_with("[ Flagi AI | kierownik=nie ]\n", "kierownik=tak,R2,H", "po,drzwi_centralne=tak", "R3,stopien=nie,proba_hamulca=nie"))}; + + CHECK(flagged.error == plain.error); + CHECK(contents(flagged.data) == contents(plain.data)); +} + +TEST_CASE("timetable: entries which aren't flags stay in the station ware") { + service_flags read_flags; + SUBCASE("no flags: the list as it was, empty entries too") { + CHECK(timetable::extract_flags("po,,R2", read_flags) == "po,,R2"); + CHECK(timetable::extract_flags("", read_flags).empty()); + CHECK(read_flags.empty()); + } + SUBCASE("an unknown key stays, a known one with an unknown value is dropped") { + CHECK(timetable::extract_flags("po,foo=1,kierownik=moze,R2", read_flags) == "po,foo=1,R2"); + CHECK(read_flags.empty()); + } + SUBCASE("keys and values in either case, 1 and 0 for tak and nie") { + CHECK(timetable::extract_flags("Kierownik=NIE,STOPIEN=1,ph", read_flags) == "ph"); + CHECK(read_flags == flags(unset, yes, no, unset)); + } +} + +TEST_CASE("timetable: a truncated timetable is an error, not a hang") { + auto const text{timetable_with("", "R2,H", "po", "R3")}; + // cut in the middle of a station, in the middle of the header, right after the top line: the reader used to go + // on reading past the end of the file forever + for (auto const cut : {text.find("Srodkowa"), text.find("Wymagany"), text.find("Rodzaj")}) { + CAPTURE(cut); + auto const [error, data]{read(text.substr(0, cut))}; + CHECK(error == Mtable::timetable_truncated); + } + // cut between two stations: the row the reader expects isn't there + auto const [error, data]{read(text.substr(0, text.find("[ 9.16")))}; + CHECK(error == -4); + CHECK(data.StationCount == 3); +} + +TEST_CASE("timetable: a timetable longer than the table is an error") { + auto const text{timetable_with("", "R2,H", "po", "R3")}; + auto const begin{text.find("[ 5.06")}; + auto const end{text.find("[ 9.16")}; + auto const station{text.substr(begin, end - begin)}; + std::string stations; + for (auto i{0}; i < Mtable::MaxTTableSize; ++i) { + stations += station; + } + auto const [error, data]{read(text.substr(0, begin) + stations + text.substr(end))}; + CHECK(error == Mtable::timetable_too_long); + CHECK(data.StationCount == Mtable::MaxTTableSize); +} + +TEST_CASE("timetable: the reader starts from an empty table, whatever the data held before") { + auto const text{timetable_with("", "R2,H", "po", "R3")}; + auto const [error, fresh]{read(text)}; + REQUIRE(error == 0); + // a count past the table, a negative one, a stale one: the reader used to go on from it and index out of the table + for (auto const count : {Mtable::MaxTTableSize, Mtable::MaxTTableSize + 7, -3, 2}) { + CAPTURE(count); + std::istringstream input{text}; + Mtable::timetable_data data; + data.TrainName = "file"; + data.StationCount = count; + data.TimeTable[fresh.StationCount + 1].StationName = "stale"; + CHECK(Mtable::read_timetable(input, data) == 0); + CHECK(contents(data) == contents(fresh)); + CHECK(data.TimeTable[fresh.StationCount + 1].StationName == "nowhere"); + } +} + +TEST_CASE("timetable: the entry whose flags hold at the stop and on the way") { + // before the timetable is loaded, and with none + CHECK(timetable::stop_flags_entry(0, 0) == 0); + CHECK(timetable::run_flags_entry(0, 0) == 0); + CHECK(timetable::run_flags_entry(1, 0) == 0); + // making for (or standing at) the first station: its flags at the stop, the header's on the way + CHECK(timetable::stop_flags_entry(1, 3) == 1); + CHECK(timetable::run_flags_entry(1, 3) == 0); + // after the departure from the second station + CHECK(timetable::stop_flags_entry(3, 3) == 3); + CHECK(timetable::run_flags_entry(3, 3) == 2); + // past the end of the timetable + CHECK(timetable::stop_flags_entry(4, 3) == 3); + CHECK(timetable::run_flags_entry(5, 3) == 3); +} + +TEST_CASE("timetable: the AI opens the doors from the cab as the vehicle and the timetable say") { + test::vehicle unit{test::definition::load("wagon")}; + auto const central{flags(yes, unset, unset, unset)}; + auto const notcentral{flags(no, unset, unset, unset)}; + + unit->Doors.open_control = control_t::driver; + CHECK(timetable::opens_doors(unit.mover(), {})); + CHECK(timetable::opens_doors(unit.mover(), notcentral)); // the driver's doors open only from the cab + unit->Doors.open_control = control_t::conductor; + CHECK(timetable::opens_doors(unit.mover(), {})); + // doors of mixed control are left to the passengers, unless the timetable has the driver open them all + unit->Doors.open_control = control_t::mixed; + CHECK_FALSE(timetable::opens_doors(unit.mover(), {})); + CHECK_FALSE(timetable::opens_doors(unit.mover(), notcentral)); + CHECK(timetable::opens_doors(unit.mover(), central)); + // the passengers' own doors and the automatic ones can't be opened from the cab + unit->Doors.open_control = control_t::passenger; + CHECK_FALSE(timetable::opens_doors(unit.mover(), central)); + unit->Doors.open_control = control_t::autonomous; + CHECK_FALSE(timetable::opens_doors(unit.mover(), central)); +} + +TEST_CASE("timetable: the doorsteps, the conductor and the brake test as the timetable says") { + // no flags: the doorsteps as they are, the conductor and the brake test as before + CHECK_FALSE(timetable::doorstep({}).has_value()); + CHECK(timetable::has_conductor({})); + CHECK(timetable::makes_brake_test({})); + + CHECK(timetable::doorstep(flags(unset, no, unset, unset)) == false); + CHECK(timetable::doorstep(flags(unset, yes, unset, unset)) == true); + CHECK_FALSE(timetable::has_conductor(flags(unset, unset, no, unset))); + CHECK(timetable::has_conductor(flags(unset, unset, yes, unset))); + CHECK_FALSE(timetable::makes_brake_test(flags(unset, unset, unset, no))); + CHECK(timetable::makes_brake_test(flags(unset, unset, unset, yes))); +} + +// reads every .txt file under the folder given in EU07_UNIT_TESTS_TIMETABLES (the scenery/ of the game), the way the +// game reads a timetable, and checks none of them has flags; EU07_UNIT_TESTS_TIMETABLES_DUMP names a file to write +// what was read to, to compare the reading of two builds +TEST_CASE("timetable: the timetables of the game, when asked for") { + auto const *source{std::getenv("EU07_UNIT_TESTS_TIMETABLES")}; + if (source == nullptr) { + return; + } + std::vector files; + for (auto const &entry : std::filesystem::recursive_directory_iterator{source}) { + if (entry.is_regular_file() && ToLower(entry.path().extension().string()) == ".txt") { + files.push_back(entry.path()); + } + } + std::ranges::sort(files); + std::string dump; + auto timetables{0}; + for (auto const &file : files) { + auto const name{std::filesystem::relative(file, source).generic_string()}; + CAPTURE(name); + std::ifstream input{file}; + Mtable::timetable_data data; + data.TrainName = file.stem().string(); + auto const error{Mtable::read_timetable(input, data)}; + if (error == 0 && data.StationCount > 0) { + ++timetables; + } + CHECK(data.Flags.empty()); + for (auto i{0}; i <= data.StationCount; ++i) { + CHECK(data.TimeTable[i].flags.empty()); + } + dump += std::format("== {} error {}\n", name, error) + contents(data); + } + MESSAGE(std::format("{} files, {} read as timetables", files.size(), timetables)); + if (auto const *output{std::getenv("EU07_UNIT_TESTS_TIMETABLES_DUMP")}; output != nullptr) { + std::ofstream{output, std::ios::binary} << dump; + } +} diff --git a/tests/unit/test_timetable_start.cpp b/tests/unit/test_timetable_start.cpp new file mode 100644 index 000000000..de00eba52 --- /dev/null +++ b/tests/unit/test_timetable_start.cpp @@ -0,0 +1,39 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "world/timetablestart.h" + +// the first row of a timetable is the station of departure, a stop the train waits at for its departure time, +// when it names the station the relation starts at. the loader then takes the departure time for the arrival +// one, which the row usually leaves out; a row without an arrival time is otherwise a station passed through + +TEST_CASE("timetable: the first row naming the station of the relation is the station of departure") { + CHECK(timetable::starts_at("Stacja1", "Stacja1")); + CHECK(timetable::starts_at("Zagorz", "Zagorz")); +} + +TEST_CASE("timetable: the station of departure written in capitals in the rows is still the one of the relation") { + // linia_107_poludnie.scn, Os33733: ZAGORZ in the rows, Zagorz in the relation (both with the polish letters + // stripped by the loader). taken for a station passed through, the AI left before its departure time and the + // train manager never gave the departure signal + CHECK(timetable::starts_at("ZAGORZ", "Zagorz")); + CHECK(timetable::starts_at("LEOSIN", "Leosin")); + CHECK(timetable::starts_at("Warszawa_Wschodnia", "WARSZAWA_WSCHODNIA")); +} + +TEST_CASE("timetable: a first row naming another station is not the station of departure") { + // a timetable which starts on the way, at a station the train passes through + CHECK_FALSE(timetable::starts_at("Tarnawa_Dolna", "Zagorz")); + CHECK_FALSE(timetable::starts_at("Nowy_Zagorz", "Zagorz")); + CHECK_FALSE(timetable::starts_at("Zagorz", "Nowy_Zagorz")); + // a name which only begins like the other one + CHECK_FALSE(timetable::starts_at("Zagorz_Towarowy", "Zagorz")); + CHECK_FALSE(timetable::starts_at("Zagorz", "Zagorz_Towarowy")); +} + +TEST_CASE("timetable: the station names are compared as a whole, letters and the rest") { + CHECK_FALSE(timetable::starts_at("Stacja1", "Stacja2")); + CHECK_FALSE(timetable::starts_at("Stacja_1", "Stacja-1")); + CHECK_FALSE(timetable::starts_at("Stacja1", "")); + CHECK_FALSE(timetable::starts_at("", "Stacja1")); +} diff --git a/tests/unit/test_track_buckle.cpp b/tests/unit/test_track_buckle.cpp new file mode 100644 index 000000000..589ed125d --- /dev/null +++ b/tests/unit/test_track_buckle.cpp @@ -0,0 +1,322 @@ +#include "stdafx.h" +#include "doctest.h" +#include "world/TrackBuckle.h" + +#include + +// the buckling of welded track in the heat, world/TrackBuckle.h: the shape the track takes, the force and the temperature of the rails, +// the limits it buckles at and the draws, repeated with the same seed + +namespace { + +double constexpr pi_squared{9.869604401089358}; + +int count_buckled(double const Rise, track_buckle::limits const &Limits, std::uint32_t const Seed, int const Passes) +{ + auto count{0}; + for (int pass = 1; pass <= Passes; ++pass) + { + auto const draw{track_buckle::draw(track_buckle::name_hash("tor_1234"), Seed, track_buckle::pass, static_cast(pass))}; + if (track_buckle::decide(Rise, Limits, true, draw) == track_buckle::verdict::under_train) + ++count; + } + return count; +} + +} // namespace + +TEST_CASE("the force in a rail held from growing longer is E*A*alpha*dT") +{ + // PLK ST-T1-A8 designs for 35 K, 665 kN in a 60E1 rail, with its own alpha of about 1.18e-5 + auto const force{track_buckle::thermal_force(track_buckle::area_60e1, 35.0)}; + CHECK(force == doctest::Approx(650e3).epsilon(0.03)); + CHECK(force == doctest::Approx(665e3).epsilon(0.03)); + // Kish, Samavedam: about 2.5 kips a rail for each degree F in a 136 lb rail (13.35 sq in), 20.0 kN/K + CHECK(track_buckle::thermal_force(13.35 * 6.4516e-4, 1.0) == doctest::Approx(20.0e3).epsilon(0.05)); + // lighter rails press less + CHECK(track_buckle::thermal_force(track_buckle::area_49e1, 35.0) < force); + CHECK(track_buckle::rail_area("49E1_rail") == track_buckle::area_49e1); + CHECK(track_buckle::rail_area("S42") == track_buckle::area_s42); + CHECK(track_buckle::rail_area("") == track_buckle::area_60e1); +} + +TEST_CASE("a rail is as warm as the air at night or under clouds, 17 K warmer in full sun") +{ + CHECK(track_buckle::rail_temperature(30.0, -10.0, 0.0) == doctest::Approx(30.0)); + CHECK(track_buckle::rail_temperature(30.0, 90.0, 0.0) == doctest::Approx(47.0)); + CHECK(track_buckle::rail_temperature(30.0, 90.0, 1.0) == doctest::Approx(30.0)); + // rain cools as much as clouds + CHECK(track_buckle::rail_temperature(30.0, 90.0, 2.0) == doctest::Approx(30.0)); + CHECK(track_buckle::rail_temperature(30.0, 30.0, 0.0) == doctest::Approx(38.5)); + CHECK(track_buckle::rail_temperature(30.0, 60.0, 0.5) == doctest::Approx(30.0 + 17.0 * std::sin(60.0 * 3.141592653589793 / 180.0) * 0.5)); +} + +TEST_CASE("the limits of the grades meet the heat the tracks of PLK deform in") +{ + track_buckle::cwr track; + auto const average{track_buckle::limits_of(track, 0.0, 0.0)}; + // at the neutral 26 C under a train from rails at 58 C, by itself from 71 C: PLK, deformations with the rails above 70 C + CHECK(track.neutral + average.low == doctest::Approx(58.0)); + CHECK(track.neutral + average.high == doctest::Approx(71.0)); + // Kish, Samavedam: the chance of a buckle of a straight track grows fast from rails at 63 C with the neutral at 27 C, 36 K + CHECK(36.0 > average.low); + CHECK(36.0 < average.high); + // the design of PLK, 35 K, is short of where a good track buckles under a train + track.grade = track_buckle::grade::good; + CHECK(track_buckle::limits_of(track, 0.0, 0.0).low > 35.0); + // worked lately: weak whatever the grade + track.worked = true; + auto const worked{track_buckle::limits_of(track, 0.0, 0.0)}; + CHECK(worked.low == doctest::Approx(22.0)); + CHECK(worked.high == doctest::Approx(32.0)); + // curves and an uneven line lower them + track = {}; + CHECK(track_buckle::limits_of(track, 500.0, 0.0).low == doctest::Approx(29.0)); + CHECK(track_buckle::limits_of(track, -250.0, 0.0).low == doctest::Approx(26.0)); + CHECK(track_buckle::limits_of(track, 2000.0, 0.0).low == doctest::Approx(32.0)); + CHECK(track_buckle::limits_of(track, 0.0, 20.0).high == doctest::Approx(42.0)); + // FRA, the dynamic test: a 7.5 degree curve (233 m) with a 19 mm misalignment buckled under the train at 34 K + auto const fra{track_buckle::limits_of(track, 233.0, 19.0)}; + CHECK(34.0 > fra.low); + CHECK(34.0 < fra.high); +} + +TEST_CASE("below the lower limit a track never buckles, at the upper one it buckles by itself") +{ + track_buckle::limits const limits{32.0, 45.0}; + for (auto const draw : {0.0, 0.3, 0.999}) + { + CHECK(track_buckle::decide(31.9, limits, true, draw) == track_buckle::verdict::none); + CHECK(track_buckle::decide(31.9, limits, false, draw) == track_buckle::verdict::none); + CHECK(track_buckle::decide(45.0, limits, false, draw) == track_buckle::verdict::by_itself); + // in between only under a train + CHECK(track_buckle::decide(44.0, limits, false, draw) == track_buckle::verdict::none); + } + CHECK(track_buckle::chance(32.0, limits) == doctest::Approx(0.0)); + CHECK(track_buckle::chance(38.5, limits) == doctest::Approx(0.5)); + CHECK(track_buckle::chance(50.0, limits) == doctest::Approx(1.0)); + // a train going slowly and not braking doesn't stir it up + CHECK_FALSE(track_buckle::stirs(30.0, false)); + CHECK(track_buckle::stirs(30.0, true)); + CHECK(track_buckle::stirs(60.0, false)); + CHECK_FALSE(track_buckle::stirs(3.0, true)); +} + +TEST_CASE("the share of the passes that buckle a track grows with the heat, and repeats with the seed") +{ + track_buckle::limits const limits{32.0, 45.0}; + auto const passes{4000}; + auto const quarter{count_buckled(32.0 + 0.25 * 13.0, limits, 7, passes)}; + auto const most{count_buckled(32.0 + 0.75 * 13.0, limits, 7, passes)}; + CHECK(quarter == doctest::Approx(0.25 * passes).epsilon(0.1)); + CHECK(most == doctest::Approx(0.75 * passes).epsilon(0.05)); + CHECK(count_buckled(31.0, limits, 7, passes) == 0); + // the same seed and track, the same passes + CHECK(count_buckled(38.0, limits, 7, passes) == count_buckled(38.0, limits, 7, passes)); + auto const key{track_buckle::name_hash("tor_1234")}; + CHECK(track_buckle::draw(key, 7, track_buckle::pass, 3) == track_buckle::draw(key, 7, track_buckle::pass, 3)); + // another seed, other draws + auto differ{0}; + for (std::uint64_t pass = 1; pass <= 100; ++pass) + if (track_buckle::draw(key, 7, track_buckle::pass, pass) != track_buckle::draw(key, 8, track_buckle::pass, pass)) + ++differ; + CHECK(differ == 100); + // and another track + CHECK(track_buckle::draw(track_buckle::name_hash("tor_1235"), 7, track_buckle::pass, 3) != track_buckle::draw(key, 7, track_buckle::pass, 3)); + // the draws spread over 0 to 1 + auto low{0}; + for (std::uint64_t pass = 1; pass <= 1000; ++pass) + { + auto const draw{track_buckle::draw(key, 7, track_buckle::pass, pass)}; + CHECK(draw >= 0.0); + CHECK(draw < 1.0); + if (draw < 0.5) + ++low; + } + CHECK(low == doctest::Approx(500).epsilon(0.1)); +} + +TEST_CASE("the heat buckles a track at one place in about 10 km, and wherever the bed was worked on") +{ + auto sites{0}; + auto const tracks{20000}; + for (int track = 0; track < tracks; ++track) + if (track_buckle::weak_spot(track_buckle::name_hash("t" + std::to_string(track)), 3, 500.0, false)) + ++sites; + // 500 m each, 10 000 km together: about 1000 + CHECK(sites == doctest::Approx(1000).epsilon(0.1)); + CHECK(track_buckle::weak_spot(track_buckle::name_hash("t1"), 3, 1.0, true)); +} + +TEST_CASE("the buckle has its amplitude in the middle, side lobes the other way and ends smoothly") +{ + track_buckle::shape const shape{0.4, 14.0, 60.0}; + CHECK(track_buckle::offset(shape, 60.0) == doctest::Approx(0.4)); + CHECK(track_buckle::slope(shape, 60.0) == doctest::Approx(0.0)); + // the main lobe crosses the line one length apart + CHECK(track_buckle::offset(shape, 60.0 - 7.0) == doctest::Approx(0.0)); + CHECK(track_buckle::offset(shape, 60.0 + 7.0) == doctest::Approx(0.0)); + // the side lobes the other way, a quarter as far out + CHECK(track_buckle::offset(shape, 60.0 + 14.0) == doctest::Approx(-0.1)); + CHECK(track_buckle::offset(shape, 60.0 - 14.0) == doctest::Approx(-0.1)); + // into the straight track at the ends with no displacement, slope or curvature + CHECK(track_buckle::reach(shape) == doctest::Approx(21.0)); + for (auto const at : {-21.0 + 1e-6, 21.0 - 1e-6}) + { + CAPTURE(at); + CHECK(track_buckle::offset(shape, 60.0 + at) == doctest::Approx(0.0)); + CHECK(track_buckle::slope(shape, 60.0 + at) == doctest::Approx(0.0)); + CHECK(track_buckle::bend(shape, 60.0 + at) == doctest::Approx(0.0)); + } + // nothing beyond + CHECK(track_buckle::offset(shape, 60.0 + 21.5) == 0.0); + CHECK(track_buckle::bend(shape, 60.0 - 30.0) == 0.0); + // symmetric + for (auto const at : {1.0, 4.0, 7.5, 12.0, 16.0, 20.0}) + CHECK(track_buckle::offset(shape, 60.0 + at) == doctest::Approx(track_buckle::offset(shape, 60.0 - at))); + // the largest curvature 11/9 pi^2 a / L^2 in the middle, bending back towards the line + auto const peak{track_buckle::peak_bend(0.4, 14.0)}; + CHECK(peak == doctest::Approx(11.0 / 9.0 * pi_squared * 0.4 / (14.0 * 14.0))); + CHECK(track_buckle::bend(shape, 60.0) == doctest::Approx(-peak)); + // none larger anywhere, and the curvature with no jumps + auto previous{track_buckle::bend(shape, 35.0)}; + for (auto step = 0; step <= 5000; ++step) + { + auto const at{35.0 + 0.01 * step}; + auto const bend{track_buckle::bend(shape, at)}; + CHECK(std::abs(bend) <= peak * 1.0001); + CHECK(std::abs(bend - previous) < 0.01 * peak); + previous = bend; + } + // the curvature as the displacement has it + auto const step{0.01}; + for (auto const at : {42.0, 50.5, 55.0, 61.0, 66.0, 73.0, 79.0}) + { + CAPTURE(at); + auto const slope{(track_buckle::offset(shape, at + step) - track_buckle::offset(shape, at - step)) / (2.0 * step)}; + auto const bend{(track_buckle::offset(shape, at + step) - 2.0 * track_buckle::offset(shape, at) + track_buckle::offset(shape, at - step)) / (step * step)}; + CHECK(track_buckle::slope(shape, at) == doctest::Approx(slope).epsilon(1e-4)); + CHECK(track_buckle::bend(shape, at) == doctest::Approx(bend).epsilon(1e-3)); + } + // to the left + track_buckle::shape const left{-0.4, 14.0, 60.0}; + CHECK(track_buckle::offset(left, 60.0) == doctest::Approx(-0.4)); + CHECK(track_buckle::bend(left, 60.0) == doctest::Approx(peak)); + // none + CHECK(track_buckle::offset(track_buckle::shape{}, 60.0) == 0.0); + CHECK_FALSE(track_buckle::active(track_buckle::shape{})); +} + +TEST_CASE("a bogie feels the curvature of the buckle averaged over its wheelbase, a body that of its pivots") +{ + track_buckle::shape const shape{0.3, 20.0, 50.0}; + auto const peak{track_buckle::peak_bend(0.3, 20.0)}; + CHECK(track_buckle::mean_bend(shape, 50.0, 0.0) == doctest::Approx(track_buckle::bend(shape, 50.0))); + // a bogie 2.5 m long, almost the whole of it + CHECK(std::abs(track_buckle::mean_bend(shape, 50.0, 2.5)) > 0.95 * peak); + // the mean of the curvature over the stretch, anywhere + for (auto const at : {32.0, 42.0, 50.0, 57.5, 64.0}) + { + CAPTURE(at); + auto sum{0.0}; + auto const parts{2500}; + for (int part = 0; part < parts; ++part) + sum += track_buckle::bend(shape, at - 1.25 + (part + 0.5) * 2.5 / parts); + CHECK(track_buckle::mean_bend(shape, at, 2.5) == doctest::Approx(sum / parts).epsilon(1e-3)); + } + // a body on the pivots 0 apart is a bogie + CHECK(track_buckle::body_bend(shape, 47.0, 0.0, 2.5) == doctest::Approx(track_buckle::mean_bend(shape, 47.0, 2.5))); + // a coach with its pivots 17 m apart over the main lobe: its pivots are on the flanks, which bend the other way + auto const across{track_buckle::body_bend(shape, 50.0, 17.0, 2.5)}; + CHECK(std::abs(across) < 0.5 * peak); + // the most the body feels, at any place, is less than a bogie does + auto most{0.0}; + for (auto step = 0; step <= 1200; ++step) + most = std::max(most, std::abs(track_buckle::body_bend(shape, 20.0 + 0.05 * step, 17.0, 2.5))); + CHECK(most < 0.95 * peak); + CHECK(most > 0.3 * peak); +} + +TEST_CASE("the equivalent radius of a buckle") +{ + // the default ones as sharp as the raised cosine lobes of the research note: 0.4 m by 18 m on a straight 41 m, 0.2 by 14 in a curve 50 m + CHECK(1.0 / track_buckle::peak_bend(track_buckle::straight_amplitude, track_buckle::straight_length) == doctest::Approx(41.0).epsilon(0.02)); + CHECK(1.0 / track_buckle::peak_bend(track_buckle::curve_amplitude, track_buckle::curve_length) == doctest::Approx(49.6).epsilon(0.02)); + CHECK(1.0 / track_buckle::peak_bend(0.3, 20.0) == doctest::Approx(110.5).epsilon(0.01)); +} + +TEST_CASE("the entries buckle and cwr are read and written back") +{ + auto const buckle{track_buckle::read_buckle("400;18;60")}; + CHECK(buckle.amplitude == 400.f); + CHECK(buckle.length == 18.f); + CHECK(buckle.centre == 60.f); + CHECK(buckle.side == 0); + CHECK(track_buckle::write_buckle(buckle) == "buckle 400;18;60 "); + auto const left{track_buckle::read_buckle("250;;;-1")}; + CHECK(left.amplitude == 250.f); + CHECK(left.length < 0.f); + CHECK(left.centre < 0.f); + CHECK(left.side == -1); + CHECK(track_buckle::write_buckle(left) == "buckle 250;;;-1 "); + CHECK(track_buckle::read_buckle(track_buckle::write_buckle(left).substr(7)).side == -1); + // kept within bounds + auto const wild{track_buckle::read_buckle("5000;100;-5;3")}; + CHECK(wild.amplitude == 1000.f); + CHECK(wild.length == 60.f); + CHECK(wild.centre < 0.f); + CHECK(wild.side == 1); + CHECK(track_buckle::read_buckle("300;1").length == 4.f); + // none + CHECK_FALSE(track_buckle::given(track_buckle::read_buckle("0;18;60"))); + CHECK_FALSE(track_buckle::given(track_buckle::read_buckle("x"))); + CHECK(track_buckle::write_buckle(track_buckle::declared{}).empty()); + + auto const cwr{track_buckle::read_cwr("20;2;1")}; + CHECK(cwr.neutral == 20.f); + CHECK(cwr.grade == track_buckle::grade::weak); + CHECK(cwr.worked); + CHECK(track_buckle::write_cwr(cwr) == "cwr 20;2;1 "); + auto const partial{track_buckle::read_cwr("22")}; + CHECK(partial.neutral == 22.f); + CHECK(partial.grade == track_buckle::grade::average); + CHECK_FALSE(partial.worked); + CHECK(track_buckle::write_cwr(partial) == "cwr 22;1 "); + auto const bounded{track_buckle::read_cwr("99;7")}; + CHECK(bounded.neutral == 60.f); + CHECK(bounded.grade == 2); + // the default isn't written + CHECK(track_buckle::write_cwr(track_buckle::read_cwr("26;1;0")).empty()); +} + +TEST_CASE("a buckle is laid into its track away from the ends, out of a curve") +{ + auto const values{track_buckle::read_buckle("400;18;60")}; + auto const straight{track_buckle::resolve(values, 200.0, 0, 0.0, 0.5, 0.2)}; + CHECK(straight.centre == 60.0); + CHECK(straight.length == 18.0); + // the side drawn on a straight + CHECK(straight.amplitude == doctest::Approx(-0.4)); + CHECK(track_buckle::resolve(values, 200.0, 0, 0.0, 0.5, 0.7).amplitude == doctest::Approx(0.4)); + // out of a curve, whatever the draw + CHECK(track_buckle::resolve(values, 200.0, 1, 400.0, 0.5, 0.2).amplitude == doctest::Approx(0.4)); + CHECK(track_buckle::resolve(values, 200.0, -1, 400.0, 0.5, 0.7).amplitude == doctest::Approx(-0.4)); + // the side given wins + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18;60;-1"), 200.0, 1, 400.0, 0.5, 0.7).amplitude == doctest::Approx(-0.4)); + // the centre kept away from the ends by the reach, 1.5 lengths, and a margin + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18;5"), 200.0, 0, 0.0, 0.5, 0.2).centre == doctest::Approx(29.0)); + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18;195"), 200.0, 0, 0.0, 0.5, 0.2).centre == doctest::Approx(171.0)); + // drawn where not given + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18"), 200.0, 0, 0.0, 0.0, 0.2).centre == doctest::Approx(29.0)); + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18"), 200.0, 0, 0.0, 1.0, 0.2).centre == doctest::Approx(171.0)); + // the length by the shape of the track: a curve goes out less far and shorter + CHECK(track_buckle::resolve(track_buckle::read_buckle("200"), 200.0, 1, 400.0, 0.5, 0.2).length == track_buckle::curve_length); + CHECK(track_buckle::resolve(track_buckle::read_buckle("400"), 200.0, 0, 0.0, 0.5, 0.2).length == track_buckle::straight_length); + CHECK(track_buckle::resolve(track_buckle::read_buckle("400"), 200.0, 1, 3000.0, 0.5, 0.2).length == track_buckle::straight_length); + // too short a track + CHECK_FALSE(track_buckle::active(track_buckle::resolve(values, 57.9, 0, 0.0, 0.5, 0.2))); + CHECK(track_buckle::active(track_buckle::resolve(values, 58.0, 0, 0.0, 0.5, 0.2))); + // the natural ones + CHECK(track_buckle::natural(true).amplitude == 200.f); + CHECK(track_buckle::natural(false).length == 14.f); +} diff --git a/tests/unit/test_track_buckle_derailment.cpp b/tests/unit/test_track_buckle_derailment.cpp new file mode 100644 index 000000000..2f5d99592 --- /dev/null +++ b/tests/unit/test_track_buckle_derailment.cpp @@ -0,0 +1,135 @@ +#include "stdafx.h" +#include "doctest.h" +#include "McZapkie/derailment.h" +#include "world/TrackBuckle.h" + +#include + +// a vehicle over a buckled track, by the criteria of derailment.h: the curvature of the buckle goes into the track +// under the vehicle as buckle_curvature (world/TrackBuckle.h: the body by the mean of its pivots, each bogie over its +// wheelbase), whole, as the curvature of the curve does + +namespace { + +// a four-axle coach: 42 t, 24.5 m over the buffers, the pivots 17.2 m and the axles of a bogie 2.5 m apart +derailment::vehicle_state coach() +{ + derailment::vehicle_state vehicle; + vehicle.mass = 42000.0; + vehicle.axles = 4; + vehicle.length = 24.5; + vehicle.axle_base = 2.5; + vehicle.centre_of_gravity = 1.4; + return vehicle; +} +double constexpr pivots{17.2}; + +// a two-axle wagon: 25 t, 14 m over the buffers, the axles 9 m apart, which are its pivots +derailment::vehicle_state wagon() +{ + derailment::vehicle_state vehicle; + vehicle.mass = 25000.0; + vehicle.axles = 2; + vehicle.length = 14.0; + vehicle.axle_base = 9.0; + vehicle.centre_of_gravity = 1.6; + return vehicle; +} + +struct rolling_stock { + derailment::vehicle_state vehicle; + double pivots; + double base; // of the bogies, 0 without +}; +rolling_stock const four_axle{coach(), pivots, 2.5}; +rolling_stock const two_axle{wagon(), 9.0, 0.0}; + +// Outward: the side out of the curve of Radius (-1 left, 1 right), 0 on a straight track +derailment::outcome ride(track_buckle::shape const &Shape, double const Radius, int const Outward, double const Speed, double const Step, rolling_stock const &Stock = four_axle) +{ + auto const &vehicle{Stock.vehicle}; + derailment::monitor monitor; + auto const velocity{Speed / 3.6}; + auto const reach{track_buckle::reach(Shape) + Stock.pivots}; + auto const start{Shape.centre - reach - 5.0}; + auto const advance{velocity * Step}; + auto const steps{static_cast(std::floor((2.0 * (reach + 5.0)) / advance))}; + for (auto step = 0; step <= steps; ++step) + { + auto const at{start + step * advance}; + derailment::track_state track; + track.radius = Radius; + auto const bend{track_buckle::body_bend(Shape, at, Stock.pivots, Stock.base)}; + // positive bending with the curve, whose centre is away from the outer side + track.buckle_curvature = (Outward != 0 ? -Outward * bend : bend); + auto const verdict{monitor.update(vehicle, track, velocity, velocity * Step)}; + if (verdict.result != derailment::outcome::none) + return verdict.result; + } + return derailment::outcome::none; +} + +// the lowest speed it leaves the rails at, km/h, to 0.5 km/h +double limit(track_buckle::shape const &Shape, double const Radius, int const Outward, double const Step, rolling_stock const &Stock = four_axle) +{ + auto low{5.0}; + auto high{300.0}; + while (high - low > 0.5) + { + auto const middle{0.5 * (low + high)}; + if (ride(Shape, Radius, Outward, middle, Step, Stock) != derailment::outcome::none) + high = middle; + else + low = middle; + } + return high; +} + +} // namespace + +TEST_CASE("a coach goes over a buckle slowly, and leaves the rails on it fast") +{ + // 0.3 m out over a main lobe of 20 m on a straight track: an equivalent radius of 110 m, felt by the body less + track_buckle::shape const shape{0.3, 20.0, 60.0}; + CHECK(ride(shape, 0.0, 0, 30.0, 0.01) == derailment::outcome::none); + CHECK(ride(shape, 0.0, 0, 60.0, 0.01) == derailment::outcome::none); + CHECK(ride(shape, 0.0, 0, 140.0, 0.01) != derailment::outcome::none); + auto const speed{limit(shape, 0.0, 0, 0.01)}; + MESSAGE("coach over a buckle 0.3 m by 20 m on a straight track: off the rails from ", speed, " km/h"); + CHECK(speed > 60.0); + CHECK(speed < 140.0); + // the same with any step + CHECK(limit(shape, 0.0, 0, 0.002) == doctest::Approx(speed).epsilon(2.0 / speed)); + CHECK(limit(shape, 0.0, 0, 0.03) == doctest::Approx(speed).epsilon(2.0 / speed)); + // either way on a straight track + track_buckle::shape const left{-0.3, 20.0, 60.0}; + CHECK(limit(left, 0.0, 0, 0.01) == doctest::Approx(speed).epsilon(1.0 / speed)); + // a larger buckle derails it slower + auto const large{limit(track_buckle::shape{0.6, 20.0, 60.0}, 0.0, 0, 0.01)}; + MESSAGE("0.6 m by 20 m: ", large, " km/h"); + CHECK(large < speed); + // the default one of a straight track, 0.4 m by 14 m + auto const natural{limit(track_buckle::shape{track_buckle::straight_amplitude, track_buckle::straight_length, 60.0}, 0.0, 0, 0.01)}; + MESSAGE("the default buckle of a straight track, 0.4 m by 14 m: ", natural, " km/h"); + CHECK(natural < speed); + // a body on two axles 9 m apart doesn't span the main lobe as one on bogies 17.2 m apart does: it follows the + // buckle closer, and goes off the rails slower + auto const short_wagon{limit(shape, 0.0, 0, 0.01, two_axle)}; + MESSAGE("a two-axle wagon over 0.3 m by 20 m: ", short_wagon, " km/h"); + CHECK(short_wagon < speed); + CHECK(ride(shape, 0.0, 0, 30.0, 0.01, two_axle) == derailment::outcome::none); +} + +TEST_CASE("a buckle out of a curve derails a coach slower than the same on a straight track") +{ + track_buckle::shape const shape{0.3, 20.0, 60.0}; + auto const straight{limit(shape, 0.0, 0, 0.01)}; + // a curve of 600 m without cant, the buckle to the right out of it (a curve to the left) + auto const curve{limit(track_buckle::shape{}, 600.0, 0, 0.01)}; + auto const outwards{limit(shape, 600.0, 1, 0.01)}; + MESSAGE("R 600 m: the curve alone from ", curve, " km/h, with the buckle out of it from ", outwards, " km/h, on a straight ", straight, " km/h"); + CHECK(outwards < straight); + CHECK(outwards < curve); + // one into the curve (not what the heat does) still lowers it, by its flanks which bend with the curve + CHECK(limit(track_buckle::shape{-0.3, 20.0, 60.0}, 600.0, 1, 0.01) < curve); +} diff --git a/tests/unit/test_track_check.cpp b/tests/unit/test_track_check.cpp new file mode 100644 index 000000000..f9f015f96 --- /dev/null +++ b/tests/unit/test_track_check.cpp @@ -0,0 +1,184 @@ +#include "stdafx.h" +#include "doctest.h" +#include "world/TrackCheck.h" + +#include +#include +#include +#include + +// physics.trackcheck: the geometry of the rail tracks of a scenery the criteria of derailment find suspicious, see +// world/TrackCheck.h + +namespace tc = track_check; + +namespace { + +bool has(tc::findings const &Found, tc::kind const Kind) { + return std::find(Found.kinds.begin(), Found.kinds.end(), Kind) != Found.kinds.end(); +} + +tc::track curve(double const Radius, double const Velocity, double const Cant = 0.0) { + tc::track track; + track.name = "t1"; + track.radius = Radius; + track.velocity = Velocity; + track.cant = {Cant, Cant}; + return track; +} + +double overturning(double const Radius, double const Cant = 0.0) { + auto const &eu07{tc::default_references().front().vehicle}; + return derailment::overturning_speed(Radius, std::asin(Cant / 1500.0), eu07.centre_of_gravity, 1.435) * 3.6; +} + +} // namespace + +TEST_CASE("trackcheck: the default vehicles") { + auto const &references{tc::default_references()}; + REQUIRE(references.size() == 2); + CHECK(references[0].name == "EU07"); + CHECK(references[0].vehicle.centre_of_gravity == doctest::Approx(1.65).epsilon(0.01)); + CHECK(references[1].vehicle.centre_of_gravity == doctest::Approx(1.42).epsilon(0.01)); + // the EU07 overturns at 108 km/h in a curve of 300 m without cant + CHECK(overturning(300.0) == doctest::Approx(108.0).epsilon(0.02)); +} + +TEST_CASE("trackcheck: the speed limit of a curve") { + auto const critical{overturning(300.0)}; + SUBCASE("under the speeds of the vehicles nothing") { + CHECK(tc::check(curve(300.0, critical - 10.0)).empty()); + } + SUBCASE("over the overturning speed of the EU07") { + auto const found{tc::check(curve(300.0, critical + 5.0))}; + CHECK(has(found, tc::kind::overturning)); + CHECK_FALSE(has(found, tc::kind::unlimited_curve)); + CHECK(found.defective()); + CHECK(found.text.find("over the overturning speed of EU07") != std::string::npos); + CHECK(found.text.find("speed limit 113 km/h") != std::string::npos); + } + SUBCASE("the cant raises it") { + CHECK(tc::check(curve(300.0, critical + 5.0, 100.0)).empty()); + } + SUBCASE("without a speed limit of its own it's no defect, the speed it takes is told") { + auto const found{tc::check(curve(300.0, -1.0))}; + CHECK(has(found, tc::kind::unlimited_curve)); + CHECK_FALSE(has(found, tc::kind::overturning)); + CHECK_FALSE(found.defective()); + CHECK_FALSE(tc::is_defect(tc::kind::unlimited_curve)); + CHECK(found.unlimited_speed == doctest::Approx(critical)); + CHECK(found.text.starts_with("no speed limit set (not a defect): the curve takes at most ")); + CHECK(found.text.find(" km/h, the overturning speed of EU07") != std::string::npos); + CHECK(found.text.find("speed limit none") != std::string::npos); + } + SUBCASE("nor anything when it takes them at the top speed of the EU07") { + CHECK(tc::check(curve(600.0, -1.0)).empty()); + } + SUBCASE("a tram loop of 30 m without a speed limit is no tight curve too fast") { + // the tram tracks of Tomaszewo (tramwaj106...): no category of their own, no speed limit + auto const found{tc::check(curve(30.0, -1.0))}; + CHECK(found.kinds == std::vector{tc::kind::unlimited_curve}); + CHECK(found.unlimited_speed == doctest::Approx(overturning(30.0))); + CHECK(found.unlimited_speed < 40.0); + } + SUBCASE("a closed track (speed 0) is not checked") { + CHECK(tc::check(curve(100.0, 0.0)).empty()); + } + SUBCASE("nor the speed of a switch") { + auto track{curve(150.0, 100.0)}; + track.plain = false; + CHECK(tc::check(track).empty()); + } + SUBCASE("the cant at the end with the less of it") { + auto track{curve(300.0, critical + 5.0, 100.0)}; + track.cant[0] = 0.0; + CHECK(has(tc::check(track), tc::kind::overturning)); + } +} + +TEST_CASE("trackcheck: the cant") { + SUBCASE("the same cant at both ends of a straight track") { + auto const found{tc::check(curve(0.0, 100.0, 60.0))}; + CHECK(has(found, tc::kind::cant_on_straight)); + CHECK(found.text.starts_with("cant 60 / 60 mm on a straight track")); + } + SUBCASE("a transition has it at one end only") { + auto track{curve(0.0, 100.0, 60.0)}; + track.cant[0] = 0.0; + CHECK(tc::check(track).empty()); + } + SUBCASE("a few mm are left alone") { + CHECK(tc::check(curve(0.0, 100.0, 4.0)).empty()); + } + SUBCASE("over 160 mm") { + auto const found{tc::check(curve(1000.0, 60.0, 170.0))}; + CHECK(has(found, tc::kind::cant_excess)); + CHECK(found.kinds.size() == 1); + CHECK(tc::check(curve(1000.0, 60.0, 150.0)).empty()); + } +} + +TEST_CASE("trackcheck: a tight curve") { + CHECK(has(tc::check(curve(30.0, 50.0)), tc::kind::tight_curve)); + CHECK_FALSE(has(tc::check(curve(30.0, 30.0)), tc::kind::tight_curve)); + CHECK_FALSE(has(tc::check(curve(60.0, 50.0)), tc::kind::tight_curve)); +} + +TEST_CASE("trackcheck: the unevenness") { + auto track{curve(0.0, 100.0)}; + track.uneven.value = 14.f; + track.uneven.side = 20.f; + track.uneven.cross = 20.f; + CHECK(tc::check(track).empty()); + track.uneven.side = 40.f; + track.uneven.cross = 26.f; + auto const found{tc::check(track)}; + CHECK(has(found, tc::kind::uneven)); + CHECK(found.text.starts_with("uneven side 40, cross 26 mm out of range")); +} + +TEST_CASE("trackcheck: the scan of a scenery") { + std::vector tracks; + tracks.push_back(curve(300.0, 140.0)); + tracks.back().name = "fast"; + tracks.push_back(curve(0.0, 100.0)); + tracks.back().name = "worn"; + tracks.back().damage = 31; + tracks.push_back(curve(0.0, 100.0, 50.0)); + tracks.back().name = "leaning"; + tracks.back().damage = 31; + tracks.push_back(curve(0.0, 100.0)); + tracks.back().name = "fine"; + tracks.back().damage = 2; + tracks.push_back(curve(30.0, -1.0)); + tracks.back().name = "tram_1"; + tracks.push_back(curve(150.0, -1.0)); + tracks.back().name = "siding_1"; + + std::vector log; + auto const summary{tc::scan(tracks, [&](std::string const &Line) { log.push_back(Line); })}; + CHECK(summary.tracks == 6); + // the curves without a speed limit are told apart from the defects + CHECK(summary.suspicious == 2); + CHECK(summary.unlimited == 2); + CHECK(summary.slowest == doctest::Approx(overturning(30.0))); + CHECK(summary.count(tc::kind::overturning) == 1); + CHECK(summary.count(tc::kind::cant_on_straight) == 1); + CHECK(summary.count(tc::kind::tight_curve) == 0); + CHECK(summary.count(tc::kind::unlimited_curve) == 2); + // the damage flags are counted, not told track by track + CHECK(summary.damage.at(31) == 2); + CHECK(summary.damage.at(2) == 1); + REQUIRE(log.size() == 7); + CHECK(log[0].starts_with("trackcheck: fast: speed limit 140 km/h over the overturning speed of EU07")); + CHECK(log[1].starts_with("trackcheck: leaning: cant 50 / 50 mm on a straight track")); + CHECK(log[1].ends_with("damage 31)")); + CHECK(log[2].starts_with("trackcheck: tram_1: no speed limit set (not a defect): the curve takes at most ")); + CHECK(log[3].starts_with("trackcheck: siding_1: no speed limit set (not a defect)")); + CHECK(log[4] == "trackcheck: 6 rail tracks checked, 2 suspicious: overturning 1; flange climbing 0; cant on a straight 1; cant too high 0; tight curve too fast 0; uneven out of range 0"); + CHECK(log[5].starts_with("trackcheck: curves without a speed limit: 2 taking the reference vehicles under 125 km/h (not a defect), the slowest at ")); + CHECK(log[6] == "trackcheck: damage flags: 2 on 1; 31 on 2"); + for (auto const &line : log) { + CHECK(line.starts_with("trackcheck: ")); + } +} diff --git a/tests/unit/test_universal_drag.cpp b/tests/unit/test_universal_drag.cpp new file mode 100644 index 000000000..f520b694f --- /dev/null +++ b/tests/unit/test_universal_drag.cpp @@ -0,0 +1,143 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/universaldrag.h" + +// smooth regulation of the universal cab controls (MaSzyna-EU07/maszyna#62): a universal with "drag: " +// in its definition is dragged with the mouse to any position between its ends and stays there when let go; a click +// and the keys move it to its ends. the mouse and TGauge are not part of the core library, the rules they follow are + +using universal_drag::direction; + +TEST_CASE("universal drag: the values of the drag key") { + CHECK(universal_drag::parse("up") == direction::up); + CHECK(universal_drag::parse("down") == direction::down); + CHECK(universal_drag::parse("left") == direction::left); + CHECK(universal_drag::parse("right") == direction::right); + // yes drags it up, as the sliders of the controllers + CHECK(universal_drag::parse("yes") == direction::up); + CHECK(universal_drag::parse("true") == direction::up); + CHECK(universal_drag::parse("1") == direction::up); + CHECK(universal_drag::parse("no") == direction::none); + CHECK(universal_drag::parse("false") == direction::none); + CHECK(universal_drag::parse("0") == direction::none); + CHECK(universal_drag::parse("none") == direction::none); + // a value it doesn't know is reported, and the control can't be dragged + CHECK_FALSE(universal_drag::parse("sideways").has_value()); + CHECK_FALSE(universal_drag::parse("").has_value()); + CHECK_FALSE(universal_drag::parse("Up").has_value()); +} + +TEST_CASE("universal drag: a push universal can't be dragged, it springs back when let go") { + CHECK(universal_drag::effective(direction::up, true) == direction::none); + CHECK(universal_drag::effective(direction::left, true) == direction::none); + CHECK(universal_drag::effective(direction::up, false) == direction::up); + CHECK(universal_drag::effective(direction::none, false) == direction::none); +} + +TEST_CASE("universal drag: the move of the cursor along the direction") { + auto const size{600.0}; + // the cursor's y grows downwards + CHECK(universal_drag::along(direction::up, 0.0, -60.0, size) == doctest::Approx(0.1)); + CHECK(universal_drag::along(direction::up, 0.0, 60.0, size) == doctest::Approx(-0.1)); + CHECK(universal_drag::along(direction::down, 0.0, 60.0, size) == doctest::Approx(0.1)); + CHECK(universal_drag::along(direction::left, -150.0, 0.0, size) == doctest::Approx(0.25)); + CHECK(universal_drag::along(direction::right, -150.0, 0.0, size) == doctest::Approx(-0.25)); + // the move across the direction doesn't count + CHECK(universal_drag::along(direction::up, 300.0, 0.0, size) == 0.0); + CHECK(universal_drag::along(direction::left, 0.0, 300.0, size) == 0.0); + // nothing to drag + CHECK(universal_drag::along(direction::none, 100.0, 100.0, size) == 0.0); + CHECK(universal_drag::along(direction::up, 0.0, -60.0, 0.0) == 0.0); +} + +TEST_CASE("universal drag: the position is kept between the ends") { + CHECK(universal_drag::clamp(-0.5) == 0.f); + CHECK(universal_drag::clamp(1.5) == 1.f); + CHECK(universal_drag::clamp(0.25) == doctest::Approx(0.25f)); +} + +TEST_CASE("universal drag: the keys and a click move the control to the end farther from its position") { + CHECK(universal_drag::toggled(0.f) == 1.f); + CHECK(universal_drag::toggled(1.f) == 0.f); + // a control left in between + CHECK(universal_drag::toggled(0.3f) == 1.f); + CHECK(universal_drag::toggled(0.7f) == 0.f); + // half way, as the two-state universals always did + CHECK(universal_drag::toggled(0.5f) == 0.f); +} + +TEST_CASE("universal drag: a drag takes the control to a position between its ends, where it stays") { + auto const size{600.0}; + universal_drag::drag drag{direction::up, 0.f}; + // the first position of the cursor is where the drag starts from, even if the hidden cursor was moved + CHECK_FALSE(drag.move(400.0, 500.0, size)); + CHECK(drag.position() == 0.f); + CHECK(drag.is_click()); + // up by a quarter of the size + CHECK(drag.move(400.0, 350.0, size)); + CHECK(drag.position() == doctest::Approx(0.25f)); + // sideways it stays + CHECK_FALSE(drag.move(700.0, 350.0, size)); + CHECK(drag.position() == doctest::Approx(0.25f)); + // back down a little + CHECK(drag.move(700.0, 380.0, size)); + CHECK(drag.position() == doctest::Approx(0.2f)); + CHECK_FALSE(drag.is_click()); + // let go: the position is what the drag left, the control keeps it + CHECK(drag.start() == 0.f); + CHECK(drag.position() == doctest::Approx(0.2f)); +} + +TEST_CASE("universal drag: the control stops at its ends, and moving back takes it back at once") { + auto const size{100.0}; + universal_drag::drag drag{direction::right, 0.9f}; + drag.move(0.0, 0.0, size); + CHECK(drag.move(50.0, 0.0, size)); + CHECK(drag.position() == 1.f); + // further on it stays at the end + CHECK_FALSE(drag.move(200.0, 0.0, size)); + CHECK(drag.position() == 1.f); + // back: from the end, not from where the cursor went past it + CHECK(drag.move(190.0, 0.0, size)); + CHECK(drag.position() == doctest::Approx(0.9f)); + // and the other end + CHECK(drag.move(0.0, 0.0, size)); + CHECK(drag.position() == 0.f); +} + +TEST_CASE("universal drag: a press let go with the cursor barely moved is a click") { + auto const size{600.0}; + universal_drag::drag drag{direction::down, 0.4f}; + drag.move(10.0, 10.0, size); + // a jitter of the hand, under the travel of a click + drag.move(11.0, 13.0, size); + drag.move(10.0, 11.0, size); + CHECK(drag.is_click()); + // the click moves it to the end farther from it, as the key does + CHECK(universal_drag::toggled(drag.position()) == 1.f); + // a drag there and back is a drag, though it ends where it started + universal_drag::drag back{direction::down, 0.4f}; + back.move(0.0, 0.0, size); + back.move(0.0, 60.0, size); + back.move(0.0, 0.0, size); + CHECK_FALSE(back.is_click()); + CHECK(back.position() == doctest::Approx(0.4f)); +} + +TEST_CASE("universal drag: a drag starts from the position the control is set to") { + universal_drag::drag drag{direction::up, 0.6f}; + CHECK(drag.start() == doctest::Approx(0.6f)); + CHECK(drag.position() == doctest::Approx(0.6f)); + // a position out of the range is brought into it + CHECK(universal_drag::drag{direction::up, 3.f}.position() == 1.f); + CHECK(universal_drag::drag{direction::up, -1.f}.position() == 0.f); +} + +TEST_CASE("universal drag: a control which can't be dragged doesn't move") { + universal_drag::drag drag{direction::none, 0.f}; + drag.move(0.0, 0.0, 600.0); + CHECK_FALSE(drag.move(300.0, -300.0, 600.0)); + CHECK(drag.position() == 0.f); + CHECK(drag.is_click()); +} diff --git a/tests/unit/test_utilities.cpp b/tests/unit/test_utilities.cpp index 3bcb565a8..1b12f1b9a 100644 --- a/tests/unit/test_utilities.cpp +++ b/tests/unit/test_utilities.cpp @@ -9,6 +9,8 @@ #include "utilities/utilities.h" #include +#include +#include #include // the helpers of utilities/utilities.cpp and utilities.h as they behave now: the numbers and texts they give, their @@ -234,10 +236,39 @@ TEST_CASE("utilities: the seed a text stands for is its number, or its hash the // a number which isn't a seed is a word: negative, or too big CHECK(seed_of("-5") == 1448u); CHECK(seed_of("4294967296") == 3632702254u); + CHECK(seed_of("+5") == 1386u); + CHECK(seed_of("-0") == 1443u); // the bytes over ascii count as positive CHECK(seed_of("\xB9") == 185u); - // a word starting with digits is taken for the number in front of it - CHECK(seed_of("12abc") == 12u); + // leading zeros are the same number + CHECK(seed_of("007") == 7u); + CHECK(seed_of("00") == 0u); +} + +TEST_CASE("utilities: a seed is the whole text as a number, or the whole text as a word") { + // digits with something after them are a word, not the number in front of them + CHECK(seed_of("4242abc") == 386617702u); + CHECK(seed_of("4242abc") != 4242u); + CHECK(seed_of("12abc") == 46838433u); + CHECK(seed_of("0x10") == 1546855u); + // a space is part of the word as well: the settings and the command line give the seed without them + CHECK(seed_of("4242 ") == 49564196u); + CHECK(seed_of(" 4242") == 31151516u); + // so two words starting with the same digits stand for two seeds + CHECK(seed_of("12abc") != seed_of("12xyz")); +} + +TEST_CASE("utilities: randomseed and -seed give a seed, 0 too, and an empty text none") { + CHECK(seed_given("0") == std::optional{0u}); + CHECK(seed_given("00") == std::optional{0u}); + CHECK(seed_given("4242") == std::optional{4242u}); + CHECK(seed_given("hello") == std::optional{99162322u}); + CHECK(seed_given("4242abc") == std::optional{386617702u}); + CHECK_FALSE(seed_given("").has_value()); + // a seed which is given is not the same as none, whatever its number + CHECK(seed_given("0").has_value()); + // and the settings start without one, to be drawn + CHECK(std::make_unique()->random_seed_given == false); } TEST_CASE("utilities: a version 4 uuid is drawn from the random numbers of the simulation") { @@ -405,18 +436,18 @@ TEST_CASE("utilities: a text for the timetable loses its marks, control characte CHECK(Bezogonkow("Bia\xA3" "a_Podlaska", true) == "BiaLa Podlaska"); } -TEST_CASE("utilities: the polish letters from 0xB2 on lose their marks only in a build which makes one byte of the table's mark") { - // the table of Bezogonkow() has a plus-minus sign for 0xB1, written as the character in the source, a utf-8 file. - // MSVC puts it into the table as the one byte of the system's code page, and the table is as it was meant. - // GCC and Clang put the two bytes of utf-8 there, which moves the entries after it by one (see COVERAGE.md) - if (Bezogonkow("\xB1") == "\xB1") { - CHECK(Bezogonkow(kWin1250) == "ACELNOSZZacelnoszz"); - } - else { - // the first byte of the sign for 0xB1, the second for 0xB2, and each letter after them as the entry before its own - CHECK(Bezogonkow("\xB1\xB2") == "\xC2\xB1"); - CHECK(Bezogonkow(kWin1250) == "ALELDNSZZ,le,dnszl"); - } +TEST_CASE("utilities: the polish letters from 0xB2 on lose their marks in every build") { + // the table of Bezogonkow() has the plus-minus sign for 0xB1. it used to be written as the character in the source, + // a utf-8 file: GCC and Clang put the two bytes of utf-8 into the table, which moved the entries after it by one + // (the polish letters came out as "ALELDNSZZ,le,dnszl"). now it's the byte, and the table is the same everywhere + CHECK(Bezogonkow("\xB1") == "\xB1"); + CHECK(Bezogonkow("\xB1\xB2") == "\xB1,"); + CHECK(Bezogonkow(kWin1250) == "ACELNOSZZacelnoszz"); + // the last entry of the table, and the first: none is left out and none added + CHECK(Bezogonkow("\xFF") == "?"); + CHECK(Bezogonkow("\x80") == "E"); + // the letters of other languages the table knows (c-caron, e-caron, s-caron, u-ring, a-acute) + CHECK(Bezogonkow("\xE8\xEC\x9A\xF9\xE1") == "cesua"); } TEST_CASE("utilities: utf-8 is decoded into code points of one to four bytes") { @@ -697,11 +728,84 @@ TEST_CASE("utilities: the folders of the user's settings and of the cache are na #if defined(_WIN32) CHECK(user_config_path("eu07.ini").empty() == (std::getenv("APPDATA") == nullptr)); CHECK(user_cache_path("x").empty() == (std::getenv("LOCALAPPDATA") == nullptr)); -#else +#elif defined(__APPLE__) CHECK(user_config_path("eu07.ini").empty() == (std::getenv("HOME") == nullptr)); +#else + // the folders the XDG variables of this environment give, or the ones in the home folder + auto const expected{[](char const *Variable, char const *Fallback, char const *Filename) { + auto const base{xdg_base_directory(std::getenv(Variable), std::getenv("HOME"), Fallback)}; + return base.empty() ? std::filesystem::path{} : base / "MaSzyna" / Filename; + }}; + auto const config{xdg_config_folder(std::getenv("XDG_CONFIG_HOME"), std::getenv("HOME"))}; + CHECK(user_config_path("eu07.ini") == (config.empty() ? std::filesystem::path{} : config / "eu07.ini")); + CHECK(user_cache_path("geoportal") == expected("XDG_CACHE_HOME", ".cache", "geoportal")); #endif } +TEST_CASE("utilities: the folders of the XDG base directory spec, as Linux finds them") { + using path = std::filesystem::path; + SUBCASE("the variable, when it is set to an absolute path") { + CHECK(xdg_base_directory("/srv/config", "/home/user", ".config") == path{"/srv/config"}); + CHECK(xdg_base_directory("/srv/config", nullptr, ".config") == path{"/srv/config"}); + CHECK(xdg_base_directory("/srv/config", "", ".config") == path{"/srv/config"}); + CHECK(xdg_base_directory("/", "/home/user", ".cache") == path{"/"}); + } + SUBCASE("the folder in the home one, when the variable isn't set, is empty or holds a relative path") { + CHECK(xdg_base_directory(nullptr, "/home/user", ".config") == path{"/home/user"} / ".config"); + CHECK(xdg_base_directory("", "/home/user", ".config") == path{"/home/user"} / ".config"); + CHECK(xdg_base_directory("config", "/home/user", ".config") == path{"/home/user"} / ".config"); + CHECK(xdg_base_directory("./cache", "/home/user", ".cache") == path{"/home/user"} / ".cache"); + CHECK(xdg_base_directory("~/cache", "/home/user", ".cache") == path{"/home/user"} / ".cache"); + } + SUBCASE("none, without the variable and without the home folder") { + CHECK(xdg_base_directory(nullptr, nullptr, ".config").empty()); + CHECK(xdg_base_directory("", "", ".cache").empty()); + CHECK(xdg_base_directory("relative", nullptr, ".cache").empty()); + } + SUBCASE("the settings and the cache: each of its own variable, the same home") { + auto const config{xdg_base_directory("/xdg/config", "/home/user", ".config")}; + auto const cache{xdg_base_directory(nullptr, "/home/user", ".cache")}; + CHECK(config / "MaSzyna" / "eu07.ini" == path{"/xdg/config/MaSzyna/eu07.ini"}); + CHECK(cache / "MaSzyna" / "geoportal" == path{"/home/user/.cache/MaSzyna/geoportal"}); + } +} + +TEST_CASE("utilities: the settings stay in ~/.config/MaSzyna while XDG_CONFIG_HOME has no MaSzyna folder") { + using path = std::filesystem::path; + // in the working folder, as the other tests do: a fixed name in the shared temp folder could be taken over by another user + auto const home{std::filesystem::current_path() / "eu07_unit_xdg_config_home"}; + std::filesystem::remove_all(home); + auto const homename{home.string()}; + // an absolute posix path which doesn't exist, on every system the tests run on + char const *const xdg{"/eu07_test_xdg_config_nowhere"}; + SUBCASE("without the old folder the settings go where XDG says") { + CHECK(xdg_config_folder(xdg, homename.c_str()) == path{xdg} / "MaSzyna"); + CHECK(xdg_config_folder(nullptr, homename.c_str()) == home / ".config" / "MaSzyna"); + } + SUBCASE("the old folder is kept while the new one doesn't exist") { + std::filesystem::create_directories(home / ".config" / "MaSzyna"); + CHECK(xdg_config_folder(xdg, homename.c_str()) == home / ".config" / "MaSzyna"); + CHECK(xdg_config_folder(nullptr, homename.c_str()) == home / ".config" / "MaSzyna"); + // the old folder needs the home folder to be found + CHECK(xdg_config_folder(xdg, nullptr) == path{xdg} / "MaSzyna"); + } + SUBCASE("a file of that name isn't the old folder") { + std::filesystem::create_directories(home / ".config"); + std::ofstream{home / ".config" / "MaSzyna"} << "x"; + CHECK(xdg_config_folder(xdg, homename.c_str()) == path{xdg} / "MaSzyna"); + } +#ifndef _WIN32 + SUBCASE("the new folder is taken once it exists") { + auto const config{home / "xdg"}; + std::filesystem::create_directories(config / "MaSzyna"); + std::filesystem::create_directories(home / ".config" / "MaSzyna"); + auto const configname{config.string()}; + CHECK(xdg_config_folder(configname.c_str(), homename.c_str()) == config / "MaSzyna"); + } +#endif + std::filesystem::remove_all(home); +} + // numbers ------------------------------------------------------------------------------------------------------------- TEST_CASE("utilities: the sign of a number, and a number rounded to a whole one") { diff --git a/tests/unit/test_whole_file.cpp b/tests/unit/test_whole_file.cpp new file mode 100644 index 000000000..f1cd98b5c --- /dev/null +++ b/tests/unit/test_whole_file.cpp @@ -0,0 +1,59 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scratch.h" + +#include "utilities/wholefile.h" + +#include +#include + +// the read of a whole file in one go (utilities/wholefile.cpp), which the loader of the binary models (.e3d) parses +// from memory: the bytes come as they are in the file, whatever they are + +using namespace std::string_view_literals; + +namespace { + +std::string_view content(whole_file const &File) { + return {File.data.get(), File.size}; +} + +} // namespace + +TEST_CASE("whole file: the bytes come as they are in the file, the line ends and the text end marks too") { + test::scratch_folder const folder{"whole_file"}; + // all the byte values, then a size which isn't a multiple of any buffer, so the end of the file is read as well + std::string bytes; + for (int i{0}; i < 256; ++i) { + bytes += static_cast(i); + } + bytes += "\r\n\n\r\x1a\x00\xff"sv; + std::string text; + while (text.size() < 70000) { + text += bytes; + } + text += "end"; + auto const path{folder.write("model.e3d", text)}; + + auto const file{read_whole_file(path)}; + REQUIRE(file.size == text.size()); + CHECK(content(file) == text); +} + +TEST_CASE("whole file: a small file is read whole") { + test::scratch_folder const folder{"whole_file_small"}; + auto const path{folder.write("e3d0.e3d", "E3D0")}; + auto const file{read_whole_file(path)}; + CHECK(content(file) == "E3D0"); +} + +TEST_CASE("whole file: an empty file and a file which isn't there give no data") { + test::scratch_folder const folder{"whole_file_none"}; + auto const empty{read_whole_file(folder.write("empty.e3d", ""))}; + CHECK(empty.size == 0); + CHECK(empty.data == nullptr); + + auto const missing{read_whole_file(folder.path("missing.e3d"))}; + CHECK(missing.size == 0); + CHECK(missing.data == nullptr); +} diff --git a/tests/unit/test_win1250.cpp b/tests/unit/test_win1250.cpp index f1d861e94..77fe35a5f 100644 --- a/tests/unit/test_win1250.cpp +++ b/tests/unit/test_win1250.cpp @@ -8,6 +8,8 @@ namespace std::string const kWin1250{"\xA5\xC6\xCA\xA3\xD1\xD3\x8C\x8F\xAF\xB9\xE6\xEA\xB3\xF1\xF3\x9C\x9F\xBF"}; std::string const kUtf8{"\xC4\x84\xC4\x86\xC4\x98\xC5\x81\xC5\x83\xC3\x93\xC5\x9A\xC5\xB9\xC5\xBB" "\xC4\x85\xC4\x87\xC4\x99\xC5\x82\xC5\x84\xC3\xB3\xC5\x9B\xC5\xBA\xC5\xBC"}; +// the name of a station the way a timetable has it: Biala_Podlaska with its l-stroke, in windows-1250 +std::string const kBiala{"Bia\xB3" "a_Podlaska"}; } // namespace TEST_CASE("win1250: the polish letters of a scenery file read as utf-8") { @@ -32,3 +34,82 @@ TEST_CASE("win1250: utf-8 written back the way a scenery file has it") { // the letters other than the polish ones turn into question marks CHECK(utf8_to_win1250("\xC3\xA9t\xC3\xA9") == "?t?"); } + +TEST_CASE("win1250: a text of a data file is turned into utf-8 for the user interface") { + // plain ascii stays + CHECK(data_text_to_utf8("tor 1, km 0.178") == "tor 1, km 0.178"); + CHECK(data_text_to_utf8("").empty()); + // windows-1250: the polish letters + CHECK(data_text_to_utf8(kWin1250) == kUtf8); + CHECK(data_text_to_utf8(kBiala) == "Bia\xC5\x82" "a_Podlaska"); + // and the letters of the other languages of the code page: a-acute, z-caron, i-acute, u-diaeresis, o-double-acute + CHECK(data_text_to_utf8("n\xE1" "dra\x9E\xED") == "n\xC3\xA1" "dra\xC5\xBE\xC3\xAD"); + CHECK(data_text_to_utf8("\xFC\xF5") == "\xC3\xBC\xC5\x91"); + // a character outside of the two-byte range (the euro sign), and a byte the code page has nothing for + CHECK(data_text_to_utf8("5 \x80") == "5 \xE2\x82\xAC"); + CHECK(data_text_to_utf8("a\x81" "b") == "a?b"); + // a text already in utf-8 stays as it is + CHECK(data_text_to_utf8(kUtf8) == kUtf8); + CHECK(data_text_to_utf8("Bia\xC5\x82" "a Podlaska") == "Bia\xC5\x82" "a Podlaska"); + CHECK(data_text_to_utf8("\xE2\x94\x82 60 \xE2\x94\x82") == "\xE2\x94\x82 60 \xE2\x94\x82"); + // capital letters with marks in a row make valid utf-8 by chance (O-acute and L-stroke: D3 A3), but of a + // cyrillic letter; they are read as the windows-1250 they are + CHECK(data_text_to_utf8("W\xD3\xA3KA") == "W\xC3\x93\xC5\x81KA"); + CHECK(data_text_to_utf8("R\xD3\xAF" "A") == "R\xC3\x93\xC5\xBB" "A"); + // line ends and tabs of a longer text stay + CHECK(data_text_to_utf8("jedna\n\tdruga \xB3") == "jedna\n\tdruga \xC5\x82"); + // what comes out is valid utf-8 + std::u32string decoded; + std::string all; + for (auto value{0x20}; value < 0x100; ++value) { + all += static_cast(value); + } + REQUIRE(utf8_to_utf32(data_text_to_utf8(all), decoded)); + CHECK(decoded.size() == all.size()); +} + +TEST_CASE("win1250: a name of a data file is shown in one line, with its letters") { + // what Bezogonkow() did for the user interface, but for the marks: control characters and, when asked, + // underscores turn into spaces + CHECK(data_name_to_utf8("a\tb\nc") == "a b c"); + CHECK(data_name_to_utf8(kBiala) == "Bia\xC5\x82" "a_Podlaska"); + CHECK(data_name_to_utf8(kBiala, true) == "Bia\xC5\x82" "a Podlaska"); + CHECK(data_name_to_utf8("Warszawa_Zachodnia", true) == "Warszawa Zachodnia"); + CHECK(data_name_to_utf8("Warszawa_Zachodnia") == "Warszawa_Zachodnia"); + CHECK(data_name_to_utf8("Bia\xC5\x82" "a_Podlaska\r", true) == "Bia\xC5\x82" "a Podlaska "); + // for a name without letters outside of ascii it gives what Bezogonkow() gave + for (auto const *name : {"Warszawa_Zachodnia", "Gorna", "tor 1\t2", "", "Os1234"}) { + CAPTURE(name); + CHECK(data_name_to_utf8(name) == Bezogonkow(name)); + CHECK(data_name_to_utf8(name, true) == Bezogonkow(name, true)); + } +} + +TEST_CASE("win1250: a column of the timetable panel is as wide in letters as it was in bytes") { + CHECK(utf8_length("") == 0); + CHECK(utf8_length("Gorna") == 5); + CHECK(utf8_length("Bia\xC5\x82" "a Podlaska") == 14); + CHECK(utf8_length(kUtf8) == 18); + CHECK(utf8_length("\xE2\x94\x82 60 \xE2\x94\x82") == 6); + // a byte which is no part of a valid sequence counts as a character + CHECK(utf8_length("a\xB3" "b") == 3); + CHECK(utf8_length("a\xC5") == 2); + + // filled with spaces + CHECK(utf8_fit("Gorna", 8) == "Gorna "); + CHECK(utf8_fit("", 3) == " "); + auto const caption{data_name_to_utf8(kBiala, true)}; + auto const fitted{utf8_fit(caption, 34)}; + CHECK(utf8_length(fitted) == 34); + CHECK(fitted.size() == 35); // one letter of two bytes + CHECK(fitted.starts_with(caption)); + // cut between the letters, never inside of one + CHECK(utf8_fit("Bia\xC5\x82" "a Podlaska", 4) == "Bia\xC5\x82"); + CHECK(utf8_fit("Bia\xC5\x82" "a Podlaska", 3) == "Bia"); + CHECK(utf8_fit(kUtf8, 2) == "\xC4\x84\xC4\x86"); + CHECK(utf8_fit("Gorna", 0).empty()); + // a name of ascii fits the way the panel cut it before + std::string const longname{"Bardzo_Dluga_Nazwa_Stacji_Wezlowej_Osobowej"}; + CHECK(utf8_fit(longname, 34) == (longname + " ").substr(0, 34)); + CHECK(utf8_fit("Gorna", 34) == (std::string{"Gorna"} + " ").substr(0, 34)); +} diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp index e38999f7d..afbac8680 100644 --- a/tests/unit/vehicle.cpp +++ b/tests/unit/vehicle.cpp @@ -170,6 +170,8 @@ TTrackShape shape_of(track const &Track) { TTrackShape shape; shape.Len = 1000.0; shape.dHtrack = Track.gradient; + shape.R = Track.radius; + shape.dHrail = Track.cant; return shape; } @@ -177,6 +179,7 @@ TTrackParam parameters_of(track const &Track, TMoverParameters const &Mover) { TTrackParam param; param.Width = Track.width; param.friction = Track.friction; + param.Name = &Track.name; // the vehicle's own kind of way: a road vehicle on rails derails as soon as it moves if (Track.category != 0) { param.CategoryFlag = Track.category; @@ -192,6 +195,7 @@ TTrackParam parameters_of(track const &Track, TMoverParameters const &Mover) { double vehicle::fast_move(track const &Track, double Dt, TLocation const &Location) { // TDynamicObject::FastUpdate(), the iterations of a frame before the last one auto param{parameters_of(Track, *m_mover)}; + param.DamageFlag = m_trackdamage; return m_mover->FastComputeMovement(Dt, shape_of(Track), param, Location, TRotation{0.0, 0.0, 0.0}); } @@ -214,7 +218,8 @@ void vehicle::forces(double Dt) { double vehicle::move(track const &Track, double Dt, TLocation const &Location, double Trainpipe) { auto const shape{shape_of(Track)}; - auto const param{parameters_of(Track, *m_mover)}; + auto param{parameters_of(Track, *m_mover)}; + param.DamageFlag = m_trackdamage; TRotation const rotation{0.0, 0.0, 0.0}; // what TDynamicObject::Update() does before the movement. a raised pantograph touches the wire at once, @@ -332,6 +337,8 @@ void pair::step(track const &Track, double Dt) { auto const &mover{placed.owner->mover()}; placed.position += placed.heading * placed.owner->move(Track, Dt, TLocation{placed.position, 0.0, 0.0}, mover.PipePress); } + // vehicle_table::update_brake_pipes() + TMoverParameters::UpdatePipeCouplers({&m_vehicles[0].owner->mover(), &m_vehicles[1].owner->mover()}, Dt); } void pair::run(double Seconds, track const &Track, double Dt) { diff --git a/tests/unit/vehicle.h b/tests/unit/vehicle.h index e14f4e464..05c03dbf6 100644 --- a/tests/unit/vehicle.h +++ b/tests/unit/vehicle.h @@ -66,6 +66,9 @@ struct track { int category{0}; int iterations{1}; double width{1.435}; + double radius{0.0}; // of a curve [m], 0 straight + double cant{0.0}; // [rad] + std::string name; // for the log }; // the catenary of the Polish railways [V] @@ -89,6 +92,9 @@ public: // keeps the main reservoir at the given pressure [bar], as a running compressor or a coupled vehicle // feeding it would; a negative value leaves it alone void hold_main_reservoir(double Pressure) { m_reservoirpressure = Pressure; } + // the track under this vehicle alone has the damage flags (dtrack_*) from now on: dtrack_norail runs it off the + // end of the track in its next step, as the legacy derailment has it + void damage_track(int Flags) { m_trackdamage = Flags; } // advances the physics by one frame of Track.iterations steps of Dt, the way the simulation loop does void step(track const &Track = {}, double Dt = 0.01); @@ -113,6 +119,7 @@ private: int m_cab{0}; double m_pipepressure{-1.0}; double m_reservoirpressure{-1.0}; + int m_trackdamage{0}; trace *m_trace{nullptr}; double m_time{0.0}; // of the simulation, since the vehicle got created }; diff --git a/tools/track_uneven_grade.py b/tools/track_uneven_grade.py index ba60be900..889e0ad0f 100644 --- a/tools/track_uneven_grade.py +++ b/tools/track_uneven_grade.py @@ -7,7 +7,7 @@ curves, speed and road crossings. The originals stay as they are, graded copies python track_uneven_grade.py scenery/baltyk_skm1.scn --out graded --route -107,2300 -4120,2491 --straight tor0290,tor0906 python track_uneven_grade.py scenery/mytracks.scm --root scenery --out graded --gain 1.2 -With no --out it only reports. See track_uneven_doc.md for the attribute. Python 3.8 or later, no other packages. +With no --out it only reports. See docs/track_uneven_doc.md for the attribute. Python 3.8 or later, no other packages. """ import argparse import collections diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 71ab7987c..97b6b33b1 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationenvironment.h" #include "vehicle/Driver.h" #include "utilities/Logs.h" +#include "utilities/inionlysettings.h" #include "utilities/utilities.h" #include "world/catenary_span.h" #include "Console.h" @@ -244,6 +245,65 @@ bool global_settings::ConfigParseAudio(cParser& Parser, const std::string& token return true; } + return ConfigParseAudioDevice(Parser, token); +} + +bool global_settings::ConfigParseAudioDevice(cParser& Parser, const std::string& token) +{ + if (token == "sound.outputmode") + { + AudioOutputMode = Parser.getToken(true); + return true; + } + + if (token == "sound.hrtf") + { + AudioHrtf = Parser.getToken(true); + return true; + } + + if (token == "sound.hrtf.profile") + { + AudioHrtfProfile = Parser.getToken(false); + return true; + } + + if (token == "sound.resampler") + { + AudioResampler = Parser.getToken(false); + return true; + } + + if (token == "sound.limiter") + { + AudioLimiter = Parser.getToken(true); + return true; + } + + if (token == "sound.frequency") + { + ParseOneClamped(Parser, AudioFrequency, 0, 192000); + return true; + } + + if (token == "sound.doppler") + { + ParseOneClamped(Parser, AudioDoppler, 0.f, 10.f); + return true; + } + + if (token == "sound.efx.lowpass") + { + ParseOne(Parser, AudioLowpass); + return true; + } + + if (token == "sound.efx.airabsorption") + { + ParseOneClamped(Parser, AudioAirAbsorption, 0.f, 10.f); + return true; + } + return false; } @@ -477,6 +537,13 @@ bool global_settings::ConfigParseInput(cParser& Parser, const std::string& token return true; } + if (token == "consistviews") + { + // no: [Shift]+[F4] cycles through the four views of the train it had before the views of its vehicles + ParseOne(Parser, ConsistViews); + return true; + } + if (token == "input.gamepad") { ParseOne(Parser, InputGamepad); @@ -579,6 +646,14 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + // the saved odometer states of the vehicles not run for this many days are dropped, 0 = never (vehicle/odometer.h) + if (token == "odometer.expiry") + { + ParseOne(Parser, odometer_expiry); + odometer_expiry = std::max(0, odometer_expiry); + return true; + } + if (token == "blackbox") { bool blackbox{false}; @@ -931,7 +1006,12 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& { std::string text; ParseOne(Parser, text); - Global.random_seed = seed_of(text); + // nothing after the key gives no seed; anything else does, 0 too + if (auto const seed{seed_given(text)}) + { + Global.random_seed = *seed; + Global.random_seed_given = true; + } return true; } @@ -953,6 +1033,20 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + if (token == "physics.trackbuckling") + { + // off, scenery: the buckles of the scenery and its events, auto: also by the temperature of the rails + std::string mode; + ParseOne(Parser, mode, 1); + if (mode == "off" || mode == "no") + track_buckling = track_buckling_mode::off; + else if (mode == "auto") + track_buckling = track_buckling_mode::automatic; + else + track_buckling = track_buckling_mode::scenery; + return true; + } + if (token == "couplerphysics") { // yes: the player's train and the trains it closes in on, all: every train @@ -963,6 +1057,32 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + if (token == "physics.derailment") + { + // new: the physical criteria (McZapkie/derailment.h), old: the legacy draw, off: no derailment from the speed, + // monitor: the legacy draw, and the criteria to the log + std::string model; + ParseOne(Parser, model, 1); + derailment = derailment_model_of(model); + return true; + } + + if (token == "physics.trackcheck") + { + ParseOne(Parser, track_check, 1); + return true; + } + + if (token == "physics.collisions") + { + // new: the crush of the ends past the buffers (McZapkie/collision.h), old: the legacy rule, monitor: the legacy + // rule, and the crush to the log + std::string model; + ParseOne(Parser, model, 1); + collisions = collision_model_of(model); + return true; + } + if (token == "controlcoupling.enginecheck") { ParseOne(Parser, control_coupling_engine_check, 1); @@ -1037,6 +1157,15 @@ bool global_settings::ConfigParseScriptScreens(cParser& Parser, std::string_view return true; } + // the scenery scripts (lua in the .scn) with all of LuaJIT's libraries, for a scenery that needs io, ffi or + // require: they then reach files and programs as the player does. from eu07.ini only: a config block of the + // scenery doesn't change it (utilities/inionlysettings.h) + if (token == "lua.fulllibraries") + { + ParseOne(Parser, lua_fulllibraries, 1); + return true; + } + if (token == "wasm.enabled") { ParseOne(Parser, wasm_enabled, 1); @@ -1536,8 +1665,10 @@ bool global_settings::ConfigParseDebug(cParser& Parser, const std::string& token return false; } -void global_settings::ConfigParse(cParser& Parser) +void global_settings::ConfigParse(cParser& Parser, config_source const Source) { + // what a scenery doesn't change, kept before its keys are read + std::optional const inionly{Source == config_source::scenery ? std::make_optional(*this) : std::nullopt}; std::string token; do @@ -1595,6 +1726,15 @@ void global_settings::ConfigParse(cParser& Parser) } while (true); + if (inionly.has_value()) + { + // put back before FinalizeConfig() acts on them (feedbackmode) + for (auto const key : inionly->restore(*this)) + { + ErrorLog("scenery config: \"" + std::string(key) + "\" is read from eu07.ini only, ignored"); + } + } + FinalizeConfig(); } @@ -2343,8 +2483,19 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "fmradio.enabled", fmradio_enabled ); export_as_text( Output, "fmradio.cleansound", fmradio_cleansound ); export_as_text( Output, "fmradio.stations", fmradio_stations ); + export_as_text( Output, "sound.maxsources", audio_max_sources ); + export_as_text( Output, "sound.outputmode", AudioOutputMode ); + export_as_text( Output, "sound.hrtf", AudioHrtf ); + export_as_text( Output, "sound.hrtf.profile", AudioHrtfProfile ); + export_as_text( Output, "sound.resampler", AudioResampler ); + export_as_text( Output, "sound.limiter", AudioLimiter ); + export_as_text( Output, "sound.frequency", AudioFrequency ); + export_as_text( Output, "sound.doppler", AudioDoppler ); + export_as_text( Output, "sound.efx.lowpass", AudioLowpass ); + export_as_text( Output, "sound.efx.airabsorption", AudioAirAbsorption ); export_as_text( Output, "physicslog", WriteLogFlag ); export_as_text( Output, "physicslog.trains", WriteTrainLogFlag ); + export_as_text( Output, "odometer.expiry", odometer_expiry ); if( BlackBox ) { export_as_text( Output, "blackbox", *BlackBox ); } @@ -2364,6 +2515,7 @@ global_settings::export_as_text( std::ostream &Output ) const { << fMouseXScale << " " << fMouseYScale << "\n"; export_as_text( Output, "mousecontrol", InputMouse ); + export_as_text( Output, "consistviews", ConsistViews ); export_as_text( Output, "enabletraction", bEnableTraction ); export_as_text( Output, "loadtraction", bLoadTraction ); export_as_text( Output, "friction", fFriction ); @@ -2386,6 +2538,10 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "scenario.time.offset", ScenarioTimeOffset ); export_as_text( Output, "scenario.time.current", ScenarioTimeCurrent ); export_as_text( Output, "scenario.weather.temperature", AirTemperature ); + export_as_text( Output, "physics.trackbuckling", std::string{ + track_buckling == track_buckling_mode::off ? "off" : + track_buckling == track_buckling_mode::automatic ? "auto" : + "scenery" } ); export_as_text( Output, "ai.trainman", AITrainman ); export_as_text( Output, "controlcoupling.enginecheck", control_coupling_engine_check ); std::string couplerphysics { coupler_physics ? "yes" : "no" }; @@ -2393,6 +2549,9 @@ global_settings::export_as_text( std::ostream &Output ) const { couplerphysics = "all"; } export_as_text( Output, "couplerphysics", couplerphysics ); + export_as_text( Output, "physics.derailment", std::string{ name_of( derailment ) } ); + export_as_text( Output, "physics.trackcheck", track_check ); + export_as_text( Output, "physics.collisions", std::string{ name_of( collisions ) } ); export_as_text( Output, "ai.brakesetting.cw1", AIBrakeSettingCw1 ); export_as_text( Output, "scalespeculars", ScaleSpecularValues ); export_as_text( Output, "gfxrenderer", GfxRenderer ); @@ -2721,6 +2880,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "python.uploadmain", python_uploadmain ); export_as_text( Output, "python.mipmaps", python_mipmaps ); export_as_text( Output, "luascreens.enabled", luascreens_enabled ); + export_as_text( Output, "lua.fulllibraries", lua_fulllibraries ); export_as_text( Output, "wasm.enabled", wasm_enabled ); export_as_text( Output, "screens.cabframes", screens_cabframes ); export_as_text( Output, "screens.externalframes", screens_externalframes ); diff --git a/utilities/Globals.h b/utilities/Globals.h index 2998ca813..f9ecb9fbb 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -25,6 +25,12 @@ http://mozilla.org/MPL/2.0/. #include "input/zmq_input.h" #endif +// where the keys global_settings::ConfigParse reads come from +enum class config_source { + ini, // eu07.ini, and the file given with -ini + scenery // a config block of a scenery (.scn, .inc), read as it loads +}; + struct global_settings { // members // data items @@ -50,6 +56,9 @@ struct global_settings { bool ready_to_load{ false }; std::time_t starting_timestamp = 0; // starting time, in local timezone uint32_t random_seed = 0; + // whether random_seed was given (-seed, randomseed, the server of a network session) or is still to be drawn: + // 0 is a seed like any other, so it can't stand for none + bool random_seed_given{ false }; TCamera pCamera; // parametry kamery TCamera pDebugCamera; std::array FreeCameraInit; // pozycje kamery @@ -123,6 +132,9 @@ struct global_settings { bool ParserLogIncludes{ true }; // simulation bool RealisticControlMode{ false }; // controls ability to steer the vehicle from outside views + // odometer.expiry: the saved odometer state of a vehicle not run for longer than this many days is dropped from the + // store (vehicle/odometer.h); 0 = never + int odometer_expiry{ 365 }; bool bEnableTraction{ true }; float fFriction{ 1.f }; // mnożnik tarcia - KURS90 float FrictionWeatherFactor{ 1.f }; @@ -273,6 +285,16 @@ struct global_settings { bool fmradio_enabled{ true }; // allows cab radio receivers to play internet radio streams bool fmradio_cleansound{ false }; // disables simulation of the receiver speaker std::string fmradio_stations{ "fmradio.txt" }; // list of stations available to the receivers + // OpenAL Soft device and mixing options; the defaults leave the choice to the library, as before they existed + std::string AudioOutputMode{ "auto" }; // sound.outputmode: auto, mono, stereo, stereo-basic, uhj, headphones, quad, 5.1, 6.1, 7.1 + std::string AudioHrtf{ "auto" }; // sound.hrtf: auto, on, off + std::string AudioHrtfProfile; // sound.hrtf.profile: name of the HRTF data set, empty for the library's choice + std::string AudioResampler; // sound.resampler: name of the resampler, empty for the library's default + std::string AudioLimiter{ "auto" }; // sound.limiter: auto, on, off + int AudioFrequency{ 0 }; // sound.frequency: mixing rate in Hz, 0 for the device's + float AudioDoppler{ 0.25f }; // sound.doppler: strength of the Doppler effect + bool AudioLowpass{ false }; // sound.efx.lowpass: soundproofing also muffles the high frequencies + float AudioAirAbsorption{ 0.f }; // sound.efx.airabsorption: 0-10, high frequencies fade with distance // input float fMouseXScale{ 1.5f }; float fMouseYScale{ 0.2f }; @@ -280,6 +302,7 @@ struct global_settings { int iFeedbackPort{ 0 }; // dodatkowy adres dla informacji zwrotnych bool InputGamepad{ true }; // whether gamepad support is enabled bool InputMouse{ true }; // whether control pick mode can be activated + bool ConsistViews{ true }; // whether [Shift]+[F4] goes on to the orbit, shunting, coupling and trackside views of the train (eu07/maszyna#551) double fBrakeStep { 1.0 }; // krok zmiany hamulca innych niż FV4a dla klawiszy [Num3] i [Num9] double brake_speed { 3.0 }; // prędkość przesuwu hamulca dla FV4a // parametry kalibracyjne wejść z pulpitu @@ -332,12 +355,34 @@ struct global_settings { bool captureonstart = true; bool render_cab = true; bool crash_damage = true; + // the buckling of welded track in the heat (physics.trackbuckling in eu07.ini, see world/TrackBuckle.h): off, none; scenery, the + // buckles the scenery enters and its trackbuckle events; automatic, also by the temperature of the rails at the weak places + enum class track_buckling_mode { off, scenery, automatic }; + track_buckling_mode track_buckling = track_buckling_mode::scenery; // the physical model of the couplings (McZapkie/couplerphysics.h): progressive buffers and draw gear with hysteresis, // the play of the coupling, its yield and breaking; the legacy model of TMoverParameters::CouplerForce() without it. // it covers the player's train and the trains it closes in on (vehicle_table::update_coupler_physics()), or every // train with coupler_physics_all bool coupler_physics = false; bool coupler_physics_all = false; + // a vehicle too fast in a curve (physics.derailment in eu07.ini): new, it overturns or its flange climbs the rail + // by the criteria of McZapkie/derailment.h held over 2 m, and slides on with the friction of the ballast; old, the + // legacy draw of the lateral acceleration against the gauge to the height of the vehicle in every step, which stops + // it; off, it stays on the rails at any speed; monitor, the legacy draw decides and the log tells where the criteria + // would derail a vehicle (derailment monitor:, once for a vehicle on a track), for the run of a scenery as it was. + // monitor is the default until the speed limits of the bundled sceneries are checked against the criteria (some + // tracks allow more than the reference vehicle survives there): new is opt-in until then + enum class derailment_model { off, old, physical, monitor }; + derailment_model derailment = derailment_model::monitor; + // the collisions of rail vehicles past their buffers (physics.collisions in eu07.ini): new, the ends crush, a vehicle + // may ride up onto the other one or be pushed off the track (McZapkie/collision.h); old, the legacy rule of the safe + // closing speed weighed by the masses; monitor, the legacy rule decides and the log tells what the crush would be + // (collision monitor:, once for a hit). the road vehicles of the traffic keep the legacy rule with any + enum class collision_model { old, physical, monitor }; + collision_model collisions = collision_model::physical; + // physics.trackcheck: the geometry of the rail tracks the criteria of derailment find suspicious, to the log once the + // scenery loaded (trackcheck:, see world/TrackCheck.h) + bool track_check = false; bool control_coupling_engine_check = true; // no multiple-unit control between electric and diesel traction vehicles (eu07/maszyna#520) bool gui_defaultwindows = true; bool gui_showtranscripts = true; @@ -360,6 +405,7 @@ struct global_settings { bool python_uploadmain = true; std::chrono::duration python_minframetime {0.01f}; bool luascreens_enabled{true}; // screens drawn by Lua scripts (luascreen:, luadestinationsign: in the .mmd) + bool lua_fulllibraries{false}; // the scenery scripts (lua in the .scn) get all of LuaJIT's libraries (io, os, ffi, require...), not only the sandboxed ones bool wasm_enabled{true}; // screens drawn by WebAssembly modules (wasmscreen:, wasmdestinationsign: in the .mmd) int screens_cabframes{4}; // the script screens in the cab are refreshed every so many rendered frames int screens_externalframes{30}; // the script screens outside the cab (destination signs) are refreshed every so many rendered frames @@ -728,9 +774,12 @@ struct global_settings { // methods void LoadIniFile( std::string asFileName ); void FinalizeConfig(); - void ConfigParse(cParser &parser); + // the keys of eu07.ini. Source: where they come from, eu07.ini or a config block of a scenery, which doesn't change + // the settings only eu07.ini sets (utilities/inionlysettings.h) + void ConfigParse(cParser &parser, config_source Source = config_source::ini); bool ConfigParseGeneral(cParser& Parser, const std::string& token); bool ConfigParseAudio(cParser& Parser, const std::string& token); + bool ConfigParseAudioDevice(cParser& Parser, const std::string& token); bool ConfigParseGraphics(cParser& Parser, const std::string& token); bool ConfigParseInput(cParser& Parser, const std::string& token); bool ConfigParseSimulation(cParser& Parser, const std::string& token); @@ -768,6 +817,37 @@ template <> void global_settings::export_as_text( std::ostream &Output, std::string const Key, bool const &Value ) const; +// the models of physics.collisions by their names in eu07.ini: new (the default, also for a name it doesn't know), old, +// monitor +inline global_settings::collision_model collision_model_of( std::string_view const Name ) { + if( Name == "old" ) { return global_settings::collision_model::old; } + if( Name == "monitor" ) { return global_settings::collision_model::monitor; } + return global_settings::collision_model::physical; +} +inline std::string_view name_of( global_settings::collision_model const Model ) { + switch( Model ) { + case global_settings::collision_model::old: { return "old"; } + case global_settings::collision_model::monitor: { return "monitor"; } + default: { return "new"; } + } +} +// the models of physics.derailment by their names in eu07.ini: new, old, off or no, monitor (the default, also for a +// name it doesn't know) +inline global_settings::derailment_model derailment_model_of(std::string_view const Name) { + if( Name == "new" ) { return global_settings::derailment_model::physical; } + if( Name == "old" ) { return global_settings::derailment_model::old; } + if( Name == "off" || Name == "no" ) { return global_settings::derailment_model::off; } + return global_settings::derailment_model::monitor; +} +inline std::string_view name_of( global_settings::derailment_model const Model ) { + switch( Model ) { + case global_settings::derailment_model::old: { return "old"; } + case global_settings::derailment_model::off: { return "off"; } + case global_settings::derailment_model::monitor: { return "monitor"; } + default: { return "new"; } + } +} + extern global_settings& GetGlobalSettings(); #define Global (GetGlobalSettings()) diff --git a/utilities/Logs.cpp b/utilities/Logs.cpp index 7eb99ad7c..47852be26 100644 --- a/utilities/Logs.cpp +++ b/utilities/Logs.cpp @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "utilities/Logs.h" +#include "utilities/logfiles.h" #include "utilities/crashsignals.h" #include @@ -83,6 +84,12 @@ std::atomic &log_stopped() static std::atomic stopped{false}; return stopped; } +// set once the settings are read: the files are named by them (multiplelogs, the scenery) +std::atomic &log_files_open() +{ + static std::atomic open{false}; + return open; +} } // namespace void StopLogService() @@ -90,6 +97,11 @@ void StopLogService() log_stopped() = true; } +void OpenLogFiles() +{ + log_files_open() = true; +} + void LogService() { @@ -97,6 +109,13 @@ void LogService() for (bool last{false}; false == last;) { last = log_stopped(); + // what is logged before the settings are read waits for them, or it would open (and empty) the shared log.txt + // of a run that writes its own files in logs/. a start that stops before that writes it anyway + if (false == log_files_open() && false == last) + { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + continue; + } { // --- Obsługa InfoStack --- while (!InfoStack.empty()) @@ -115,7 +134,7 @@ void LogService() { if (!output.is_open()) { - std::string filename = Global.MultipleLogs ? "logs/log (" + filename_scenery() + ") " + filename_date() + ".txt" : "log.txt"; + std::string const filename { log_file_name(log_file::log, Global.MultipleLogs, filename_scenery(), filename_date()) }; output.open(filename, std::ios::trunc); crashdump_set_log_file(crashdump_log_file::log, filename); // the stack of a crash on Linux goes to the end of this file @@ -155,7 +174,7 @@ void LogService() if (!errors.is_open()) { - std::string filename = Global.MultipleLogs ? "logs/errors (" + filename_scenery() + ") " + filename_date() + ".txt" : "errors.txt"; + std::string const filename { log_file_name(log_file::errors, Global.MultipleLogs, filename_scenery(), filename_date()) }; errors.open(filename, std::ios::trunc); crashdump_set_log_file(crashdump_log_file::errors, filename); errors << "EU07.EXE " + Global.asVersion << "\n"; diff --git a/utilities/Logs.h b/utilities/Logs.h index 63727de9c..5fd5d4a56 100644 --- a/utilities/Logs.h +++ b/utilities/Logs.h @@ -26,6 +26,9 @@ enum class logtype : unsigned int { // writes the log until StopLogService(), and all of it that came before void LogService(); void StopLogService(); +// the settings are read: the log files can be named and written from now on; until then the log service keeps what +// is logged +void OpenLogFiles(); void WriteLog( const char *str, logtype const Type = logtype::generic, bool isError = false ); void Error( const std::string &asMessage, bool box = false ); void Error( const char* &asMessage, bool box = false ); diff --git a/utilities/comparison.h b/utilities/comparison.h index f0fc5d0af..1345e690b 100644 --- a/utilities/comparison.h +++ b/utilities/comparison.h @@ -48,11 +48,23 @@ to_string( comparison_operator const Operator ) { case lt: { return "<"; } case gt: { return ">"; } case lt_eq: { return "<="; } - case gt_eq: { return ">"; } + case gt_eq: { return ">="; } default: { return "??"; } } } +inline +std::string +to_string( comparison_pass const Pass ) { + switch( Pass ) { + using enum comparison_pass; + case all: { return "all"; } + case any: { return "any"; } + case none: { return "none"; } + default: { return "all"; } + } +} + inline comparison_pass comparison_pass_from_string( std::string const &Input ) { diff --git a/utilities/hardwareinfo.cpp b/utilities/hardwareinfo.cpp new file mode 100644 index 000000000..3124307ba --- /dev/null +++ b/utilities/hardwareinfo.cpp @@ -0,0 +1,441 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "utilities/hardwareinfo.h" + +#include +#include +#include +#include +#include + +namespace hardware { + +namespace { + +std::string lowercase(std::string_view Text) +{ + std::string result{Text}; + for (auto &c : result) + c = static_cast(std::tolower(static_cast(c))); + return result; +} + +bool contains(std::string_view Text, std::string_view What) +{ + return Text.find(What) != std::string_view::npos; +} + +void erase_all(std::string &Text, std::string_view What) +{ + auto at = Text.find(What); + while (at != std::string::npos) + { + Text.erase(at, What.size()); + at = Text.find(What, at); + } +} + +// the words of a GPU name, lowercase: without the (TM) and (R) marks, and without what follows them in parentheses +// (Mesa adds the driver and the chip: "AMD Radeon Graphics (radeonsi, renoir, LLVM 15.0.7)") +std::vector name_words(std::string_view Name) +{ + auto name{lowercase(Name)}; + erase_all(name, "(tm)"); + erase_all(name, "(r)"); + if (auto const parenthesis = name.find('('); parenthesis != std::string::npos) + name.erase(parenthesis); + std::vector words; + std::string word; + for (auto const c : name) + { + if (std::isalnum(static_cast(c))) + { + word += c; + } + else if (!word.empty()) + { + words.push_back(std::move(word)); + word.clear(); + } + } + if (!word.empty()) + words.push_back(std::move(word)); + return words; +} + +// whether the words hold First directly followed by Second +bool has_pair(std::vector const &Words, std::string_view First, std::string_view Second) +{ + for (std::size_t i = 0; i + 1 < Words.size(); ++i) + if (Words[i] == First && Words[i + 1] == Second) + return true; + return false; +} + +bool has_word(std::vector const &Words, std::string_view What) +{ + return std::ranges::find(Words, What) != Words.end(); +} + +bool is_number(std::string_view Word) +{ + return !Word.empty() && std::ranges::all_of(Word, [](char const c) { return std::isdigit(static_cast(c)) != 0; }); +} + +bool is_software_name(std::string_view Name) +{ + constexpr std::array markers{"llvmpipe", "softpipe", "swiftshader", "gdi generic", "software rasterizer", "basic render driver"}; + auto const name{lowercase(Name)}; + return std::ranges::any_of(markers, [&name](std::string_view const Marker) { return contains(name, Marker); }); +} + +gpu_kind classify_intel(std::vector const &Words) +{ + using enum gpu_kind; + // Iris Xe MAX (DG1) is a laptop card + for (std::size_t i = 0; i + 2 < Words.size(); ++i) + if (Words[i] == "iris" && Words[i + 1] == "xe" && Words[i + 2] == "max") + return discrete; + // the Arc cards have a letter and a number after "Arc" (A310, A770, B580) or are the Pro ones; the integrated Arc + // are "Arc Graphics" (Meteor Lake), "Arc 140V" (Lunar Lake) and "Arc B370", "Arc B390" (Panther Lake), the B3xx + // range, below the B570 and B580 cards + for (std::size_t i = 0; i + 1 < Words.size(); ++i) + { + if (Words[i] != "arc") + continue; + auto const &model{Words[i + 1]}; + if (model == "pro") + return discrete; + if (model.size() >= 2 && model[0] == 'b' && model[1] == '3') + return integrated; + if (model.size() >= 2 && std::isalpha(static_cast(model[0])) && std::isdigit(static_cast(model[1]))) + return discrete; + } + return integrated; +} + +// Raven Ridge and Picasso APUs: "Radeon RX Vega 11 Graphics", "Radeon RX Vega 10 Graphics". the RX Vega cards have +// no "Graphics" ("Radeon RX Vega 56"), and Kaby Lake G's own-memory chip has a letter ("Radeon RX Vega M GH Graphics") +bool is_rx_vega_apu(std::vector const &Words) +{ + if (Words.empty() || Words.back() != "graphics") + return false; + for (std::size_t i = 0; i + 2 < Words.size(); ++i) + if (Words[i] == "rx" && Words[i + 1] == "vega" && is_number(Words[i + 2])) + return true; + return false; +} + +gpu_kind classify_amd(std::vector const &Words) +{ + using enum gpu_kind; + if (is_rx_vega_apu(Words)) + return integrated; + if (has_word(Words, "rx") || has_word(Words, "firepro") || has_word(Words, "instinct") || has_pair(Words, "radeon", "pro") || has_pair(Words, "radeon", "vii")) + return discrete; + // the APUs are "Radeon Graphics", "Radeon Vega 8 Graphics", "Radeon R7 Graphics", "Radeon 780M Graphics"; the + // cards are named by their model ("Radeon RX 580 Series", "Radeon R7 370") + if (!Words.empty() && Words.back() == "graphics") + return integrated; + return unknown; +} + +std::string_view yes_no(int const Value) +{ + if (Value > 0) + return "yes"; + if (Value == 0) + return "no"; + return "unknown"; +} + +// "Key: value" of /proc/cpuinfo and /proc/meminfo +std::pair split_entry(std::string_view Line) +{ + auto const colon = Line.find(':'); + if (colon == std::string_view::npos) + return {}; + auto key{Line.substr(0, colon)}; + auto value{Line.substr(colon + 1)}; + while (!key.empty() && std::isspace(static_cast(key.back()))) + key.remove_suffix(1); + while (!value.empty() && std::isspace(static_cast(value.front()))) + value.remove_prefix(1); + while (!value.empty() && std::isspace(static_cast(value.back()))) + value.remove_suffix(1); + return {key, value}; +} + +template void for_each_line(std::string_view Text, Function &&Each) +{ + while (!Text.empty()) + { + auto const end = Text.find('\n'); + Each(Text.substr(0, end)); + if (end == std::string_view::npos) + break; + Text.remove_prefix(end + 1); + } +} + +std::uint64_t to_number(std::string_view Text) +{ + std::uint64_t result{0}; + for (auto const c : Text) + { + if (!std::isdigit(static_cast(c))) + break; + result = result * 10 + static_cast(c - '0'); + } + return result; +} + +// the state of reading /proc/cpuinfo, line by line +struct cpuinfo_reader +{ + cpu_info cpu; + std::set> cores; // (physical id, core id) + std::set> packages; + int cores_per_package{0}; + std::string package; + + void read(std::string_view Line); +}; + +void cpuinfo_reader::read(std::string_view const Line) +{ + auto const [key, value] = split_entry(Line); + if (key == "processor") + { + ++cpu.logical_cores; + package.clear(); + } + else if ((key == "model name" || key == "Model") && cpu.model.empty()) + { + cpu.model = tidy_name(value); + } + else if (key == "physical id") + { + package = value; + packages.emplace(value); + } + else if (key == "core id") + { + cores.emplace(package, value); + } + else if (key == "cpu cores" && cores_per_package == 0) + { + cores_per_package = static_cast(to_number(value)); + } + else if (key == "flags" && cpu.avx2 < 0) + { + auto const flags{name_words(value)}; + cpu.avx2 = has_word(flags, "avx2") ? 1 : 0; + } +} + +} // namespace + +std::string_view to_string(gpu_kind const Kind) +{ + using enum gpu_kind; + switch (Kind) + { + case integrated: + return "integrated"; + case discrete: + return "discrete"; + case software: + return "software"; + default: + return "unknown"; + } +} + +gpu_kind classify_gpu(std::uint32_t const VendorId, std::string_view const Name) +{ + using enum gpu_kind; + if (is_software_name(Name)) + return software; + auto const words{name_words(Name)}; + switch (VendorId) + { + case vendor_nvidia: + return discrete; + case vendor_intel: + return classify_intel(words); + case vendor_amd: + case vendor_amd_alt: + return classify_amd(words); + default: + return unknown; + } +} + +std::uint32_t vendor_from_gl(std::string_view const GlVendor, std::string_view const GlRenderer) +{ + // the vendor first; Mesa ("Mesa", "X.Org", "Collabora Ltd") and the D3D12 layer ("Microsoft Corporation") name + // the maker of the chip in the renderer + for (auto const &text : {lowercase(GlVendor), lowercase(GlRenderer)}) + { + if (contains(text, "nvidia") || contains(text, "geforce") || contains(text, "quadro")) + return vendor_nvidia; + if (contains(text, "ati technologies") || contains(text, "advanced micro devices") || contains(text, "radeon") || has_word(name_words(text), "amd")) + return vendor_amd; + if (contains(text, "intel")) + return vendor_intel; + } + return 0; +} + +bool is_software_gl(std::string_view const GlVendor, std::string_view const GlRenderer) +{ + return is_software_name(GlRenderer) || is_software_name(GlVendor); +} + +gpu_kind classify_gl(std::string_view const GlVendor, std::string_view const GlRenderer) +{ + if (is_software_gl(GlVendor, GlRenderer)) + return gpu_kind::software; + return classify_gpu(vendor_from_gl(GlVendor, GlRenderer), GlRenderer); +} + +std::string format_size(std::uint64_t const Bytes) +{ + constexpr std::uint64_t mebibyte{1024 * 1024}; + constexpr std::uint64_t gibibyte{1024 * mebibyte}; + if (Bytes < gibibyte) + return std::format("{} MiB", (Bytes + mebibyte / 2) / mebibyte); + return std::format("{:.1f} GiB", static_cast(Bytes) / static_cast(gibibyte)); +} + +std::string tidy_name(std::string_view const Name) +{ + std::string result; + for (auto const c : Name) + { + if (c == '\0') + break; + if (std::isspace(static_cast(c))) + { + if (!result.empty() && result.back() != ' ') + result += ' '; + continue; + } + result += c; + } + if (!result.empty() && result.back() == ' ') + result.pop_back(); + return result; +} + +cpu_info parse_cpuinfo(std::string_view const Text) +{ + cpuinfo_reader reader; + for_each_line(Text, [&reader](std::string_view const Line) { reader.read(Line); }); + auto cpu{std::move(reader.cpu)}; + if (!reader.cores.empty()) + cpu.physical_cores = static_cast(reader.cores.size()); + else if (reader.cores_per_package > 0) + cpu.physical_cores = reader.cores_per_package * static_cast(std::max(reader.packages.size(), 1)); + return cpu; +} + +memory_info parse_meminfo(std::string_view const Text) +{ + memory_info memory; + for_each_line(Text, [&memory](std::string_view const Line) { + auto const [key, value] = split_entry(Line); + // the values are in kB (kibibytes, whatever the unit says) + if (key == "MemTotal") + memory.total = to_number(value) * 1024; + else if (key == "MemAvailable") + memory.available = to_number(value) * 1024; + }); + return memory; +} + +std::string format_cpu(cpu_info const &Cpu) +{ + auto line{std::format("hardware: cpu: {}", Cpu.model.empty() ? std::string{"unknown"} : Cpu.model)}; + if (Cpu.physical_cores > 0) + line += std::format(", {} cores", Cpu.physical_cores); + if (Cpu.logical_cores > 0) + line += std::format(", {} threads", Cpu.logical_cores); + line += std::format(", avx2 {}", yes_no(Cpu.avx2)); + return line; +} + +std::string format_memory(memory_info const &Memory) +{ + auto line{std::format("hardware: ram: {} total", Memory.total > 0 ? format_size(Memory.total) : std::string{"unknown"})}; + if (Memory.available > 0) + line += std::format(", {} available", format_size(Memory.available)); + return line; +} + +std::string format_adapter(int const Index, gpu_adapter const &Adapter) +{ + return std::format("hardware: gpu {}: {} (vendor 0x{:04x}, device 0x{:04x}), {} dedicated, {} shared, {} outputs, {}", Index, Adapter.description, Adapter.vendor_id, Adapter.device_id, + format_size(Adapter.dedicated_video_memory), format_size(Adapter.shared_system_memory), Adapter.outputs, + Adapter.software ? to_string(gpu_kind::software) : to_string(classify_gpu(Adapter.vendor_id, Adapter.description))); +} + +std::string format_gl(std::string_view const GlVendor, std::string_view const GlRenderer) +{ + return std::format("hardware: opengl gpu: {} ({}), {}", GlRenderer, GlVendor, to_string(classify_gl(GlVendor, GlRenderer))); +} + +std::string format_gl_memory(gl_memory_info const &Memory) +{ + std::string line{"hardware: opengl gpu memory:"}; + if (Memory.dedicated > 0) + line += std::format(" {} dedicated", format_size(Memory.dedicated)); + if (Memory.available > 0) + line += std::format("{} {} free", Memory.dedicated > 0 ? "," : "", format_size(Memory.available)); + if (Memory.dedicated == 0 && Memory.available == 0) + line += " unknown"; + return line; +} + +std::vector gl_warnings(std::vector const &Adapters, std::string_view const GlVendor, std::string_view const GlRenderer) +{ + std::vector warnings; + auto const kind{classify_gl(GlVendor, GlRenderer)}; + if (kind == gpu_kind::software) + { + warnings.push_back(std::format("hardware: warning: OpenGL draws on the cpu ({}), the graphics driver is missing or not used", GlRenderer)); + return warnings; + } + if (kind != gpu_kind::integrated) + return warnings; + if (auto const discrete = std::ranges::find_if(Adapters, [](gpu_adapter const &Adapter) { + return !Adapter.software && classify_gpu(Adapter.vendor_id, Adapter.description) == gpu_kind::discrete; + }); + discrete != Adapters.end()) + { + warnings.push_back(std::format("hardware: warning: OpenGL runs on the integrated GPU ({}) though there is a dedicated one ({}); " + "choose High performance for the game in the Windows graphics settings or the GPU control panel, " + "and connect the monitor to the dedicated GPU", + GlRenderer, discrete->description)); + } + return warnings; +} + +std::vector cpu_warnings(cpu_info const &Cpu, bool const BuildNeedsAvx2) +{ + std::vector warnings; + if (BuildNeedsAvx2 && Cpu.avx2 == 0) + warnings.emplace_back("hardware: warning: the cpu has no AVX2, which this build of the game needs"); + return warnings; +} + +} // namespace hardware diff --git a/utilities/hardwareinfo.h b/utilities/hardwareinfo.h new file mode 100644 index 000000000..54fdbd02d --- /dev/null +++ b/utilities/hardwareinfo.h @@ -0,0 +1,114 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include +#include + +// what the log says about the machine at startup: the cpu, the memory, the graphics adapters and the one OpenGL runs +// on. a bug report then shows whether the game ran on the integrated GPU of a laptop instead of the dedicated one. +// this part holds the rules and the text, which need nothing of the machine; the probing is in hardwareprobe.cpp +namespace hardware { + +// the PCI vendor ids of the graphics adapters +constexpr std::uint32_t vendor_nvidia{0x10de}; +constexpr std::uint32_t vendor_amd{0x1002}; +constexpr std::uint32_t vendor_amd_alt{0x1022}; // AMD's cpu id, shown by some APUs +constexpr std::uint32_t vendor_intel{0x8086}; +constexpr std::uint32_t vendor_microsoft{0x1414}; // Microsoft Basic Render Driver, the software adapter + +enum class gpu_kind { + unknown, // can't tell from the name; never taken for either of the other two + integrated, // part of the cpu, shares the system memory + discrete, // a card (or a chip) with its own memory + software, // drawn by the cpu (Microsoft Basic Render Driver, GDI Generic, llvmpipe) +}; + +std::string_view to_string(gpu_kind Kind); + +// whether a GPU is integrated or discrete, from its vendor and its name (the DXGI description or GL_RENDERER). +// conservative, by the names the vendors give their chips: +// - NVIDIA: discrete (PC NVIDIA graphics have been cards or laptop chips with their own memory since the nForce days) +// - Intel: discrete only for the Arc cards (Arc A380/A770/B580, Arc Pro A60) and Iris Xe MAX; the rest (HD, UHD, +// Iris, Arc Graphics, Arc 140V and Arc B370/B390 of Meteor/Lunar/Panther Lake) is integrated +// - AMD: discrete for Radeon RX/Pro/VII, FirePro and Instinct; integrated for the APU names, which have no model +// number before "Graphics" (Radeon(TM) Graphics, Radeon Vega 8 Graphics, Radeon 780M Graphics, Radeon 8060S +// Graphics), and Radeon RX Vega 11 Graphics of Raven Ridge; anything else (an old Radeon HD, R7 ...) is unknown, as +// both cards and APUs were named so +// - software renderers are software; any other vendor (virtual machines, Qualcomm) is unknown +gpu_kind classify_gpu(std::uint32_t VendorId, std::string_view Name); + +// the PCI vendor id behind the GL_VENDOR and GL_RENDERER strings (Mesa names the vendor in the renderer); 0 if none +std::uint32_t vendor_from_gl(std::string_view GlVendor, std::string_view GlRenderer); + +// whether GL_VENDOR and GL_RENDERER name a renderer that draws on the cpu +bool is_software_gl(std::string_view GlVendor, std::string_view GlRenderer); + +// the kind of the GPU an OpenGL context runs on +gpu_kind classify_gl(std::string_view GlVendor, std::string_view GlRenderer); + +// a graphics adapter of the system (on Windows, as DXGI lists it) +struct gpu_adapter { + std::string description; + std::uint32_t vendor_id{0}; + std::uint32_t device_id{0}; + std::uint64_t dedicated_video_memory{0}; // bytes + std::uint64_t shared_system_memory{0}; // bytes + int outputs{0}; // the monitors connected to it + bool software{false}; +}; + +struct cpu_info { + std::string model; + int logical_cores{0}; // 0: unknown + int physical_cores{0}; // 0: unknown + int avx2{-1}; // 1 yes, 0 no, -1 unknown +}; + +struct memory_info { + std::uint64_t total{0}; // bytes, 0: unknown + std::uint64_t available{0}; // bytes, 0: unknown +}; + +// what the context's driver says of its memory (GL_NVX_gpu_memory_info, GL_ATI_meminfo), in bytes, 0: not told +struct gl_memory_info { + std::uint64_t dedicated{0}; + std::uint64_t available{0}; +}; + +// a size for a person to read: "512 MiB", "7.9 GiB" +std::string format_size(std::uint64_t Bytes); + +// trims the padding cpuid and the registry leave in the cpu brand string, squeezes the runs of spaces +std::string tidy_name(std::string_view Name); + +// what /proc/cpuinfo says of the cpu: the model name, the processors (logical cores) and the distinct cores +cpu_info parse_cpuinfo(std::string_view Text); + +// what /proc/meminfo says of the memory: MemTotal and MemAvailable +memory_info parse_meminfo(std::string_view Text); + +// the lines of the log, every one starting with "hardware: " so a single grep finds them all +std::string format_cpu(cpu_info const &Cpu); +std::string format_memory(memory_info const &Memory); +std::string format_adapter(int Index, gpu_adapter const &Adapter); +std::string format_gl(std::string_view GlVendor, std::string_view GlRenderer); +std::string format_gl_memory(gl_memory_info const &Memory); + +// the warnings of the log about the GPU OpenGL runs on: on the cpu, or on an integrated GPU while the system has a +// discrete one (Adapters: as the system lists them; the software ones are passed over). nothing if all is well +std::vector gl_warnings(std::vector const &Adapters, std::string_view GlVendor, std::string_view GlRenderer); + +// the warning of the log about a cpu without AVX2 when the build needs it. nothing if all is well +std::vector cpu_warnings(cpu_info const &Cpu, bool BuildNeedsAvx2); + +} // namespace hardware diff --git a/utilities/hardwareprobe.cpp b/utilities/hardwareprobe.cpp new file mode 100644 index 000000000..b7574281b --- /dev/null +++ b/utilities/hardwareprobe.cpp @@ -0,0 +1,336 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "utilities/hardwareprobe.h" + +#include "utilities/hardwareinfo.h" +#include "utilities/Logs.h" + +#include +#include + +#if defined(_M_X64) || defined(_M_IX86) || defined(__x86_64__) || defined(__i386__) +#define EU07_HARDWARE_X86 1 +#ifdef _MSC_VER +#include +#else +#include +#endif +#endif + +#ifdef _WIN32 +#include +#endif + +namespace hardware { + +namespace { + +// the adapters log_system() found, for the warning of log_gl_context() +std::vector &system_adapters() +{ + static std::vector adapters; + return adapters; +} + +#ifdef EU07_HARDWARE_X86 +// the eax, ebx, ecx and edx the cpuid instruction gives for the provided leaf and subleaf +std::array cpuid(unsigned int const Leaf, unsigned int const Subleaf) +{ + std::array result{}; +#ifdef _MSC_VER + std::array registers{}; + __cpuidex(registers.data(), static_cast(Leaf), static_cast(Subleaf)); + for (std::size_t i = 0; i < result.size(); ++i) + result[i] = static_cast(registers[i]); +#else + __cpuid_count(Leaf, Subleaf, result[0], result[1], result[2], result[3]); +#endif + return result; +} + +// the brand string of the cpu ("AMD Ryzen 5 5600X 6-Core Processor"); empty if the cpu has none +std::string cpu_brand() +{ + if (cpuid(0x80000000u, 0)[0] < 0x80000004u) + return {}; + std::array brand{}; + for (unsigned int leaf = 0; leaf < 3; ++leaf) + { + auto const registers{cpuid(0x80000002u + leaf, 0)}; + std::memcpy(brand.data() + leaf * 16, registers.data(), 16); + } + return tidy_name(brand.data()); +} + +// whether the cpu has AVX2 and the system saves the AVX registers +int cpu_avx2() +{ +#ifdef _MSC_VER + if (cpuid(0, 0)[0] < 7) + return 0; + auto const features{cpuid(1, 0)}; + auto const osxsave{(features[2] & (1u << 27)) != 0}; + auto const avx{(features[2] & (1u << 28)) != 0}; + if (!osxsave || !avx) + return 0; + if ((_xgetbv(0) & 0x6) != 0x6) // the system saves xmm and ymm + return 0; + return (cpuid(7, 0)[1] & (1u << 5)) != 0 ? 1 : 0; +#else + // checks the system's support as well + __builtin_cpu_init(); + return __builtin_cpu_supports("avx2") ? 1 : 0; +#endif +} +#endif + +#ifdef _WIN32 +std::string narrow(wchar_t const *Text) +{ + auto const length{WideCharToMultiByte(CP_UTF8, 0, Text, -1, nullptr, 0, nullptr, nullptr)}; + if (length <= 1) + return {}; + std::string result(static_cast(length - 1), '\0'); + WideCharToMultiByte(CP_UTF8, 0, Text, -1, result.data(), length, nullptr, nullptr); + return result; +} + +std::string registry_cpu_name() +{ + char name[256]{}; + DWORD size{sizeof(name)}; + if (RegGetValueA(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", "ProcessorNameString", RRF_RT_REG_SZ, nullptr, name, &size) != ERROR_SUCCESS) + return {}; + return tidy_name(name); +} + +int physical_cores() +{ + DWORD length{0}; + GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &length); + if (length == 0) + return 0; + std::vector buffer(length); + auto *records{reinterpret_cast(buffer.data())}; + if (!GetLogicalProcessorInformationEx(RelationProcessorCore, records, &length)) + return 0; + int cores{0}; + for (DWORD offset = 0; offset < length;) + { + auto const *record{reinterpret_cast(buffer.data() + offset)}; + if (record->Size == 0) + break; + ++cores; + offset += record->Size; + } + return cores; +} + +cpu_info probe_cpu() +{ + cpu_info cpu; +#ifdef EU07_HARDWARE_X86 + cpu.model = cpu_brand(); + cpu.avx2 = cpu_avx2(); +#endif + if (cpu.model.empty()) + cpu.model = registry_cpu_name(); + cpu.logical_cores = static_cast(GetActiveProcessorCount(ALL_PROCESSOR_GROUPS)); + cpu.physical_cores = physical_cores(); + return cpu; +} + +memory_info probe_memory() +{ + memory_info memory; + MEMORYSTATUSEX status{}; + status.dwLength = sizeof(status); + if (GlobalMemoryStatusEx(&status)) + { + memory.total = status.ullTotalPhys; + memory.available = status.ullAvailPhys; + } + return memory; +} + +// the adapters DXGI lists, the software one left out. dxgi.dll is loaded only for this, so the game doesn't link it; +// from System32 only, so a proxy dxgi.dll left in the game folder (ReShade, ENB) isn't loaded with it +std::vector probe_adapters() +{ + std::vector adapters; + auto *library{LoadLibraryExW(L"dxgi.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32)}; + if (library == nullptr) + { + WriteLog("hardware: gpus: dxgi.dll not found"); + return adapters; + } + using create_factory = HRESULT(WINAPI *)(REFIID, void **); + auto const create{reinterpret_cast(reinterpret_cast(GetProcAddress(library, "CreateDXGIFactory1")))}; + IDXGIFactory1 *factory{nullptr}; + if (create == nullptr || FAILED(create(__uuidof(IDXGIFactory1), reinterpret_cast(&factory))) || factory == nullptr) + { + WriteLog("hardware: gpus: can't create a DXGI factory"); + FreeLibrary(library); + return adapters; + } + IDXGIAdapter1 *adapter{nullptr}; + for (UINT index = 0; SUCCEEDED(factory->EnumAdapters1(index, &adapter)); ++index) + { + DXGI_ADAPTER_DESC1 description{}; + if (SUCCEEDED(adapter->GetDesc1(&description))) + { + gpu_adapter entry; + entry.description = tidy_name(narrow(description.Description)); + entry.vendor_id = description.VendorId; + entry.device_id = description.DeviceId; + entry.dedicated_video_memory = description.DedicatedVideoMemory; + entry.shared_system_memory = description.SharedSystemMemory; + entry.software = (description.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) != 0 || description.VendorId == vendor_microsoft; + IDXGIOutput *output{nullptr}; + while (SUCCEEDED(adapter->EnumOutputs(static_cast(entry.outputs), &output))) + { + output->Release(); + ++entry.outputs; + } + if (!entry.software) + adapters.push_back(std::move(entry)); + } + adapter->Release(); + } + factory->Release(); + FreeLibrary(library); + return adapters; +} +#else +std::string read_file(char const *Path) +{ + std::ifstream file{Path}; + if (!file) + return {}; + std::stringstream text; + text << file.rdbuf(); + return text.str(); +} + +cpu_info probe_cpu() +{ + auto cpu{parse_cpuinfo(read_file("/proc/cpuinfo"))}; +#ifdef EU07_HARDWARE_X86 + if (cpu.model.empty()) + cpu.model = cpu_brand(); + cpu.avx2 = cpu_avx2(); +#endif + if (cpu.logical_cores == 0) + cpu.logical_cores = static_cast(std::thread::hardware_concurrency()); + return cpu; +} + +memory_info probe_memory() +{ + return parse_meminfo(read_file("/proc/meminfo")); +} +#endif + +std::string gl_string(GLenum const Name) +{ + auto const *text{reinterpret_cast(glGetString(Name))}; + return text != nullptr ? std::string{text} : std::string{"unknown"}; +} + +bool has_gl_extension(std::string_view const Name) +{ + if (glGetStringi != nullptr) + { + GLint count{0}; + glGetIntegerv(GL_NUM_EXTENSIONS, &count); + for (GLint i = 0; i < count; ++i) + { + auto const *extension{reinterpret_cast(glGetStringi(GL_EXTENSIONS, static_cast(i)))}; + if (extension != nullptr && Name == extension) + return true; + } + return false; + } + // OpenGL ES 2: one string of them all + auto const *extensions{reinterpret_cast(glGetString(GL_EXTENSIONS))}; + return extensions != nullptr && std::string_view{extensions}.find(Name) != std::string_view::npos; +} + +gl_memory_info probe_gl_memory() +{ + // GL_NVX_gpu_memory_info and GL_ATI_meminfo tokens, in kilobytes + constexpr GLenum gpu_memory_info_dedicated_vidmem_nvx{0x9047}; + constexpr GLenum gpu_memory_info_current_available_vidmem_nvx{0x9049}; + constexpr GLenum texture_free_memory_ati{0x87fc}; + + gl_memory_info memory; + if (has_gl_extension("GL_NVX_gpu_memory_info")) + { + GLint kilobytes{0}; + glGetIntegerv(gpu_memory_info_dedicated_vidmem_nvx, &kilobytes); + memory.dedicated = static_cast(std::max(kilobytes, 0)) * 1024; + kilobytes = 0; + glGetIntegerv(gpu_memory_info_current_available_vidmem_nvx, &kilobytes); + memory.available = static_cast(std::max(kilobytes, 0)) * 1024; + } + else if (has_gl_extension("GL_ATI_meminfo")) + { + // the free memory of the texture pool, the largest free block, and the same of the auxiliary memory + std::array kilobytes{}; + glGetIntegerv(texture_free_memory_ati, kilobytes.data()); + memory.available = static_cast(std::max(kilobytes[0], 0)) * 1024; + } + // a driver that takes the queries amiss leaves an error the renderer would report as its own. each call takes one + // error off; a lost context may keep reporting one, hence the limit + constexpr int max_errors{32}; + for (int i = 0; i < max_errors && glGetError() != GL_NO_ERROR; ++i) + { + // nothing else to do + } + return memory; +} + +} // namespace + +void log_system() +{ + auto const cpu{probe_cpu()}; + WriteLog(format_cpu(cpu)); + // an AVX2 build on a cpu without it may die on an illegal instruction before this line; when it gets here (the + // start so far ran without an AVX2 or FMA instruction), the line names the cause of the crash that comes later +#ifdef __AVX2__ + constexpr bool build_needs_avx2{true}; +#else + constexpr bool build_needs_avx2{false}; +#endif + for (auto const &warning : cpu_warnings(cpu, build_needs_avx2)) + WriteLog(warning); + WriteLog(format_memory(probe_memory())); +#ifdef _WIN32 + auto &adapters{system_adapters()}; + adapters = probe_adapters(); + for (std::size_t index = 0; index < adapters.size(); ++index) + WriteLog(format_adapter(static_cast(index), adapters[index])); +#endif +} + +void log_gl_context() +{ + auto const vendor{gl_string(GL_VENDOR)}; + auto const renderer{gl_string(GL_RENDERER)}; + WriteLog(format_gl(vendor, renderer)); + if (auto const memory{probe_gl_memory()}; memory.dedicated > 0 || memory.available > 0) + WriteLog(format_gl_memory(memory)); + for (auto const &warning : gl_warnings(system_adapters(), vendor, renderer)) + WriteLog(warning); +} + +} // namespace hardware diff --git a/utilities/hardwareprobe.h b/utilities/hardwareprobe.h new file mode 100644 index 000000000..75cb1e405 --- /dev/null +++ b/utilities/hardwareprobe.h @@ -0,0 +1,22 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +// writes the machine to the log at startup, every line starting with "hardware: " (see hardwareinfo.h) +namespace hardware { + +// the cpu, the memory and, on Windows, the graphics adapters DXGI lists +void log_system(); + +// the GPU the current OpenGL context runs on, its memory where the driver tells it, and a warning when it's the +// integrated GPU while the system has a dedicated one. after log_system(), with the context current +void log_gl_context(); + +} // namespace hardware diff --git a/utilities/inionlysettings.cpp b/utilities/inionlysettings.cpp new file mode 100644 index 000000000..fb8d8f58f --- /dev/null +++ b/utilities/inionlysettings.cpp @@ -0,0 +1,96 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "utilities/inionlysettings.h" + +namespace +{ + +// puts Kept back into Current, and adds Key to Changed when they differed +template void keep(Type_ &Current, Type_ const &Kept, std::string_view const Key, std::vector &Changed) +{ + if (false == (Current == Kept)) + { + Current = Kept; + Changed.push_back(Key); + } +} + +// a switch a scenery may turn off but not on: puts Kept back into Current, and adds Key to Changed, only when the +// scenery turned it on. turned off it stays so, as before these keys were kept +void keep_off(bool &Current, bool const Kept, std::string_view const Key, std::vector &Changed) +{ + if (Current && false == Kept) + { + Current = false; + Changed.push_back(Key); + } +} + +} // namespace + +ini_only_settings::ini_only_settings(global_settings const &Settings) + : m_exec_on_exit{Settings.exec_on_exit}, m_screenshot_dir{Settings.screenshot_dir}, m_extcam_cmd{Settings.extcam_cmd}, + m_extcam_rec{Settings.extcam_rec}, m_network_servers{Settings.network_servers}, m_network_client{Settings.network_client}, +#ifdef WITH_ZMQ + m_zmq_address{Settings.zmq_address}, +#endif + m_motiontelemetry{Settings.motiontelemetry_conf}, +#ifdef WITH_UART + m_uart{Settings.uart_conf}, +#endif + m_feedback_mode{Settings.iFeedbackMode}, m_feedback_port{Settings.iFeedbackPort}, m_python_enabled{Settings.python_enabled}, + m_luascreens_enabled{Settings.luascreens_enabled}, m_lua_fulllibraries{Settings.lua_fulllibraries}, m_wasm_enabled{Settings.wasm_enabled}, + m_odometer_expiry{Settings.odometer_expiry} +{ +} + +std::vector ini_only_settings::restore(global_settings &Settings) const +{ + std::vector changed; + keep(Settings.exec_on_exit, m_exec_on_exit, "execonexit", changed); + keep(Settings.screenshot_dir, m_screenshot_dir, "screenshotsdir", changed); + keep(Settings.extcam_cmd, m_extcam_cmd, "extcam.cmd", changed); + keep(Settings.extcam_rec, m_extcam_rec, "extcam.rec", changed); + keep(Settings.network_servers, m_network_servers, "network.server", changed); + keep(Settings.network_client, m_network_client, "network.client", changed); +#ifdef WITH_ZMQ + keep(Settings.zmq_address, m_zmq_address, "zmq.address", changed); +#endif + // the structures as a whole, told apart by what turns them on and where they lead + { + auto ¤t{Settings.motiontelemetry_conf}; + if (current.enable != m_motiontelemetry.enable || current.proto != m_motiontelemetry.proto || current.address != m_motiontelemetry.address || + current.port != m_motiontelemetry.port) + { + changed.emplace_back("motiontelemetry"); + } + current = m_motiontelemetry; + } +#ifdef WITH_UART + { + auto ¤t{Settings.uart_conf}; + if (current.enable != m_uart.enable || current.port != m_uart.port) + { + changed.emplace_back("uart"); + } + current = m_uart; + } +#endif + keep(Settings.iFeedbackMode, m_feedback_mode, "feedbackmode", changed); + keep(Settings.iFeedbackPort, m_feedback_port, "feedbackport", changed); + // a scenery may switch a runtime off, and keep its scripts in the sandbox + keep_off(Settings.python_enabled, m_python_enabled, "python.enabled", changed); + keep_off(Settings.luascreens_enabled, m_luascreens_enabled, "luascreens.enabled", changed); + keep_off(Settings.lua_fulllibraries, m_lua_fulllibraries, "lua.fulllibraries", changed); + keep_off(Settings.wasm_enabled, m_wasm_enabled, "wasm.enabled", changed); + keep(Settings.odometer_expiry, m_odometer_expiry, "odometer.expiry", changed); + return changed; +} diff --git a/utilities/inionlysettings.h b/utilities/inionlysettings.h new file mode 100644 index 000000000..6dba86927 --- /dev/null +++ b/utilities/inionlysettings.h @@ -0,0 +1,58 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include "utilities/Globals.h" + +#include +#include +#include +#include +#include + +// the settings only eu07.ini sets. a scenery's config block is read by the parser of eu07.ini +// (state_serializer::deserialize_config, global_settings::ConfigParse), and with these keys it would run a program +// (execonexit, extcam.cmd, extcam.rec), write the screenshots elsewhere (screenshotsdir), open connections and ports +// (network.server, network.client, zmq.address, motiontelemetry, uart, feedbackmode, feedbackport), switch back on a +// script runtime the player switched off (python.enabled, luascreens.enabled, wasm.enabled), take its own scripts +// out of the sandbox (lua.fulllibraries) or drop the odometer states the player keeps (odometer.expiry). they keep +// what eu07.ini set; a scenery may still switch a runtime off, or keep its scripts in the sandbox when eu07.ini didn't, +// as it always could +class ini_only_settings +{ + public: + // what Settings holds now, as eu07.ini set it + explicit ini_only_settings(global_settings const &Settings); + + // puts back into Settings what changed since, and gives the keys of eu07.ini whose settings changed + std::vector restore(global_settings &Settings) const; + + private: + std::string m_exec_on_exit; + std::string m_screenshot_dir; + std::string m_extcam_cmd; + std::string m_extcam_rec; + std::vector> m_network_servers; + std::optional> m_network_client; +#ifdef WITH_ZMQ + std::string m_zmq_address; +#endif + motiontelemetry::conf_t m_motiontelemetry; +#ifdef WITH_UART + uart_input::conf_t m_uart; +#endif + int m_feedback_mode; + int m_feedback_port; + bool m_python_enabled; + bool m_luascreens_enabled; + bool m_lua_fulllibraries; + bool m_wasm_enabled; + int m_odometer_expiry; +}; diff --git a/utilities/logfiles.cpp b/utilities/logfiles.cpp new file mode 100644 index 000000000..7dd9a6745 --- /dev/null +++ b/utilities/logfiles.cpp @@ -0,0 +1,26 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "utilities/logfiles.h" + +#include + +std::string log_file_name(log_file const Kind, bool const MultipleLogs, std::string_view const Scenery, std::string_view const Date) +{ + std::string_view const name{Kind == log_file::errors ? "errors" : "log"}; + return MultipleLogs ? std::format("logs/{} ({}) {}.txt", name, Scenery, Date) : std::format("{}.txt", name); +} + +std::vector stale_log_files(bool const MultipleLogs) +{ + if (MultipleLogs) + return {}; + return {log_file_name(log_file::log, false, {}, {}), log_file_name(log_file::errors, false, {}, {})}; +} diff --git a/utilities/logfiles.h b/utilities/logfiles.h new file mode 100644 index 000000000..7c88ea436 --- /dev/null +++ b/utilities/logfiles.h @@ -0,0 +1,29 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include + +// the files the log is written to, and which of them a run clears when it starts. kept apart from the log service so +// the unit tests can check them + +// the log of everything, and the list of the errors (made at the first error) +enum class log_file { log, errors }; + +// the name of a log file: the shared one in the game folder, or with multiplelogs the run's own in logs/, named after +// the scenery and the time +std::string log_file_name(log_file Kind, bool MultipleLogs, std::string_view Scenery, std::string_view Date); + +// the shared log files a run deletes when it starts: the ones it writes itself, that is without multiplelogs, so an +// errors.txt of an earlier run doesn't stay behind when this one logs no error. with multiplelogs the run writes files +// of its own in logs/, and the log.txt / errors.txt of the last ordinary run are kept +std::vector stale_log_files(bool MultipleLogs); diff --git a/utilities/parser.h b/utilities/parser.h index 19fc34f18..fa4c2c597 100644 --- a/utilities/parser.h +++ b/utilities/parser.h @@ -62,10 +62,12 @@ class cParser //: public std::stringstream std::string out; readToken(out); return out == Value; }; + // the end of the data: of this text, and of the file included last in it, which an include directive at the very + // end of the text leaves to be read inline bool - eof() { - return mEofBit; }; + eof() const { + return mEofBit && ( mIncludeParser == nullptr || mIncludeParser->eof() ); }; inline bool ok() { diff --git a/utilities/translation.cpp b/utilities/translation.cpp index 1048dcfb8..58c9746ab 100644 --- a/utilities/translation.cpp +++ b/utilities/translation.cpp @@ -267,6 +267,8 @@ std::string locale::label_cab_control(std::string const &Label) { "fuelpump_sw:", STRN("fuel pump") }, { "oilpump_sw:", STRN("oil pump") }, { "oilfuelpump_sw:", STRN("oil and fuel pumps") }, + { "tractionmode_sw:", STRN("traction mode selector") }, + { "genset_sw:", STRN("diesel generator") }, { "motorblowersfront_sw:", STRN("motor blowers A") }, { "motorblowersrear_sw:", STRN("motor blowers B") }, { "motorblowersalloff_sw:", STRN("all motor blowers") }, diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index 9d5c614d7..cb5e5777a 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -16,6 +16,7 @@ Copyright (C) 2007-2014 Maciej Cierniak //#include //#include #include +#include #include #include //#ifndef WIN32 @@ -57,6 +58,33 @@ std::string Now() #endif } +std::filesystem::path xdg_base_directory(char const *Variable, char const *Home, char const *Fallback) +{ + // as the spec has it: a variable which isn't set, is empty or holds a relative path counts as not set. absolute is + // said the way a posix system says it, so the answer is the same on every system the tests run on + if (Variable != nullptr && Variable[0] == '/') + return std::filesystem::path(Variable); + if (Home != nullptr && Home[0] != '\0') + return std::filesystem::path(Home) / Fallback; + return {}; +} + +std::filesystem::path xdg_config_folder(char const *Variable, char const *Home) +{ + auto const base{xdg_base_directory(Variable, Home, ".config")}; + if (base.empty()) + return {}; + auto folder{base / "MaSzyna"}; + if (Home != nullptr && Home[0] != '\0') + { + auto legacy{std::filesystem::path(Home) / ".config" / "MaSzyna"}; + std::error_code error; + if (legacy != folder && false == std::filesystem::exists(folder, error) && std::filesystem::is_directory(legacy, error)) + return legacy; + } + return folder; +} + std::filesystem::path user_config_path(const std::string &filename) { namespace fs = std::filesystem; @@ -67,8 +95,17 @@ std::filesystem::path user_config_path(const std::string &filename) if (const char *home = std::getenv("HOME")) return fs::path(home) / "Library" / "Application Support" / "MaSzyna" / filename; #else - if (const char *home = std::getenv("HOME")) - return fs::path(home) / ".config" / "MaSzyna" / filename; + if (auto const folder{xdg_config_folder(std::getenv("XDG_CONFIG_HOME"), std::getenv("HOME"))}; false == folder.empty()) + { + if (auto const wanted{xdg_base_directory(std::getenv("XDG_CONFIG_HOME"), std::getenv("HOME"), ".config") / "MaSzyna"}; + folder != wanted) + { + // said once, so whoever set XDG_CONFIG_HOME knows why the settings aren't there + static std::once_flag told; + std::call_once(told, [&] { WriteLog(std::format("Settings kept in \"{}\", the folder of the earlier releases, since \"{}\" doesn't exist", folder.string(), wanted.string())); }); + } + return folder / filename; + } #endif return {}; // env var missing → caller falls back to CWD-relative filename } @@ -83,10 +120,8 @@ std::filesystem::path user_cache_path(const std::string &filename) if (const char *home = std::getenv("HOME")) return fs::path(home) / "Library" / "Caches" / "MaSzyna" / filename; #else - if (const char *cache = std::getenv("XDG_CACHE_HOME"); cache != nullptr && *cache != '\0') - return fs::path(cache) / "MaSzyna" / filename; - if (const char *home = std::getenv("HOME")) - return fs::path(home) / ".cache" / "MaSzyna" / filename; + if (auto const base{xdg_base_directory(std::getenv("XDG_CACHE_HOME"), std::getenv("HOME"), ".cache")}; false == base.empty()) + return base / "MaSzyna" / filename; #endif return {}; } @@ -198,10 +233,19 @@ std::uint64_t true_random_seed() std::uint32_t seed_of(std::string const &Text) { - if (std::uint32_t number{}; std::from_chars(Text.data(), Text.data() + Text.size(), number).ec == std::errc{}) + auto const *const end{Text.data() + Text.size()}; + std::uint32_t number{}; + auto const [last, error]{std::from_chars(Text.data(), end, number)}; + if (error == std::errc{} && last == end) { return number; } + if (error == std::errc{}) + { + // digits with something after them are a word like any other, not the number in front of them: "4242abc" + // isn't seed 4242. said in the log, since whoever wrote it most likely meant a number + WriteLog(std::format("seed \"{}\" isn't a number, taken as a word", Text)); + } std::uint32_t hash{}; for (auto const character : Text) { @@ -210,6 +254,15 @@ std::uint32_t seed_of(std::string const &Text) return hash; } +std::optional seed_given(std::string const &Text) +{ + if (Text.empty()) + { + return std::nullopt; + } + return seed_of(Text); +} + std::string generate_uuid_v4() { std::uniform_int_distribution dist(0, 255); @@ -338,7 +391,7 @@ std::string ToUpper(std::string const &text) void win1250_to_ascii(std::string &Input) { - std::unordered_map const charmap{{165, 'A'}, {198, 'C'}, {202, 'E'}, {163, 'L'}, {209, 'N'}, {211, 'O'}, {140, 'S'}, {143, 'Z'}, {175, 'Z'}, + static std::unordered_map const charmap{{165, 'A'}, {198, 'C'}, {202, 'E'}, {163, 'L'}, {209, 'N'}, {211, 'O'}, {140, 'S'}, {143, 'Z'}, {175, 'Z'}, {185, 'a'}, {230, 'c'}, {234, 'e'}, {179, 'l'}, {241, 'n'}, {243, 'o'}, {156, 's'}, {159, 'z'}, {191, 'z'}}; std::unordered_map::const_iterator lookup; for (auto &input : Input) @@ -472,9 +525,126 @@ void win1250_to_utf32(std::string const &Text, std::u32string &Output) } } +namespace +{ +void append_utf8(std::string &Output, char32_t const Codepoint) +{ + if (Codepoint < 0x80) + { + Output += static_cast(Codepoint); + } + else if (Codepoint < 0x800) + { + Output += static_cast(0xC0 | (Codepoint >> 6)); + Output += static_cast(0x80 | (Codepoint & 0x3F)); + } + else if (Codepoint < 0x10000) + { + Output += static_cast(0xE0 | (Codepoint >> 12)); + Output += static_cast(0x80 | ((Codepoint >> 6) & 0x3F)); + Output += static_cast(0x80 | (Codepoint & 0x3F)); + } + else + { + Output += static_cast(0xF0 | (Codepoint >> 18)); + Output += static_cast(0x80 | ((Codepoint >> 12) & 0x3F)); + Output += static_cast(0x80 | ((Codepoint >> 6) & 0x3F)); + Output += static_cast(0x80 | (Codepoint & 0x3F)); + } +} +} // namespace + +std::string data_text_to_utf8(std::string const &Text) +{ + if (std::ranges::all_of(Text, [](char const Character) { return static_cast(Character) < 0x80; })) + { + return Text; + } + std::u32string codepoints; + // a text in windows-1250 can happen to be valid utf-8 as well: two capital letters with marks in a row, as the bytes + // D3 A3 of "WOLKA" with its marks, make a sequence of two bytes. such a pair decodes to a letter between U+0180 and + // U+07FF (cyrillic, greek and the like), which the texts of the data files, when they are in utf-8, don't have + if (utf8_to_utf32(Text, codepoints) && std::ranges::none_of(codepoints, [](char32_t const Codepoint) { return Codepoint >= 0x180 && Codepoint < 0x800; })) + { + return Text; + } + // the code page the data files are written in + win1250_to_utf32(Text, codepoints); + std::string output; + output.reserve(Text.size() + 8); + for (auto const codepoint : codepoints) + { + // the bytes the code page has no character for come as 0 + append_utf8(output, codepoint != 0 ? codepoint : U'?'); + } + return output; +} + +std::string data_name_to_utf8(std::string const &Name, bool const Underscorestospaces) +{ + auto name{data_text_to_utf8(Name)}; + // in utf-8 the bytes below 0x80 are characters of their own, never a part of another one + for (auto &character : name) + { + if (static_cast(character) < 0x20 || (Underscorestospaces && character == '_')) + { + character = ' '; + } + } + return name; +} + +namespace +{ +// number of bytes of the character of a text in utf-8 which starts at given position; 1 for a byte which starts no valid sequence +std::size_t utf8_character_size(std::string_view const Text, std::size_t const Position) +{ + auto const length{utf8_sequence_length(static_cast(Text[Position]))}; + if (length < 2 || Position + length > Text.size()) + { + return 1; + } + for (std::size_t offset = 1; offset < length; ++offset) + { + if ((static_cast(Text[Position + offset]) & std::byte{0xC0}) != std::byte{0x80}) + { + return 1; + } + } + return length; +} +} // namespace + +std::size_t utf8_length(std::string_view const Text) +{ + std::size_t length{0}; + for (std::size_t position = 0; position < Text.size(); position += utf8_character_size(Text, position)) + { + ++length; + } + return length; +} + +std::string utf8_fit(std::string_view const Text, std::size_t const Width) +{ + std::size_t length{0}; + std::size_t position{0}; + while (position < Text.size() && length < Width) + { + position += utf8_character_size(Text, position); + ++length; + } + std::string output{Text.substr(0, position)}; + output.append(Width - length, ' '); + return output; +} + // Ra: tymczasowe rozwiązanie kwestii zagranicznych (czeskich) napisów +// NOTE: the entry of 0xB1 (the plus-minus sign of windows-1250, left as it is) is written as its byte. written as the +// character it took two bytes in the builds which keep the texts of the sources in utf-8 (GCC, Clang, MSVC with /utf-8), +// and every entry after it was off by one char const charsetconversiontable[] = "E?,?\"_++?%Sstzz" - " ^^L$A|S^CS<--RZo±,l'uP.,as>L\"lz" + " ^^L$A|S^CS<--RZo\xB1,l'uP.,as>L\"lz" "RAAAALCCCEEEEIIDDNNOOOOxRUUUUYTB" "raaaalccceeeeiiddnnoooo-ruuuuyt?"; diff --git a/utilities/utilities.h b/utilities/utilities.h index aa457b3d3..8acec8aca 100644 --- a/utilities/utilities.h +++ b/utilities/utilities.h @@ -12,6 +12,8 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "utilities/parser.h" +#include + /*rozne takie duperele do operacji na stringach w paszczalu, pewnie w delfi sa lepsze*/ /*konwersja zmiennych na stringi, funkcje matematyczne, logiczne, lancuchowe, I/O etc*/ @@ -25,7 +27,16 @@ template constexpr T sq(T v) return v * v; } -// returns the per-user config path for `filename` (platform-specific dir), +// a base folder of the XDG base directory spec, of the values of its variable (XDG_CONFIG_HOME, XDG_CACHE_HOME) and +// of HOME, either of them null when not set: the variable when it holds an absolute path, else `Fallback` (.config, +// .cache) in the home folder, else an empty path. what Linux uses; apart from the environment, so tests can call it +std::filesystem::path xdg_base_directory(char const *Variable, char const *Home, char const *Fallback); +// the folder of the settings on Linux, of the values of XDG_CONFIG_HOME and HOME: MaSzyna in the base folder of the +// settings, but ~/.config/MaSzyna, where the releases which didn't read XDG_CONFIG_HOME kept them, while it exists and +// the new one doesn't, so the settings already there keep working. an empty path as xdg_base_directory +std::filesystem::path xdg_config_folder(char const *Variable, char const *Home); +// returns the per-user config path for `filename` (platform-specific dir: %APPDATA%\MaSzyna, +// ~/Library/Application Support/MaSzyna, $XDG_CONFIG_HOME/MaSzyna or ~/.config/MaSzyna), // or an empty path if the home/appdata env var is unavailable std::filesystem::path user_config_path(const std::string &filename); // the per-user path for `filename` among the files kept only to be fetched again faster, which don't roam with the profile: @@ -79,11 +90,15 @@ void set_thread_random_engine(std::mt19937 *Engine); // NOSONAR: randomness of t /// @return A random seed as 64 bit unsigned integer std::uint64_t true_random_seed(); -// The seed a word stands for. A number is taken as it is written; anything else is +// The seed a word stands for. A number is taken as it is written - the whole text, so +// "4242abc" is a word, not 4242 - and 0 is a seed like any other; anything else is // hashed the way Java's String.hashCode does it, so the same word gives the same // world on every platform and every build - which is the whole point of telling // somebody a seed. std::uint32_t seed_of(std::string const &Text); +// the seed a text of the settings (randomseed) or of the command line (-seed) gives: none for +// an empty text, else seed_of() it, 0 included +std::optional seed_given(std::string const &Text); std::string generate_uuid_v4(); double LocalRandom(double a, double b); @@ -183,6 +198,17 @@ std::string utf8_to_win1250(std::string const &Text); bool utf8_to_utf32(std::string const &Text, std::u32string &Output); // decodes windows-1250 (ansi) encoded text into unicode code points void win1250_to_utf32(std::string const &Text, std::u32string &Output); +// a text of the data files as utf-8, for the user interface. the files are in windows-1250, some of the newer ones in +// utf-8: a text which is valid utf-8 stays as it is, any other is read as windows-1250, every letter of the code page +// (not only the polish ones win1250_to_utf8() knows) turned into utf-8 +std::string data_text_to_utf8(std::string const &Text); +// the same for a name (of a station, a train, an event, a node, a file) shown in a line of the user interface: what +// Bezogonkow() is for, but the letters keep their marks. control characters become spaces and, when asked, underscores too +std::string data_name_to_utf8(std::string const &Name, bool Underscorestospaces = false); +// number of characters (code points) of a text in utf-8; a byte which isn't a part of a valid sequence counts as one +std::size_t utf8_length(std::string_view Text); +// a text in utf-8 cut or filled with spaces to given number of characters, for the columns of the fixed width +std::string utf8_fit(std::string_view Text, std::size_t Width); inline std::string extract_value(std::string const &Key, std::string const &Input) { diff --git a/utilities/wholefile.cpp b/utilities/wholefile.cpp new file mode 100644 index 000000000..573f0f1ab --- /dev/null +++ b/utilities/wholefile.cpp @@ -0,0 +1,43 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "utilities/wholefile.h" + +#include + +whole_file read_whole_file(std::string const &Path) +{ + whole_file result; + + auto *const file{std::fopen(Path.c_str(), "rb")}; + if (file == nullptr) + { + return result; + } + // without a buffer of its own the stream hands the read to the system in one piece, straight into the memory + std::setvbuf(file, nullptr, _IONBF, 0); +#ifdef _WIN32 + _fseeki64(file, 0, SEEK_END); + auto const length{_ftelli64(file)}; + _fseeki64(file, 0, SEEK_SET); +#else + fseeko(file, 0, SEEK_END); + auto const length{ftello(file)}; + fseeko(file, 0, SEEK_SET); +#endif + if (length > 0) + { + result.data.reset(new char[static_cast(length)]); + result.size = std::fread(result.data.get(), 1, static_cast(length), file); + } + std::fclose(file); + + return result; +} diff --git a/utilities/wholefile.h b/utilities/wholefile.h new file mode 100644 index 000000000..992ea8086 --- /dev/null +++ b/utilities/wholefile.h @@ -0,0 +1,26 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include + +// the content of a whole file, kept in memory +struct whole_file +{ + std::unique_ptr data; + std::size_t size{0}; +}; + +// reads the whole file with one large read. a file stream reads a file which isn't in the system's cache yet from a +// hard disk in small pieces, slower (2026-11, .e3d files of a scenario: about 24 MB/s against 38 MB/s for one read). +// a file which can't be opened or is empty gives no data; a read which stops early gives what was read +whole_file read_whole_file(std::string const &Path); diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index de012f039..4b8a68ed4 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -20,10 +20,15 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/physicslog.h" #include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" #include "vehicle/brakesetting.h" #include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" #include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" #include "world/mtable.h" +#include "world/stationnames.h" #include "vehicle/DynObj.h" #include "world/Event.h" #include "world/MemCell.h" @@ -329,9 +334,7 @@ bool TSpeedPos::Update() // trzeba zazanaczyć, że minięty iFlags |= spElapsed; } - else { - bSeenAhead = true; - } + bSeenAhead = signal_passing::seen_ahead_on_update( fDist, bSeenAhead ); if (iFlags & spTrack) { // road/track if (trTrack) { @@ -417,18 +420,14 @@ bool TSpeedPos::IsProperSemaphor(TOrders order) return false; // true gdy zatrzymanie, wtedy nie ma po co skanować dalej } -// how far behind the head an event found in the scan may lie and still count as one the head had ahead [m] -constexpr double SeenAheadTolerance { 5.0 }; - -bool TSpeedPos::Set(basic_event *event, double dist, double length, TOrders order) +bool TSpeedPos::Set(basic_event *event, double dist, double length, TOrders order, bool const Standing) { // zapamiętanie zdarzenia fDist = dist; - // an event already behind the head when found (under a train set across a signal) wasn't passed by it. the - // distance is found in steps of a metre from the position of the memory cell, so a signal just ahead of the head - // may come out a few metres behind it: those still count as seen ahead. the price is that a train set less than - // the tolerance past a signal at stop is still reported to pass it; a train standing that close to a signal can't - // be told from one stopped just short of it, which really passes the signal if it goes on - bSeenAhead = ( dist >= -SeenAheadTolerance ); + // an event already behind the head when found (under a train set across a signal) wasn't passed by it. a moving + // train may be just passing it, and the distance is found in steps of a metre, so for a moving train an event a + // little behind the head still counts as seen ahead. a standing train passes nothing: an event found behind its + // head counts only once an update finds it ahead + bSeenAhead = signal_passing::seen_ahead_when_found( dist, Standing ); iFlags = spEvent; evEvent = event; vPos = event->input_location(); // współrzędne eventu albo komórki pamięci (zrzutować na tor?) @@ -579,15 +578,21 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) } else { if( iTableDirection == 0 ) { return; } - // NOTE: belt and braces; TablePurger() used to leave these pointing past the end of the table - if( SemNextIndex != npos - && SemNextIndex >= sSpeedTable.size() ) { - SemNextIndex = npos; - } - if( SemNextStopIndex != npos - && SemNextStopIndex >= sSpeedTable.size() ) { - SemNextStopIndex = npos; - } + // NOTE: belt and braces; TablePurger() used to leave these pointing past the end of the table. + // nothing is known to do that any more, so say so when it happens + auto const dropstaleindex = [this, fDistance]( std::size_t &Index, std::string_view const Name ) { + if( Index == npos + || Index < sSpeedTable.size() ) { + return; + } + ErrorLog( std::format( + "Speed table for {}: {} {} points past the end of the table ({} records), last track {} at {:.1f} m, scan range {:.1f} m; reset", + OwnerName(), Name, Index, sSpeedTable.size(), + ( iLast >= 0 && sSpeedTable[ iLast ].trTrack != nullptr ? sSpeedTable[ iLast ].trTrack->name() : "none" ), + ( iLast >= 0 ? sSpeedTable[ iLast ].fDist : 0.0 ), fDistance ) ); + Index = npos; }; + dropstaleindex( SemNextIndex, "SemNextIndex" ); + dropstaleindex( SemNextStopIndex, "SemNextStopIndex" ); // kontynuacja skanowania od ostatnio sprawdzonego toru (w ostatniej pozycji zawsze jest tor) if( SemNextStopIndex != npos && sSpeedTable[SemNextStopIndex].fVelNext == 0.0 ) { @@ -651,7 +656,7 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) typeid( *pEvent ) == typeid( road_order ) ? fCurrentDistance + ProjectEventOnTrack( pEvent, pTrack, fLastDir ) : GetDistanceToEvent( pTrack, pEvent, fLastDir, fCurrentDistance ) }; - if (newspeedpoint.Set(pEvent, eventdistance, fLength, OrderCurrentGet())) + if (newspeedpoint.Set(pEvent, eventdistance, fLength, OrderCurrentGet(), mvOccupied->Vel < EU07_AI_NOMOVEMENT)) { fDistance = newspeedpoint.fDist; // jeśli sygnał stop, to nie ma potrzeby dalej skanować @@ -927,9 +932,8 @@ std::uint8_t passing_flags_of( TSpeedPos const &Point, double const Speedatsigna void TController::CheckSignalPassed( TSpeedPos const &Point, bool const Passedbefore ) const { - if( Passedbefore - || false == TestFlag( Point.iFlags, spElapsed ) - || false == Point.bSeenAhead // found already behind the head: the train stood across it, it didn't pass it + // not bSeenAhead: found already behind the head, the train stood across it or past it, it didn't pass it + if( false == signal_passing::passed_now( Passedbefore, TestFlag( Point.iFlags, spElapsed ), Point.bSeenAhead ) || ( mvOccupied->CategoryFlag & 1 ) == 0 ) { // railway only return; } @@ -1224,8 +1228,9 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub if( ( OrderCurrentGet() & ( Shunt | Loose_shunt | Obey_train | Bank ) ) == 0 ) { return true; } // jeśli przystanek, trzeba obsłużyć wg rozkładu iDrivigFlags |= moveStopPointFound; - // first 19 chars of the command is expected to be "PassengerStopPoint:" so we skip them - if( ToLower( Point.evEvent->input_text() ).compare( 19, sizeof( asNextStop ), ToLower( asNextStop ) ) != 0 ) + // the W4 and the timetable name the station each in its own file, so the two spellings are compared by their key: + // with or without the polish letters, in any case, with spaces or underscores + if( false == timetable::stop_point_is_for( Point.evEvent->input_text(), asNextStop ) ) { // jeśli nazwa nie jest zgodna if( false == IsScheduledPassengerStopVisible // check if our next scheduled stop didn't show up earlier in the scan && Point.fDist < 1.15 * fBrakeDist + 300 @@ -1369,6 +1374,8 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub if (TrainParams.UpdateMTable( simulation::Time, asNextStop) ) { // to się wykona tylko raz po zatrzymaniu na W4 record_station( Point, blackbox::station_kinds::stopped ); + // the service flags of this stop hold for its doors and departure + m_stopflags = TrainParams.stop_flags(); if( TrainParams.StationIndex < TrainParams.StationCount ) { // jeśli są dalsze stacje, bez trąbienia przed odjazdem // also ignore any horn cue that may be potentially set below 1 km/h and before the actual full stop @@ -1467,7 +1474,8 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub if( Command == TCommandType::cm_Unknown ) { // jeśli nie było komendy wcześniej Command = TCommandType::cm_Ready; // gotów do odjazdu z W4 (semafor może zatrzymać) } - if( false == tsGuardSignal.empty() ) { + if( false == tsGuardSignal.empty() + && true == timetable::has_conductor( m_stopflags ) ) { // jeśli mamy głos kierownika, to odegrać iDrivigFlags |= moveGuardSignal; } @@ -1475,7 +1483,8 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub } // koniec startu z zatrzymania else { cue_action(driver_hint::waitdeparturetime); - if (TrainParams.IsTimeToGo(simulation::Time.data().wHour, simulation::Time.data().wMinute + simulation::Time.data().wSecond*0.0167 + 0.1)) { //if is less than 6 sec to departure + if (timetable::has_conductor(m_stopflags) // no conductor, no door kept open for him + && TrainParams.IsTimeToGo(simulation::Time.data().wHour, simulation::Time.data().wMinute + simulation::Time.data().wSecond*0.0167 + 0.1)) { //if is less than 6 sec to departure iDrivigFlags |= moveGuardOpenDoor; GuardOpenDoor(); } @@ -2738,8 +2747,10 @@ double TController::ESMVelocity(bool Main) } IF = std::min(IF, mvControlling->Imax*fCurrentCoeff); double R = mvControlling->RList[MCPN].R + mvControlling->CircuitRes + mvControlling->RList[MCPN].Mn*mvControlling->WindingRes; - double pole = mvControlling->MotorParam[SCPN].fi * - std::max(abs(IF) / (abs(IF) + mvControlling->MotorParam[SCPN].Isat) - mvControlling->MotorParam[SCPN].fi0, 0.0); + // SCPN may come from the .fiz (RList ScndAct) unchecked: read it with the bounds-safe accessor, as MomentumF() does + auto const &motorparam{mvControlling->motor_param(SCPN)}; + double pole = motorparam.fi * + std::max(abs(IF) / (abs(IF) + motorparam.Isat) - motorparam.fi0, 0.0); double Us = abs(mvControlling->EngineVoltage) - IF*R; double ns = std::max(0.0, Us / (pole*mvControlling->RList[MCPN].Mn)); ESMVel = ns * mvControlling->WheelDiameter*M_PI*3.6/mvControlling->Transmision.Ratio; @@ -2888,7 +2899,7 @@ bool TController::CheckVehicles(TOrders user) = 0; } - if( OrderCurrentGet() & ( Shunt | Loose_shunt | Obey_train | Bank ) ) { + if( brake_setting::inspects_train( OrderCurrentGet(), user == Connect ) ) { // nastawianie hamulca do jazdy pociągowej AutoRewident(); /* @@ -3252,15 +3263,15 @@ bool TController::PrepareEngine() close_line_breaker(); } + auto const sufficientpantographpressure { ( + is_emu() ? + 2.5 : // Ra 2013-12: Niebugocław mówi, że w EZT podnoszą się przy 2.5 + 3.5 ) + + 0.1 }; // leeway margin + if( mvPantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector && mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 0 ) { // if our pantograph unit isn't a pantograph-devoid fallback - auto const sufficientpantographpressure { ( - is_emu() ? - 2.5 : // Ra 2013-12: Niebugocław mówi, że w EZT podnoszą się przy 2.5 - 3.5 ) - + 0.1 }; // leeway margin - if (mvPantographUnit->PantPress < sufficientpantographpressure) { // załączenie małej sprężarki if( false == mvPantographUnit->PantAutoValve ) { @@ -3290,6 +3301,9 @@ bool TController::PrepareEngine() auto const ispoweravailable = mvControlling->EnginePowerSource.SourceType != TPowerSource::CurrentCollector || std::max(mvControlling->GetTrainsetHighVoltage(), mvControlling->PantographVoltage) > mvControlling->EnginePowerSource.CollectorParameters.MinV; + // standing with the pantographs up and no voltage, nothing the driver does starts the vehicle. it says so, and keeps + // trying: towed back under the wire, or with the power switched on, the vehicle gets prepared after all + report_power_stall( ispoweravailable, sufficientpantographpressure ); bool isready = false; @@ -3330,6 +3344,7 @@ bool TController::PrepareEngine() cue_action( driver_hint::rearmotorblowerson ); } } + control_field_shunting(); // sync virtual brake state with the 'real' one if( mvOccupied->BrakeHandle != TBrakeHandle::NoHandle ) { std::unordered_map const brakepositions{ @@ -3342,9 +3357,13 @@ bool TController::PrepareEngine() } } // set up train brake - if( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_RP ) ) { - if ( !mvOccupied->Handle->Time - || mvOccupied->Handle->GetCP() < mvOccupied->HighPipePress - 0.05 ); + if( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) { + // standing: the locomotive brake first, then the pipe is filled + secure_standing_train(); + } + else if( ( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_RP ) ) + && ( ( false == mvOccupied->Handle->Time ) + || ( mvOccupied->Handle->GetCP() < mvOccupied->HighPipePress - 0.05 ) ) ) { cue_action( driver_hint::trainbrakerelease ); } // sync spring brake state across consist @@ -3376,6 +3395,39 @@ bool TController::PrepareEngine() return iEngineActive; } +// tells in the log, once, of standing with the pantographs up and no voltage at them, past the end of the overhead +// wire or under a wire switched off (eu07/maszyna#421). Poweravailable is what PrepareEngine() found, Pantographpressure +// the air the pantographs need to rise +void +TController::report_power_stall( bool const Poweravailable, double const Pantographpressure ) { + + ai_power::state state; + state.collector = mvControlling->EnginePowerSource.SourceType == TPowerSource::CurrentCollector; + state.power = Poweravailable; + state.standing = mvOccupied->Vel < EU07_AI_NOMOVEMENT; + if( mvPantographUnit->PantPress >= Pantographpressure ) { + state.pantographs_up = + mvPantographUnit->Pantographs[ end::front ].is_active + || mvPantographUnit->Pantographs[ end::rear ].is_active; + } + // the pantographs of the vehicle carrying them hold the wire they found above them + if( auto const *carrier { pVehicle->FindPantographCarrier() }; + carrier != nullptr && carrier->MoverParameters == mvPantographUnit ) { + auto const pantographcount { std::min( carrier->iAnimType[ ANIM_PANTS ], static_cast( carrier->MoverParameters->Pantographs.size() ) ) }; + for( auto index { 0 }; index < pantographcount; ++index ) { + if( true == carrier->MoverParameters->Pantographs[ index ].is_active + && carrier->pants[ index ].fParamPants->hvPowerWire != nullptr ) { + state.wire = true; + } + } + } + // a user driving the vehicle sees the voltmeters for themselves + if( auto const stall { m_powerstall.update( AIControllFlag ? ai_power::check( state ) : ai_power::stall::waiting, ElapsedTime ) }; + stall.has_value() ) { + ErrorLog( ai_power::message( *stall, pVehicle->asName, pVehicle->GetPosition() ), logtype::traction ); + } +} + // wyłączanie silnika (test wyłączenia, a część wykonawcza tylko jeśli steruje komputer) bool TController::ReleaseEngine() { /* @@ -3773,6 +3825,13 @@ bool TController::DecBrake() { // any release now raises the pipe, and a long train releases more than the handle is moved back, too late // to apply again before the train stands: keep the brake as it is, and the locomotive brake with it break; + } + if( brake_charge::holds_application( + bBrakeChargeHold, IsConsistCharged, mvOccupied->Vel < EU07_AI_NOMOVEMENT, BrakeCtrlPosition ) ) { + // the order to go came while the train still charges: released now, the wagons let go as their + // reservoirs fill and the train stands on a locomotive brake that doesn't hold it. the locomotive + // brake stays on with it + break; } if (deltaAcc < 0 && /*GBH mvOccupied->BrakeCtrlPosR*/ BrakeCtrlPosition > 0) { OK = /*mvOccupied->*/ BrakeLevelAdd(-0.25); @@ -3782,10 +3841,16 @@ bool TController::DecBrake() { if (BrakeCtrlPosition < 0.74) /*mvOccupied->*/ BrakeLevelSet(gbh_RP); } - if( !OK ) { + // standing, the locomotive brake holds the train until its brakes are charged: off before, a train + // released on a gradient rolls with no air to brake with. nor through DecBrakeEIM(), which takes it off + // as well (the locomotive brake of a vehicle without the integrated handle) + auto const holdlocomotive { + ( false == IsConsistCharged ) + && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) }; + if( ( !OK ) && ( false == holdlocomotive ) ) { OK = mvOccupied->DecLocalBrakeLevel(2); } - if( !OK ) { + if( ( !OK ) && ( false == holdlocomotive ) ) { OK = DecBrakeEIM(); } /* @@ -4486,7 +4551,16 @@ void TController::SpeedCntrl(double DesiredSpeed) { if( false == mvControlling->SpeedCtrl ) { return; } - if (mvControlling->EngineType == TEngineType::DieselEngine) + if (mvControlling->IsSpeedCtrlSeparate()) + { + // a switch of its own, the secondary controller left to the field shunting (eu07/maszyna#69) + if (DesiredSpeed < 0.1) { + DesiredSpeed = 0; + } + mvControlling->SpeedCtrlSwitch(DesiredSpeed > 0); + mvControlling->RunCommand("SpeedCntrl", DesiredSpeed, mvControlling->CabActive); + } + else if (mvControlling->EngineType == TEngineType::DieselEngine) { if (DesiredSpeed < 0.1) { mvControlling->DecScndCtrl(2); @@ -4510,7 +4584,7 @@ void TController::SpeedCntrl(double DesiredSpeed) while( mvControlling->ScndCtrlPos < DesiredPos && true == mvControlling->IncScndCtrl(1) ) { ; } // all work is done in the condition loop } - if( mvControlling->SpeedCtrlUnit.PowerStep > 0 && mvControlling->ScndCtrlPos > 0 ) { + if( mvControlling->SpeedCtrlUnit.PowerStep > 0 && mvControlling->IsSpeedCtrlEngaged() ) { while (mvControlling->SpeedCtrlUnit.DesiredPower < mvControlling->SpeedCtrlUnit.MaxPower) { mvControlling->SpeedCtrlPowerInc(); @@ -4802,6 +4876,11 @@ void TController::Doors( bool const Open, int const Side ) { auto const lewe = pVehicle->DirectionGet() > 0 ? 1 : 2; auto const prawe = 3 - lewe; + // doorsteps as the timetable asks, before the doors open (eu07/maszyna#95) + if( auto const doorstep { timetable::doorstep( m_stopflags ) }; + doorstep.has_value() && mvOccupied->Doors.step_enabled != *doorstep ) { + cue_action( *doorstep ? driver_hint::doorstepon : driver_hint::doorstepoff ); + } // grant door control permission if it's not automatic // TBD: stricter requirements? if( true == pVehicle->MoverParameters->Doors.permit_needed ) { @@ -4813,10 +4892,9 @@ void TController::Doors( bool const Open, int const Side ) { } } // consist-wide remote signals to open doors doors - if( pVehicle->MoverParameters->Doors.open_control == control_t::conductor - || pVehicle->MoverParameters->Doors.open_control == control_t::driver - // NOTE: disabled for mixed controls, leave it up to passengers to open doors by themselves -/* || ( pVehicle->MoverParameters->Doors.open_control == control_t::mixed ) */ ) { + // NOTE: mixed controls are left up to passengers to open doors by themselves, unless the timetable has + // the driver open all the doors + if( true == timetable::opens_doors( *pVehicle->MoverParameters, m_stopflags ) ) { if( Side & prawe ) { cue_action( driver_hint::doorrightopen ); } @@ -4966,6 +5044,7 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N TrainParams = TTrainParameters(NewCommand); // rozkład jazdy tsGuardSignal = sound_source { sound_placement::internal, 2 * EU07_SOUND_CABCONTROLSCUTOFFRANGE }; // wywalenie kierownika m_lastexchangestop.clear(); + m_stopflags = {}; if (NewCommand != "none") { if (false == TrainParams.LoadTTfile( @@ -5000,6 +5079,8 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N TrainParams.StationIndexInc(); // przejście do następnej TrainParams.StationStart = TrainParams.StationIndex; asNextStop = TrainParams.NextStop(); + // the flags of the first station until the train stops there + m_stopflags = TrainParams.stop_flags(); m_lastannouncement = announcement_t::idle; iDrivigFlags |= movePrimary; // skoro dostał rozkład, to jest teraz głównym // NewCommand = Global.asCurrentSceneryPath + NewCommand; @@ -6152,7 +6233,8 @@ std::string TController::NextStop() const if (asNextStop == "[End of route]") return ""; // nie zawiera nazwy stacji, gdy dojechał do końca // dodać godzinę odjazdu - auto nextstop{ Bezogonkow( asNextStop, true ) }; + // the name the way the timetable spells it, in utf-8 as the user interface takes it + auto nextstop{ TrainParams.station_caption( asNextStop ) }; auto const *t{ TrainParams.TimeTable + TrainParams.StationIndex }; if( t->Ah >= 0 ) { // przyjazd @@ -6568,12 +6650,18 @@ TController::determine_consist_state() { auto released { true }; // the brakes are off, the hold of an uphill start not counted auto mostapplied { 0.0 }; // the most applied brake, the hold of an uphill start not counted auto momentum { 0.0 }; + auto chargelevel { std::numeric_limits::max() }; // the lowest pipe or auxiliary reservoir pressure of a working brake while (p) { // sprawdzenie odhamowania wszystkich połączonych pojazdów auto *vehicle { p->MoverParameters }; auto const bp { std::max( 0.0, vehicle->BrakePress - ( vehicle->SpeedCtrlUnit.Parking ? vehicle->MaxBrakePress[ 0 ] * vehicle->StopBrakeDecc : 0.0 ) ) }; momentum += vehicle->TotalMass * vehicle->V * ( p->DirectionGet() == iDirection ? 1 : -1 ); mostapplied = std::max( bp, mostapplied ); + if( ( vehicle->BrakeSystem != TBrakeSystem::Individual ) + && ( vehicle->MaxBrakePress[ 3 ] > 0.0 ) + && ( false == TestFlag( vehicle->Hamulec->GetBrakeStatus(), b_dmg ) ) ) { // a brake cut out doesn't count + chargelevel = std::min( { chargelevel, vehicle->PipePress, vehicle->Hamulec->GetBRP() } ); + } auto const wasready { Ready }; if( released || Ready ) { // bo jak coś nie odhamowane, to dalej nie ma co sprawdzać @@ -6708,6 +6796,69 @@ TController::determine_consist_state() { IsConsistReleased = released || ( fAccGravity < -0.05 && mostapplied < 0.8 ); // the frame of the vehicle the AI drives from, as for fAccGravity and AbsAccS fConsistVelocity = 3.6 * momentum / std::max( 1.0, fMass ) * ( iDirection >= 0 ? 1 : -1 ); + // standing, the train starts only with its brakes charged: released alone, a train prepared from cold has no air to + // brake with while its auxiliary reservoirs fill. with the train brake applied (held for an uphill start, a light + // application while charging) they charge to what the head of the pipe has. + // only the start the charge is in question for: the first after the train was prepared standing, or one with the + // pipe near empty (after an emergency application, brake_charge::empty_level). after an ordinary stop the + // reservoirs refill as the brake releases, and waiting for the last tenths of a bar there only delays the train and + // those behind it. + // and only the pneumatic brake: multiple units with the electro-pneumatic one start as before + if( mvOccupied->Vel > 1.0 ) { + // the start is made. a shunting engine coupling wagons moves at a walking pace: a higher speed would leave its + // every start the first, waiting for each cut of wagons placed cold to charge + bBrakeChargeStart = false; + bBrakeChargeHold = false; + bHasRun = true; + } + auto const chargeable { + ( BrakeSystem == TBrakeSystem::Pneumatic ) + && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) + && ( chargelevel < std::numeric_limits::max() ) }; + if( chargeable && ( chargelevel < brake_charge::empty_level ) ) { + bBrakeChargeStart = true; + } + if( chargeable && bBrakeChargeStart ) { + if( ( VelDesired <= 0.0 ) || ( AccDesired <= EU07_AI_NOACCELERATION ) ) { + // to stand: the next start is checked anew + BrakeCharge.going = false; + } + auto const trainbrakeapplied { + AIControllFlag ? + BrakeCtrlPosition > 0.0 : + // a human driver's handle, which BrakeCtrlPosition doesn't follow + mvOccupied->fBrakeCtrlPos > mvOccupied->Handle->GetPos( bh_RP ) + 0.2 }; + auto const reference { + brake_charge::reference( mvOccupied->PipePress, std::min( mvOccupied->Handle->GetRP(), 5.0 ), trainbrakeapplied ) }; + // air to charge with: the engine prepared, the main reservoir above what the pipe charges to, and the driver's + // brake valve feeding the pipe at the head of the train. a train still being prepared from cold can't charge, + // nor one whose pipe is locked (unlocked by control_releaser()): it waits without that counting as a stall, held + // by its brakes as it can't release them either + auto const supplied { + iEngineActive + && ( std::max( mvControlling->Compressor, mvOccupied->Compressor ) > reference ) + && ( mvOccupied->PipePress >= reference - brake_charge::margin ) }; + auto const wasstalled { BrakeCharge.stalled }; + IsConsistCharged = brake_charge::charged( BrakeCharge, chargelevel, reference, ElapsedTime, supplied ); + if( BrakeCharge.stalled && ( false == wasstalled ) ) { + WriteLog( + "AI: " + mvOccupied->Name + " stopped charging its brakes at " + to_string( chargelevel, 2 ) + + " bar of " + to_string( reference, 2 ) + ", starting all the same" ); + } + if( false == IsConsistCharged ) { + // a human driver is told to wait as the ai does, the locomotive brake applied + cue_action( driver_hint::waitbrakecharge ); + } + } + else { + IsConsistCharged = true; + BrakeCharge = {}; + } + if( AIControllFlag + && ( false == IsConsistCharged ) + && ( false == heldforstart ) ) { + Ready = false; + } auto const departblocked { AIControllFlag && mvOccupied->Vel < EU07_AI_NOMOVEMENT @@ -6747,15 +6898,38 @@ TController::determine_consist_state() { void TController::control_wheelslip() { + // a start that has slipped once keeps the sand on until the train is under way. with the sand off as soon as the + // wheels grip again, the next notch slips again, and a heavy train on poor rails slips, grips and snatches over + // and over, and may never get going (#187). a vehicle without sand starts as before + auto const velocity { std::abs( mvOccupied->Vel ) }; + if( mvControlling->SlippingWheels + && velocity < EU07_AI_SANDEDSTARTVELOCITY + && false == mvControlling->IsMainCtrlNoPowerPos() + && mvControlling->Sand > 0.0 ) { + bSandedStart = true; + } + else if( velocity >= EU07_AI_SANDEDSTARTVELOCITY + || ( velocity < EU07_AI_NOMOVEMENT && VelDesired == 0.0 ) ) { + bSandedStart = false; + } // wheel slip if( mvControlling->SlippingWheels ) { cue_action( driver_hint::sandingon ); // piasku! - cue_action( driver_hint::tractiveforcedecrease ); + if( false == bSandedStart ) { + cue_action( driver_hint::tractiveforcedecrease ); + cue_action( driver_hint::antislip ); + } + else if( ElapsedTime - fSandedStartDecreaseTime >= 1.0 ) { + // starting, a step down at a time, and no anti-slip brake: taking the power off at once and braking the + // locomotive brings a heavy train that has just got moving to a stand again, and the start begins anew + cue_action( driver_hint::tractiveforcedecrease ); + fSandedStartDecreaseTime = ElapsedTime; + } cue_action( driver_hint::brakingforcedecrease ); - cue_action( driver_hint::antislip ); ++iDriverFailCount; } - else if( std::fabs( mvControlling->Im ) > 0.75 * mvControlling->ImaxHi ) { + else if( ( std::fabs( mvControlling->Im ) > 0.75 * mvControlling->ImaxHi ) + || ( bSandedStart && false == mvControlling->IsMainCtrlNoPowerPos() ) ) { cue_action( driver_hint::sandingon ); // piaskujemy tory, coby się nie ślizgać } else { @@ -8267,8 +8441,16 @@ TController::adjust_desired_speed_for_braking_curve( double const Vel ) { // independent brake, which leaves the train brake handle where it is, kept braking earlier // and earlier the whole way in, to crawl the last tens of metres to the stop point auto const fillbrakea0 { bStopTargetIsPassengerStop ? 1.0 : fBrake_a0[ 0 ] }; + // once the brake is on, the room it takes to fill is behind; a vehicle running alone brakes with its + // independent brake and leaves the train brake handle in running, so that brake counts as well braking_curve::approach const approach { - Vel, VelNext, ActualProximityDist, brakingpointoffset, fAccGravity, AbsAccS, BrakeCtrlPosition > 0.0, + Vel, VelNext, ActualProximityDist, brakingpointoffset, fAccGravity, AbsAccS, + braking_curve::brake_acting( + BrakeCtrlPosition, + // IncLocalBrakeLevel() moves the independent brake handle on a vehicle without one too + ( mvOccupied->LocalBrake == TLocalBrake::PneumaticBrake || mvOccupied->LocalBrake == TLocalBrake::HydraulicBrake ) ? + mvOccupied->LocalBrakePosA : + 0.0 ), brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ), brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fillbrakea0 ) }; auto const deceleration { braking_curve::demand( approach, BrakeSystem == TBrakeSystem::Pneumatic ? &braketable : nullptr ) }; @@ -8578,6 +8760,8 @@ TController::adjust_desired_speed_for_braking_test() { // if( false == Global.DynamicBrakeTest ) { return; } if( DynamicBrakeTest >= 5 ) { return; } // all done + if( ( DynamicBrakeTest == 0 ) + && ( false == timetable::makes_brake_test( TrainParams.run_flags() ) ) ) { return; } // the timetable says there's none (eu07/maszyna#95) if( false == is_train() ) { return; } // not applicable if( mvOccupied->BrakeHandle == TBrakeHandle::FVel6 ) { return; } // leads to bugs in DecBrake, disable for now if( false == TestFlag( OrderCurrentGet(), Obey_train ) ) { return; } // not applicable @@ -8711,9 +8895,24 @@ TController::control_tractive_and_braking_force() { #endif } +// the switch of the field shunting of a diesel-electric that has one (AutoRelay=Optional with FieldShuntSwitch=Yes): off, +// the field stays full. checked while running too, since a vehicle taken over with its engine running doesn't go through +// PrepareEngine(). a diesel-electric with AutoRelay=Optional alone is left as before, shunting by hand with the switch off +void TController::control_field_shunting() { + + if( AIControllFlag + && mvControlling->EngineType == TEngineType::DieselElectric + && fieldshunting::has_switch( mvControlling->AutoRelayType, mvControlling->FieldShuntSwitch ) + && false == mvControlling->AutoRelayFlag ) { + mvControlling->AutoRelaySwitch( true ); + } +} + // ensure relays are active void TController::control_relays() { + control_field_shunting(); + if( fActionTime < 0.0 ) { return; } if( IsAnyMotorOverloadRelayOpen ) { @@ -8817,7 +9016,8 @@ void TController::control_uphill_start() { && ( fConsistVelocity > -0.5 ) && ( AccDesired > EU07_AI_NOACCELERATION ) && ( VelDesired > 0.0 ) - && ( BrakeCtrlPosition > 0.0 ) ) { // only with the train brake still applied to hold the train + && ( BrakeCtrlPosition > 0.0 ) // only with the train brake still applied to hold the train + && ( IsConsistCharged ) ) { // and charged to what the pipe has, or the brake that holds the train has no air bUphillStart = true; bUphillRelease = false; UphillTopUp = {}; @@ -8911,6 +9111,55 @@ void TController::end_uphill_start() { bUphillBrakeTopUp = false; } +// standing, a train is prepared as a driver does it: the locomotive brake first, then the brake pipe is filled. the pipe +// filled at once releases the distributors while the auxiliary reservoirs are still empty: the train has no brake left, +// and on a gradient rolls away as it releases. where the locomotive brake alone doesn't hold the train, the train brake +// is applied lightly, so the reservoirs charge with the train held. the locomotive brake comes off only once the train +// is charged and to start (DecBrake()) +void TController::secure_standing_train() { + + if( BrakeSystem != TBrakeSystem::Pneumatic ) { + // the electro-pneumatic brake of a multiple unit is released as before: nothing there takes the locomotive + // brake off again when the unit starts + cue_action( driver_hint::trainbrakerelease ); + return; + } + // the first start of a train that hasn't run yet waits for the brakes to charge. one that has run, prepared again + // (a change of direction, an engine started anew), has its reservoirs charged from the run and starts as before + if( false == bHasRun ) { + bBrakeChargeStart = true; + } + if( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) { + cue_action( driver_hint::independentbrakeapply ); + } + if( false == brake_charge::locomotive_brake_holds( locomotive_brake_force(), fMass * fAccGravity ) ) { + // the first service position: the pipe and the reservoirs charge to a little below the working pressure, the + // distributors keep a light application. a stronger application already there is left as it is, but not + // the emergency one or an empty pipe's, which don't charge + if( AIControllFlag + && ( ( BrakeCtrlPosition < 1.0 ) || ( BrakeCtrlPosition > uphill_start::top_up_position ) ) ) { + BrakeLevelSet( 1.0 ); + } + bBrakeChargeHold = true; + return; + } + bBrakeChargeHold = false; + cue_action( driver_hint::trainbrakerelease ); +} + +// the brake force of the locomotive brake at full application [N]. of the occupied vehicle alone: its handle acts on +// no other, not on a second section or a locomotive in multiple control either, let alone one hauled dead +double TController::locomotive_brake_force() const { + + if( ( mvOccupied->LocalBrake == TLocalBrake::ManualBrake ) + || ( mvOccupied->MaxBrakePress[ 0 ] <= 0.0 ) ) { + return 0.0; + } + return brake_charge::locomotive_brake_force( + mvOccupied->BrakeForceP( mvOccupied->MaxBrakePress[ 0 ], 0.0 ), + mvOccupied->TotalMassxg ); +} + void TController::increase_tractive_force() { if( fActionTime < 0.0 ) { return; } // gdy jest nakaz poczekać z jazdą, to nie ruszać @@ -9073,7 +9322,14 @@ void TController::control_braking_force() { } if ( (accdesiredresultant < fAccGravity - 0.05 || AccDesired >= EU07_AI_NOACCELERATION) // no braking asked for, yet the train is slowing down more than that - && accdesiredresultant - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 && OrderCurrentGet() != Disconnect && VelDesired > 0.0 ) { + && accdesiredresultant - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 && OrderCurrentGet() != Disconnect && VelDesired > 0.0 + // a human driver standing with the train not charged yet keeps the locomotive brake on, told so by the + // waitbrakecharge hint; the ai is held back in DecBrake() + && ( AIControllFlag + || ( false == brake_charge::release_waits( + IsConsistCharged, + mvOccupied->Vel < EU07_AI_NOMOVEMENT, + mvOccupied->fBrakeCtrlPos > mvOccupied->Handle->GetPos( bh_RP ) + 0.2 ) ) ) ) { // the human driver's handle // jak hamuje, to nie tykaj kranu za często // yB: luzuje hamulec dopiero przy różnicy opóźnień rzędu 0.2 // przy odłączaniu nie zwalniamy tu hamulca @@ -9146,39 +9402,34 @@ void TController::control_releaser() { if( false == hasreleaser ) { return; } - auto actuate { false }; + brake_releaser::conditions state; + state.acceleration_desired = AccDesired; + state.pipe_pressure = mvOccupied->PipePress; + state.cylinder_pressure = mvOccupied->BrakePress; + state.control_pressure = mvOccupied->Hamulec->GetCRP(); + state.velocity = mvOccupied->Vel; + state.uphill_start = bUphillStart; + state.pressing = TestFlag( iDrivigFlags, movePress ); + // stage 3 of uncoupling (UpdateDisconnect), from the direction change until the coupler lets go + state.compressing_buffers = + state.pressing && ( OrderCurrentGet() & Disconnect ) != 0 && iVehicleCount >= 0 && iDirection == iDirectionOrder; + // a train prepared standing charges its brakes before its first start. a pipe left below the lock of the driver's + // brake valve (a train placed cold, as after an emergency application) is unlocked as the train stands, not only + // once it is to go: else it charges only after the order to go, and starts on what the reservoirs got by then. + // a handle which has to be moved to unlock is left where it holds the train with the train brake + state.charging_standing = + bBrakeChargeStart + && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) + && ( ( mvOccupied->HandleUnlock == -3 ) || ( BrakeCtrlPosition <= 0.0 ) ); + auto const wanted { brake_releaser::decide( state ) }; + auto const actuate { wanted.actuate }; auto isbrakehandleinrightposition { true }; - if( AccDesired > EU07_AI_NOACCELERATION ) { - // fill up brake pipe if needed - if( mvOccupied->PipePress < 3.0 ) { - actuate = true; - // some vehicles require brake handle to be moved to specific position - if( mvOccupied->HandleUnlock != -3 ) { - cue_action( driver_hint::trainbrakesetpipeunlock ); - isbrakehandleinrightposition &= BrakeCtrlPosition == mvOccupied->HandleUnlock; - } - } - // wyluzuj lokomotywę, to szybciej ruszymy - // this rule is for starting off, so only below 1 km/h: at speed, just after an application, it would vent - // the control reservoir of a locomotive that may have to brake again before the pipe has refilled it - if( mvOccupied->BrakePress > 0.4 - && ( mvOccupied->Hamulec->GetCRP() > 4.9 - // starting uphill the train brake stays applied on purpose, and the locomotive's own share of it has to go - // for the power to come on (asynchronous drives and the pressure switch cut the power while it is applied) - || bUphillStart ) - && mvOccupied->Vel < 1.0 ) { - actuate = true; - } - // keep engine brakes released during coupling/uncoupling - if( true == TestFlag(iDrivigFlags, movePress) - && mvOccupied->BrakePress > 0.1 ) { - actuate = true; - } - } - // don't overcharge train brake pipe - if( mvOccupied->PipePress > 5.2 ) { - actuate = false; + // some vehicles require brake handle to be moved to specific position to fill up the brake pipe + if( wanted.fill_pipe + && mvOccupied->HandleUnlock != -3 ) { + cue_action( driver_hint::trainbrakesetpipeunlock ); + isbrakehandleinrightposition = ( BrakeCtrlPosition == mvOccupied->HandleUnlock ); } if( actuate ) { @@ -9199,7 +9450,9 @@ void TController::control_releaser() { void TController::control_main_pipe() { // unlocking main pipe - if( AccDesired > -0.03 + if( ( AccDesired > -0.03 + // standing to charge before the first start, as in control_releaser() + || ( bBrakeChargeStart && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) ) ) && true == mvOccupied->LockPipe ) { UniversalBrakeButtons |= TUniversalBrake::ub_UnlockPipe; } @@ -9231,9 +9484,12 @@ void TController::control_main_pipe() { update_brake_charging(); - if( mvOccupied->Compressor < 5.0 - || ( BrakeCtrlPosition < gbh_RP - && ( mvOccupied->EqvtPipePress > (fReady < 0.25 ? 5.1 : 5.2) || is_brake_charging_done() ) ) ) { + if( ( mvOccupied->Compressor < 5.0 + || ( BrakeCtrlPosition < gbh_RP + && ( mvOccupied->EqvtPipePress > (fReady < 0.25 ? 5.1 : 5.2) || is_brake_charging_done() ) ) ) + // the light application a charging train stands on stays, as in DecBrake() + && ( false == brake_charge::holds_application( + bBrakeChargeHold, IsConsistCharged, mvOccupied->Vel < EU07_AI_NOMOVEMENT, BrakeCtrlPosition ) ) ) { cue_action( driver_hint::trainbrakerelease ); } } diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 62b326696..0eae2caf1 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -20,7 +20,9 @@ http://mozilla.org/MPL/2.0/. #include "utilities/translation.h" #include "application/driverhints.h" #include "vehicle/uphillstart.h" +#include "vehicle/brakecharge.h" #include "vehicle/blackbox.h" +#include "vehicle/aipower.h" auto const EU07_AI_ACCELERATION = 0.05; auto const EU07_AI_NOACCELERATION = -0.05; @@ -30,6 +32,7 @@ auto const EU07_AI_MOVEMENT = 1.0; // deliberate movement velocity threshold auto const EU07_AI_UPHILLGRAVITY = -0.025; // [m/s2] about 2.5 per mille up: the gradient that rolls a standing train back auto const EU07_AI_UPHILLRELEASETIME = 60.0; // [s] the longest an uphill start keeps the power on while the train brake releases auto const EU07_AI_SPEEDLIMITEXTENDSBEYONDSCANRANGE = 10000.0; +auto const EU07_AI_SANDEDSTARTVELOCITY = 15.0; // [km/h] a start that slipped keeps the sand on up to this speed enum TOrders { // rozkazy dla AI @@ -186,7 +189,8 @@ class TSpeedPos void UpdateDistance( double dist ) { fDist -= dist; } - bool Set(basic_event *e, double d, double length, TOrders order = Wait_for_orders); + // Standing: the train stands, so an event found behind its head wasn't passed by it + bool Set(basic_event *e, double d, double length, TOrders order = Wait_for_orders, bool Standing = false); void Set(TTrack *t, double d, int f); std::string TableText() const; std::string GetName() const; @@ -341,6 +345,8 @@ private: void control_uphill_start(); void end_uphill_start(); bool uphill_brake_top_up(); + void secure_standing_train(); + double locomotive_brake_force() const; std::pair train_proximity_margins( bool const Passengerstop ) const; void update_timers( double const dt ); @@ -392,6 +398,7 @@ private: bool is_brake_charging_done() const; double consist_max_crp() const; bool is_departure_blocked( double const Delay ) const; + void control_field_shunting(); void control_relays(); void control_motor_connectors(); void control_tractive_force(); @@ -444,6 +451,8 @@ private: double fShortfallTime = 0.0; // when that was checked int iShortfallGrowth = 0; // how many checks in a row the shortfall has grown bool bUphillStart = false; // starting uphill: the train brake holds the train until the power does + bool bSandedStart = false; // the wheels slipped while starting: sand while under power until the train is under way + double fSandedStartDecreaseTime = -1.0; // when the power was last taken down a step for a slip while starting double fUphillStartTime = 0.0; // when the uphill start began bool bUphillRelease = false; // starting uphill, the power holds the train and the train brake is being released bool bUphillBrakeTopUp = false; // starting uphill, the train brake is applied further before the locomotive brake comes off @@ -452,6 +461,13 @@ private: double fUphillTractiveForce = 0.0; // the tractive force of the consist while starting uphill [N] double fUphillHoldingForce = 0.0; // the grade force on the consist while starting uphill [N] bool IsConsistReleased = true; // the brakes of the consist are off, the hold of an uphill start not counted + bool IsConsistCharged = true; // standing, the brake pipe and the auxiliary reservoirs are charged to start (or stopped charging) + brake_charge::state BrakeCharge; // standing, how the charge of the brakes rose + // the next start waits for the brakes to charge: the first after the train was prepared standing, or one with the + // pipe near empty. cleared once the train runs + bool bBrakeChargeStart = false; + bool bHasRun = false; // the train has moved (above 1 km/h) since it was placed + bool bBrakeChargeHold = false; // charging, the train stands on a light application of the train brake as well double fConsistVelocity = 0.0; // the mass-weighted speed of the consist, positive in the direction of travel [km/h] double fAccDesiredGravity = 0.0; // część AccDesired odjęta na spadku jako kompensacja pochylenia; AbsAccS zawiera ją już sam double VelforDriver = -1.0; // prędkość, używana przy zmianie kierunku (ograniczenie przy nieznajmości szlaku?) @@ -680,6 +696,7 @@ private: std::string m_lastexchangestop; // HACK: safeguard to prevent multiple load exchanges per station int m_lastexchangeplatforms { 0 }; // cached station platforms for last exchange int m_lastexchangedirection { 0 }; // + timetable::service_flags m_stopflags; // service flags of the timetable at the stop the train is at or left last double fLastStopExpDist = -1.0; // odległość wygasania ostateniego przystanku int iRadioChannel = 1; // numer aktualnego kanału radiowego int iGuardRadio = 0; // numer kanału radiowego kierownika (0, gdy nie używa radia) @@ -693,6 +710,9 @@ public: bool CheckVehicles( TOrders user = Wait_for_orders ); private: bool PrepareEngine(); + // tells in the log, once, of standing with the pantographs up and no voltage (eu07/maszyna#421) + void report_power_stall( bool const Poweravailable, double const Pantographpressure ); + ai_power::reporter m_powerstall; // the reports of report_power_stall() void close_line_breaker(); bool ReleaseEngine(); void Doors( bool const Open, int const Side = 0 ); diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index e5e387198..9d7b7397a 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -23,12 +23,20 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Camera.h" #include "vehicle/Train.h" #include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" #include "vehicle/Driver.h" #include +#include #include +#include #include +#include +#include +#include #include +#include +#include #include "utilities/Globals.h" #include "utilities/Timer.h" #include "utilities/workerpool.h" @@ -41,6 +49,7 @@ http://mozilla.org/MPL/2.0/. #include "model/Model3d.h" #include "vehicle/doorwings.h" #include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" #include "application/uitranscripts.h" #include "input/messaging.h" #include "application/application.h" @@ -319,9 +328,13 @@ namespace { void deserialize_script_sign( cParser &Parser, script_screens::screen_config &Sign, std::string const &Folder ) { Sign.deserialize( Parser ); - if( false == Sign.script.empty() - && substr_path( Sign.script ).empty() ) { - Sign.script = Folder + Sign.script; + if( Sign.script.empty() ) { return; } + if( auto path { script_screens::screen_script_path( Folder, Sign.script ) }; path.has_value() ) { + Sign.script = std::move( *path ); + } + else { + ErrorLog( "Bad script sign: \"" + Sign.script + "\" leads outside the game's folder" ); + Sign.script.clear(); } } @@ -702,6 +715,62 @@ void TDynamicObject::UpdateDoorPlug(TAnim *pAnim) { } } +// a wing animated in its own way (animdoor: of the .mmd): as far along its own range as the door of its side is +void TDynamicObject::UpdateDoorWing( TAnim *pAnim, door_wings::wing_spec const &Spec ) { + + if( pAnim->smAnimated == nullptr ) { return; } + + auto const position { door_wings::wing_position( door_position( *MoverParameters, pAnim ), MoverParameters->Doors.range, Spec.range ) }; + for( auto *wing : wing_parts( pAnim ) ) { + if( wing == nullptr ) { continue; } + switch( Spec.type ) { + case door_wings::shift_type: { + wing->SetTranslate( door_wings::slide( position ) ); + break; + } + case door_wings::rotate_type: { + wing->SetRotate( float3( 1, 0, 0 ), position ); + break; + } + case door_wings::fold_type: { + fold_wing( wing, door_wings::fold( position ) ); + break; + } + case door_wings::plug_type: { + wing->SetTranslate( door_wings::plug( position, Spec.range_out ) ); + break; + } + default: { + break; + } + } + } +} + +void TDynamicObject::bind_door_animation( TAnim &Animation ) { + + if( auto const *spec { door_wings::find( m_doorwings, Animation.iNumber ) } ) { + Animation.yUpdate = [ this, spec = *spec ]( TAnim *pAnim ) { UpdateDoorWing( pAnim, spec ); }; + return; + } + switch( MoverParameters->Doors.type ) { // od razu zapinamy potrzebny typ animacji + case 1: + Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorTranslate, this, std::placeholders::_1 ); + break; + case 2: + Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorRotate, this, std::placeholders::_1 ); + break; + case 3: + Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorFold, this, std::placeholders::_1 ); + break; // obrót 3 kolejnych submodeli + case 4: + Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorPlug, this, std::placeholders::_1 ); + break; + default: + break; + } +} + void TDynamicObject::UpdatePant(TAnim *pAnim) { // animacja pantografu - 4 obracane ramiona, ślizg piąty float a, b, c; @@ -1541,6 +1610,14 @@ void TDynamicObject::ABuBogies() { // Obracanie wozkow na zakretach. Na razie // uwzględnia tylko zakręty, // bez zadnych gorek i innych przeszkod. + if( smBogie[ 0 ] != nullptr && smBogie[ 1 ] != nullptr && MoverParameters->OffTrack.active() ) { + // off the track the bogies stay straight under the body, they don't follow the track any more + bogieRot[ 0 ] = glm::vec3 { 0.f }; + bogieRot[ 1 ] = glm::vec3 { 0.f }; + smBogie[ 0 ]->SetRotateXYZ( bogieRot[ 0 ] ); + smBogie[ 1 ]->SetRotateXYZ( bogieRot[ 1 ] ); + return; + } if (smBogie[0] != nullptr && smBogie[1] != nullptr) { // modelRot.z=ABuAcos(Axle0.pPosition-Axle1.pPosition); //kąt obrotu pojazdu @@ -1577,7 +1654,7 @@ void TDynamicObject::ABuCheckMyTrack() // Ra: w poniższej funkcji jest problem ze sprzęgami TDynamicObject * -TDynamicObject::ABuFindObject( int &Foundcoupler, double &Distance, TTrack const *Track, int const Direction, int const Mycoupler ) const +TDynamicObject::ABuFindObject( int &Foundcoupler, double &Distance, TTrack const *Track, int const Direction, int const Mycoupler, bool const InLine ) const { // Zwraca wskaźnik najbliższego obiektu znajdującego się // na torze w określonym kierunku, ale tylko wtedy, kiedy // obiekty mogą się zderzyć, tzn. nie mijają się. @@ -1619,6 +1696,10 @@ TDynamicObject::ABuFindObject( int &Foundcoupler, double &Distance, TTrack const for( auto dynamic : Track->Dynamics ) { if( dynamic == this ) { continue; } // szukający się nie liczy + // physics.derailment new: one of the two off the track beside the other one, they don't meet + if( InLine && ( MoverParameters->OffTrack.active() || dynamic->MoverParameters->OffTrack.active() ) && false == in_line_with( *dynamic ) ) { + continue; + } /* if( ( ( dynamic == PrevConnected ) && ( MoverParameters->Couplers[ TMoverParameters::side::front ].CouplingFlag != coupling::faux ) ) || ( ( dynamic == NextConnected ) && ( MoverParameters->Couplers[ TMoverParameters::side::rear ].CouplingFlag != coupling::faux ) ) ){ @@ -2000,6 +2081,9 @@ void TDynamicObject::place_on_track(TTrack *Track, double fDist, bool Reversed) Axle1.Move((iDirection ? fDist : -fDist) - fAxleDistHalf, false); // false, żeby nie generować eventów break; } + // the stretches the criteria of derailment held over were on the track the vehicle left (consistteleport) + MoverParameters->derailment_monitor.reset(); + MoverParameters->derailment_distance = 0.0; // potrzebne do wyliczenia aktualnej pozycji; nie może być zero, bo nie przeliczy pozycji // teraz jeszcze trzeba przypisać pojazdy do nowego toru, bo przesuwanie początkowe osi nie // zrobiło tego @@ -2031,6 +2115,14 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" // another run of the same scenario, with another seed, dresses it differently m_variantseed = hash_string( asName, Global.random_seed ); std::string asAnimName; // zmienna robocza do wyszukiwania osi i wózków + // a vehicle prepared for being hauled dead (parameter H after its coupling, MaSzyna-EU07/maszyna#64) has nobody + // driving it, whatever its crew entry says: its cab can't be activated, and a driver in it would either take + // the train or be one more for the train's driver to put to sleep + auto const hauled { pullee_mode::requested( MoreParams ) }; + if( hauled && ( DriverType == "headdriver" || DriverType == "reardriver" ) ) { + WriteLog( "Vehicle " + asName + " is prepared for hauling (parameter H), the driver it was given is left out" ); + DriverType = "nobody"; + } // Ra: zmieniamy znaczenie obsady na jednoliterowe, żeby dosadzić kierownika if (DriverType == "headdriver") DriverType = "1"; // sterujący kabiną +1 @@ -2350,6 +2442,11 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" */ } // koniec while kropka + if( hauled ) { + // once the vehicle has its starting state: the hand brake and the spring brake of a standing one let go, battery off + MoverParameters->PulleeModeSwitch( true ); + } + if (MoverParameters->CategoryFlag & 2) // jeśli samochód { // ustawianie samochodow na poboczu albo na środku drogi if( Track->fTrackWidth < 3.5 // jeśli droga wąska @@ -2707,6 +2804,22 @@ void TDynamicObject::FastMove(double fDistance) } void TDynamicObject::Move(double fDistance) +{ + if( MoverParameters->OffTrack.active() ) { + // physics.derailment new: off the track it goes on the ground + move_off_track( fDistance ); + return; + } + move_axles( fDistance ); + if( fDistance != 0.0 || m_offtrackplaced ) // nie liczyć ponownie, jeśli stoi + { // liczenie pozycji pojazdu tutaj, bo jest używane w wielu miejscach + // (also once the vehicle off the track is back on the rails) + m_offtrackplaced = false; + place_by_axles(); + } +} + +void TDynamicObject::move_axles(double fDistance) { // przesuwanie pojazdu po // trajektorii polega na // przesuwaniu poszczególnych osi @@ -2738,8 +2851,10 @@ void TDynamicObject::Move(double fDistance) bEnabled &= Axle1.Move(fDistance, iAxleFirst != 0); // oś z tyłu pojazdu prusza się pierwsza bEnabled &= Axle0.Move(fDistance, iAxleFirst == 0); // oś z przodu pojazdu } - if (fDistance != 0.0) // nie liczyć ponownie, jeśli stoi - { // liczenie pozycji pojazdu tutaj, bo jest używane w wielu miejscach +} + +void TDynamicObject::place_by_axles() +{ // liczenie pozycji pojazdu tutaj, bo jest używane w wielu miejscach vPosition = 0.5 * (Axle1.pPosition + Axle0.pPosition); //środek między skrajnymi osiami vFront = Axle0.pPosition - Axle1.pPosition; // wektor pomiędzy skrajnymi osiami // Ra 2F1J: to nie jest stabilne (powoduje rzucanie taborem) i wymaga @@ -2849,8 +2964,448 @@ void TDynamicObject::Move(double fDistance) } } } +} + +namespace { + +using ground_triangles = std::vector; + +bool outside( glm::dvec3 const &Centre, double const Radius, glm::dvec2 const &Min, glm::dvec2 const &Max ) { + return Centre.x + Radius < Min.x || Centre.x - Radius > Max.x || Centre.z + Radius < Min.y || Centre.z - Radius > Max.y; +} + +void add_triangle( glm::dvec3 const &A, glm::dvec3 const &B, glm::dvec3 const &C, glm::dvec2 const &Min, glm::dvec2 const &Max, ground_triangles &Out ) { + if( std::max( { A.x, B.x, C.x } ) < Min.x || std::min( { A.x, B.x, C.x } ) > Max.x + || std::max( { A.z, B.z, C.z } ) < Min.y || std::min( { A.z, B.z, C.z } ) > Max.y ) { + return; } -}; + Out.push_back( { A, B, C } ); +} + +// the triangles of a piece of the scenery's geometry within the rectangle (x, z), as the editor gathers the ground +void add_shape( scene::shape_node const &Shape, glm::dvec2 const &Min, glm::dvec2 const &Max, ground_triangles &Out ) { + auto const &data { Shape.data() }; + if( data.area.radius >= 0.f && outside( data.area.center, data.area.radius, Min, Max ) ) { + return; + } + if( false == data.vertices.empty() ) { + for( std::size_t i = 0; i + 2 < data.vertices.size(); i += 3 ) { + add_triangle( data.vertices[ i ].position, data.vertices[ i + 1 ].position, data.vertices[ i + 2 ].position, Min, Max, Out ); + } + return; + } + // once the shape is uploaded its world-space source is released; the renderer keeps an origin-relative copy + if( data.geometry.bank == 0 && data.geometry.chunk == 0 ) { + return; + } + auto const &vertices { GfxRenderer->Vertices( data.geometry ) }; + auto const &indices { GfxRenderer->Indices( data.geometry ) }; + auto const point = [ &data, &vertices ]( std::size_t const Index ) { return data.origin + glm::dvec3 { vertices[ Index ].position }; }; + if( indices.empty() ) { + for( std::size_t i = 0; i + 2 < vertices.size(); i += 3 ) { + add_triangle( point( i ), point( i + 1 ), point( i + 2 ), Min, Max, Out ); + } + return; + } + for( std::size_t i = 0; i + 2 < indices.size(); i += 3 ) { + if( std::max( { indices[ i ], indices[ i + 1 ], indices[ i + 2 ] } ) >= vertices.size() ) { + continue; + } + add_triangle( point( indices[ i ] ), point( indices[ i + 1 ] ), point( indices[ i + 2 ] ), Min, Max, Out ); + } +} + +// the ground of the scenery within the rectangle (x, z): its terrain and the other opaque geometry of its sections, +// and the heightmap terrain where it is loaded. the models aren't ground +ground_triangles scenery_ground( glm::dvec2 const &Min, glm::dvec2 const &Max ) { + ground_triangles triangles; + if( simulation::Region == nullptr ) { + return triangles; + } + auto const centre { 0.5 * ( Min + Max ) }; + std::vector sections; + simulation::Region->sections( glm::dvec3 { centre.x, 0.0, centre.y }, static_cast( 0.5 * glm::length( Max - Min ) ), sections ); + for( auto const *section : sections ) { + for( auto const &shape : section->m_shapes ) { + add_shape( shape, Min, Max, triangles ); + } + for( auto const &cell : section->m_cells ) { + if( outside( cell.m_area.center, cell.m_area.radius, Min, Max ) ) { + continue; + } + for( auto const &shape : cell.m_shapesopaque ) { + add_shape( shape, Min, Max, triangles ); + } + } + } + if( EditorTerrain.active() ) { + EditorTerrain.gather_triangles( Min, Max, triangles ); + } + return triangles; +} + +glm::dvec3 level_left_of( glm::dvec3 const &Front ) { + return glm::dvec3 { Front.z, 0.0, -Front.x }; +} + +// the end of the vehicle where it meets the one coupled to it: the middle of its buffer beam, the way it faces. off the +// track, over its base on the ground as it stands: rolled over, its ends go with it as far as the coupling holds them, +// and the buffers of the side it rolled to miss those of an upright one +derail_motion::end_point end_point_of( TDynamicObject const &Vehicle, int const End ) { + auto const facing { End == end::front ? 1.0 : -1.0 }; + auto const &motion { Vehicle.MoverParameters->OffTrack }; + glm::dvec3 const front { Vehicle.VectorFront().x, 0.0, Vehicle.VectorFront().z }; + auto const length { glm::length( front ) }; + auto const axis { length > 1e-6 ? front / length : glm::dvec3 { 0.0, 0.0, 1.0 } }; + auto const middle { motion.active() ? motion.base() : Vehicle.GetPosition() }; + return derail_motion::end_point { + middle + glm::dvec3 { 0.0, derail_motion::buffer_height, 0.0 } + axis * ( facing * 0.5 * Vehicle.MoverParameters->Dim.L ), + axis * facing, + motion.active() ? motion.tipping() : 0.0 }; +} + +// the push of the buffers on the end of the vehicle [N], negative the pull of its coupling +double compression_of( TMoverParameters const &Vehicle, int const End ) { + return ( End == end::front ? -1.0 : 1.0 ) * Vehicle.Couplers[ End ].CForce; +} + +// the time spent off the track in a frame which makes it worth a warning [s] +constexpr double off_track_slow { 0.02 }; + +using off_track_clock = std::chrono::steady_clock; + +double seconds_since( off_track_clock::time_point const Start ) { + return std::chrono::duration( off_track_clock::now() - Start ).count(); +} + +std::string_view side_name( int const Side ) { + if( Side > 0 ) { + return "left"; + } + return Side < 0 ? "right" : "none"; +} + +} // namespace + +double TDynamicObject::off_track_gap( int const End ) const { + + auto const *neighbour { MoverParameters->Neighbours[ End ].vehicle }; + if( neighbour == nullptr ) { + return 0.0; + } + return derail_motion::meet( end_point_of( *this, End ), end_point_of( *neighbour, MoverParameters->Neighbours[ End ].vehicle_end ) ).gap; +} + +double TDynamicObject::off_track_offset() const { + + if( false == MoverParameters->OffTrack.active() ) { + return 0.0; + } + auto const middle { 0.5 * ( Axle0.pPosition + Axle1.pPosition ) }; + auto const offset { vPosition - middle }; + return glm::dot( glm::dvec3 { offset.x, 0.0, offset.z }, level_left_of( track_front() ) ); +} + +glm::dvec3 TDynamicObject::track_front() const { + + auto const along { Axle0.pPosition - Axle1.pPosition }; + glm::dvec3 const flat { along.x, 0.0, along.z }; + auto const length { glm::length( flat ) }; + return length > 1e-6 ? flat / length : glm::dvec3 { 0.0, 0.0, 1.0 }; +} + +derail_motion::formation TDynamicObject::track_bed() const { + + derail_motion::formation bed; + bed.point = 0.5 * ( Axle0.pPosition + Axle1.pPosition ); + bed.direction = track_front(); + if( auto const *track { RaTrackGet() }; track != nullptr ) { + // the ballast out of the rails, as wide as the track draws it + bed.half_width = std::clamp( 0.5 * std::abs( track->fTrackWidth ) + std::abs( track->fTexWidth ), 1.2, 3.5 ); + } + return bed; +} + +int TDynamicObject::outward_side() const { + + // the track as designed turns from the rear axle to the front one: the outside of its curve, or its inside where a + // buckle bends the line the other way more than the curve does (the criteria of derailment, McZapkie/derailment.h) + if( auto const design { std::sin( Axle1.vAngles.z - Axle0.vAngles.z ) }; std::abs( design ) >= 1e-4 ) { + auto const outside { design > 0.0 ? -1 : 1 }; + return MoverParameters->DerailAcceleration < 0.0 ? -outside : outside; + } + // a straight track: the path under the vehicle as it is, a buckle on it, turns from the rear axle to the front one + auto const front { Axle0.PathDirection() }; + auto const rear { Axle1.PathDirection() }; + auto const turn { glm::dot( front, level_left_of( rear ) ) }; + // a turn under a tenth of a milliradian is a straight track + if( std::abs( turn ) < 1e-4 ) { + return 0; + } + // turning left, the outside of the curve is on the right + return turn > 0.0 ? -1 : 1; +} + +void TDynamicObject::gather_off_track_terrain() { + + auto const &mover { *MoverParameters }; + auto const &position { mover.OffTrack.active() ? mover.OffTrack.current().position : vPosition }; + // as far as it may slide, and some + auto const slide { derail_motion::stopping_distance( mover.V, derailment::off_rails_friction ).value_or( 0.0 ) }; + auto const reach { std::min( slide + mover.Dim.L + 50.0, 600.0 ) }; + m_offtrackgathered = m_offtracktotal; + m_offtrackcropped = false; + // the terrain of another vehicle, where it covers the way this one goes: around it and around where it stops going + // straight on, by its length and the margin the terrain is gathered again at + glm::dvec3 heading { vFront.x, 0.0, vFront.z }; + if( mover.OffTrack.active() ) { + heading = mover.OffTrack.heading(); + } + auto const length { glm::length( heading ) }; + auto const stop { length > 1e-6 ? position + heading * ( std::copysign( std::max( reach - mover.Dim.L - 50.0, 0.0 ), mover.V ) / length ) : position }; + auto const margin { mover.Dim.L + 30.0 }; + if( auto shared { simulation::Vehicles.off_track_terrain( + glm::dvec2 { std::min( position.x, stop.x ) - margin, std::min( position.z, stop.z ) - margin }, + glm::dvec2 { std::max( position.x, stop.x ) + margin, std::max( position.z, stop.z ) + margin } ) }; + shared != nullptr ) { + m_offtrackterrain = std::move( shared ); + m_offtrackmin = m_offtrackterrain->minimum(); + m_offtrackmax = m_offtrackterrain->maximum(); + m_offtracksite.terrain( m_offtrackterrain.get() ); + return; + } + m_offtrackmin = glm::dvec2 { position.x - reach, position.z - reach }; + m_offtrackmax = glm::dvec2 { position.x + reach, position.z + reach }; + auto const started { off_track_clock::now() }; + auto triangles { scenery_ground( m_offtrackmin, m_offtrackmax ) }; + auto const trimmed { triangles.size() > off_track_triangles }; + if( trimmed ) { + // a scenery dense enough to make it slow: the triangles nearest to it are enough + std::nth_element( triangles.begin(), triangles.begin() + off_track_triangles, triangles.end(), + [ &position ]( auto const &Left, auto const &Right ) { + auto const distance = [ &position ]( auto const &Triangle ) { + auto const middle { ( Triangle[ 0 ] + Triangle[ 1 ] + Triangle[ 2 ] ) / 3.0 }; + return std::max( std::abs( middle.x - position.x ), std::abs( middle.z - position.z ) ); }; + return distance( Left ) < distance( Right ); } ); + triangles.resize( off_track_triangles ); + ErrorLog( std::format( "derailment: warning: {} found more than {} triangles of terrain around it, took the nearest", MoverParameters->Name, off_track_triangles ) ); + } + if( triangles.empty() ) { + // a scenery without terrain: level with the top of the ballast + m_offtrackterrain.reset(); + } + else { + m_offtrackterrain = std::make_shared( triangles, m_offtrackmin, m_offtrackmax ); + // the vehicles sliding over it take it as it is; the nearest triangles of a dense scenery are its own + if( false == trimmed ) { + simulation::Vehicles.share_off_track_terrain( m_offtrackterrain ); + } + } + m_offtracksite.terrain( m_offtrackterrain.get() ); + auto const took { seconds_since( started ) }; + if( took > off_track_slow ) { + ErrorLog( std::format( "derailment: warning: gathering the terrain of {:.0f} m around {} took {:.0f} ms ({} triangles)", reach, MoverParameters->Name, took * 1000.0, triangles.size() ) ); + } +} + +void TDynamicObject::crop_off_track_terrain() { + + if( m_offtrackcropped || m_offtrackterrain == nullptr ) { + return; + } + m_offtrackcropped = true; + // the ground under it, and as far around as it gathers the terrain anew once it moves again + auto const &position { MoverParameters->OffTrack.current().position }; + auto const reach { 0.5 * MoverParameters->Dim.L + 40.0 }; + m_offtrackmin = glm::dvec2 { position.x - reach, position.z - reach }; + m_offtrackmax = glm::dvec2 { position.x + reach, position.z + reach }; + m_offtrackterrain = std::make_shared( m_offtrackterrain->cropped( m_offtrackmin, m_offtrackmax ) ); + m_offtracksite.terrain( m_offtrackterrain.get() ); +} + +void TDynamicObject::begin_off_track() { + + auto &mover { *MoverParameters }; + derail_motion::vehicle_shape shape; + shape.length = mover.Dim.L; + shape.width = mover.Dim.W > 0.5 ? mover.Dim.W : 3.0; + // a height up to 2 m in the definition is the height of the floor, the older meaning of the key + shape.height = mover.Dim.H > 2.0 ? mover.Dim.H : 4.0; + shape.centre_of_gravity = mover.centre_of_gravity(); + shape.contact_spacing = derailment::contact_spacing( mover.TrackW ); + shape.base = std::max( static_cast( fAxleDist ), 1.0 ); + shape.mass = mover.TotalMass; + + derail_motion::start start; + start.position = vPosition; + start.front = vFront; + start.line = track_front(); + start.speed = mover.V; + start.reason = mover.DerailCause; + start.outward = ( mover.DerailSide != 0 ? mover.DerailSide : outward_side() ); + start.acceleration = mover.DerailAcceleration; + + // the terrain as far as it may slide, and some + m_offtracktotal = 0.0; + gather_off_track_terrain(); + m_offtracksite = derail_motion::site { m_offtrackterrain.get(), track_bed() }; + // each vehicle its own way of going off, from the seed of the run (the same seed, the same way) + auto const scatter { derail_motion::draw_scatter( derail_motion::seed_of( Global.random_seed, mover.Name ) ) }; + mover.OffTrack.begin( start, shape, m_offtracksite, scatter ); + m_pulledoff = {}; + m_offtracklogdue = 0.0; + m_offtrackslowdue = 0.0; + m_offtrackaxles = 0.0; + m_offtrackfrom = mover.OffTrack.current().position; + + auto const heading { mover.OffTrack.heading() }; + auto const front { glm::dvec3 { vFront.x, 0.0, vFront.z } }; + auto const turn { std::asin( std::clamp( glm::dot( heading, level_left_of( glm::normalize( front ) ) ), -1.0, 1.0 ) ) }; + std::string terrain { "no terrain, level ground" }; + if( m_offtrackterrain != nullptr ) { + terrain = std::format( "{} triangles of terrain", m_offtrackterrain->size() ); + } + WriteLog( std::format( + "derailment: {} leaves the track at {:.0f} km/h on track {}, heading turned {:.1f} deg to the {}, the outside of the curve to the {}; {} around it", + mover.Name, std::abs( mover.V ) * 3.6, MyTrack != nullptr ? MyTrack->name() : std::string { "(none)" }, + std::abs( glm::degrees( turn ) ), side_name( turn >= 0.0 ? 1 : -1 ), side_name( start.outward ), terrain ) ); + WriteLog( std::format( + "derailment: {} scattered by {:+.2f} deg of departure, {:+.2f} deg of yaw at {:+.3f} rad/s, the friction under its ends x{:.2f} / x{:.2f}{}", + mover.Name, glm::degrees( scatter.departure ), glm::degrees( scatter.yaw ), scatter.yaw_rate, scatter.friction_front, scatter.friction_rear, + scatter.dig_in >= 0.0 ? std::format( ", its leading end digs in after {:.2f} s, x{:.2f} for {:.2f} s", scatter.dig_in, scatter.dig_in_friction, scatter.dig_in_time ) : std::string {} ) ); +} + +void TDynamicObject::move_off_track( double const Distance ) { + + auto const started { off_track_clock::now() }; + auto &motion { MoverParameters->OffTrack }; + auto const time { std::exchange( m_offtracktime, 0.0 ) }; + m_offtracktotal += time; + // near the edge of the terrain gathered, the terrain further on; not more than once a second, whatever happens + if( m_offtrackterrain != nullptr && Distance != 0.0 && m_offtracktotal - m_offtrackgathered >= 1.0 ) { + auto const &position { motion.current().position }; + constexpr double margin { 30.0 }; + if( position.x - margin < m_offtrackmin.x || position.x + margin > m_offtrackmax.x + || position.z - margin < m_offtrackmin.y || position.z + margin > m_offtrackmax.y ) { + gather_off_track_terrain(); + } + } + m_offtracksite.bed( track_bed() ); + // the buffers and the couplings of its ends push and pull it, at an angle to it where the vehicle coupled there is + std::array ends {}; + for( int end = end::front; end <= end::rear; ++end ) { + auto const *neighbour { MoverParameters->Neighbours[ end ].vehicle }; + auto const compression { compression_of( *MoverParameters, end ) }; + if( neighbour == nullptr || compression == 0.0 ) { + continue; + } + ends[ end ] = derail_motion::force_on( + derail_motion::meet( end_point_of( *this, end ), end_point_of( *neighbour, MoverParameters->Neighbours[ end ].vehicle_end ) ), compression ); + } + auto const reversals { motion.reversals() }; + motion.step( time, Distance, MoverParameters->V, m_offtracksite, ends ); + if( ( motion.reversals() - reversals ) % 2 != 0 ) { + // the body turned about against the way it goes: the vehicle goes rear first, its speed the other way along it + MoverParameters->V = -MoverParameters->V; + } + auto const &pose { motion.current() }; + // the axles go along the track as far as the vehicle went along it, for the track nearest to it: the vehicles on it + // find it there, the events of the track are passed. by 10 cm at least: a body turning or rocking in place moves + // the axles back and forth by millimetres, which over the end of a track would fire its events every frame. from + // where it was the last time, so the moves out of the other bodies between the frames go into the axles too + m_offtrackaxles += glm::dot( pose.position - std::exchange( m_offtrackfrom, pose.position ), track_front() ); + if( std::abs( m_offtrackaxles ) >= 0.1 ) { + move_axles( std::exchange( m_offtrackaxles, 0.0 ) ); + } + + place_off_track(); + if( motion.at_rest() ) { + crop_off_track_terrain(); + } + + pull_neighbours( Distance ); + + // what it cost: a frame of the vehicle off the track should take well under a millisecond + auto const took { seconds_since( started ) }; + m_offtrackslowdue -= time; + if( took > off_track_slow && m_offtrackslowdue <= 0.0 ) { + m_offtrackslowdue = 1.0; + ErrorLog( std::format( "derailment: warning: moving {} off the track took {:.0f} ms in a frame of {:.3f} s", MoverParameters->Name, took * 1000.0, time ) ); + } +} + +void TDynamicObject::place_off_track() { + + auto const &pose { MoverParameters->OffTrack.current() }; + vPosition = pose.position; + vFront = pose.front; + vLeft = pose.left; + vUp = pose.up; + modelRot.z = std::atan2( -vFront.x, vFront.z ); + mMatrix = glm::inverse( BasisChange( vLeft, vUp, vFront ) ); + auto const half { 0.5 * MoverParameters->Dim.L * vFront }; + vCoulpler[ end::front ] = vPosition + half; + vCoulpler[ end::rear ] = vPosition - half; + m_offtrackplaced = true; +} + +void TDynamicObject::pull_neighbours( double const Distance ) { + + for( int end = end::front; end <= end::rear; ++end ) { + auto const &coupler { MoverParameters->Couplers[ end ] }; + auto *neighbour { MoverParameters->Neighbours[ end ].vehicle }; + if( coupler.CouplingFlag == coupling::faux || neighbour == nullptr || neighbour->MoverParameters->OffTrack.active() + || TestFlag( neighbour->MoverParameters->DamageFlag, dtrain_out ) ) { + m_pulledoff[ end ].reset(); + continue; + } + auto &other { *neighbour->MoverParameters }; + auto const otherend { MoverParameters->Neighbours[ end ].vehicle_end }; + glm::dvec3 const otherfront { neighbour->vFront.x, 0.0, neighbour->vFront.z }; + if( glm::length( otherfront ) < 1e-6 ) { + continue; + } + // the coupling pulls the end of the other vehicle towards the beam of this one, the buffers push it along the + // bisector of the bend between them: at an angle to its axis, the part across it on its leading wheels + auto const compression { compression_of( other, otherend ) }; + auto const force { derail_motion::force_on( derail_motion::meet( end_point_of( *neighbour, otherend ), end_point_of( *this, end ) ), compression ).force }; + auto const axis { glm::normalize( otherfront ) }; + auto const across { glm::dot( force, level_left_of( axis ) ) }; + auto const angle { std::atan2( std::abs( across ), std::abs( glm::dot( force, axis ) ) ) }; + auto const magnitude { glm::length( glm::dvec3 { force.x, 0.0, force.z } ) }; + auto const mass { other.TotalMass - other.Mred }; + auto const ratio { derail_motion::pull_ratio( magnitude, angle, mass, other.NAxles ) }; + if( false == m_pulledoff[ end ].update( ratio >= derailment::climbing_limit, Distance ) ) { + continue; + } + // the way the force across it goes: towards this one pulled, away from it pushed + auto const side { across >= 0.0 ? 1 : -1 }; + other.pull_off( + side, + mass > 0.0 ? std::abs( across ) / mass : 0.0, + std::format( "Y/Q {:.2f} from the {} of {} at {:.0f} deg, {:.0f} kN", ratio, compression > 0.0 ? "buffers" : "coupling", MoverParameters->Name, glm::degrees( angle ), magnitude / 1000.0 ) ); + m_pulledoff[ end ].reset(); + } +} + +void TDynamicObject::update_off_track( double const Deltatime ) { + + auto const &motion { MoverParameters->OffTrack }; + if( false == motion.active() || m_offtracklogdue < 0.0 ) { + // on the track, or came to rest and told so + return; + } + m_offtracklogdue -= Deltatime; + auto const resting { motion.at_rest() }; + if( m_offtracklogdue > 0.0 && false == resting ) { + return; + } + m_offtracklogdue = ( resting ? -1.0 : 1.0 ); + WriteLog( std::format( + "derailment: {} {} {:.1f} m from where it left the rails, {:.1f} m from the axis of the track, at {:.1f} km/h, sliding sideways at {:.1f} m/s, tipped {:.0f} deg, roll {:.0f} deg, yaw {:+.1f} deg turning at {:+.1f} deg/s{}", + MoverParameters->Name, resting ? "came to rest" : "off the track", motion.travelled(), off_track_offset(), std::abs( MoverParameters->V ) * 3.6, motion.sideways(), + glm::degrees( motion.tipping() ), glm::degrees( motion.roll() ), glm::degrees( motion.yaw() ), glm::degrees( motion.yaw_rate() ), motion.lying() ? ", lying on its side" : "" ) ); +} void TDynamicObject::AttachNext(TDynamicObject *Object, int iType) { // Ra: doczepia Object na końcu składu (nazwa funkcji może być myląca) @@ -3204,9 +3759,52 @@ bool TDynamicObject::Update(double dt, double dt1) { if (dt1 == 0.0) return true; // Ra: pauza + // physics.derailment new: all of the update of a vehicle off the track, timed; a warning once a second at most when it + // takes long, to find what makes a derailment slow + // (no vehicle when it is on the track: nothing is timed then) + class off_track_watch { + public: + off_track_watch( TDynamicObject *Vehicle, double const Frame ) : + vehicle { Vehicle }, frame { Frame } { + if( vehicle != nullptr ) { + started = off_track_clock::now(); + } + } + off_track_watch( off_track_watch const & ) = delete; + off_track_watch &operator=( off_track_watch const & ) = delete; + ~off_track_watch() { + if( vehicle == nullptr ) { + return; + } + auto const took { seconds_since( started ) }; + vehicle->m_offtrackupdatedue -= frame; + if( took > off_track_slow && vehicle->m_offtrackupdatedue <= 0.0 ) { + vehicle->m_offtrackupdatedue = 1.0; + ErrorLog( std::format( "derailment: warning: the update of {} off the track took {:.0f} ms in a frame of {:.3f} s", vehicle->MoverParameters->Name, took * 1000.0, frame ) ); + } + } + private: + TDynamicObject *vehicle; + double frame; + off_track_clock::time_point started {}; + }; + off_track_watch const watch { MoverParameters->OffTrack.active() ? this : nullptr, dt1 }; + if( m_offtrackterrain != nullptr && false == MoverParameters->OffTrack.active() ) { + // physics.derailment new: back on the rails (rerail()), the terrain it slid over is let go + m_offtrackterrain.reset(); + m_offtracksite.terrain( nullptr ); + } if (!MoverParameters->PhysicActivation && - !MechInside) // to drugie, bo będąc w maszynowym blokuje się fizyka + !MechInside) { // to drugie, bo będąc w maszynowym blokuje się fizyka + // physics.derailment new: a vehicle off the track stopped along its heading still settles: it slides down a + // slope, falls over, or comes to rest after the step its physics stopped in + if( MoverParameters->OffTrack.active() && false == MoverParameters->OffTrack.at_rest() && bEnabled ) { + m_offtracktime = dt1; + Move( 0.0 ); + update_off_track( dt1 ); + } return true; // McZapkie: wylaczanie fizyki gdy nie potrzeba + } if (!MyTrack) return false; // pojazdy postawione na torach portalowych mają MyTrack==NULL if (!bEnabled) @@ -3242,6 +3840,11 @@ bool TDynamicObject::Update(double dt, double dt1) // między skrajnymi osiami // (!!!odwrotny) ts.dHrail = (Axle1.GetRoll() + Axle0.GetRoll()) * 0.5; //średnia przechyłka pudła + // the uneven track under the outer axles, for the criteria of derailment: its lateral curvature, and its cross level + ts.uneven_curvature = glm::dot( 0.5 * ( Axle0.UnevenBend() + Axle1.UnevenBend() ), vLeft ); + ts.uneven_cross = MyTrack->uneven_underway().cross; + // a buckle of the track under the body: the mean of the curvatures at the outer axles, each over the wheelbase of its bogie + ts.buckle_curvature = 0.5 * ( Axle0.BuckleCurvature( MoverParameters->ADist ) + Axle1.BuckleCurvature( MoverParameters->ADist ) ); // TTrackParam tp; tp.Width = MyTrack->fTrackWidth; // McZapkie-250202 @@ -3249,6 +3852,7 @@ bool TDynamicObject::Update(double dt, double dt1) tp.CategoryFlag = MyTrack->iCategoryFlag & 15; tp.DamageFlag = MyTrack->iDamageFlag; tp.QualityFlag = MyTrack->iQualityFlag; + tp.Name = &MyTrack->name(); // couplers if( MoverParameters->Couplers[0].CouplingFlag != coupling::faux @@ -3287,7 +3891,8 @@ bool TDynamicObject::Update(double dt, double dt1) if( MoverParameters->Pantographs[end::front].is_active || MoverParameters->Pantographs[end::rear].is_active ) { if( MoverParameters->Mains // Ra 15-01: logować tylko, jeśli WS załączony - && MoverParameters->GetTrainsetHighVoltage() < 0.1f ) { // yB 16-03: i nie jest to asynchron zasilany z daleka + && MoverParameters->GetTrainsetHighVoltage() < 0.1f // yB 16-03: i nie jest to asynchron zasilany z daleka + && false == MoverParameters->GensetSelected() ) { // nor a dual-mode vehicle running on its genset // Ra 15-01: bezwzględne współrzędne pantografu nie są dostępne więc lepiej się tego nie zaloguje ErrorLog( "Bad traction: " + MoverParameters->Name @@ -3441,7 +4046,9 @@ bool TDynamicObject::Update(double dt, double dt1) { Fzad = std::min(LBR * FmaxED, FfulED); } - if (MoverParameters->ShuntMode && eimic <= 0 || doorisopen /*|| + // the holding brake lets go once power has been demanded for its delay (SBDReleaseDelay, none by default) + auto const holdingbrakereleased { MoverParameters->UpdateStopBrakeRelease( eimic, dt1 ) }; + if (MoverParameters->ShuntMode && false == holdingbrakereleased || doorisopen /*|| (MoverParameters->V * MoverParameters->DirAbsolute < -0.2)*/) { auto const sbd { ( MoverParameters->SpringBrake.IsActive && MoverParameters->ReleaseParkingBySpringBrake ? 0.0 : MoverParameters->StopBrakeDecc ) }; @@ -3716,8 +4323,14 @@ bool TDynamicObject::Update(double dt, double dt1) // TBD: place the meter on mover logic level? simulation::Train->add_distance( dDOMoveLen ); } + // physics.derailment new: derailed, the vehicle leaves the track and goes on the ground + if( MoverParameters->leaves_track() ) { + begin_off_track(); + } + m_offtracktime = dt1; glm::dvec3 old_pos = vPosition; Move(dDOMoveLen); + update_off_track( dt1 ); m_future_movement = (vPosition - old_pos) / dt1 * Timer::GetDeltaRenderTime(); @@ -3847,12 +4460,9 @@ bool TDynamicObject::Update(double dt, double dt1) double k; // tymczasowy kąt double PantDiff; TAnimPant *p; // wskaźnik do obiektu danych pantografu - double fCurrent = ( - MoverParameters->DynamicBrakeFlag && MoverParameters->ResistorsFlag ? - 0 : - std::abs( MoverParameters->Itot ) * MoverParameters->IsVehicleEIMBrakingFactor() ) - + MoverParameters->TotalCurrent; // prąd pobierany przez pojazd - bez sensu z tym (TotalCurrent) + // prąd pobierany przez pojazd z sieci: trakcyjny (on the genset of a dual-mode vehicle none) i TotalCurrent // TotalCurrent to bedzie prad nietrakcyjny (niezwiazany z napedem) + double fCurrent = MoverParameters->CatenaryCurrent(); // fCurrent+=fabs(MoverParameters->Voltage)*1e-6; //prąd płynący przez woltomierz, rozładowuje kondensator orgromowy 4µF /* double fPantCurrent = fCurrent; // normalnie cały prąd przez jeden pantograf @@ -5258,6 +5868,18 @@ void TDynamicObject::RenderSounds() { MoverParameters->SoundFlag = 0; // McZapkie! - koniec obslugi dzwiekow z mover.pas + // physics.derailment new: off the track the vehicle scrapes along the ground until it stops, or until it is put back + // on the rails (rerail()) while still sliding + if( MoverParameters->OffTrack.active() && false == MoverParameters->OffTrack.at_rest() ) { + if( false == rsDerailment.is_playing() ) { + rsDerailment.play( sound_flags::exclusive | sound_flags::looping ); + } + m_offtrackscraping = true; + } + else if( std::exchange( m_offtrackscraping, false ) && rsDerailment.is_playing() ) { + rsDerailment.stop(); + } + // special events if( MoverParameters->EventFlag ) { // McZapkie: w razie wykolejenia @@ -5900,24 +6522,8 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co if (pAnimations[i + j].smAnimated) { //++iAnimatedDoors; pAnimations[i + j].smAnimated->WillBeAnimated(); // wyłączenie optymalizacji transformu - switch( MoverParameters->Doors.type ) - { // od razu zapinamy potrzebny typ animacji - case 1: - pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdateDoorTranslate, this, std::placeholders::_1 ); - break; - case 2: - pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdateDoorRotate, this, std::placeholders::_1 ); - break; - case 3: - pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdateDoorFold, this, std::placeholders::_1 ); - break; // obrót 3 kolejnych submodeli - case 4: - pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdateDoorPlug, this, std::placeholders::_1 ); - break; - default: - break; - } pAnimations[i + j].iNumber = i + 1; // parzyste działają inaczej niż nieparzyste + bind_door_animation( pAnimations[ i + j ] ); // od razu zapinamy potrzebny typ animacji pAnimations[i + j].fMaxDist = 300 * 300; // drzwi to z daleka widać /* // NOTE: no longer used @@ -5928,6 +6534,34 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co } } + else if( token == "animdoor:" ) { + // own kind of animation of one door wing, in place of the one of the .fiz (eu07/maszyna#70): + // animdoor: { type: range: rangeout: } + // the keys left out keep the values of the .fiz. the wing still follows the door of its side + door_wings::wing_spec spec { + 0, + MoverParameters->Doors.type, + MoverParameters->Doors.range, + MoverParameters->Doors.range_out }; + auto error { door_wings::read_spec( parser, spec ) }; + if( error.empty() + && ( spec.number < 1 || spec.number > iAnimType[ ANIM_DOORS ] ) ) { + error = "no door wing " + std::to_string( spec.number ) + " among the door animations"; + } + if( false == error.empty() ) { + ErrorLog( "Bad model: " + asFileName + " - animdoor: " + error, logtype::model ); + } + else { + door_wings::store( m_doorwings, spec ); + // a wing animdoorprefix has found already gets the new kind of animation now; the ones it + // finds later get it then + auto const index { static_cast( std::accumulate( std::begin( iAnimType ), std::begin( iAnimType ) + ANIM_DOORS, 0 ) + spec.number - 1 ) }; + if( index < pAnimations.size() && pAnimations[ index ].yUpdate ) { + bind_door_animation( pAnimations[ index ] ); + } + } + } + else if( token == "animstepprefix:" ) { // animated doorstep submodel name prefix int i, j; @@ -7760,6 +8394,11 @@ TDynamicObject::update_neighbours() { // neighbour.vehicle = coupler.Connected; // neighbour.vehicle_end = coupler.ConnectedNr; neighbour.distance = TMoverParameters::CouplerDist( MoverParameters, coupler.Connected ); + if( MoverParameters->OffTrack.active() || neighbour.vehicle->MoverParameters->OffTrack.active() ) { + // physics.derailment new: off the track the bodies turn against each other, the ends meet where they are + // (the distance between the middles less the half lengths would press the buffers of a bent pair) + neighbour.distance = off_track_gap( end ); + } // take into account potential adapters attached to the couplers auto const &othercoupler { neighbour.vehicle->MoverParameters->Couplers[ neighbour.vehicle_end ] }; neighbour.distance -= coupler.adapter_length; @@ -7771,7 +8410,9 @@ TDynamicObject::update_neighbours() { neighbour = neighbour_data(); // 10m ~= 140 km/h at 4 fps + safety margin, potential distance between outer axles of involved vehicles auto const scanrange { std::max( 10.0, std::abs( MoverParameters->V ) ) + 40.0 }; - auto const lookup { find_vehicle( end, scanrange ) }; + // physics.derailment new: a vehicle off the track beside the other one doesn't run into it, the scan goes on + // past it to the vehicles beyond + auto const lookup { find_vehicle( end, scanrange, true ) }; if( false == std::get( lookup ) ) { continue; } @@ -7783,6 +8424,10 @@ TDynamicObject::update_neighbours() { && neighbour.distance < (neighbour.vehicle->MoverParameters->CategoryFlag == 2 ? 50 : 100) ) { // at short distances (re)calculate range between couplers directly neighbour.distance = TMoverParameters::CouplerDist( MoverParameters, neighbour.vehicle->MoverParameters ); + if( MoverParameters->OffTrack.active() || neighbour.vehicle->MoverParameters->OffTrack.active() ) { + // physics.derailment new: the ends where they are, as for a coupled pair + neighbour.distance = off_track_gap( end ); + } // take into account potential adapters attached to the couplers auto const &othercoupler { neighbour.vehicle->MoverParameters->Couplers[ neighbour.vehicle_end ] }; neighbour.distance -= coupler.adapter_length; @@ -7792,10 +8437,20 @@ TDynamicObject::update_neighbours() { } } +bool +TDynamicObject::in_line_with( TDynamicObject const &Other ) const { + + // the middle of the other one off the axis of this one, and this one off the axis of the other one, by less than + // the half widths of both: their ends can meet + auto const reach { 0.5 * ( MoverParameters->Dim.W + Other.MoverParameters->Dim.W ) }; + auto const apart { Other.vPosition - vPosition }; + return std::abs( glm::dot( apart, vLeft ) ) < reach && std::abs( glm::dot( apart, Other.vLeft ) ) < reach; +} + // locates potential collision source within specified range, scanning track in specified direction. returns: true if neighbour was located, false otherwise // NOTE: reuses legacy code. TBD, TODO: review, refactor? std::tuple -TDynamicObject::find_vehicle( int const Direction, double const Distance ) const { +TDynamicObject::find_vehicle( int const Direction, double const Distance, bool const InLine ) const { auto direction { ( Direction == end::front ? 1 : -1 ) }; auto const initialdirection { direction }; // zapamiętanie kierunku poszukiwań na torze początkowym, względem sprzęgów @@ -7810,7 +8465,7 @@ TDynamicObject::find_vehicle( int const Direction, double const Distance ) const auto const mycoupler { ( initialdirection < 0 ? end::rear : end::front ) }; // numer sprzęgu do podłączenia w obiekcie szukajacym auto foundcoupler { -1 }; // numer sprzęgu w znalezionym obiekcie (znaleziony wypełni) auto distance { 0.0 }; // przeskanowana odleglość; odległość do zawalidrogi - auto *foundobject { ABuFindObject( foundcoupler, distance, track, direction, mycoupler ) }; // zaczynamy szukać na tym samym torze + auto *foundobject { ABuFindObject( foundcoupler, distance, track, direction, mycoupler, InLine ) }; // zaczynamy szukać na tym samym torze if( foundobject == nullptr ) { // jeśli nie ma na tym samym, szukamy po okolicy szukanie najblizszego toru z jakims obiektem @@ -7847,7 +8502,7 @@ TDynamicObject::find_vehicle( int const Direction, double const Distance ) const } if (track) { // jesli jest kolejny odcinek toru - foundobject = ABuFindObject(foundcoupler, distance, track, direction, mycoupler); // przejrzenie pojazdów tego toru + foundobject = ABuFindObject(foundcoupler, distance, track, direction, mycoupler, InLine); // przejrzenie pojazdów tego toru if (foundobject) { break; } @@ -8114,6 +8769,10 @@ std::shared_ptr TDynamicObject::draw_script_texture( std::string auto const script { Name.substr( 5, query == std::string::npos ? std::string::npos : query - 5 ) }; auto const language { script_language_of( script ) }; if( false == language.has_value() ) { return nullptr; } // a python texture, made by the texture itself + if( false == script_screens::screen_script_path( "", script ).has_value() ) { + ErrorLog( "Bad script texture: \"" + script + "\" leads outside the game's folder" ); + return nullptr; + } auto &queue { Application.screens() }; auto &texture { GfxRenderer->Texture( GfxRenderer->Material( Material )->GetTexture( 0 ) ) }; @@ -9171,6 +9830,7 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { } lap( index++, Timer::subsystem.vehicles_forces_kind, mark ); } + update_brake_pipes( Deltatime ); } } { @@ -9185,6 +9845,8 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { } Timer::subsystem.vehicles_forces.stop(); + update_off_track_contacts( totaltime ); + Timer::subsystem.vehicles_update.start(); { std::size_t index { 0 }; @@ -9197,6 +9859,7 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { } } Timer::subsystem.vehicles_update.stop(); + update_brake_pipes( Deltatime ); // jeśli jest coś do usunięcia z listy, to trzeba na końcu erase_disabled(); @@ -9208,6 +9871,230 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { } } +namespace { + +// the body of the vehicle as it stands, for the contacts: off the track by its motion, on the track upright on it +derail_motion::footprint footprint_of( TDynamicObject const &Vehicle ) { + + auto const &mover { *Vehicle.MoverParameters }; + derail_motion::pose pose; + if( mover.OffTrack.active() ) { + pose = mover.OffTrack.current(); + } + else { + pose.position = Vehicle.GetPosition(); + pose.front = Vehicle.VectorFront(); + pose.left = Vehicle.VectorLeft(); + pose.up = Vehicle.VectorUp(); + } + auto const &shape { mover.OffTrack.shape() }; + return derail_motion::footprint_of( + pose, mover.Dim.L, + mover.OffTrack.active() ? shape.width : ( mover.Dim.W > 0.5 ? mover.Dim.W : 3.0 ), + mover.OffTrack.active() ? shape.height : ( mover.Dim.H > 2.0 ? mover.Dim.H : 4.0 ) ); +} + +// the vehicle as a body in a contact +derail_motion::contact_body contact_body_of( TDynamicObject const &Vehicle ) { + + auto const &mover { *Vehicle.MoverParameters }; + derail_motion::contact_body body; + body.mass = mover.TotalMass; + if( mover.OffTrack.active() ) { + body.base = mover.OffTrack.base(); + body.velocity = mover.OffTrack.velocity(); + body.yaw_rate = mover.OffTrack.yaw_rate(); + body.gyration = mover.OffTrack.gyration(); + } + else { + // on the rails it goes along them only + glm::dvec3 const front { Vehicle.VectorFront().x, 0.0, Vehicle.VectorFront().z }; + auto const length { glm::length( front ) }; + body.guided = true; + body.guide = length > 1e-6 ? front / length : glm::dvec3 { 0.0, 0.0, 1.0 }; + body.base = Vehicle.GetPosition(); + body.velocity = body.guide * mover.V; + } + return body; +} + +// how the two came to overlap, for the log +std::string_view overlap_kind( TDynamicObject const &First, TDynamicObject const &Second ) { + + auto const offtrack { First.MoverParameters->OffTrack.active() && Second.MoverParameters->OffTrack.active() }; + for( int end = end::front; end <= end::rear; ++end ) { + if( First.MoverParameters->Couplers[ end ].Connected == Second.MoverParameters + && First.MoverParameters->Couplers[ end ].CouplingFlag != coupling::faux ) { + return offtrack ? "coupled, both off the track" : "coupled, one on the rails"; + } + if( First.MoverParameters->Neighbours[ end ].vehicle == &Second ) { + return offtrack ? "neighbours, both off the track" : "neighbours, one on the rails"; + } + } + return offtrack ? "not neighbours, both off the track" : "not neighbours, one on the rails"; +} + +} // namespace + +void +vehicle_table::update_off_track_contacts( double const Deltatime ) { + + if( Global.derailment != global_settings::derailment_model::physical || Deltatime <= 0.0 ) { + return; + } + // by their places in the table: the order the pairs are taken in is the same in every run + std::vector offtrack; + for( std::size_t index = 0; index < m_items.size(); ++index ) { + if( m_items[ index ]->bEnabled && m_items[ index ]->MoverParameters->OffTrack.active() ) { + offtrack.push_back( index ); + } + } + if( offtrack.empty() ) { + return; + } + auto const started { off_track_clock::now() }; + auto deepest { 0.0 }; + std::string deepestpair; + auto resting { true }; + for( auto const place : offtrack ) { + auto *vehicle { m_items[ place ] }; + resting = resting && vehicle->MoverParameters->OffTrack.at_rest(); + auto const print { footprint_of( *vehicle ) }; + auto const reach { std::hypot( print.half_length, print.half_width ) }; + for( std::size_t otherplace = 0; otherplace < m_items.size(); ++otherplace ) { + auto *other { m_items[ otherplace ] }; + if( otherplace == place || false == other->bEnabled ) { + continue; + } + // each pair of two off the track once + auto const otheroff { other->MoverParameters->OffTrack.active() }; + if( otheroff && otherplace < place ) { + continue; + } + // the bounding circles first + auto const apart { other->GetPosition() - vehicle->GetPosition() }; + auto const otherreach { 0.5 * other->MoverParameters->Dim.L + std::max( other->MoverParameters->Dim.W, other->MoverParameters->Dim.H ) }; + if( glm::length( glm::dvec3 { apart.x, 0.0, apart.z } ) > reach + otherreach + 1.0 ) { + continue; + } + auto const otherprint { footprint_of( *other ) }; + auto const hit { derail_motion::collide( print, otherprint ) }; + if( false == hit.has_value() ) { + continue; + } + if( hit->depth > deepest ) { + deepest = hit->depth; + deepestpair = std::format( "{} and {}, {}", vehicle->MoverParameters->Name, other->MoverParameters->Name, overlap_kind( *vehicle, *other ) ); + } + auto const body { contact_body_of( *vehicle ) }; + auto const otherbody { contact_body_of( *other ) }; + auto const impulse { derail_motion::contact_impulse( *hit, body, otherbody ) }; + // the one off the track: kicked, and moved out of the other one (half of the way when both are off it) + auto const [ velocity, yawrate ] { derail_motion::impulse_change( body, -impulse, hit->point ) }; + auto &motion { vehicle->MoverParameters->OffTrack }; + auto const share { otheroff ? 0.5 : 1.0 }; + auto const correction { derail_motion::contact_correction * std::max( 0.0, hit->depth - derail_motion::contact_slop ) }; + if( glm::length( impulse ) > 0.0 ) { + motion.kick( velocity, yawrate ); + vehicle->MoverParameters->V = motion.speed(); + } + if( correction > 0.0 ) { + motion.nudge( -hit->normal * ( share * correction ) ); + vehicle->place_off_track(); + } + if( otheroff ) { + auto const [ othervelocity, otheryawrate ] { derail_motion::impulse_change( otherbody, impulse, hit->point ) }; + auto &othermotion { other->MoverParameters->OffTrack }; + if( glm::length( impulse ) > 0.0 ) { + othermotion.kick( othervelocity, otheryawrate ); + other->MoverParameters->V = othermotion.speed(); + } + if( correction > 0.0 ) { + othermotion.nudge( hit->normal * ( share * correction ) ); + other->place_off_track(); + } + continue; + } + // one on the rails: along them into its speed, across them on its wheels, as a coupling pulls them off + auto &othermover { *other->MoverParameters }; + othermover.V += glm::dot( impulse, otherbody.guide ) / std::max( othermover.TotalMass, 1.0 ); + if( TestFlag( othermover.DamageFlag, dtrain_out ) ) { + continue; + } + glm::dvec3 const otherleft { otherbody.guide.z, 0.0, -otherbody.guide.x }; + auto const across { glm::dot( impulse, otherleft ) / Deltatime }; + auto const mass { othermover.TotalMass - othermover.Mred }; + auto const ratio { derail_motion::pull_ratio( std::abs( across ), 0.5 * std::numbers::pi, mass, othermover.NAxles ) }; + // held over the window of the climbing as the bodies slide along each other, or a hit three times as hard + // at once: the wheels jump the rail + auto const sliding { glm::length( derail_motion::velocity_at( body, hit->point ) - otherbody.velocity ) * Deltatime }; + if( other->m_struck.update( ratio >= derailment::climbing_limit, sliding ) || ratio >= 3.0 * derailment::climbing_limit ) { + othermover.pull_off( + across >= 0.0 ? 1 : -1, + mass > 0.0 ? std::abs( across ) / mass : 0.0, + std::format( "Y/Q {:.2f} from {} running into it, {:.0f} kN across", ratio, vehicle->MoverParameters->Name, std::abs( across ) / 1000.0 ) ); + other->m_struck.reset(); + } + } + } + // the log: every second the most the bodies overlapped by, once more when all of them are at rest + if( deepest > m_overlapmost ) { + m_overlapmost = deepest; + m_overlappair = deepestpair; + } + m_overlapdue -= Deltatime; + if( ( m_overlapdue <= 0.0 && false == resting ) || ( resting && false == m_overlaplogged ) ) { + WriteLog( std::format( + "derailment: the bodies overlap by up to {:.2f} m{} over the last second, {:.2f} m now{}", + m_overlapmost, m_overlapmost > 0.0 ? " (" + m_overlappair + ")" : std::string {}, deepest, resting ? ", all at rest" : "" ) ); + m_overlapmost = 0.0; + m_overlappair.clear(); + m_overlapdue = 1.0; + m_overlaplogged = resting; + } + if( false == resting ) { + m_overlaplogged = false; + } + auto const took { seconds_since( started ) }; + if( took > off_track_slow ) { + ErrorLog( std::format( "derailment: warning: the contacts of {} vehicles off the track took {:.0f} ms", offtrack.size(), took * 1000.0 ) ); + } +} + +std::shared_ptr +vehicle_table::off_track_terrain( glm::dvec2 const &Min, glm::dvec2 const &Max ) { + + std::erase_if( m_offtrackterrains, []( auto const &Terrain ) { return Terrain.expired(); } ); + for( auto const &terrain : m_offtrackterrains ) { + if( auto shared { terrain.lock() }; shared != nullptr && shared->covers( Min, Max ) ) { + return shared; + } + } + return {}; +} + +void +vehicle_table::share_off_track_terrain( std::shared_ptr const &Terrain ) { + + if( Terrain != nullptr ) { + m_offtrackterrains.emplace_back( Terrain ); + } +} + +// the air exchange through the brake and main reservoir hoses of the vehicles which stepped their physics, after all of them did +void +vehicle_table::update_brake_pipes( double const Deltatime ) { + + m_brakepipes.clear(); + for( auto *vehicle : m_items ) { + if( ( true == vehicle->MoverParameters->PipeCouplersPending ) + || ( true == vehicle->MoverParameters->ScndPipeCouplersPending ) ) { + m_brakepipes.push_back( vehicle->MoverParameters ); + } + } + TMoverParameters::UpdatePipeCouplers( m_brakepipes, Deltatime ); +} + // records the odometer states of the vehicles and saves them for the next sessions (eu07/maszyna#72) void vehicle_table::save_odometers() { @@ -9307,6 +10194,9 @@ vehicle_table::update_steps_parallel( double const Deltatime, int const Iteratio auto const steps = [ & ]( std::uint32_t const Group ) { auto const &members { m_groups[ Group ] }; if( Iterationcount > 1 ) { + // the air exchange through the hoses after each step, as update_brake_pipes() does in update(): the vehicles coupled + // with hoses are in the same group + std::vector brakepipes; // ABu: ponizsze wykonujemy tylko jesli wiecej niz jedna iteracja for( int iteration = 0; iteration < Iterationcount - 1; ++iteration ) { for( auto const index : members ) { @@ -9315,6 +10205,14 @@ vehicle_table::update_steps_parallel( double const Deltatime, int const Iteratio for( auto const index : members ) { if( false == coarse( index ) ) { m_items[ index ]->FastUpdate( Deltatime ); } } + brakepipes.clear(); + for( auto const index : members ) { + auto *mover { m_items[ index ]->MoverParameters }; + if( mover->PipeCouplersPending || mover->ScndPipeCouplersPending ) { + brakepipes.push_back( mover ); + } + } + TMoverParameters::UpdatePipeCouplers( brakepipes, Deltatime ); } } for( auto const index : members ) { diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index 41601d3dc..e5ea881e0 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -22,8 +22,10 @@ http://mozilla.org/MPL/2.0/. #include "audio/sound.h" #include "world/Spring.h" #include "vehicle/mirrors.h" +#include "vehicle/doorwings.h" #include "scripting/scriptscreenrules.h" +#include #include #include @@ -198,6 +200,7 @@ struct material_data { class TDynamicObject { // klasa pojazdu friend opengl46_renderer; + friend class vehicle_table; public: static bool bDynamicRemove; // moved from ground @@ -304,6 +307,12 @@ private: void UpdateDoorRotate(TAnim *pAnim); // animacja drzwi - obrót void UpdateDoorFold(TAnim *pAnim); // animacja drzwi - składanie void UpdateDoorPlug(TAnim *pAnim); // animacja drzwi - odskokowo-przesuwne + // a wing with its own kind of animation, given in the .mmd (animdoor:), in place of the one of the .fiz + void UpdateDoorWing( TAnim *pAnim, door_wings::wing_spec const &Spec ); + // sets the update of a door wing animation, for its own kind if the .mmd gives one, otherwise for the .fiz + void bind_door_animation( TAnim &Animation ); + // door wings animated in their own way, from the .mmd (eu07/maszyna#70) + std::vector m_doorwings; void UpdatePant(TAnim *pAnim); // animacja pantografu void UpdatePlatformTranslate(TAnim *pAnim); // doorstep animation, shift void UpdatePlatformRotate(TAnim *pAnim); // doorstep animation, rotate @@ -646,7 +655,7 @@ private: std::string asModel; private: - TDynamicObject *ABuFindObject( int &Foundcoupler, double &Distance, TTrack const *Track, int const Direction, int const Mycoupler ) const; + TDynamicObject *ABuFindObject( int &Foundcoupler, double &Distance, TTrack const *Track, int const Direction, int const Mycoupler, bool const InLine = false ) const; void ABuCheckMyTrack(); std::string rTypeName; // nazwa typu pojazdu @@ -743,6 +752,61 @@ private: bool FastUpdate(double dt); void Move(double fDistance); void FastMove(double fDistance); + // physics.derailment new, the vehicle off the track (vehicle/derailmotion.h): the offset of its body from the axis of + // the track at the place nearest to it, to the left of its front positive [m]; 0 while it's on the track + double off_track_offset() const; + // the gap between the ends of the vehicle and the one at its End, as they meet off the track [m]: negative the + // buffers pressed in + double off_track_gap( int End ) const; +private: + // the axles moved along their tracks by the distance + void move_axles( double Distance ); + // the vehicle placed on the track by its axles + void place_by_axles(); + // the vehicle leaves the track: its motion on the ground begun, with the terrain around it + void begin_off_track(); + // the vehicle off the track moved on the ground, by the distance along its heading, in the time of the frame + void move_off_track( double Distance ); + // the terrain of the scenery around the vehicle off the track, as far as it may slide, for the ground under it: the + // one gathered for another vehicle where it covers that, gathered anew where it doesn't + void gather_off_track_terrain(); + // at rest it keeps only the terrain under it, the rest of what was gathered (shared with others, perhaps) let go + void crop_off_track_terrain(); + // the bed of the track at the axles, the level direction of the track there, and the side the derailment throws the + // vehicle to (1 the left of the front, -1 the right, 0 none): out of the curve of the track as designed, into it + // where a buckle bends the line the other way more (McZapkie/derailment.h); on a straight track out of the turn of + // the path as it lies, a buckle on it + derail_motion::formation track_bed() const; + glm::dvec3 track_front() const; + int outward_side() const; + // the couplings of this vehicle off the track pull the vehicles coupled to it off the rails sideways, the step + // having travelled the distance + void pull_neighbours( double Distance ); + // the scraping of the vehicle off the track, until it stops, and its state to the log every second + void update_off_track( double Deltatime ); + + std::shared_ptr m_offtrackterrain; // none in a scenery without terrain + glm::dvec2 m_offtrackmin { 0.0 }; // what the terrain was gathered for + glm::dvec2 m_offtrackmax { 0.0 }; + bool m_offtrackcropped { false }; // the terrain cut down to the one under it at rest + derail_motion::site m_offtracksite; + double m_offtracktime { 0.0 }; // of the frame, for the motion + double m_offtracklogdue { 0.0 }; + double m_offtracktotal { 0.0 }; // the time off the track [s] + double m_offtrackgathered { 0.0 }; // the time the terrain was gathered at [s] + double m_offtrackslowdue { 0.0 }; // till another warning of a slow frame [s] + double m_offtrackupdatedue { 0.0 }; // and of a slow update + double m_offtrackaxles { 0.0 }; // the move along the track the axles didn't make yet [m] + glm::dvec3 m_offtrackfrom { 0.0 }; // where the body was when its move went into the axles last + bool m_offtrackscraping { false }; // the scraping of the vehicle off the track plays, looped + // the most triangles of terrain taken around the vehicle off the track + static constexpr std::size_t off_track_triangles { 400000 }; + bool m_offtrackplaced { false }; // placed off the track: placed on it again once it's back on the rails + std::array m_pulledoff; // the distance the coupling of an end pulled the vehicle coupled there over the climbing limit + derailment::stretch m_struck; // on the rails: the distance a body off the track pushed it sideways over the climbing limit + // the model, the axes and the coupling points placed by the motion off the track + void place_off_track(); +public: void RenderSounds(); // plays the sounds of the mirrors on the Side, of the occupied cab, starting the Event void play_mirror_sounds( side const Side, mirror_moves::event const Event ); @@ -846,8 +910,12 @@ private: TDynamicObject * Neighbour(int &dir); // updates potential collision sources void update_neighbours(); - // locates potential collision source within specified range, scanning its route in specified direction - auto find_vehicle( int const Direction, double const Range ) const -> std::tuple; + // physics.derailment new: the vehicle and the other one, one of them off the track, are in line, close enough + // across to run into each other + bool in_line_with( TDynamicObject const &Other ) const; + // locates potential collision source within specified range, scanning its route in specified direction. InLine: + // physics.derailment new, the scan goes on past a vehicle off the track beside the line (or beside this one off it) + auto find_vehicle( int const Direction, double const Range, bool const InLine = false ) const -> std::tuple; // locates potential vehicle connected with specific coupling type and satisfying supplied predicate template auto find_vehicle( coupling const Coupling, Predicate_ const Predicate ) -> TDynamicObject *; @@ -948,6 +1016,13 @@ public: // records the odometer states of the vehicles and saves them for the next sessions void save_odometers(); + // physics.derailment new: the terrain gathered for a vehicle off the track which covers the rectangle from Min to Max + // (x, z), shared by the vehicles which slide over it; none where no vehicle has one. it lives as long as one of them + // keeps it + std::shared_ptr + off_track_terrain( glm::dvec2 const &Min, glm::dvec2 const &Max ); + void + share_off_track_terrain( std::shared_ptr const &Terrain ); private: // maintenance; removes from tracks consists with vehicles marked as disabled @@ -965,8 +1040,24 @@ private: // the trains it closes in on void update_coupler_physics() const; + // the air exchange through the brake and main reservoir hoses of the vehicles which stepped their physics, after all of them did + void + update_brake_pipes( double const Deltatime ); + // physics.derailment new: the bodies of the vehicles off the track and those near them run into each other instead + // of into one another: the impulses of the hits, the bodies moved apart, a vehicle on the rails pushed off them; + // what the bodies overlap by goes to the log every second + void + update_off_track_contacts( double const Deltatime ); double m_odometersavetimer { 0.0 }; // simulation time since the odometers were last saved + // the most the bodies overlapped by, of the vehicles of update_off_track_contacts(), since it was logged last [m], and + // which ones; till the next line in the log [s]; once all of them came to rest it is logged no more + double m_overlapmost { 0.0 }; + std::string m_overlappair; + double m_overlapdue { 1.0 }; + bool m_overlaplogged { false }; + std::vector m_brakepipes; // the vehicles of update_brake_pipes(), kept for the memory + std::vector> m_offtrackterrains; // of off_track_terrain() }; diff --git a/vehicle/Gauge.cpp b/vehicle/Gauge.cpp index 52bf7795d..0944fe83b 100644 --- a/vehicle/Gauge.cpp +++ b/vehicle/Gauge.cpp @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Gauge.h" #include "vehicle/gaugepositions.h" #include "vehicle/gaugeduplicates.h" +#include "vehicle/gaugewrap.h" #include "utilities/parser.h" #include "model/Model3d.h" #include "vehicle/DynObj.h" @@ -121,8 +122,9 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu Parser.getTokens(); if( Parser.peek() != "{" ) { // old fixed size config - // it has no scaletable:, drop the one of an earlier definition of the same control + // it has no scaletable: nor drag:, drop the ones of an earlier definition of the same control m_scaletable.clear(); + m_drag = universal_drag::direction::none; Parser >> submodelname; gaugetypename = Parser.getToken( true ); Parser.getTokens( 3, false ); @@ -168,6 +170,7 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu } gauge_scale::sort( scratchpad.scaletable ); m_scaletable = std::move( scratchpad.scaletable ); + m_drag = scratchpad.drag; // post-deserialization cleanup // set provided custom soundproofing to assigned sounds (for sounds without their own custom soundproofing) if( scratchpad.soundproofing ) { @@ -209,15 +212,15 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu m_sourcemodel = nullptr; std::array sources { Owner->mdKabina, Owner->mdLowPolyInt }; for( auto const *source : sources ) { - if( source != nullptr - && ( submodel = source->GetFromName( submodelname ) ) != nullptr ) { - // got what we wanted, bail out - m_sourcemodel = source; - break; + if( source == nullptr ) { + continue; } - // there's a possibility the default submodel was named with _off suffix - if( source != nullptr - && ( submodel = source->GetFromName( submodelname + "_off" ) ) != nullptr ) { + submodel = source->GetFromName( submodelname ); + if( submodel == nullptr ) { + // there's a possibility the default submodel was named with _off suffix + submodel = source->GetFromName( submodelname + "_off" ); + } + if( submodel != nullptr ) { // got what we wanted, bail out m_sourcemodel = source; break; @@ -229,8 +232,11 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu // see if we can locate optional submodel for active state, with _on suffix TSubModel *submodelon { nullptr }; for( auto const *source : sources ) { - if( source != nullptr - && ( submodelon = source->GetFromName( submodelname + "_on" ) ) != nullptr ) { + if( source == nullptr ) { + continue; + } + submodelon = source->GetFromName( submodelname + "_on" ); + if( submodelon != nullptr ) { // got what we wanted, bail out break; } @@ -308,6 +314,16 @@ TGauge::Load_mapping( cParser &Input, TGauge::scratch_data &Scratchpad ) { >> soundproofing[ 5 ]; Scratchpad.soundproofing = soundproofing; } + else if( key == "drag:" ) { + // the mouse drags the control to any position between its ends, moving in the given direction to open it + // (MaSzyna-EU07/maszyna#62) + auto const value { Input.getToken( true, "\n\r\t ,;" ) }; + auto const drag { universal_drag::parse( value ) }; + if( false == drag.has_value() ) { + ErrorLog( "Bad model: unknown drag direction \"" + value + "\" of a cab control, it takes up, down, left, right, yes or no", logtype::model ); + } + Scratchpad.drag = drag.value_or( universal_drag::direction::none ); + } else if( key == "scaletable:" ) { // non-uniform scale in format [ value1 scaled1, value2 scaled2, ... ] return Load_scaletable( Input, Scratchpad ); @@ -386,6 +402,26 @@ TGauge::UpdateValue( float fNewDesired ) { return false; // no suitable sound was found } +void +TGauge::UpdateValueWrapped( float const fNewDesired, bool const Forward, int const Positions, std::optional &Fallbacksound ) { + + if( auto const turn { ( + m_animation == TGaugeAnimation::gt_Rotate && false == m_interpolatescale && m_scaletable.empty() ? + gauge_wrap::full_turn( m_scale, Positions ) : + std::nullopt ) }; + turn.has_value() ) { + // the knob stands the same one turn earlier (later), from there it turns on to the new position + // rather than all the way back, sounding the position it reaches + m_value = gauge_wrap::turned_round( m_value, *turn, Forward ); + m_targetvalue = gauge_wrap::turned_round( m_targetvalue, *turn, Forward ); + UpdateValue( fNewDesired, Fallbacksound ); + return; + } + // a switch that doesn't turn all the way round jumps to the new position, which still sounds + UpdateValue( fNewDesired, Fallbacksound ); + m_value = m_targetvalue; +} + void TGauge::PutValue(float fNewDesired) { // McZapkie-281102: natychmiastowe wpisanie wartosci m_targetvalue = fNewDesired; diff --git a/vehicle/Gauge.h b/vehicle/Gauge.h index c16509f79..9c93057c1 100644 --- a/vehicle/Gauge.h +++ b/vehicle/Gauge.h @@ -12,6 +12,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Classes.h" #include "audio/sound.h" #include "vehicle/gaugescale.h" +#include "vehicle/universaldrag.h" enum class TGaugeAnimation { // typ ruchu @@ -46,6 +47,10 @@ public: void Load(cParser &Parser, TDynamicObject const *Owner, double const mul = 1.0); bool UpdateValue( float fNewDesired ); bool UpdateValue( float fNewDesired, std::optional &Fallbacksound ); + // sets a multi-position switch of Positions positions, turned on past its last position to the first one (Forward) + // or back past the first one to the last, to the position at fNewDesired. A knob which turns all the way round + // turns on the same way, others jump there; either way the position reached sounds + void UpdateValueWrapped( float fNewDesired, bool Forward, int Positions, std::optional &Fallbacksound ); void PutValue(float fNewDesired); float GetValue() const; float GetDesiredValue() const; @@ -86,6 +91,10 @@ public: // true if the gauge was given a non-uniform scale (scaletable:) bool has_scaletable() const { return false == m_scaletable.empty(); } + // the direction the mouse drags the control in to any position between its ends (drag:, MaSzyna-EU07/maszyna#62), + // none for a control set only to its ends. a push control springs back, so it isn't dragged + universal_drag::direction drag() const { + return universal_drag::effective( m_drag, is_push() ); } // members TSubModel *SubModel { nullptr }; // McZapkie-310302: zeby mozna bylo sprawdzac czy zainicjowany poprawnie TSubModel *SubModelOn { nullptr }; // optional submodel visible when the state input is set @@ -96,6 +105,7 @@ private: std::optional< std::array > soundproofing; bool duplicate { false }; // the definition is a duplicate submodel of the control defined before std::vector scaletable; // as read, in the units of the config + universal_drag::direction drag { universal_drag::direction::none }; }; // methods // imports member data pair from the config file @@ -127,6 +137,7 @@ private: float m_endvalue { -1.f }; // end value of accepted value range bool m_interpolatescale { false }; std::vector m_scaletable; // optional non-uniform scale, sorted by value; replaces scale and offset + universal_drag::direction m_drag { universal_drag::direction::none }; // the mouse drags the control smoothly, drag: char m_datatype { '\0' }; // typ zmiennej parametru: f-float, d-double, i-int, b-bool; none until one is assigned union { diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index ee1b07038..3c4e5f6fe 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/horn.h" #include "vehicle/linebreaker.h" #include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" #include "vehicle/odometer.h" #include "vehicle/mainctrlact.h" @@ -361,6 +362,12 @@ TTrain::commandhandler_map const TTrain::m_commandhandlers = { {user_command::oilfuelpumptoggle, &TTrain::OnCommand_oilfuelpumptoggle}, {user_command::oilpumpenable, &TTrain::OnCommand_oilpumpenable}, {user_command::oilpumpdisable, &TTrain::OnCommand_oilpumpdisable}, + {user_command::tractionmodetoggle, &TTrain::OnCommand_tractionmodetoggle}, + {user_command::tractionmodecatenary, &TTrain::OnCommand_tractionmodecatenary}, + {user_command::tractionmodegenset, &TTrain::OnCommand_tractionmodegenset}, + {user_command::gensettoggle, &TTrain::OnCommand_gensettoggle}, + {user_command::gensetenable, &TTrain::OnCommand_gensetenable}, + {user_command::gensetdisable, &TTrain::OnCommand_gensetdisable}, {user_command::waterheaterbreakertoggle, &TTrain::OnCommand_waterheaterbreakertoggle}, {user_command::waterheaterbreakerclose, &TTrain::OnCommand_waterheaterbreakerclose}, {user_command::waterheaterbreakeropen, &TTrain::OnCommand_waterheaterbreakeropen}, @@ -544,6 +551,36 @@ TTrain::commandhandler_map const TTrain::m_commandhandlers = { {user_command::generictoggle27, &TTrain::OnCommand_generictoggle}, {user_command::generictoggle28, &TTrain::OnCommand_generictoggle}, {user_command::generictoggle29, &TTrain::OnCommand_generictoggle}, + {user_command::genericset0, &TTrain::OnCommand_genericset}, + {user_command::genericset1, &TTrain::OnCommand_genericset}, + {user_command::genericset2, &TTrain::OnCommand_genericset}, + {user_command::genericset3, &TTrain::OnCommand_genericset}, + {user_command::genericset4, &TTrain::OnCommand_genericset}, + {user_command::genericset5, &TTrain::OnCommand_genericset}, + {user_command::genericset6, &TTrain::OnCommand_genericset}, + {user_command::genericset7, &TTrain::OnCommand_genericset}, + {user_command::genericset8, &TTrain::OnCommand_genericset}, + {user_command::genericset9, &TTrain::OnCommand_genericset}, + {user_command::genericset10, &TTrain::OnCommand_genericset}, + {user_command::genericset11, &TTrain::OnCommand_genericset}, + {user_command::genericset12, &TTrain::OnCommand_genericset}, + {user_command::genericset13, &TTrain::OnCommand_genericset}, + {user_command::genericset14, &TTrain::OnCommand_genericset}, + {user_command::genericset15, &TTrain::OnCommand_genericset}, + {user_command::genericset16, &TTrain::OnCommand_genericset}, + {user_command::genericset17, &TTrain::OnCommand_genericset}, + {user_command::genericset18, &TTrain::OnCommand_genericset}, + {user_command::genericset19, &TTrain::OnCommand_genericset}, + {user_command::genericset20, &TTrain::OnCommand_genericset}, + {user_command::genericset21, &TTrain::OnCommand_genericset}, + {user_command::genericset22, &TTrain::OnCommand_genericset}, + {user_command::genericset23, &TTrain::OnCommand_genericset}, + {user_command::genericset24, &TTrain::OnCommand_genericset}, + {user_command::genericset25, &TTrain::OnCommand_genericset}, + {user_command::genericset26, &TTrain::OnCommand_genericset}, + {user_command::genericset27, &TTrain::OnCommand_genericset}, + {user_command::genericset28, &TTrain::OnCommand_genericset}, + {user_command::genericset29, &TTrain::OnCommand_genericset}, {user_command::vehiclemoveforwards, &TTrain::OnCommand_vehiclemoveforwards}, {user_command::vehiclemovebackwards, &TTrain::OnCommand_vehiclemovebackwards}, {user_command::vehicleboost, &TTrain::OnCommand_vehicleboost}, @@ -1454,8 +1491,8 @@ void TTrain::OnCommand_secondcontrollerincrease(TTrain *Train, command_data cons auto const neutralposition{Train->ggScndCtrl.is_toggle() ? 0.5f : 0.f}; Train->ggScndCtrl.UpdateValue(Command.action == GLFW_RELEASE ? neutralposition : activeposition, Train->dsbSwitch); } - // potentially animate tempomat button - if (Train->ggScndCtrlButton.is_push() && Train->mvControlled->ScndCtrlPos <= 1) + // potentially animate tempomat button, unless the cruise control has its own + if (Train->ggScndCtrlButton.is_push() && Train->mvControlled->ScndCtrlPos <= 1 && false == Train->mvControlled->IsSpeedCtrlSeparate()) { Train->ggScndCtrlButton.UpdateValue(Command.action == GLFW_RELEASE ? 0.f : 1.f, Train->dsbSwitch); } @@ -1495,6 +1532,8 @@ void TTrain::OnCommand_notchingrelaytoggle(TTrain *Train, command_data const &Co // turn off Train->mvOccupied->AutoRelaySwitch(false); } + // visual feedback + Train->ggAutoRelayButton.UpdateValue(Train->mvOccupied->AutoRelayFlag ? 1.f : 0.f, Train->dsbSwitch); } } @@ -1518,17 +1557,17 @@ void TTrain::OnCommand_tempomattoggle(TTrain *Train, command_data const &Command return; } // glfw_press - if (Train->mvControlled->ScndCtrlPos == 0) + if (false == Train->mvControlled->IsSpeedCtrlEngaged()) { // turn on if it's not active - Train->mvControlled->IncScndCtrl(1); + Train->mvControlled->SpeedCtrlSwitch(true); // visual feedback Train->ggScndCtrlButton.UpdateValue(1.0, Train->dsbSwitch); } else { // otherwise turn off - Train->mvControlled->DecScndCtrl(2); + Train->mvControlled->SpeedCtrlSwitch(false); // visual feedback if (Train->m_controlmapper.contains("tempomatoff_sw:")) { @@ -1548,17 +1587,17 @@ void TTrain::OnCommand_tempomattoggle(TTrain *Train, command_data const &Command return; } - if (Train->mvControlled->ScndCtrlPos == 0) + if (false == Train->mvControlled->IsSpeedCtrlEngaged()) { // turn on - Train->mvControlled->IncScndCtrl(1); + Train->mvControlled->SpeedCtrlSwitch(true); // visual feedback Train->ggScndCtrlButton.UpdateValue(1.0, Train->dsbSwitch); } else { // turn off - Train->mvControlled->DecScndCtrl(2); + Train->mvControlled->SpeedCtrlSwitch(false); // visual feedback Train->ggScndCtrlButton.UpdateValue(0.0, Train->dsbSwitch); } @@ -1660,8 +1699,8 @@ void TTrain::OnCommand_secondcontrollerdecrease(TTrain *Train, command_data cons auto const neutralposition{Train->ggScndCtrl.is_toggle() ? 0.5f : 0.f}; Train->ggScndCtrl.UpdateValue(Command.action == GLFW_RELEASE ? neutralposition : activeposition, Train->dsbSwitch); } - // potentially animate tempomat button - if (Train->ggScndCtrlButton.is_push() && Train->mvControlled->ScndCtrlPos <= 1) + // potentially animate tempomat button, unless the cruise control has its own + if (Train->ggScndCtrlButton.is_push() && Train->mvControlled->ScndCtrlPos <= 1 && false == Train->mvControlled->IsSpeedCtrlSeparate()) { if (Train->m_controlmapper.contains("tempomatoff_sw:")) { @@ -3724,7 +3763,7 @@ void TTrain::OnCommand_linebreakertoggle(TTrain *Train, command_data const &Comm { // only impulse switches react to release events // NOTE: we presume dedicated state switch is of impulse type - if (Train->m_linebreakerstate == 0) + if (Train->m_linebreakerstate == linebreaker::state::open) { // ...after opening circuit, or holding for too short time to close it OnCommand_linebreakeropen(Train, Command); @@ -3777,14 +3816,14 @@ void TTrain::OnCommand_linebreakeropen(TTrain *Train, command_data const &Comman // play sound immediately when the switch is hit, not after release Train->fMainRelayTimer = 0.0f; - if (Train->m_linebreakerstate == 0) + if (Train->m_linebreakerstate == linebreaker::state::open) { return; } // already in the desired state if (true == Train->mvControlled->MainSwitch(false, Train->mvControlled->MainSwitchRange())) { - Train->m_linebreakerstate = 0; + Train->m_linebreakerstate = linebreaker::state::open; if (Train->mvControlled->MainSwitchRange() != range_t::local) { // the engines of the vehicles in multiple stopped along: their two-state switches go off too, left on @@ -3859,7 +3898,7 @@ void TTrain::OnCommand_linebreakerclose(TTrain *Train, command_data const &Comma Train->ggMainButton.UpdateValue(0.5, Train->dsbSwitch); } - if (Train->m_linebreakerstate == 1) + if (Train->m_linebreakerstate == linebreaker::state::closed) { return; } // already in the desired state @@ -3867,10 +3906,10 @@ void TTrain::OnCommand_linebreakerclose(TTrain *Train, command_data const &Comma // we don't need to start the diesel twice, but the other types (with impulse switch setup) still need to be launched // NOTE: this behaviour should depend on MainOnButton presence and type_delayed // TODO: change it when/if vehicle definition files get their proper switch types - if (Train->m_linebreakerstate == 2 && Train->mvControlled->EngineType == TEngineType::ElectricSeriesMotor) + if (Train->m_linebreakerstate == linebreaker::state::closing && Train->mvControlled->EngineType == TEngineType::ElectricSeriesMotor) { // try to finalize state change of the line breaker, set the state based on the outcome - Train->m_linebreakerstate = Train->mvControlled->MainSwitch(true, Train->mvControlled->MainSwitchRange()) ? 1 : 0; + Train->m_linebreakerstate = Train->mvControlled->MainSwitch(true, Train->mvControlled->MainSwitchRange()) ? linebreaker::state::closed : linebreaker::state::open; } // on button release reset the closing timer Train->fMainRelayTimer = 0.0f; @@ -4250,6 +4289,95 @@ void TTrain::OnCommand_oilfuelpumptoggle(TTrain *Train, command_data const &Comm vehicle->OilPumpSwitchOff(false == enable); } +// the traction selector of a dual-mode vehicle (eu07/maszyna#536), a two-state switch +void TTrain::OnCommand_tractionmodetoggle(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + if (Train->mvControlled->GensetSelected()) + { + OnCommand_tractionmodecatenary(Train, Command); + } + else + { + OnCommand_tractionmodegenset(Train, Command); + } +} + +void TTrain::OnCommand_tractionmodecatenary(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + // refused with the line breaker closed: then the switch doesn't move + Train->mvControlled->TractionModeSwitch(TMoverParameters::traction_mode::catenary, range_t::consist); + if (false == Train->mvControlled->GensetSelected()) + { + Train->ggTractionModeSwitch.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_tractionmodegenset(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + // refused with the line breaker closed, or without a genset: then the switch doesn't move + Train->mvControlled->TractionModeSwitch(TMoverParameters::traction_mode::genset, range_t::consist); + if (Train->mvControlled->GensetSelected()) + { + Train->ggTractionModeSwitch.UpdateValue(1.0, Train->dsbSwitch); + } +} + +// the start request of the genset of a dual-mode vehicle, a two-state switch +void TTrain::OnCommand_gensettoggle(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + if (false == Train->mvControlled->Genset.is_enabled) + { + OnCommand_gensetenable(Train, Command); + } + else + { + OnCommand_gensetdisable(Train, Command); + } +} + +void TTrain::OnCommand_gensetenable(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + // ignored by a genset which starts on its own: then the switch doesn't move + Train->mvControlled->GensetSwitch(true, range_t::consist); + if (Train->mvControlled->Genset.is_enabled) + { + Train->ggGensetButton.UpdateValue(1.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_gensetdisable(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + Train->mvControlled->GensetSwitch(false, range_t::consist); + if (false == Train->mvControlled->Genset.is_enabled) + { + Train->ggGensetButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + void TTrain::OnCommand_waterheaterbreakertoggle(TTrain *Train, command_data const &Command) { @@ -5432,14 +5560,15 @@ void TTrain::OnCommand_lightspresetactivatenext(TTrain *Train, command_data cons // visual feedback if (Train->ggLightsButton.SubModel != nullptr) { - // HACK: skip submodel animation when restarting cycle, since it plays in the 'wrong' direction if (false == restartcycle) { Train->ggLightsButton.UpdateValue(static_cast(Train->mvOccupied->LightsPos - 1), Train->dsbSwitch); } else { - Train->ggLightsButton.PutValue(static_cast(Train->mvOccupied->LightsPos - 1)); + // past the last position to the first one: a knob turning all the way round turns on rather than + // back across all the positions, and the position reached sounds (eu07/maszyna#464) + Train->ggLightsButton.UpdateValueWrapped(static_cast(Train->mvOccupied->LightsPos - 1), true, Train->mvOccupied->LightsPosNo, Train->dsbSwitch); } } } @@ -5470,14 +5599,14 @@ void TTrain::OnCommand_lightspresetactivateprevious(TTrain *Train, command_data // visual feedback if (Train->ggLightsButton.SubModel != nullptr) { - // HACK: skip submodel animation when restarting cycle, since it plays in the 'wrong' direction if (false == restartcycle) { Train->ggLightsButton.UpdateValue(static_cast(Train->mvOccupied->LightsPos - 1), Train->dsbSwitch); } else { - Train->ggLightsButton.PutValue(static_cast(Train->mvOccupied->LightsPos - 1)); + // back past the first position to the last one, the same way (eu07/maszyna#464) + Train->ggLightsButton.UpdateValueWrapped(static_cast(Train->mvOccupied->LightsPos - 1), false, Train->mvOccupied->LightsPosNo, Train->dsbSwitch); } } } @@ -6612,6 +6741,16 @@ void TTrain::OnCommand_compartmentlightstoggle(TTrain *Train, command_data const return; } + if (Command.action == GLFW_RELEASE) + { + // the press changed the state the command is picked from below, so a release picked from it went to the other + // command and the push button that was pressed never withdrew its request. The release goes to both commands: + // each returns its own push type control to the neutral position and withdraws its request + OnCommand_compartmentlightsenable(Train, Command); + OnCommand_compartmentlightsdisable(Train, Command); + return; + } + // keep the switch from flipping back and forth if key is held down if (false == Train->mvOccupied->CompartmentLights.is_active && false == Train->mvOccupied->CompartmentLights.is_enabled) { @@ -6631,13 +6770,11 @@ void TTrain::OnCommand_compartmentlightsenable(TTrain *Train, command_data const if (Command.action == GLFW_PRESS) { Train->mvOccupied->CompartmentLightsSwitch(true); - if (Train->m_controlmapper.contains("compartmentlights_sw:")) + // withdraw the off request, unless a push type control in the cab withdraws it when released + if (compartment_lights_switch::withdraws_other_request(Train->m_controlmapper.contains("compartmentlights_sw:"), Train->ggCompartmentLightsButton.is_toggle(), + Train->m_controlmapper.contains("compartmentlightsoff_sw:"))) { - auto const istoggle{(static_cast(Train->ggCompartmentLightsButton.type()) & static_cast(TGaugeType::toggle)) != 0}; - if (istoggle) - { - Train->mvOccupied->CompartmentLightsSwitchOff(false); - } + Train->mvOccupied->CompartmentLightsSwitchOff(false); } // visual feedback if (Train->m_controlmapper.contains("compartmentlights_sw:")) @@ -6672,13 +6809,11 @@ void TTrain::OnCommand_compartmentlightsdisable(TTrain *Train, command_data cons if (Command.action == GLFW_PRESS) { Train->mvOccupied->CompartmentLightsSwitchOff(true); - if (Train->m_controlmapper.contains("compartmentlights_sw:")) + // withdraw the on request, unless a push type control in the cab withdraws it when released + if (compartment_lights_switch::withdraws_other_request(Train->m_controlmapper.contains("compartmentlights_sw:"), Train->ggCompartmentLightsButton.is_toggle(), + Train->m_controlmapper.contains("compartmentlightson_sw:"))) { - auto const istoggle{(static_cast(Train->ggCompartmentLightsButton.type()) & static_cast(TGaugeType::toggle)) != 0}; - if (istoggle) - { - Train->mvOccupied->CompartmentLightsSwitch(false); - } + Train->mvOccupied->CompartmentLightsSwitch(false); } // visual feedback if (Train->m_controlmapper.contains("compartmentlights_sw:")) @@ -7001,19 +7136,9 @@ void TTrain::OnCommand_generictoggle(TTrain *Train, command_data const &Command) } else { - // two-state switch - if (item.GetDesiredValue() < 0.5) - { - // turn on - // visual feedback - item.UpdateValue(1.0); - } - else - { - // turn off - // visual feedback - item.UpdateValue(0.0); - } + // two-state switch, or one dragged in between its ends with the mouse: to the end farther from it + // visual feedback + item.UpdateValue(universal_drag::toggled(item.GetDesiredValue())); } } else if (Command.action == GLFW_RELEASE && item.type() == TGaugeType::push) @@ -7025,6 +7150,46 @@ void TTrain::OnCommand_generictoggle(TTrain *Train, command_data const &Command) } } +// sets a universal control to the position given in param1, from 0 to 1 (MaSzyna-EU07/maszyna#62): the mouse drags +// the ones with drag: in their definition, and it can be bound to an axis of a gamepad. it stays where it is set +void TTrain::OnCommand_genericset(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_RELEASE) + { + return; + } + auto const itemindex = static_cast(Command.command) - static_cast(user_command::genericset0); + auto &item = Train->ggUniversals[itemindex]; + if (item.is_push()) + { + // an impulse switch springs back, it has no position to be left in + return; + } + // visual feedback + item.UpdateValue(universal_drag::clamp(Command.param1)); +} + +universal_drag::direction TTrain::universal_drag_direction(int const Index) const +{ + + if (Index < 0 || Index >= static_cast(ggUniversals.size()) || ggUniversals[Index].SubModel == nullptr) + { + return universal_drag::direction::none; + } + return ggUniversals[Index].drag(); +} + +float TTrain::universal_position(int const Index) const +{ + + if (Index < 0 || Index >= static_cast(ggUniversals.size())) + { + return 0.f; + } + return ggUniversals[Index].GetDesiredValue(); +} + void TTrain::OnCommand_springbraketoggle(TTrain *Train, command_data const &Command) { @@ -8753,16 +8918,16 @@ bool TTrain::Update(double const Deltatime) { // train state update // line breaker: - if (m_linebreakerstate == 0 && true == mvControlled->Mains) + if (m_linebreakerstate == linebreaker::state::open && true == mvControlled->Mains) { // crude way to sync state of the linebreaker with ai-issued commands - m_linebreakerstate = 1; + m_linebreakerstate = linebreaker::state::closed; } - if (m_linebreakerstate == 1 && false == (mvControlled->Mains || mvControlled->dizel_startup)) + if (m_linebreakerstate == linebreaker::state::closed && false == (mvControlled->Mains || mvControlled->dizel_startup)) { // crude way to catch cases where the main was knocked out // because the state of the line breaker isn't changed to match, we need to do it here manually - m_linebreakerstate = 0; + m_linebreakerstate = linebreaker::state::open; } if (is_hold_coil_lever(ggMainOffButton) && hold_coil_lever::cuts_off(ggMainOffButton.GetDesiredValue())) { @@ -8772,10 +8937,10 @@ bool TTrain::Update(double const Deltatime) // put the lever back on to match, like the line breaker state above ggMainOffButton.UpdateValue(0.0); } - else if (m_linebreakerstate == 2) + else if (m_linebreakerstate == linebreaker::state::closing) { // the hold coil was cut off while the closing button was held, the line breaker won't close on its release - m_linebreakerstate = 0; + m_linebreakerstate = linebreaker::state::open; } } @@ -8799,18 +8964,18 @@ bool TTrain::Update(double const Deltatime) // if the button disconnecting the line breaker is down prevent the timer from accumulating fMainRelayTimer = 0.0f; } - if (m_linebreakerstate == 0 && fMainRelayTimer > mvControlled->InitialCtrlDelay) + if (m_linebreakerstate == linebreaker::state::open && fMainRelayTimer > mvControlled->InitialCtrlDelay) { // wlaczanie WSa z opoznieniem // mark the line breaker as ready to close; for electric series vehicles with impulse switch the setup is completed on button release - m_linebreakerstate = 2; + m_linebreakerstate = linebreaker::state::closing; } // for diesels and/or vehicles with toggle switch setup we complete the engine start here // TODO: make it a test for main_on_bt of type push_delayed instead - if (m_linebreakerstate == 2 && (ggMainOnButton.SubModel == nullptr || mvControlled->EngineType != TEngineType::ElectricSeriesMotor)) + if (m_linebreakerstate == linebreaker::state::closing && (ggMainOnButton.SubModel == nullptr || mvControlled->EngineType != TEngineType::ElectricSeriesMotor)) { // try to finalize state change of the line breaker, set the state based on the outcome - m_linebreakerstate = mvControlled->MainSwitch(true, mvControlled->MainSwitchRange()) ? 1 : 0; + m_linebreakerstate = mvControlled->MainSwitch(true, mvControlled->MainSwitchRange()) ? linebreaker::state::closed : linebreaker::state::open; } // the switches of the other vehicles in multiple update_remote_linebreakers(Deltatime); @@ -9384,10 +9549,10 @@ bool TTrain::Update(double const Deltatime) btLampkaSHP.Turn(mvOccupied->SecuritySystem.is_cabsignal_blinking()); btLampkaCzuwakaSHP.Turn(btLampkaSHP.GetValue() || btLampkaCzuwaka.GetValue()); - btLampkaWylSzybki.Turn(m_linebreakerstate == 2 || mvControlled->Mains); - btLampkaWylSzybkiOff.Turn(m_linebreakerstate != 2 && !mvControlled->Mains); - btLampkaMainBreakerReady.Turn(mvControlled->MainsInitTimeCountdown <= 0.0 && m_linebreakerstate != 2 && !mvControlled->Mains); - btLampkaMainBreakerBlinkingIfReady.Turn(m_linebreakerstate == 2 || mvControlled->Mains || mvControlled->MainsInitTimeCountdown < 0.0 && simulation::Time.data().wMilliseconds > 500); + btLampkaWylSzybki.Turn(m_linebreakerstate == linebreaker::state::closing || mvControlled->Mains); + btLampkaWylSzybkiOff.Turn(m_linebreakerstate != linebreaker::state::closing && !mvControlled->Mains); + btLampkaMainBreakerReady.Turn(mvControlled->MainsInitTimeCountdown <= 0.0 && m_linebreakerstate != linebreaker::state::closing && !mvControlled->Mains); + btLampkaMainBreakerBlinkingIfReady.Turn(m_linebreakerstate == linebreaker::state::closing || mvControlled->Mains || mvControlled->MainsInitTimeCountdown < 0.0 && simulation::Time.data().wMilliseconds > 500); btLampkaPrzetw.Turn(mvOccupied->Power110vIsAvailable); btLampkaPrzetwOff.Turn(!mvOccupied->Power110vIsAvailable); @@ -9784,7 +9949,7 @@ bool TTrain::Update(double const Deltatime) { if (ggScndCtrlButton.is_toggle()) { - ggScndCtrlButton.UpdateValue(mvControlled->ScndCtrlPos > 0 ? 1.f : 0.f, dsbSwitch); + ggScndCtrlButton.UpdateValue(mvControlled->IsSpeedCtrlEngaged() ? 1.f : 0.f, dsbSwitch); } ggScndCtrlButton.Update(lowvoltagepower); } @@ -9881,6 +10046,8 @@ bool TTrain::Update(double const Deltatime) ggWiperSw.Update(); ggMaxCurrentCtrl.UpdateValue(true == mvControlled->ShuntModeAllow ? (true == mvControlled->ShuntMode ? 1.f : 0.f) : mvControlled->MotorOverloadRelayHighThreshold ? 1.f : 0.f); ggMaxCurrentCtrl.Update(); + ggAutoRelayButton.UpdateValue(mvOccupied->AutoRelayFlag ? 1.f : 0.f); + ggAutoRelayButton.Update(); // NBMX wrzesien 2003 - drzwi ggDoorLeftPermitButton.Update(lowvoltagepower); ggDoorRightPermitButton.Update(lowvoltagepower); @@ -9995,7 +10162,17 @@ bool TTrain::Update(double const Deltatime) ggDimHeadlightsButton.Update(); ggDimHeadlightsButton.Update(); //------------ + // the converter switches follow the vehicle when something else flips them (the AI driver, the other cab, + // the pressure switch of an EMU), not only when the cab is entered (set_cab_controls()) + if (ggConverterButton.SubModel != nullptr && mvOccupied->ConvSwitchType != "impulse" && mvOccupied->ConverterStart == start_t::manual) + { + ggConverterButton.UpdateValue(mvOccupied->ConverterAllow ? 1.f : 0.f, dsbSwitch); + } ggConverterButton.Update(); + if (ggConverterLocalButton.SubModel != nullptr) + { + ggConverterLocalButton.UpdateValue(mvOccupied->ConverterAllowLocal ? 1.f : 0.f, dsbSwitch); + } ggConverterLocalButton.Update(); ggConverterOffButton.Update(); ggTrainHeatingButton.Update(); @@ -10064,6 +10241,8 @@ bool TTrain::Update(double const Deltatime) ggFuelPumpButton.Update(); ggOilPumpButton.Update(); ggOilFuelPumpButton.Update(); + ggTractionModeSwitch.Update(); + ggGensetButton.Update(); ggMotorBlowersFrontButton.Update(); ggMotorBlowersRearButton.Update(); ggMotorBlowersAllOffButton.Update(); @@ -10731,9 +10910,14 @@ void TTrain::load_script_screen(cParser &Parser, script_language const Language) { return; } - if (substr_path(entry.config.script).empty()) + if (auto path{script_screens::screen_script_path(DynamicObject->asBaseDir, entry.config.script)}; path.has_value()) { - entry.config.script = DynamicObject->asBaseDir + entry.config.script; + entry.config.script = std::move(*path); + } + else + { + ErrorLog(std::format("Bad script screen: \"{}\" leads outside the game's folder", entry.config.script)); + return; } TSubModel *submodel{nullptr}; @@ -11620,6 +11804,7 @@ void TTrain::clear_cab_controls() ggBrakeOperationModeCtrl.Clear(); ggWiperSw.Clear(); ggMaxCurrentCtrl.Clear(); + ggAutoRelayButton.Clear(); ggMainOffButton.Clear(); ggMainOnButton.Clear(); for (auto &remotelinebreaker : m_remotelinebreakers) @@ -11766,6 +11951,8 @@ void TTrain::clear_cab_controls() ggFuelPumpButton.Clear(); ggOilPumpButton.Clear(); ggOilFuelPumpButton.Clear(); + ggTractionModeSwitch.Clear(); + ggGensetButton.Clear(); ggMotorBlowersFrontButton.Clear(); ggMotorBlowersRearButton.Clear(); ggMotorBlowersAllOffButton.Clear(); @@ -11886,7 +12073,7 @@ void TTrain::set_cab_controls(int const Cab) // line breaker if (ggMainButton.SubModel != nullptr) { // instead of single main button there can be on/off pair - ggMainButton.PutValue(ggMainButton.type() == TGaugeType::push ? 0.5f : m_linebreakerstate > 0 ? 1.f : 0.f); + ggMainButton.PutValue(ggMainButton.type() == TGaugeType::push ? 0.5f : m_linebreakerstate != linebreaker::state::open ? 1.f : 0.f); } // line breakers of the other vehicles in multiple for (std::size_t index = 0; index < m_remotelinebreakers.size(); ++index) @@ -11983,15 +12170,17 @@ void TTrain::set_cab_controls(int const Cab) // converter if (mvOccupied->ConvSwitchType != "impulse") { - ggConverterButton.PutValue(mvControlled->ConverterAllow ? 1.f : 0.f); + ggConverterButton.PutValue(mvOccupied->ConverterAllow ? 1.f : 0.f); } - ggConverterLocalButton.PutValue(mvControlled->ConverterAllowLocal ? 1.f : 0.f); + ggConverterLocalButton.PutValue(mvOccupied->ConverterAllowLocal ? 1.f : 0.f); // compressor ggCompressorButton.PutValue(mvControlled->CompressorAllow ? 1.f : 0.f); ggCompressorLocalButton.PutValue(mvControlled->CompressorAllowLocal ? 1.f : 0.f); ggCompressorListButton.PutValue(static_cast(mvOccupied->CompressorListPos - 1)); // motor overload relay threshold / shunt mode ggMaxCurrentCtrl.PutValue(true == mvControlled->ShuntModeAllow ? (true == mvControlled->ShuntMode ? 1.f : 0.f) : mvControlled->MotorOverloadRelayHighThreshold ? 1.f : 0.f); + // automatic relays (AutoRelay) + ggAutoRelayButton.PutValue(mvOccupied->AutoRelayFlag ? 1.f : 0.f); // lights ggLightsButton.PutValue(static_cast(mvOccupied->LightsPos - 1)); @@ -12125,6 +12314,12 @@ void TTrain::set_cab_controls(int const Cab) { ggOilFuelPumpButton.PutValue(mvControlled->OilFuelPumpsEnabled() ? 1.f : 0.f); } + // traction selector and genset of a dual-mode vehicle + ggTractionModeSwitch.PutValue(mvControlled->GensetSelected() ? 1.f : 0.f); + if (ggGensetButton.type() != TGaugeType::push) + { + ggGensetButton.PutValue(mvControlled->Genset.is_enabled ? 1.f : 0.f); + } // traction motor fans if (ggMotorBlowersFrontButton.type() != TGaugeType::push) { @@ -12147,7 +12342,7 @@ void TTrain::set_cab_controls(int const Cab) // tempomat if (false == ggScndCtrlButton.is_push()) { - ggScndCtrlButton.PutValue(mvControlled->ScndCtrlPos > 0 ? 1.f : 0.f); + ggScndCtrlButton.PutValue(mvControlled->IsSpeedCtrlEngaged() ? 1.f : 0.f); } // sandbox if (ggAutoSandButton.type() != TGaugeType::push) @@ -12326,6 +12521,7 @@ bool TTrain::initialize_button(cParser &Parser, std::string const &Label, int co {"i-mainpipelock:", &mvOccupied->LockPipe}, {"i-battery:", &mvOccupied->Power24vIsAvailable}, {"i-cablight:", &Cabine[iCabn].bLight}, + {"i-compartmentlights:", &mvOccupied->CompartmentLights.is_active}, }; { auto lookup = autolights.find(Label); @@ -12396,6 +12592,7 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con {"brakeprofiler_sw:", ggBrakeProfileR}, {"brakeopmode_sw:", ggBrakeOperationModeCtrl}, {"maxcurrent_sw:", ggMaxCurrentCtrl}, + {"autorelay_sw:", ggAutoRelayButton}, {"main_off_bt:", ggMainOffButton}, {"main_on_bt:", ggMainOnButton}, {"mainb_sw:", m_remotelinebreakers[0].main_switch}, @@ -12462,6 +12659,8 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con {"fuelpump_sw:", ggFuelPumpButton}, {"oilpump_sw:", ggOilPumpButton}, {"oilfuelpump_sw:", ggOilFuelPumpButton}, + {"tractionmode_sw:", ggTractionModeSwitch}, + {"genset_sw:", ggGensetButton}, {"oilpressb:", ggOilPressB}, {"motorblowersfront_sw:", ggMotorBlowersFrontButton}, {"motorblowersrear_sw:", ggMotorBlowersRearButton}, diff --git a/vehicle/Train.h b/vehicle/Train.h index 819e8a454..8e51447ce 100644 --- a/vehicle/Train.h +++ b/vehicle/Train.h @@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Button.h" #include "vehicle/Gauge.h" #include "vehicle/enginestart.h" +#include "vehicle/linebreaker.h" #include "audio/sound.h" #include "scripting/PyInt.h" #include "input/command.h" @@ -172,6 +173,11 @@ class TTrain { inline std::string GetLabel( TSubModel const *Control ) const { return m_controlmapper.find( Control ); } + // the direction the mouse drags universal control Index in to any position between its ends, none if the control + // is only set to its ends (MaSzyna-EU07/maszyna#62) + universal_drag::direction universal_drag_direction( int const Index ) const; + // the position universal control Index is set to, from 0 to 1 + float universal_position( int const Index ) const; void UpdateCab(); bool Update( double const Deltatime ); void UpdateDirectionRelays(); @@ -369,6 +375,12 @@ class TTrain { static void OnCommand_oilfuelpumptoggle( TTrain *Train, command_data const &Command ); static void OnCommand_oilpumpenable( TTrain *Train, command_data const &Command ); static void OnCommand_oilpumpdisable( TTrain *Train, command_data const &Command ); + static void OnCommand_tractionmodetoggle( TTrain *Train, command_data const &Command ); + static void OnCommand_tractionmodecatenary( TTrain *Train, command_data const &Command ); + static void OnCommand_tractionmodegenset( TTrain *Train, command_data const &Command ); + static void OnCommand_gensettoggle( TTrain *Train, command_data const &Command ); + static void OnCommand_gensetenable( TTrain *Train, command_data const &Command ); + static void OnCommand_gensetdisable( TTrain *Train, command_data const &Command ); static void OnCommand_waterheaterbreakertoggle( TTrain *Train, command_data const &Command ); static void OnCommand_waterheaterbreakerclose( TTrain *Train, command_data const &Command ); static void OnCommand_waterheaterbreakeropen( TTrain *Train, command_data const &Command ); @@ -526,6 +538,7 @@ class TTrain { static void OnCommand_cabchangeforward( TTrain *Train, command_data const &Command ); static void OnCommand_cabchangebackward( TTrain *Train, command_data const &Command ); static void OnCommand_generictoggle( TTrain *Train, command_data const &Command ); + static void OnCommand_genericset( TTrain *Train, command_data const &Command ); static void OnCommand_vehiclemoveforwards( TTrain *Train, command_data const &Command ); static void OnCommand_vehiclemovebackwards( TTrain *Train, command_data const &Command ); static void OnCommand_vehicleboost( TTrain *Train, command_data const &Command ); @@ -555,7 +568,7 @@ class TTrain { TMoverParameters *mvThird { nullptr }; // trzeci człon (SN61) TMoverParameters *mvPantographUnit { nullptr }; // nearest pantograph equipped unit // helper variable, to prevent immediate switch between closing and opening line breaker circuit - int m_linebreakerstate { 0 }; // 0: open, 1: closed, 2: freshly closed (and yes this is awful way to go about it) + linebreaker::state m_linebreakerstate { linebreaker::state::open }; static const commandhandler_map m_commandhandlers; control_mapper m_controlmapper; @@ -600,6 +613,7 @@ public: // reszta może by?publiczna TGauge ggWiperSw; // przelacznik wycieraczek TGauge ggMaxCurrentCtrl; + TGauge ggAutoRelayButton; // przełącznik AutoRelay: rozruch automatyczny, załączenie bocznikowania spalinowozu TGauge ggMainOffButton; TGauge ggMainOnButton; @@ -745,6 +759,8 @@ public: // reszta może by?publiczna TGauge ggFuelPumpButton; // fuel pump switch TGauge ggOilPumpButton; // oil pump switch TGauge ggOilFuelPumpButton; // joint oil and fuel pump switch + TGauge ggTractionModeSwitch; // traction selector of a dual-mode vehicle (catenary/genset) + TGauge ggGensetButton; // genset start switch of a dual-mode vehicle TGauge ggMotorBlowersFrontButton; // front traction motor fan switch TGauge ggMotorBlowersRearButton; // rear traction motor fan switch TGauge ggMotorBlowersAllOffButton; // motor fans shutdown switch diff --git a/vehicle/aipower.cpp b/vehicle/aipower.cpp new file mode 100644 index 000000000..8418d5fe1 --- /dev/null +++ b/vehicle/aipower.cpp @@ -0,0 +1,56 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/aipower.h" + +#include + +namespace ai_power { + +stall check(state const &State) { + using enum stall; + if (false == State.collector || true == State.power) { + return not_stalled; + } + if (false == State.standing || false == State.pantographs_up) { + return waiting; + } + return State.wire ? no_voltage : no_wire; +} + +std::optional reporter::update(stall const Stall, double const Now) { + if (Stall == stall::not_stalled) { + m_since.reset(); + m_reported = false; + return std::nullopt; + } + if (Stall == stall::waiting) { + m_since.reset(); + return std::nullopt; + } + if (false == m_since.has_value()) { + m_since = Now; + } + if (true == m_reported || Now - *m_since < report_delay) { + return std::nullopt; + } + m_reported = true; + return Stall; +} + +std::string message(stall const Stall, std::string const &Name, glm::dvec3 const &Position) { + auto const reason{ + Stall == stall::no_wire ? + "no overhead wire above its raised pantographs" : + "no voltage in the overhead wire at its raised pantographs"}; + return std::format("AI [{}]: can't start, {} (at {:.2f}, {:.2f}, {:.2f}); it waits for the voltage", Name, reason, Position.x, Position.y, Position.z); +} + +} // namespace ai_power diff --git a/vehicle/aipower.h b/vehicle/aipower.h new file mode 100644 index 000000000..4d822980a --- /dev/null +++ b/vehicle/aipower.h @@ -0,0 +1,61 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include + +#include + +// an AI driver of an electric vehicle standing with its pantographs up and no voltage at them: past the end of the +// overhead wire, or under a wire which is switched off. no driver can start such a vehicle, it waits in +// TController::PrepareEngine() until the voltage comes, towed back under the wire or the power switched on. the +// driver tells of it in the log, once, instead of waiting without a word (eu07/maszyna#421) +namespace ai_power { + +// what the driver knows of the power of the vehicle when it prepares it +struct state { + bool collector{false}; // the vehicle takes its power from the overhead wire + bool power{false}; // there is the voltage the vehicle needs, at its pantographs or from the rest of the train + bool standing{false}; // the vehicle stands + bool pantographs_up{false}; // a pantograph is raised, with the air to hold it up + bool wire{false}; // a raised pantograph found a wire above it +}; + +enum class stall { + not_stalled, // the voltage is there, or the vehicle doesn't take it from the wire + waiting, // no voltage, but nothing to tell yet: the vehicle moves, or its pantographs aren't up + no_wire, // standing with the pantographs up and no wire above them + no_voltage // standing with a pantograph up at a wire which carries no voltage +}; + +stall check(state const &State); + +// how long [s] the vehicle stands with its pantographs up and no voltage before the driver tells of it. the +// pantographs need a few seconds to rise and the voltage a moment to come, a gap under a section insulator is +// shorter still +inline constexpr double report_delay{30.0}; + +// tells of a stall once: one report while it lasts. the voltage coming back ends it, and the next one is reported +// again; moving, or the pantographs going down, only restarts the count of report_delay +class reporter { +public: + // one look at the vehicle at the time Now [s]: the stall to report now, if any + std::optional update(stall Stall, double Now); + +private: + std::optional m_since; // when the vehicle began to stand with the pantographs up and no voltage + bool m_reported{false}; // the stall has been reported +}; + +// the line of the log telling of the stall of the vehicle Name standing at Position +std::string message(stall Stall, std::string const &Name, glm::dvec3 const &Position); + +} // namespace ai_power diff --git a/vehicle/aiwire.cpp b/vehicle/aiwire.cpp new file mode 100644 index 000000000..999d69075 --- /dev/null +++ b/vehicle/aiwire.cpp @@ -0,0 +1,78 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/aiwire.h" + +#include + +namespace ai_wire { + +contact span_contact(glm::dvec3 const &Point1, glm::dvec3 const &Parametric, glm::dvec3 const &Point, + glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double const Halfwidth) { + // Winger 170204: the parameter of the span's point in the plane of the pantograph's movement (the plane normal to + // Front through Point). the operations and their order are those the vehicles always had, so they find the same wire + auto const paramfrontdot = glm::dot(Parametric, Front); + auto const parameter = -(glm::dot(Point1, Front) - glm::dot(Point, Front)) / (paramfrontdot != 0.0 ? paramfrontdot : 0.001); + + contact result; + if (parameter < -0.001 || parameter > 1.001) { + return result; + } + // the point where the wire crosses the plane, against the pantograph + auto const crossing = Point1 + parameter * Parametric; + auto const offset = crossing - Point; + result.within = true; + result.vertical = glm::dot(offset, Up); + result.horizontal = std::abs(glm::dot(offset, Left)) - Halfwidth; + return result; +} + +bool reaches(contact const &Contact, double const Minheight, double const Maxheight) { + return Contact.within && Contact.horizontal <= 0.0 && Contact.vertical >= Minheight && Contact.vertical <= Maxheight; +} + +double wire_shortfall(std::function const &Covered, double const Pantograph, double const Stop, + double const Margin, double const Step, double const Walkback) { + if (!Covered || Step <= 0.0) { + return 0.0; + } + auto const fine{[&](double const Place) { return Covered(Place) && Covered(Place + Margin); }}; + // the pantograph at the target of the head + auto const target{Stop - Pantograph}; + if (fine(target)) { + return 0.0; + } + // the places back are counted from the target, not added up, so the steps don't drift + auto const steps{static_cast(std::floor(Walkback / Step + 1e-9))}; + for (int step = 1; step <= steps; ++step) { + auto const back{step * Step}; + if (fine(target - back)) { + return back; + } + } + return 0.0; +} + +bool stops_under_wire(bool const Collector, bool const Livetraction, bool const Overheadrestricted, stop_kind const Kind) { + if (!Collector || !Livetraction || Overheadrestricted) { + return false; + } + switch (Kind) { + case stop_kind::track_end: + case stop_kind::timetable_stop: + return true; + case stop_kind::signal: + case stop_kind::coupling: + default: + return false; + } +} + +} // namespace ai_wire diff --git a/vehicle/aiwire.h b/vehicle/aiwire.h new file mode 100644 index 000000000..89ccb1ecc --- /dev/null +++ b/vehicle/aiwire.h @@ -0,0 +1,75 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include + +#include + +// where the overhead contact wire is, for the AI driver to stop its train with the pantograph under the wire, not past +// the end of it. the geometry of a pantograph against a span of the wire is the one the vehicles use to find their wire +// (basic_cell::update_traction), so the AI sees the wire where the pantographs do +namespace ai_wire { + +// a pantograph against one span of the wire +struct contact { + // the plane of the pantograph's movement (across the vehicle, at the pantograph) cuts the span, between its ends + bool within{false}; + // height of the wire above the pantograph's base point, along the up vector. negative for a wire below it + double vertical{0.0}; + // sideways distance of the wire from the working part of the slide: |offset along the left vector| less the slide's + // half width. the wire is on the slide when it's not positive + double horizontal{0.0}; +}; + +// the pantograph with its base point at Point, on a vehicle whose front, up and left vectors are Front, Up and Left, and +// a slide of half width Halfwidth, against the span from Point1 along Parametric (the span's other end is Point1 + +// Parametric). for a span parallel to the plane of the pantograph's movement the distance to the plane is divided by +// 0.001 in place of 0 (the division by zero trap the vehicles always had), which puts the crossing outside the span +// unless the span lies in the plane +contact span_contact(glm::dvec3 const &Point1, glm::dvec3 const &Parametric, glm::dvec3 const &Point, + glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double Halfwidth); + +// the span is a wire the pantograph can reach: it crosses the plane of the pantograph's movement on the slide, between +// Minheight and Maxheight above the pantograph's base point. the heights keep out the wires of the bridges above the +// line and of the lines below it +bool reaches(contact const &Contact, double Minheight, double Maxheight); + +// the default margin of wire ahead of the pantograph at a stop, the step and the farthest distance back the stop is +// looked for under the wire, in metres +double const stop_margin{3.0}; +double const stop_step{2.0}; +double const stop_walk_back{300.0}; + +// how far short of its target a train has to stop so its pantograph stays under the wire, in metres along the route. +// the distances are along the route from the head of the train: Stop the target of the head, Pantograph the pantograph +// the train relies on (the rearmost one it raises) behind the head. Covered tells whether there's a wire over the +// route at the given distance. the pantograph at the stop is fine when there's wire over it and Margin ahead of it; +// otherwise it's moved back by Step at a time, up to Walkback, to the first place it's fine at. 0 when it's fine at the +// target, and when no place within Walkback is (not an electrified stretch, or a gap too long to tell about: stopping +// short won't help there) +double wire_shortfall(std::function const &Covered, double Pantograph, double Stop, + double Margin = stop_margin, double Step = stop_step, double Walkback = stop_walk_back); + +// what makes the train stop at a place +enum class stop_kind { + track_end, // the end of the track, e.g. a buffer stop, in train or shunting mode + timetable_stop, // a stop of the timetable (W4 indicator) + signal, // a signal at stop + coupling, // a vehicle to couple to or to uncouple from +}; + +// the train stops with its pantograph under the wire. not when it runs without the wire: without a current collector, +// with the voltage made up (livetraction off), on a stretch the scenery tells to coast or to run with the pantographs +// down. not for a signal (a wait, the wire ending before a signal is a fault of the scenery) and not for a coupling +// (the vehicle to couple to may stand on a siding without the wire) +bool stops_under_wire(bool Collector, bool Livetraction, bool Overheadrestricted, stop_kind Kind); + +} // namespace ai_wire diff --git a/vehicle/blackbox.cpp b/vehicle/blackbox.cpp index fc05f7483..0138b6acd 100644 --- a/vehicle/blackbox.cpp +++ b/vehicle/blackbox.cpp @@ -381,6 +381,22 @@ void writer::coupling(coupling_change const &Change) { emit(record::coupling); } +void writer::derailment(derailment_state const &State) { + auto &out{begin()}; + out.f64(State.time); + out.u32(State.vehicle); + out.u8(State.phase); + out.u8(State.cause); + out.dvec3(State.position); + out.f32(State.heading); + out.f32(State.speed_kmh); + out.f32(State.offset); + out.f32(State.roll); + out.f32(State.travelled); + out.u8(State.lying ? 1 : 0); + emit(record::derailment); +} + void writer::clock(double const Time, std::uint16_t const Year, std::uint16_t const Year_day, double const Second_of_day) { auto &out{begin()}; out.f64(Time); diff --git a/vehicle/blackbox.h b/vehicle/blackbox.h index 62fc1df38..26fe5c6a1 100644 --- a/vehicle/blackbox.h +++ b/vehicle/blackbox.h @@ -52,6 +52,7 @@ enum class record : std::uint8_t { station = 0x35, horn_request = 0x36, coupling = 0x37, + derailment = 0x38, end = 0x3f }; @@ -304,7 +305,7 @@ struct station_event { struct camera_state { double time{0.0}; std::uint8_t mode{camera_modes::free}; - std::uint8_t view{0}; // of an outside view: 0 the front of the train, 1 its rear, 2 a bogie, 3 drive-by + std::uint8_t view{0}; // of an outside view: 0 the front of the train, 1 its rear, 2 a bogie, 3 drive-by, 4 orbit, 5 shunting, 6 coupling, 7 trackside std::uint32_t vehicle{no_vehicle}; // the vehicle the camera goes with, no_vehicle for none glm::dvec3 position{0.0}; float heading{0.0f}; // [rad] of where it looks, from +z towards +x, as the heading of a vehicle @@ -324,6 +325,35 @@ struct coupling_change { glm::dvec3 position{0.0}; // of the coupler }; +// what put a vehicle off the rails, for the derailment record (vehicle/derailmotion.h) +namespace derailment_causes { +inline constexpr std::uint8_t flange_climbed{1}; +inline constexpr std::uint8_t overturned{2}; +inline constexpr std::uint8_t end_of_track{3}; +inline constexpr std::uint8_t pulled_off{4}; // by the coupling of a vehicle off the track +inline constexpr std::uint8_t collision{5}; +} // namespace derailment_causes + +namespace derailment_phases { +inline constexpr std::uint8_t left_track{0}; // it left the track +inline constexpr std::uint8_t at_rest{1}; // it came to rest off the track +} // namespace derailment_phases + +// a vehicle off the track (physics.derailment new): as it leaves it, and where it comes to rest +struct derailment_state { + double time{0.0}; + std::uint32_t vehicle{no_vehicle}; + std::uint8_t phase{derailment_phases::left_track}; + std::uint8_t cause{derailment_causes::flange_climbed}; + glm::dvec3 position{0.0}; // of the vehicle + float heading{0.0f}; // [rad] of its front, from +z towards +x + float speed_kmh{0.0f}; // signed: positive along its front + float offset{0.0f}; // [m] from the axis of the track at the place nearest to it, to the left of its front positive + float roll{0.0f}; // [rad] of its body against the level, to the left positive; 90 degrees on its side + float travelled{0.0f}; // [m] on the ground since it left the rails + bool lying{false}; // on its side +}; + struct vehicle_state { std::uint32_t id{no_vehicle}; glm::vec3 position{0.0f}; @@ -378,6 +408,7 @@ public: void horn_request(double Time, std::uint32_t Vehicle, float Duration, float Tone, glm::dvec3 const &Position); void camera(camera_state const &Camera); void coupling(coupling_change const &Change); + void derailment(derailment_state const &State); void vehicle(vehicle_data const &Vehicle); void vehicle_removed(double Time, std::uint32_t Id); void cab(cab_sample const &Sample); diff --git a/vehicle/brakecharge.cpp b/vehicle/brakecharge.cpp new file mode 100644 index 000000000..18668987d --- /dev/null +++ b/vehicle/brakecharge.cpp @@ -0,0 +1,65 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/brakecharge.h" + +namespace brake_charge { + +bool charged(state &State, double const Level, double const Reference, double const Time, bool const Supplied) { + + if (State.going) { + return true; + } + if (Level >= Reference - margin) { + State = {}; + State.going = true; + return true; + } + if ((State.best < 0.0) || (Level > State.best + stall_gain) || (false == Supplied)) { + // still charging, or nothing to charge with yet: the time for a stall counts from when there is + State.best = Level; + State.best_time = Time; + State.stalled = false; + return false; + } + State.stalled = (Time - State.best_time >= stall_time); + State.going = State.stalled; + return State.stalled; +} + +double locomotive_brake_force(double const Blockforce, double const Weight) { + + return std::max(0.0, std::min(Blockforce, Weight * adhesion)); +} + +bool locomotive_brake_holds(double const Locomotivebrakeforce, double const Gradeforce) { + + return Locomotivebrakeforce >= holding_force * std::abs(Gradeforce); +} + +double reference(double const Headpipe, double const Working, bool const Trainbrakeapplied) { + + if (false == Trainbrakeapplied) { + return Working; + } + return std::clamp(Headpipe, Working - service_drop + margin, Working); +} + +bool holds_application(bool const Hold, bool const Charged, bool const Standing, double const Position) { + + return Hold && (false == Charged) && Standing && (Position > 0.0) && (Position <= 1.0); +} + +bool release_waits(bool const Charged, bool const Standing, bool const Trainbrakeapplied) { + + return (false == Charged) && Standing && (false == Trainbrakeapplied); +} + +} // namespace brake_charge diff --git a/vehicle/brakecharge.h b/vehicle/brakecharge.h new file mode 100644 index 000000000..f283dade9 --- /dev/null +++ b/vehicle/brakecharge.h @@ -0,0 +1,76 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +// a standing train starts only with its brakes charged, as a driver checks before setting off: the brake pipe and the +// auxiliary reservoir of every vehicle with a working brake close to the working pressure. released alone isn't enough: +// a train prepared from cold is released at once, its pipe still filling, and has no air to brake with +// (TController::PrepareEngine(), TController::determine_consist_state()) +namespace brake_charge { + +// [bar] below the working pressure the pipe and the reservoir count as charged: 4.5 of 5.0. the last wagon of a long +// train stays at about 4.6-4.7 for good, from what leaks along the pipe +auto const margin{0.5}; +// below this the pipe counts as near empty (after an emergency application): the next start waits for the charge +// whatever came before. well below what a service application leaves: the AI stops at a station with the handle past +// the full service position, the pipe at 3.0-3.5 bar, and wagons coupled from cold come with about 3 bar. waiting there +// only delays the train, and the scenery sets the routes of the others later (calkowo_v2_osoba_jar_poranek, l053_poranek) +auto const empty_level{2.5}; // [bar] +// a charge that rises by less than this in stall_time has stopped (a leak, a hose not connected, a pipe cock shut): the +// train goes all the same, rather than stand for good +auto const stall_gain{0.02}; // [bar] +auto const stall_time{60.0}; // [s] +// standing, the locomotive brake alone has to give this multiple of the grade force to hold the train while it charges +auto const holding_force{1.1}; +// the share of a locomotive's weight its brake can hold the train with at most: what the wheels pass on to the rails, +// taken low (a wet rail). the force of the brake blocks alone is several times that +auto const adhesion{0.25}; +// [bar] how far below the working pressure the pipe is at a full service application: with the train brake applied the +// train charges to what the head of the pipe has, but a pipe below this (emptied, or just being filled) is no charge +auto const service_drop{1.5}; + +struct state { + double best{-1.0}; // the highest charge seen while it still rose [bar], -1 before the first look + double best_time{0.0}; // when it was seen [s] + bool stalled{false}; // the charge stopped rising short of charged + // the train was let go: it stays so until the driver clears this, when the train is to stand again. otherwise a + // charge rising again as the train starts (the pipe refilling behind the release) would stop it at a crawl + bool going{false}; +}; + +// Level: the lowest pressure of the brake pipes and auxiliary reservoirs among the vehicles with a working brake [bar]; +// Reference: the pressure they charge to [bar]; Time: now [s]; Supplied: there is air to charge with (the engine +// prepared, the main reservoir above the reference): without it the charge can't rise, and that isn't a stall. +// true once the train may start, and from then on +bool charged(state &State, double Level, double Reference, double Time, bool Supplied = true); + +// what the locomotive brake of a vehicle holds with at full application [N]: the force of its brake blocks (Blockforce), +// but no more than its wheels pass on to the rails, the adhesion share of its Weight [N] +double locomotive_brake_force(double Blockforce, double Weight); + +// whether the locomotive brake, Locomotivebrakeforce at full application [N], holds the standing train against its +// Gradeforce [N] on its own; when it doesn't, the train brake is applied lightly while the train charges +bool locomotive_brake_holds(double Locomotivebrakeforce, double Gradeforce); + +// the pressure the train is to be charged to [bar]: the working pressure with the train brake released; with it applied +// what the head of the pipe has (Headpipe), as the reservoirs get no more, though no less than a full service +// application leaves, or a pipe emptied by an emergency application would count as charged at once +double reference(double Headpipe, double Working, bool Trainbrakeapplied); + +// whether a light application of the train brake (Position, up to the first service position) stays on: the train +// stands on it while it charges (Hold), the locomotive brake not holding it alone +bool holds_application(bool Hold, bool Charged, bool Standing, double Position); + +// whether a release of the brakes waits for the charge: standing, a train not charged yet keeps its locomotive brake +// on. the train brake (Trainbrakeapplied) may come off all the same: released, it fills the pipe, which is what charges +// the train. the hint a human driver gets to release the brakes waits with it (driver_hint::waitbrakecharge instead) +bool release_waits(bool Charged, bool Standing, bool Trainbrakeapplied); + +} // namespace brake_charge diff --git a/vehicle/brakereleaser.cpp b/vehicle/brakereleaser.cpp new file mode 100644 index 000000000..e9c189bb2 --- /dev/null +++ b/vehicle/brakereleaser.cpp @@ -0,0 +1,65 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/brakereleaser.h" + +namespace brake_releaser { + +namespace { + +// the rules for a driver that wants to speed up +bool wanted_to_start(conditions const &State) { + // fill up the brake pipe if needed + if (State.pipe_pressure < 3.0) { + return true; + } + // wyluzuj lokomotywę, to szybciej ruszymy + // this rule is for starting off, so only below 1 km/h: at speed, just after an application, it would vent + // the control reservoir of a locomotive that may have to brake again before the pipe has refilled it + if (State.cylinder_pressure > 0.4 + && (State.control_pressure > 4.9 + // starting uphill the train brake stays applied on purpose, and the locomotive's own share of it has to go + // for the power to come on (asynchronous drives and the pressure switch cut the power while it is applied) + || State.uphill_start) + && State.velocity < 1.0) { + return true; + } + // keep engine brakes released during coupling/uncoupling + return State.pressing && State.cylinder_pressure > 0.1; +} + +} // namespace + +decision decide(conditions const &State) { + decision result; + if (State.acceleration_desired > no_acceleration) { + result.fill_pipe = State.pipe_pressure < 3.0; + result.actuate = wanted_to_start(State); + } + else if (State.charging_standing) { + // a train placed cold charges its brakes standing: only the pipe is filled up, the other rules are for a start + result.fill_pipe = State.pipe_pressure < 3.0; + result.actuate = result.fill_pipe; + } + // uncoupling, stage 3: the locomotive has to push the slack of the coupler out whatever its speed table says. + // the consist stays held by its own brakes, applied in stage 2, and the push asks for 2 km/h at most. a signal + // at stop that the consist stands across after the direction change caps the speed at 0 and so AccDesired + // below no_acceleration, and a locomotive left braked by the consist's brake application never closes the gap + if (State.compressing_buffers && State.cylinder_pressure > 0.1) { + result.actuate = true; + } + // don't overcharge train brake pipe + if (State.pipe_pressure > 5.2) { + result.actuate = false; + } + return result; +} + +} // namespace brake_releaser diff --git a/vehicle/brakereleaser.h b/vehicle/brakereleaser.h new file mode 100644 index 000000000..e4ba14ad6 --- /dev/null +++ b/vehicle/brakereleaser.h @@ -0,0 +1,42 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +// when the AI driver works the brake releaser of its locomotive (TController::control_releaser): it vents the +// locomotive's own train brake cylinders, to start off sooner, to fill up an empty brake pipe, and to let the +// locomotive press the buffers while it (un)couples +namespace brake_releaser { + +// the state of the locomotive and of its driver the decision depends on +struct conditions { + double acceleration_desired{0.0}; // AccDesired of the driver [m/s2]; above no_acceleration it wants to speed up + double pipe_pressure{0.0}; // brake pipe [bar] + double cylinder_pressure{0.0}; // the locomotive's brake cylinders [bar] + double control_pressure{0.0}; // the control reservoir of the locomotive's distributor [bar] + double velocity{0.0}; // [km/h] + bool uphill_start{false}; // starting uphill with the train brake held on purpose + bool pressing{false}; // (un)coupling: the driver presses the buffers (movePress) + bool compressing_buffers{false}; // uncoupling, stage 3: pushing towards the cut to slacken the coupler + // standing, the train charges its brakes before its first start (bBrakeChargeStart), with the brake handle where + // the pipe can be unlocked: a pipe below the lock is unlocked as the train stands, not only once it is to go + bool charging_standing{false}; +}; + +struct decision { + bool actuate{false}; // the releaser goes on (else off) + bool fill_pipe{false}; // the brake pipe is to be filled up: the brake handle goes to its unlock position +}; + +// AccDesired at or below this asks for no speeding up (EU07_AI_NOACCELERATION of Driver.h) +inline constexpr double no_acceleration{-0.05}; + +decision decide(conditions const &State); + +} // namespace brake_releaser diff --git a/vehicle/brakesetting.cpp b/vehicle/brakesetting.cpp index ceffe3180..918da3d02 100644 --- a/vehicle/brakesetting.cpp +++ b/vehicle/brakesetting.cpp @@ -177,6 +177,10 @@ bool runs_as_train(int const Orders) { return (Orders & (Obey_train | Bank)) != 0; } +bool inspects_train(int const Orders, bool const Coupled) { + return (Orders & (Shunt | Loose_shunt | Obey_train | Bank)) != 0 || ((Orders & Connect) != 0 && false == Coupled); +} + bool at_standstill(double const Velocity) { return std::abs(Velocity) < EU07_AI_MOVEMENT; } diff --git a/vehicle/brakesetting.h b/vehicle/brakesetting.h index cb7ad5225..e3e5b4974 100644 --- a/vehicle/brakesetting.h +++ b/vehicle/brakesetting.h @@ -65,6 +65,15 @@ std::vector choose(std::vector const &Consist, bool Train); // train run too (with the braking of a train). Orders is the order of the AI (TOrders) bool runs_as_train(int Orders); +// the AI has the inspector look at its train (TController::AutoRewident(): the brake settings, and the hand and +// spring brakes of the train released) under the orders it drives the train under: shunting, loose shunting, the +// train run, banking, and the run up to the wagons to couple to (Connect), which a locomotive left standing cold, +// with its hand brake on, would make pulling against it. Coupled: the look the AI takes at the moment it couples +// (CheckVehicles(Connect)); Connect doesn't count for it, so the wagons just coupled keep their hand brakes until +// the order after the coupling looks at the new train, as before: those of them to be left standing again +// (Shunt x,-y) stay braked. Orders is the order of the AI (TOrders) +bool inspects_train(int Orders, bool Coupled); + // the train stands for the inspector: slower than the AI takes for a deliberate movement (EU07_AI_MOVEMENT). // the AI looks at the train while it still creeps to a stop (at a W4, or switching from shunting to the train // run), so a stricter threshold would miss those checks; a train really on the run (an order changed mid-run) diff --git a/vehicle/brakingcurve.cpp b/vehicle/brakingcurve.cpp index d39ee2868..1cd1397aa 100644 --- a/vehicle/brakingcurve.cpp +++ b/vehicle/brakingcurve.cpp @@ -25,6 +25,10 @@ bool brake_table::known() const { return a0[size] > 0.0; } +bool brake_acting(double const Trainbrakeposition, double const Localbrakeposition) { + return (Trainbrakeposition > 0.0) || (Localbrakeposition > 0.0); +} + double shaped_demand(double const Velocity, double const Target, double const Distance, double const Gravity, brake_table const &Table) { auto const travel = [Velocity, Target, Gravity, &Table](double const Ratio) { diff --git a/vehicle/brakingcurve.h b/vehicle/brakingcurve.h index 6ed40d9bb..3b49597e5 100644 --- a/vehicle/brakingcurve.h +++ b/vehicle/brakingcurve.h @@ -40,11 +40,17 @@ struct approach { double offset; // the braking point that far short of it [m] double gravity; // tangential acceleration of the gradient [m/s2], negative uphill double acceleration; // present acceleration of the train [m/s2] - bool brake_applied; // the train brake handle is past running + bool brake_applied; // the brake the train slows down with is applied (brake_acting) double speedup_horizon; // how long the present acceleration lasts while speeding up [s] double fill_horizon; // how long the brake takes to fill once applied [s] }; +// whether the train is braking already, for approach::brake_applied: the train brake handle is past running +// (Trainbrakeposition above 0), or the independent brake is applied (Localbrakeposition above 0). a vehicle that +// runs alone, a light locomotive or a railcar, brakes with the independent brake and leaves the train brake +// handle in running +bool brake_acting(double Trainbrakeposition, double Localbrakeposition); + // acceleration [m/s2] to ask for now, negative to brake. with the worked out table of a pneumatic brake // (Pneumatictable) the demand follows the brake: planned from the state the train is in once the brake has // responded, along the shape of its force over speed. without one (nullptr for another brake, or a table left at diff --git a/vehicle/cameraviews.cpp b/vehicle/cameraviews.cpp new file mode 100644 index 000000000..ef0975088 --- /dev/null +++ b/vehicle/cameraviews.cpp @@ -0,0 +1,281 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/cameraviews.h" + +#include +#include +#include + +namespace cameraviews { + +namespace { + +glm::dvec3 const world_up{0.0, 1.0, 0.0}; + +// radians per second of the left and right keys, and of the page keys, for a key held +double constexpr orbit_turn_rate{1.2}; +double constexpr orbit_climb_rate{0.8}; +// the radius grows (or shrinks) e times in a second of a key held +double constexpr orbit_zoom_rate{1.0}; +// the height of the shunting view grows (or shrinks) e times in a second of a key held +double constexpr topdown_zoom_rate{0.8}; +// metres per second of the shunting view moved along and across, for each metre of its height +double constexpr topdown_pan_rate{0.6}; +// metres per second of the coupling view moved closer, further, up and down +double constexpr coupler_move_rate{3.0}; +// metres the coupling view stands back from the coupler, towards its vehicle +double constexpr coupler_step_back{2.0}; +// the share of the gap to the vehicle coming closer the coupling view keeps from the side of the train +double constexpr coupler_gap_share{0.7}; + +double flat_distance(glm::dvec3 const &A, glm::dvec3 const &B) { + return std::hypot(A.x - B.x, A.z - B.z); +} + +} // namespace + +glm::dvec3 flat_front(glm::dvec3 const &Front) { + glm::dvec3 const flat{Front.x, 0.0, Front.z}; + auto const length{glm::length(flat)}; + if (length < 1e-6) { + return {0.0, 0.0, -1.0}; + } + return flat / length; +} + +glm::dvec3 flat_left(glm::dvec3 const &Flatfront) { + return glm::cross(world_up, Flatfront); +} + +int step_index(int const Index, int const Count, int const Step) { + if (Count <= 0) { + return 0; + } + return std::clamp(Index + Step, 0, Count - 1); +} + +std::pair train_ends(std::vector const &Positions, glm::dvec3 const &Direction) { + if (Positions.empty()) { + return {-1, -1}; + } + auto const way{flat_front(Direction)}; + auto const along{[&way](glm::dvec3 const &Position) { return glm::dot(Position, way); }}; + auto const [tail, head]{std::ranges::minmax_element(Positions, {}, along)}; + return {static_cast(head - Positions.begin()), static_cast(tail - Positions.begin())}; +} + +int driving_facing(glm::dvec3 const &Front, glm::dvec3 const &Drivenfront, int const Cab) { + auto const cab{Cab < 0 ? -1 : 1}; + auto const aligned{glm::dot(flat_front(Front), flat_front(Drivenfront)) < 0.0 ? -1 : 1}; + return cab * aligned; +} + +// orbit + +glm::dvec3 orbit_centre(vehicle_pose const &Vehicle) { + return Vehicle.position + world_up * (0.4 * Vehicle.height); +} + +double orbit_min_radius(vehicle_pose const &Vehicle) { + return 0.5 * std::hypot(Vehicle.length, Vehicle.width) + 1.0; +} + +orbit orbit_start(vehicle_pose const &Vehicle) { + orbit start; + start.azimuth = 0.6; + start.elevation = 0.25; + start.radius = std::max(orbit_min_radius(Vehicle), Vehicle.length + 5.0); + return orbit_clamped(start, Vehicle); +} + +double orbit_lowest_elevation(vehicle_pose const &Vehicle, double const Radius) { + auto const centre{0.4 * Vehicle.height}; + auto const sine{std::clamp((rail_clearance - centre) / std::max(Radius, 1e-3), -1.0, 1.0)}; + return std::max(orbit_min_elevation, std::asin(sine)); +} + +orbit orbit_clamped(orbit Orbit, vehicle_pose const &Vehicle) { + if (Orbit.radius <= 0.0) { + Orbit.radius = orbit_start(Vehicle).radius; + } + Orbit.radius = std::clamp(Orbit.radius, orbit_min_radius(Vehicle), std::max(orbit_min_radius(Vehicle), orbit_max_radius)); + Orbit.elevation = std::clamp(Orbit.elevation, orbit_lowest_elevation(Vehicle, Orbit.radius), orbit_max_elevation); + Orbit.azimuth = std::remainder(Orbit.azimuth, 2.0 * std::numbers::pi); + return Orbit; +} + +orbit orbit_moved(orbit Orbit, move_keys const &Keys, glm::dvec2 const &Turn, double const Seconds, vehicle_pose const &Vehicle) { + Orbit = orbit_clamped(Orbit, Vehicle); + // the left key takes the camera to the left around the vehicle, as a step to the left would while looking at it: + // clockwise seen from above. so does the mouse moved to the right, which turns the view to the right + Orbit.azimuth += Keys.x * orbit_turn_rate * Seconds + Turn.y; + // the mouse moved down looks down at the vehicle, from higher up + Orbit.elevation += Keys.y * orbit_climb_rate * Seconds - Turn.x; + // the up arrow (a negative z) brings the camera closer + Orbit.radius *= std::exp(Keys.z * orbit_zoom_rate * Seconds); + return orbit_clamped(Orbit, Vehicle); +} + +placement orbit_placement(orbit const &Orbit, vehicle_pose const &Vehicle) { + auto const front{flat_front(Vehicle.front)}; + auto const left{flat_left(front)}; + auto const around{std::cos(Orbit.azimuth) * front + std::sin(Orbit.azimuth) * left}; + auto const way{std::cos(Orbit.elevation) * around + std::sin(Orbit.elevation) * world_up}; + placement place; + place.target = orbit_centre(Vehicle); + place.eye = place.target + Orbit.radius * way; + place.up = world_up; + return place; +} + +// shunting view + +double topdown_min_height(vehicle_pose const &Vehicle) { + return Vehicle.height + 3.0; +} + +topdown topdown_clamped(topdown View, vehicle_pose const &Vehicle, double const Alonglimit) { + auto const lowest{topdown_min_height(Vehicle)}; + if (View.height <= 0.0) { + View.height = 1.5 * Vehicle.length; + } + View.height = std::clamp(View.height, lowest, std::max(lowest, topdown_max_height)); + auto const along{std::max(0.0, Alonglimit)}; + View.along = std::clamp(View.along, -along, along); + View.across = std::clamp(View.across, -topdown_max_across, topdown_max_across); + return View; +} + +topdown topdown_moved(topdown View, move_keys const &Keys, double const Seconds, vehicle_pose const &Vehicle, double const Alonglimit) { + View = topdown_clamped(View, Vehicle, Alonglimit); + auto const pan{View.height * topdown_pan_rate * Seconds}; + // the up arrow (a negative z) moves the view up the screen, the way the user drives + View.along -= Keys.z * pan; + View.across += Keys.x * pan; + View.height *= std::exp(Keys.y * topdown_zoom_rate * Seconds); + return topdown_clamped(View, Vehicle, Alonglimit); +} + +placement topdown_placement(topdown const &View, vehicle_pose const &Vehicle, int const Facing) { + auto const up{flat_front(Vehicle.front) * (Facing < 0 ? -1.0 : 1.0)}; + // looking down with the screen up the way the user drives, the right of the screen is the right of that way + auto const right{-flat_left(up)}; + placement place; + auto const ground{Vehicle.position + up * View.along + right * View.across}; + place.target = ground; + place.eye = ground + world_up * View.height; + place.up = up; + return place; +} + +// coupling view + +coupler_view coupler_moved(coupler_view View, move_keys const &Keys, double const Seconds) { + if (Keys.x < 0.0) { + View.side = 1.0; + } + else if (Keys.x > 0.0) { + View.side = -1.0; + } + View.distance = std::clamp(View.distance + Keys.z * coupler_move_rate * Seconds, coupler_min_distance, coupler_max_distance); + View.height = std::clamp(View.height + Keys.y * coupler_move_rate * Seconds, coupler_min_height, coupler_max_height); + return View; +} + +placement coupler_placement(coupler_view const &View, coupler const &Coupler, glm::dvec3 const *Other) { + auto const outward{flat_front(Coupler.outward)}; + auto const aside{flat_left(outward) * (View.side < 0.0 ? -1.0 : 1.0)}; + auto const buffers{Coupler.position + world_up * buffer_height}; + auto distance{View.distance}; + placement place; + if (Other != nullptr) { + auto const otherbuffers{*Other + world_up * buffer_height}; + distance = std::max(distance, coupler_gap_share * flat_distance(Coupler.position, *Other)); + place.target = 0.5 * (buffers + otherbuffers); + } + else { + place.target = buffers + outward; + } + distance = std::min(distance, coupler_max_distance); + place.eye = buffers - outward * coupler_step_back + aside * (0.5 * Coupler.width + distance) + world_up * View.height; + place.up = world_up; + return place; +} + +int first_coupling(double const Frontgap, double const Reargap, int const Count) { + auto const watched{[](double const Gap) { return Gap >= 0.0 && Gap <= coupler_watch_range; }}; + auto const front{watched(Frontgap)}; + auto const rear{watched(Reargap)}; + if (rear && (false == front || Reargap < Frontgap)) { + return std::max(Count, 0); + } + return 0; +} + +// trackside view + +std::pair along_arc(glm::dvec3 const &Start, glm::dvec3 const &Direction, double const Curvature, double const Distance) { + auto const way{flat_front(Direction)}; + if (std::abs(Curvature) < 1e-6) { + return {Start + way * Distance, way}; + } + auto const left{flat_left(way)}; + auto const angle{Curvature * Distance}; + auto const point{Start + way * (std::sin(angle) / Curvature) + left * ((1.0 - std::cos(angle)) / Curvature)}; + auto const heading{way * std::cos(angle) + left * std::sin(angle)}; + return {point, heading}; +} + +double line_curvature(glm::dvec3 const &Positiona, glm::dvec3 const &Directiona, glm::dvec3 const &Positionb, glm::dvec3 const &Directionb) { + auto const distance{flat_distance(Positiona, Positionb)}; + if (distance < 1.0) { + return 0.0; + } + auto const ahead{flat_front(Directiona)}; + auto const behind{flat_front(Directionb)}; + // the vehicle ahead turned to the left of the one behind it: a turn about the up axis, anticlockwise from above + auto const angle{std::atan2(glm::cross(behind, ahead).y, glm::dot(behind, ahead))}; + return angle / distance; +} + +bool trackside_expired(trackside const &View, train_motion const &Train) { + if (false == View.placed) { + return true; + } + auto const way{flat_front(Train.direction)}; + auto const offset{View.spot - Train.tail}; + auto const passed{glm::dot(glm::dvec3{offset.x, 0.0, offset.z}, way) < -trackside_passed}; + return passed || flat_distance(View.spot, Train.head) > trackside_max_distance; +} + +trackside trackside_next(trackside const &View, train_motion const &Train) { + auto lead{std::clamp(Train.speed * trackside_lead_time, trackside_min_lead, trackside_max_lead)}; + // along a sharp curve the line comes round: the spot stays within a quarter of the circle + if (auto const quarter{0.5 * std::numbers::pi}; std::abs(Train.curvature) * lead > quarter) { + lead = quarter / std::abs(Train.curvature); + } + auto const [point, heading]{along_arc(Train.head, Train.direction, Train.curvature, lead)}; + trackside next; + next.side = View.placed ? -View.side : View.side; + next.spot = point + flat_left(heading) * (next.side * (0.5 * Train.width + trackside_distance)) + world_up * trackside_eye_height; + next.placed = true; + return next; +} + +placement trackside_placement(trackside const &View, glm::dvec3 const &Target) { + placement place; + place.eye = View.spot; + place.target = Target; + place.up = world_up; + return place; +} + +} // namespace cameraviews diff --git a/vehicle/cameraviews.h b/vehicle/cameraviews.h new file mode 100644 index 000000000..a23d09e55 --- /dev/null +++ b/vehicle/cameraviews.h @@ -0,0 +1,182 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include + +// The outside views of the user's train that go with one of its vehicles (eu07/maszyna#551): the orbit around a +// vehicle, the shunting view from above, the view beside a coupling and the trackside view of a railfan. Each one +// is worked out here from the place of the vehicle and the keys of the user alone, so it can be tested without the +// game; application/consistviews.cpp hands over the vehicles of the train and turns the results into the camera. +// The world has y up; the rails are at the height of the place of a vehicle (TDynamicObject::GetPosition). +namespace cameraviews { + +// a vehicle of the train, as the views see it +struct vehicle_pose { + glm::dvec3 position{}; // its middle, at the height of the rails + glm::dvec3 front{0.0, 0.0, -1.0}; // unit, towards its front coupler + double length{20.0}; + double width{3.0}; + double height{4.0}; +}; + +// where the camera stands, the point it looks at and its up +struct placement { + glm::dvec3 eye{}; + glm::dvec3 target{}; + glm::dvec3 up{0.0, 1.0, 0.0}; +}; + +// the movement keys of the camera as TCamera::Velocity has them outside the cab: x to the right, y up, z backwards +// (the up arrow gives a negative z), 1 for a key held, 5 with ctrl +using move_keys = glm::dvec3; + +// the Front of a vehicle flattened on the ground, unit; a vehicle standing upright (no heading) faces -z +glm::dvec3 flat_front(glm::dvec3 const &Front); +// to the left of the flat Front, unit +glm::dvec3 flat_left(glm::dvec3 const &Flatfront); + +// the index after Step vehicles (or couplings) from Index, among Count of them, held at the first and the last +int step_index(int Index, int Count, int Step); + +// the two ends of a train whose vehicles stand at Positions, going in the Direction: the index of the vehicle +// at its head (furthest along the Direction) and at its tail +std::pair train_ends(std::vector const &Positions, glm::dvec3 const &Direction); + +// +1 when the front of the vehicle the view goes with points the way the user drives, -1 when it points back: +// the Front of that vehicle, the Front of the vehicle the user drives and its occupied cab (1 the front one, +// -1 the rear one, 0 none) +int driving_facing(glm::dvec3 const &Front, glm::dvec3 const &Drivenfront, int Cab); + +// orbit: around the middle of the vehicle, the left and right keys (and the mouse) turn the camera around it, +// the up and down arrows bring it closer and further away, the page keys (and the mouse) raise and lower it +struct orbit { + double azimuth{0.0}; // radians around the vehicle from its front, towards its left + double elevation{0.0}; // radians above the horizon of the middle of the vehicle + double radius{0.0}; // metres from the middle of the vehicle, 0 for the default one of the vehicle +}; + +inline constexpr double orbit_max_radius{250.0}; +inline constexpr double orbit_max_elevation{1.4}; // radians, about 80 degrees +inline constexpr double orbit_min_elevation{-0.5}; // radians, about -30 degrees, if the rails let it +inline constexpr double rail_clearance{0.5}; // metres the camera keeps above the rails + +// the first orbit around a vehicle: ahead of it on its left, a little above it, as far as the vehicle is long +orbit orbit_start(vehicle_pose const &Vehicle); +// the point the orbit goes around: the middle of the vehicle, a little lower than half of its height +glm::dvec3 orbit_centre(vehicle_pose const &Vehicle); +// the nearest the camera comes to the middle of the Vehicle: outside its body whichever way it looks +double orbit_min_radius(vehicle_pose const &Vehicle); +// the lowest elevation at the Radius which keeps the camera above the rails +double orbit_lowest_elevation(vehicle_pose const &Vehicle, double Radius); +// the Orbit held within its limits around the Vehicle (radius 0 becomes the default one) +orbit orbit_clamped(orbit Orbit, vehicle_pose const &Vehicle); +// the Orbit after Seconds of the Keys held and the mouse moved by Turn (radians: x up and down, y to the left and +// right, as TCamera::Angle takes them), within its limits around the Vehicle +orbit orbit_moved(orbit Orbit, move_keys const &Keys, glm::dvec2 const &Turn, double Seconds, vehicle_pose const &Vehicle); +// the camera of the Orbit around the Vehicle, looking at its middle +placement orbit_placement(orbit const &Orbit, vehicle_pose const &Vehicle); + +// shunting view: straight down from above the vehicle, the way the user drives up the screen; it goes with the +// vehicle, the up and down arrows move it along the train, left and right across, the page keys up and down +struct topdown { + double height{0.0}; // metres above the rails, 0 for the default one of the vehicle + double along{0.0}; // metres from the middle of the vehicle along it, the way the user drives + double across{0.0}; // metres from the middle of the vehicle across it, to the right of the screen +}; + +inline constexpr double topdown_max_height{300.0}; +inline constexpr double topdown_max_across{60.0}; + +// the lowest the camera comes: above the roof of the Vehicle +double topdown_min_height(vehicle_pose const &Vehicle); +// the View held within its limits: Alonglimit metres along the vehicle either way +topdown topdown_clamped(topdown View, vehicle_pose const &Vehicle, double Alonglimit); +// the View after Seconds of the Keys held; the further the camera, the faster it moves +topdown topdown_moved(topdown View, move_keys const &Keys, double Seconds, vehicle_pose const &Vehicle, double Alonglimit); +// the camera of the View over the Vehicle; Facing +1 puts the front of the vehicle up the screen, -1 its rear +placement topdown_placement(topdown const &View, vehicle_pose const &Vehicle, int Facing); + +// coupling view: beside a coupler, low, looking along the train at it; when another vehicle comes closer to it +// the camera steps back from the track to keep both couplers in sight, looking between them +inline constexpr double buffer_height{1.06}; // metres above the rails + +struct coupler { + glm::dvec3 position{}; // the coupler at the height of the rails (TDynamicObject::CouplerPosition) + glm::dvec3 outward{0.0, 0.0, -1.0}; // unit, from its vehicle out through the coupler + double width{3.0}; // of its vehicle +}; + +struct coupler_view { + double side{1.0}; // 1 on the left of the outward way, -1 on the right + double height{0.4}; // metres above the buffers + double distance{2.5}; // metres from the side of the vehicle, before the vehicle coming closer moves it further +}; + +inline constexpr double coupler_min_distance{1.0}; +inline constexpr double coupler_max_distance{40.0}; +inline constexpr double coupler_min_height{-0.8}; // metres above the buffers: a little above the rails +inline constexpr double coupler_max_height{10.0}; +inline constexpr double coupler_watch_range{150.0}; // metres to a vehicle that still counts as coming closer + +// the View after Seconds of the Keys held: left and right move it to that side of the track, the arrows closer +// and further, the page keys up and down +coupler_view coupler_moved(coupler_view View, move_keys const &Keys, double Seconds); +// the camera beside the Coupler; Other is the facing coupler of the vehicle coming closer, when there is one +placement coupler_placement(coupler_view const &View, coupler const &Coupler, glm::dvec3 const *Other); +// the coupling of a train of Count vehicles the view starts at, numbered from 0 (its front end) to Count (its rear +// end): the end with another vehicle, not coupled, closer than coupler_watch_range (the closer one of the two), +// otherwise the front. Frontgap and Reargap are the distances to such vehicles, negative for none +int first_coupling(double Frontgap, double Reargap, int Count); + +// trackside view: a railfan standing beside the line ahead of the train, looking at it as it comes and goes by; +// once the whole train has gone past (or gone far away) the railfan walks to a new spot ahead of it, on the other +// side of the line +struct trackside { + glm::dvec3 spot{}; // the eye of the railfan + double side{-1.0}; // 1 on the left of the line, -1 on the right + bool placed{false}; +}; + +// the train as the trackside view sees it +struct train_motion { + glm::dvec3 head{}; // the vehicle at its head, the way it goes, at the height of the rails + glm::dvec3 tail{}; // the vehicle at its tail + glm::dvec3 direction{0.0, 0.0, -1.0}; // unit, flat, the way it goes + double speed{0.0}; // m/s + double curvature{0.0}; // 1/m of the line at the head, positive turning left + double width{3.0}; // of the vehicles +}; + +inline constexpr double trackside_eye_height{1.7}; +inline constexpr double trackside_distance{8.0}; // metres from the side of the train +inline constexpr double trackside_passed{40.0}; // metres the tail goes past the spot before the railfan moves on +inline constexpr double trackside_max_distance{1000.0}; // metres to the head before the railfan moves on anyway +inline constexpr double trackside_lead_time{15.0}; // seconds the train needs to reach the new spot +inline constexpr double trackside_min_lead{80.0}; +inline constexpr double trackside_max_lead{500.0}; + +// whether the railfan at the View has seen the Train go by and moves on +bool trackside_expired(trackside const &View, train_motion const &Train); +// the next spot of the railfan, ahead of the Train along its line, on the other side than the View had +trackside trackside_next(trackside const &View, train_motion const &Train); +// the camera of the railfan at the View, looking at the Target +placement trackside_placement(trackside const &View, glm::dvec3 const &Target); + +// the point and the way Distance metres on from Start going in the (flat, unit) Direction along a line which +// turns by Curvature (1/m, positive to the left) +std::pair along_arc(glm::dvec3 const &Start, glm::dvec3 const &Direction, double Curvature, double Distance); +// the curvature of the line under two vehicles of a train going its way: A ahead of B, each at its Position with +// its front (or rear) towards the way of the train; 0 when they stand too close to tell +double line_curvature(glm::dvec3 const &Positiona, glm::dvec3 const &Directiona, glm::dvec3 const &Positionb, glm::dvec3 const &Directionb); + +} // namespace cameraviews diff --git a/vehicle/compartmentlightsswitch.h b/vehicle/compartmentlightsswitch.h new file mode 100644 index 000000000..0ef6684c0 --- /dev/null +++ b/vehicle/compartmentlightsswitch.h @@ -0,0 +1,27 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +// the compartment lights get two requests: on (CompartmentLights.is_enabled) and off (is_disabled), and the off one +// wins. A two-state compartmentlights_sw: holds one of them, so turning it to one position withdraws the other request. +// A push type compartmentlights_sw: and the separate compartmentlightson_sw: / compartmentlightsoff_sw: push buttons +// withdraw their own request when they're released, so the other command leaves it alone. A cab with none of these +// controls (the keyboard toggle, ctrl+;, is all there is) acts as if it had the two-state switch, otherwise nothing +// would ever withdraw the off request and the lights couldn't be turned on again. +namespace compartment_lights_switch { + +// whether the command for one of the requests also withdraws the other one, from the cab's compartmentlights_sw: +// (whether it's there and whether it's a toggle type switch) and whether the cab has the push button of the other +// request (compartmentlightsoff_sw: for the on command, compartmentlightson_sw: for the off command) +inline bool withdraws_other_request(bool const Hasswitch, bool const Switchistoggle, bool const Hasotherbutton) { + return Hasswitch ? Switchistoggle : false == Hasotherbutton; +} + +} // namespace compartment_lights_switch diff --git a/vehicle/crew.cpp b/vehicle/crew.cpp new file mode 100644 index 000000000..d32bcc82c --- /dev/null +++ b/vehicle/crew.cpp @@ -0,0 +1,134 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/crew.h" + +#include "McZapkie/MOVER.h" +#include "vehicle/handover.h" + +namespace crew { + +namespace { + +// the scenery parser folds the ASCII letters of the names only, and so does this +char lower_ascii(char const Character) { + return Character >= 'A' && Character <= 'Z' ? static_cast(Character - 'A' + 'a') : Character; +} + +// the controllers of the vehicle to the positions giving no power, and the vehicles it controls told so +void cut_power(TMoverParameters &Vehicle) { + Vehicle.MainCtrlPos = Vehicle.MainCtrlNoPowerPos(); + Vehicle.ScndCtrlPos = 0; + // what the integrated handle and the cruise control asked for last stays in force until somebody drives + Vehicle.eimic = 0.0; + Vehicle.eimic_real = 0.0; + Vehicle.SpeedCtrlValue = 0.0; + Vehicle.SpeedCtrlUnit.IsActive = false; + Vehicle.SendCtrlToNext("MainCtrl", Vehicle.MainCtrlPosForCoupled(), Vehicle.CabActive); + Vehicle.SendCtrlToNext("ScndCtrl", Vehicle.ScndCtrlPos, Vehicle.CabActive); + Vehicle.SendCtrlToNext("EIMIC", 0.0, Vehicle.CabActive); +} + +} // namespace + +bool is_command(std::string_view const Text) { + return Text.starts_with(command_prefix); +} + +request parse(std::string_view const Text, double const Cab, double const Flags) { + request result; + if (false == is_command(Text)) { + return result; + } + result.vehicle = Text.substr(command_prefix.size()); + std::ranges::transform(result.vehicle, result.vehicle.begin(), lower_ascii); + result.cab_valid = Cab == 1.0 || Cab == -1.0 || Cab == 0.0; + if (result.cab_valid) { + result.cab = static_cast(Cab); + } + result.flags = static_cast(std::clamp(Flags, -65535.0, 65535.0)); + return result; +} + +action decide(request const &Request, vehicle_state const &State) { + using enum action; + if (false == Request.cab_valid) { + return refuse_cab; + } + if (State.occupied || (State.has_driver && false == State.driver_is_ai)) { + return refuse_user; + } + if (Request.cab == 0) { + return State.has_driver ? remove : nothing; + } + if (State.has_driver) { + return refuse_crewed; + } + if (false == State.has_cab) { + return refuse_no_cab; + } + if (State.consist_driven) { + return refuse_consist_driven; + } + return Request.cab > 0 ? add_front : add_rear; +} + +bool changes_crew(action const Action) { + return Action == action::add_front || Action == action::add_rear || Action == action::remove; +} + +std::string_view describe(action const Action) { + using enum action; + switch (Action) { + case add_front: + return "an AI driver takes cab A"; + case add_rear: + return "an AI driver takes cab B"; + case remove: + return "the AI driver leaves"; + case nothing: + return "no driver to take off"; + case refuse_cab: + return "refused, the cab has to be 1, -1 or 0"; + case refuse_user: + return "refused, a user is in the vehicle"; + case refuse_crewed: + return "refused, the vehicle has a driver already"; + case refuse_no_cab: + return "refused, the vehicle has no cab"; + case refuse_consist_driven: + return "refused, the consist has a driver in charge in another vehicle"; + default: + return ""; + } +} + +void secure(TMoverParameters &Occupied, TMoverParameters &Controlling) { + handover::release_ai_controls(Occupied, Controlling); + cut_power(Controlling); + if (&Occupied != &Controlling) { + cut_power(Occupied); + } + // the emergency position vents the brake pipe whatever the brake mode, and with nobody in the cab too + Occupied.BrakeLevelSet(Occupied.Handle->GetPos(bh_EB)); + // a vehicle with no train brake (a car, a draisine) gets the brake its driver stops it with, in full + if (Occupied.BrakeSystem == TBrakeSystem::Individual) { + if (Occupied.LocalBrake == TLocalBrake::ManualBrake) { + Occupied.IncManualBrakeLevel(ManualBrakePosNo); + } + else { + Occupied.IncLocalBrakeLevel(LocalBrakePosNo); + } + } + Occupied.CabDeactivisation(); + Occupied.CabOccupied = 0; +} + +} // namespace crew diff --git a/vehicle/crew.h b/vehicle/crew.h new file mode 100644 index 000000000..f2ab938f1 --- /dev/null +++ b/vehicle/crew.h @@ -0,0 +1,82 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include + +class TMoverParameters; + +// a driver put in a vehicle, or taken off it, while the scenario runs (eu07/maszyna#510): the command of a +// putvalues event +// event putvalues none 0 0 0 Crew: endevent +// with the name of the vehicle in the text, so the event works whatever sets it off (a key, an event +// launcher), the cab in the first value: 1 an AI driver in cab A, -1 in cab B, 0 nobody, and the second value +// reserved (0). "Crew:" with no name is for the vehicle which set the event off. +// here are the parts which need no vehicle of the game: reading the command, deciding what to do about it, +// and the state a train is left in when its driver goes. the game's side of it is in crewchange.h +namespace crew { + +// what the text of the command starts with, in this very case (the commands of the events are case sensitive) +inline constexpr std::string_view command_prefix{"Crew:"}; + +// whether the text of a putvalues event is the crew command +bool is_command(std::string_view Text); + +// the command as the event gives it +struct request { + std::string vehicle; // as the scenery keeps the names, in lower case; empty: the vehicle which set the event off + int cab{0}; // 1 a driver in cab A (the front one), -1 in cab B, 0 nobody + bool cab_valid{false}; // the value was one of the three + int flags{0}; // reserved, nothing reads it yet +}; + +// reads the command from the text of the event and its two values +request parse(std::string_view Text, double Cab, double Flags); + +// what the command finds in the vehicle +struct vehicle_state { + bool has_cab{false}; // the type of the vehicle has a driver's cab; a road vehicle or a boat counts as having one + bool has_driver{false}; + bool driver_is_ai{false}; // the driver it has is the AI, not a user + bool occupied{false}; // a user sits in the vehicle, whoever drives it + bool consist_driven{false}; // another vehicle of the consist has the driver in charge of it +}; + +enum class action { + add_front, // an AI driver goes into cab A + add_rear, // an AI driver goes into cab B + remove, // the AI driver is taken off + nothing, // asked to take the driver off a vehicle which has none + refuse_cab, // the cab asked for is none of 1, -1, 0 + refuse_user, // a user is in the vehicle, or drives it + refuse_crewed, // asked for a driver where there is one already + refuse_no_cab, // asked for a driver in a vehicle with no cab + refuse_consist_driven // asked for a driver in a consist which another vehicle's driver is in charge of +}; + +// what to do about the command. a user in the vehicle is never touched: neither replaced nor left without +// the driver the cab of the game works with +action decide(request const &Request, vehicle_state const &State); + +// whether the action changes anything +bool changes_crew(action Action); + +// the action in words, for the log +std::string_view describe(action Action); + +// the state a train is left in when the driver in charge of it goes: what the AI held is let go (as when it +// hands over to a user, see handover.h), the power is off, the driver's brake valve is in the emergency position, +// so a train on the move stops and stays braked, and the cab is neither active nor occupied. the engine, the +// pantographs and the lights stay as they were. Occupied is the vehicle of the driver, Controlling the one whose +// motors it drove (the AI's mvOccupied and mvControlling; the same one in a locomotive) +void secure(TMoverParameters &Occupied, TMoverParameters &Controlling); + +} // namespace crew diff --git a/vehicle/crewchange.cpp b/vehicle/crewchange.cpp new file mode 100644 index 000000000..e7bf4abe8 --- /dev/null +++ b/vehicle/crewchange.cpp @@ -0,0 +1,138 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/crewchange.h" + +#include "simulation/simulation.h" +#include "utilities/Logs.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "vehicle/Train.h" +#include "vehicle/handover.h" + +namespace crew { + +namespace { + +// TMoverParameters::CategoryFlag of the rail vehicles +constexpr int rail_category{1}; +// more vehicles than a consist has, for a walk along one whose couplers form a loop +constexpr int consist_walk_limit{300}; + +// calls the function for each vehicle of the consist, from one end of it to the other. goes by the couplers +// alone, as the driver's own check of the consist does, so it works for a consist nobody has put in order +template +void for_each_in_consist(TDynamicObject &Vehicle, Function_ const Function) { + auto side{static_cast(end::front)}; + auto *vehicle{Vehicle.FirstFind(side)}; + side = 1 - side; + auto count{0}; + while (vehicle != nullptr && count < consist_walk_limit) { + Function(*vehicle); + vehicle = vehicle->Neighbour(side); + ++count; + } +} + +// whether another vehicle of the consist has the driver in charge of it +bool is_consist_driven(TDynamicObject &Vehicle) { + auto driven{false}; + for_each_in_consist(Vehicle, [&Vehicle, &driven](TDynamicObject const &Other) { + if (&Other != &Vehicle && Other.Mechanik != nullptr && Other.Mechanik->primary()) { + driven = true; + } + }); + return driven; +} + +vehicle_state state_of(TDynamicObject &Vehicle) { + vehicle_state state; + // a rail vehicle has a cab when it has the driver's brake valve. the others (cars, boats) have no such valve + // to tell by, and each of them is driven from its own seat + state.has_cab = Vehicle.MoverParameters->HasDriverCab() || Vehicle.MoverParameters->CategoryFlag != rail_category; + state.has_driver = Vehicle.Mechanik != nullptr; + state.driver_is_ai = state.has_driver && Vehicle.Mechanik->AIControllFlag; + // a cab of the game is bound to the vehicle: the user's own, or another user's in a network game. the cab + // reads the driver of its vehicle all the time, so that driver stays + state.occupied = simulation::Trains.find(Vehicle.name()) != nullptr; + state.consist_driven = is_consist_driven(Vehicle); + return state; +} + +// an AI driver for the vehicle, as the scenery gives one to a vehicle of its own outside a trainset: in charge of +// the consist, with no timetable, waiting for orders when the vehicle stands and driving on when it rolls +void add_driver(TDynamicObject &Vehicle, int const Cab) { + Vehicle.MoverParameters->CabOccupied = Cab; + Vehicle.Controller = AIdriver; + Vehicle.create_controller(Cab > 0 ? "1" : "2", false); +} + +// takes the AI driver off. nothing but the vehicle and the vehicles the driver is in charge of points at a driver +// (the panels, the events, the network and the black box read it from a vehicle each time), so these are cleared +// and the driver deleted. the vehicles in its charge are looked for among all vehicles, not along the couplers: +// a coupler broken under force or in a collision (TMoverParameters::damage_coupler()) parts the train and leaves +// the vehicles parted from it in the driver's charge, as uncoupling (TDynamicObject::Dettach()) doesn't +void remove_driver(TDynamicObject &Vehicle) { + auto *driver{Vehicle.Mechanik}; + auto &occupied{*Vehicle.MoverParameters}; + auto &controlling{*Vehicle.FindPowered()->MoverParameters}; + if (driver->primary()) { + // the train this driver was in charge of stops and stays braked + secure(occupied, controlling); + } + else { + // somebody else drives the train, so only what this one held is let go + handover::release_ai_controls(occupied, controlling); + occupied.CabOccupied = 0; + } + Vehicle.Mechanik = nullptr; + auto released{0}; + for (auto *other : simulation::Vehicles.sequence()) { + if (other->ctOwner == driver) { + other->ctOwner = nullptr; + ++released; + } + } + WriteLog("Crew: [" + Vehicle.name() + "] the driver was in charge of " + std::to_string(released) + (released == 1 ? " vehicle" : " vehicles")); + delete driver; +} + +} // namespace + +void change(request const &Request, TDynamicObject const *Activator) { + std::string const name{Request.vehicle.empty() && Activator != nullptr ? Activator->name() : Request.vehicle}; + if (name.empty()) { + ErrorLog("Bad event: \"" + std::string{command_prefix} + "\" names no vehicle and no vehicle set the event off"); + return; + } + auto *vehicle{simulation::Vehicles.find(name)}; + if (vehicle == nullptr || false == vehicle->bEnabled) { + ErrorLog("Bad event: \"" + std::string{command_prefix} + name + "\" can't find the vehicle"); + return; + } + if (Request.flags != 0) { + WriteLog("Crew: [" + name + "] flags " + std::to_string(Request.flags) + " ignored, none is defined yet"); + } + auto const decision{decide(Request, state_of(*vehicle))}; + WriteLog("Crew: [" + name + "] " + std::string{describe(decision)}); + switch (decision) { + case action::add_front: + case action::add_rear: + add_driver(*vehicle, Request.cab); + break; + case action::remove: + remove_driver(*vehicle); + break; + default: + break; + } +} + +} // namespace crew diff --git a/vehicle/crewchange.h b/vehicle/crewchange.h new file mode 100644 index 000000000..3b348edaa --- /dev/null +++ b/vehicle/crewchange.h @@ -0,0 +1,24 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include "vehicle/crew.h" + +class TDynamicObject; + +namespace crew { + +// carries out the crew command of an event (see crew.h) on the vehicle it names, or on Activator, the vehicle +// which set the event off, when it names none: puts an AI driver in, the way the scenery does for a vehicle of +// its own with a driver, or takes the AI driver off and leaves the train secured. whatever it does or refuses +// goes to the log. called from the event queue, between the updates of the vehicles +void change(request const &Request, TDynamicObject const *Activator); + +} // namespace crew diff --git a/vehicle/derailmotion.cpp b/vehicle/derailmotion.cpp new file mode 100644 index 000000000..89b9a1831 --- /dev/null +++ b/vehicle/derailmotion.cpp @@ -0,0 +1,907 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/derailmotion.h" + +#include "McZapkie/derailment.h" + +#include +#include +#include +#include + +namespace derail_motion { + +namespace { + +glm::dvec3 const world_up{0.0, 1.0, 0.0}; + +// the vector level, of unit length; the fallback for one standing up +glm::dvec3 level(glm::dvec3 const &Vector, glm::dvec3 const &Fallback = {0.0, 0.0, 1.0}) { + glm::dvec3 const flat{Vector.x, 0.0, Vector.z}; + auto const length{glm::length(flat)}; + return length > 1e-9 ? flat / length : Fallback; +} + +// to the left of a level heading, as TDynamicObject has it: up x front +glm::dvec3 left_of(glm::dvec3 const &Front) { + return glm::dvec3{Front.z, 0.0, -Front.x}; +} + +// the vector turned about the axis by the angle, right-handed +glm::dvec3 turned(glm::dvec3 const &Vector, glm::dvec3 const &Axis, double const Angle) { + auto const c{std::cos(Angle)}; + auto const s{std::sin(Angle)}; + return Vector * c + glm::cross(Axis, Vector) * s + Axis * (glm::dot(Axis, Vector) * (1.0 - c)); +} + +double sign_of(double const Value) { + if (Value > 0.0) { + return 1.0; + } + return Value < 0.0 ? -1.0 : 0.0; +} + +// the height of the triangle over the point, if it is over it (in the plan) +std::optional height_in(mesh_ground::triangle const &Triangle, double const X, double const Z) { + auto const &a{Triangle[0]}; + auto const &b{Triangle[1]}; + auto const &c{Triangle[2]}; + auto const determinant{(b.z - c.z) * (a.x - c.x) + (c.x - b.x) * (a.z - c.z)}; + if (std::abs(determinant) < 1e-12) { + // standing on its edge, a wall + return std::nullopt; + } + auto const u{((b.z - c.z) * (X - c.x) + (c.x - b.x) * (Z - c.z)) / determinant}; + auto const v{((c.z - a.z) * (X - c.x) + (a.x - c.x) * (Z - c.z)) / determinant}; + auto const w{1.0 - u - v}; + constexpr double edge{-1e-9}; + if (u < edge || v < edge || w < edge) { + return std::nullopt; + } + return u * a.y + v * b.y + w * c.y; +} + +} // namespace + +namespace { + +// the angle [rad] from the first level direction to the second, to the left positive +double angle_between(glm::dvec3 const &From, glm::dvec3 const &To) { + return std::atan2(glm::dot(To, left_of(From)), glm::dot(To, From)); +} + +// the beams of two ends further apart across than this have gone past each other [m] +constexpr double beam_reach{2.0}; +// nor do they meet pressed into each other deeper than this: the buffers and the ends behind them crushed [m] +constexpr double beam_depth{1.5}; +// the buffers of two ends this far apart along the line between them are apart, the coupling straight between [m] +constexpr double buffer_reach{0.1}; + +} // namespace + +double sliding_friction(double const Tipping, bool const Guided) { + if (Guided) { + return guided_friction; + } + auto const share{std::clamp(std::abs(Tipping) / body::half_turn, 0.0, 1.0)}; + return std::lerp(derailment::off_rails_friction, derailment::overturned_friction, share); +} + +double departure_angle(cause const Cause, double const Speed, double const Acceleration) { + if (Cause == cause::end_of_track || Cause == cause::collision) { + return 0.0; + } + auto const sideways{std::sqrt(2.0 * std::abs(Acceleration) * climb_width)}; + return std::min(most_departure, std::atan2(sideways, std::max(std::abs(Speed), 1.0))); +} + +scatter draw_scatter(std::uint32_t const Seed) { + // the raw numbers of the engine are the same with every library, the distributions of aren't + std::mt19937 engine{Seed}; // NOSONAR: seeded on purpose, so that a derailment can be repeated; nothing secret is drawn + auto const uniform = [&engine](double const Low, double const High) { return Low + (High - Low) * ((static_cast(engine()) + 0.5) / 4294967296.0); }; + scatter result; + result.departure = uniform(-0.01, 0.01); + result.yaw = uniform(-0.02, 0.02); + result.yaw_rate = uniform(-0.02, 0.02); + result.friction_front = uniform(0.85, 1.15); + result.friction_rear = uniform(0.85, 1.15); + auto const bites{uniform(0.0, 1.0) < 2.0 / 3.0}; + auto const when{uniform(0.2, 1.5)}; + auto const howlong{uniform(0.3, 0.8)}; + auto const how{uniform(2.0, 4.0)}; + auto const side{uniform(0.0, 1.0) < 0.5 ? -1 : 1}; + if (bites) { + result.dig_in = when; + result.dig_in_time = howlong; + result.dig_in_friction = how; + result.dig_in_side = side; + } + return result; +} + +std::uint32_t seed_of(std::uint32_t const Run, std::string_view const Name) { + // FNV-1a of the name, mixed with the seed of the run + std::uint32_t hash{2166136261u}; + for (auto const character : Name) { + hash = (hash ^ static_cast(character)) * 16777619u; + } + hash ^= Run + 0x9e3779b9u + (hash << 6) + (hash >> 2); + return hash; +} + +meeting meet(end_point const &First, end_point const &Second) { + meeting result; + auto const outward{level(First.outward)}; + auto const otherward{level(Second.outward, -outward)}; + result.point = First.point; + result.push = level(outward - otherward, outward); + result.bend = angle_between(outward, -otherward); + glm::dvec3 const apart{Second.point.x - First.point.x, 0.0, Second.point.z - First.point.z}; + auto const along{glm::dot(apart, result.push)}; + auto const across{glm::dot(apart, left_of(result.push))}; + auto const distance{glm::length(apart)}; + result.pull = distance > 0.05 ? apart / distance : result.push; + // the ends face each other (bent by less than a right angle) and meet within the depth of the buffers and the ends + // crushed behind them + auto const facing{glm::dot(outward, otherward) < 0.0}; + if (along <= 0.0 && facing && along > -beam_depth && std::abs(across) < beam_reach) { + // the buffers press into each other + result.gap = along; + } + else if (along <= 0.0) { + // the ends went past each other, or one body turned about: only the coupling holds them, stretched + result.gap = distance; + } + else { + // apart, the coupling between the middles of the beams; as they come together, the buffers in line + result.gap = std::hypot(along, across) - std::abs(across) * std::max(0.0, 1.0 - along / buffer_reach); + } + // the buffers of the outer side of a body rolled against the other one lift or drop by its roll + auto const apartinheight{std::abs(Second.point.y - First.point.y) + buffer_half_spacing * std::abs(std::sin(Second.roll - First.roll))}; + result.overlap = std::clamp(1.0 - apartinheight / buffer_head, 0.0, 1.0); + return result; +} + +end_force force_on(meeting const &Meeting, double const Compression) { + end_force result; + result.point = Meeting.point; + if (Compression > 0.0) { + // the inner buffer of the bend takes more of the push, all of it past the play of the buffers; as far as the + // buffers meet in height, and as much of it as a buffer takes, the rest at the middle of the beam + auto const holding{buffer_half_spacing * Meeting.overlap * std::min(1.0, buffer_limit / Compression)}; + result.point += left_of(Meeting.push) * (holding * std::clamp(Meeting.bend / buffer_lock, -1.0, 1.0)); + result.force = -Meeting.push * Compression; + } + else { + result.force = Meeting.pull * (-Compression); + } + return result; +} + +footprint footprint_of(pose const &Pose, double const Length, double const Width, double const Height) { + footprint result; + result.axis = level(Pose.front); + auto const left{left_of(result.axis)}; + result.half_length = std::max(0.5 * Length - buffer_length, 0.5) * std::max(std::hypot(Pose.front.x, Pose.front.z), 0.1); + // the corners of its cross section, from the rails to the roof, as it is rolled + auto low{std::numeric_limits::max()}; + auto high{std::numeric_limits::lowest()}; + auto mostleft{std::numeric_limits::lowest()}; + auto mostright{std::numeric_limits::max()}; + for (auto const across : {-0.5 * Width, 0.5 * Width}) { + for (auto const up : {0.0, Height}) { + auto const corner{Pose.position + Pose.left * across + Pose.up * up}; + auto const aside{glm::dot(corner - Pose.position, left)}; + mostleft = std::max(mostleft, aside); + mostright = std::min(mostright, aside); + low = std::min(low, corner.y); + high = std::max(high, corner.y); + } + } + result.half_width = 0.5 * (mostleft - mostright); + result.centre = glm::dvec3{Pose.position.x, 0.0, Pose.position.z} + left * (0.5 * (mostleft + mostright)); + // pitched, the ends rise and drop by the slope over half its length + auto const rise{std::abs(Pose.front.y) / std::max(std::hypot(Pose.front.x, Pose.front.z), 0.1) * result.half_length}; + result.low = low - rise; + result.high = high + rise; + return result; +} + +namespace { + +// the corners of the footprint, in turn round it +std::array corners_of(footprint const &Print) { + auto const along{Print.axis * Print.half_length}; + auto const across{left_of(Print.axis) * Print.half_width}; + return {Print.centre + along + across, Print.centre + along - across, Print.centre - along - across, Print.centre - along + across}; +} + +// whether the point is inside the footprint (in the plan) +bool inside(footprint const &Print, glm::dvec3 const &Point) { + glm::dvec3 const offset{Point.x - Print.centre.x, 0.0, Point.z - Print.centre.z}; + return std::abs(glm::dot(offset, Print.axis)) <= Print.half_length && std::abs(glm::dot(offset, left_of(Print.axis))) <= Print.half_width; +} + +double cross_up(glm::dvec3 const &Arm, glm::dvec3 const &Force) { + // about the vertical, to the left positive + return Arm.z * Force.x - Arm.x * Force.z; +} + +// the inverse of the mass the body moves with at the point the way of the direction +double inverse_mass(contact_body const &Body, glm::dvec3 const &Point, glm::dvec3 const &Direction) { + if (Body.mass <= 0.0) { + return 0.0; + } + if (Body.guided) { + auto const along{glm::dot(Direction, Body.guide)}; + return along * along / Body.mass; + } + glm::dvec3 const arm{Point.x - Body.base.x, 0.0, Point.z - Body.base.z}; + auto const turning{cross_up(arm, Direction)}; + return (1.0 + turning * turning / std::max(Body.gyration, 1e-3)) / Body.mass; +} + +} // namespace + +std::optional collide(footprint const &First, footprint const &Second) { + if (std::min(First.high, Second.high) - std::max(First.low, Second.low) < height_overlap) { + // one goes over the other + return std::nullopt; + } + // the separating axes: the sides of both rectangles; the one they overlap least across is the way out + auto const first{corners_of(First)}; + auto const second{corners_of(Second)}; + glm::dvec3 const apart{Second.centre.x - First.centre.x, 0.0, Second.centre.z - First.centre.z}; + contact result; + result.depth = std::numeric_limits::max(); + for (auto const &axis : {First.axis, left_of(First.axis), Second.axis, left_of(Second.axis)}) { + auto spread = [&axis](std::array const &Corners) { + auto low{std::numeric_limits::max()}; + auto high{std::numeric_limits::lowest()}; + for (auto const &corner : Corners) { + auto const along{glm::dot(corner, axis)}; + low = std::min(low, along); + high = std::max(high, along); + } + return std::pair{low, high}; + }; + auto const [low1, high1]{spread(first)}; + auto const [low2, high2]{spread(second)}; + auto const overlap{std::min(high1, high2) - std::max(low1, low2)}; + if (overlap <= 0.0) { + return std::nullopt; + } + if (overlap < result.depth) { + result.depth = overlap; + result.normal = glm::dot(apart, axis) >= 0.0 ? axis : -axis; + } + } + // the point: the middle of the corners of each inside the other, or of where the overlap is + glm::dvec3 sum{0.0}; + auto count{0}; + for (auto const &corner : first) { + if (inside(Second, corner)) { + sum += corner; + ++count; + } + } + for (auto const &corner : second) { + if (inside(First, corner)) { + sum += corner; + ++count; + } + } + if (count > 0) { + result.point = sum / static_cast(count); + } + else { + // crossed without a corner inside the other (two long sides across each other): between the middles + result.point = 0.5 * (First.centre + Second.centre); + } + result.point.y = 0.0; + return result; +} + +glm::dvec3 velocity_at(contact_body const &Body, glm::dvec3 const &Point) { + if (Body.guided) { + return Body.velocity; + } + // turning about the vertical at the yaw rate: up x arm + glm::dvec3 const arm{Point.x - Body.base.x, 0.0, Point.z - Body.base.z}; + return Body.velocity + Body.yaw_rate * glm::dvec3{arm.z, 0.0, -arm.x}; +} + +glm::dvec3 contact_impulse(contact const &Contact, contact_body const &First, contact_body const &Second) { + auto const &normal{Contact.normal}; + auto const relative{velocity_at(Second, Contact.point) - velocity_at(First, Contact.point)}; + auto const closing{glm::dot(relative, normal)}; + if (closing >= 0.0) { + // parting already + return glm::dvec3{0.0}; + } + auto const inverse{inverse_mass(First, Contact.point, normal) + inverse_mass(Second, Contact.point, normal)}; + if (inverse <= 0.0) { + return glm::dvec3{0.0}; + } + auto const push{-(1.0 + contact_restitution) * closing / inverse}; + glm::dvec3 result{normal * push}; + // the friction of the sides sliding along each other, no more than stops the sliding + auto const sliding{relative - normal * closing}; + auto const slide{glm::length(sliding)}; + if (slide > 1e-6) { + auto const along{sliding / slide}; + auto const alonginverse{inverse_mass(First, Contact.point, along) + inverse_mass(Second, Contact.point, along)}; + if (alonginverse > 0.0) { + result -= along * std::min(contact_friction * push, slide / alonginverse); + } + } + return result; +} + +std::pair impulse_change(contact_body const &Body, glm::dvec3 const &Impulse, glm::dvec3 const &Point) { + if (Body.mass <= 0.0) { + return {glm::dvec3{0.0}, 0.0}; + } + if (Body.guided) { + return {Body.guide * (glm::dot(Impulse, Body.guide) / Body.mass), 0.0}; + } + glm::dvec3 const arm{Point.x - Body.base.x, 0.0, Point.z - Body.base.z}; + return {glm::dvec3{Impulse.x, 0.0, Impulse.z} / Body.mass, cross_up(arm, Impulse) / (Body.mass * std::max(Body.gyration, 1e-3))}; +} + +std::optional stopping_distance(double const Speed, double const Friction, double const Grade) { + auto const angle{std::atan(Grade)}; + auto const deceleration{gravity * (Friction * std::cos(angle) + std::sin(angle))}; + if (deceleration <= 0.0) { + return std::nullopt; + } + return Speed * Speed / (2.0 * deceleration); +} + +double pull_ratio(double const Force, double const Angle, double const Mass, int const Axles) { + auto const axles{std::max(Axles, 2)}; + auto const load{Mass * gravity / (2.0 * axles)}; + if (load <= 0.0) { + return 0.0; + } + auto const across{std::abs(Force * std::sin(Angle))}; + return across / (0.5 * axles) / load; +} + +// ---- the ground + +std::optional flat_ground::height(double, double, double) const { + return m_level; +} + +mesh_ground::mesh_ground(std::vector const &Triangles, glm::dvec2 const &Min, glm::dvec2 const &Max, double const Cell) : m_min{Min}, m_max{glm::max(Max, Min + glm::dvec2{1.0})}, m_cell{std::max(Cell, 1.0)} { + auto const size{m_max - m_min}; + // a million cells at most + m_cell = std::max(m_cell, std::sqrt(size.x * size.y / 1e6)); + m_columns = static_cast(std::ceil(size.x / m_cell)); + m_rows = static_cast(std::ceil(size.y / m_cell)); + m_cells.resize(m_columns * m_rows); + auto const column = [this](double const X) { return static_cast(std::clamp(std::floor((X - m_min.x) / m_cell), 0.0, static_cast(m_columns - 1))); }; + auto const row = [this](double const Z) { return static_cast(std::clamp(std::floor((Z - m_min.y) / m_cell), 0.0, static_cast(m_rows - 1))); }; + for (auto const &triangle : Triangles) { + auto const low{glm::min(glm::min(triangle[0], triangle[1]), triangle[2])}; + auto const high{glm::max(glm::max(triangle[0], triangle[1]), triangle[2])}; + if (high.x < m_min.x || low.x > m_max.x || high.z < m_min.y || low.z > m_max.y) { + continue; + } + auto const index{m_triangles.size()}; + m_triangles.push_back(triangle); + for (auto r = row(low.z); r <= row(high.z); ++r) { + for (auto c = column(low.x); c <= column(high.x); ++c) { + m_cells[r * m_columns + c].push_back(index); + } + } + } +} + +bool mesh_ground::covers(double const X, double const Z) const { + return X >= m_min.x && X <= m_max.x && Z >= m_min.y && Z <= m_max.y; +} + +bool mesh_ground::covers(glm::dvec2 const &Min, glm::dvec2 const &Max) const { + return Min.x >= m_min.x && Min.y >= m_min.y && Max.x <= m_max.x && Max.y <= m_max.y; +} + +mesh_ground mesh_ground::cropped(glm::dvec2 const &Min, glm::dvec2 const &Max) const { + return mesh_ground{m_triangles, Min, Max, m_cell}; +} + +std::optional mesh_ground::cell_of(double const X, double const Z) const { + if (false == covers(X, Z) || m_cells.empty()) { + return std::nullopt; + } + auto const column{std::min(static_cast((X - m_min.x) / m_cell), m_columns - 1)}; + auto const row{std::min(static_cast((Z - m_min.y) / m_cell), m_rows - 1)}; + return row * m_columns + column; +} + +std::optional mesh_ground::height(double const X, double const Z, double const Ceiling) const { + auto const cell{cell_of(X, Z)}; + if (false == cell.has_value()) { + return std::nullopt; + } + std::optional highest; + for (auto const index : m_cells[*cell]) { + auto const found{height_in(m_triangles[index], X, Z)}; + if (found.has_value() && *found <= Ceiling && (false == highest.has_value() || *found > *highest)) { + highest = found; + } + } + return highest; +} + +double formation::height(double const X, double const Z) const { + auto const across{std::abs(glm::dot(glm::dvec3{X, 0.0, Z} - glm::dvec3{point.x, 0.0, point.z}, left_of(level(direction))))}; + auto const top{point.y - depth}; + if (across <= half_width) { + return top; + } + return top - (across - half_width) / std::max(slope, 0.1); +} + +std::optional site::height(double const X, double const Z, double const Ceiling) const { + auto const bed{m_bed.height(X, Z)}; + std::optional result; + if (m_terrain == nullptr) { + // no terrain: level with the top of the ballast + result = m_bed.point.y - m_bed.depth; + } + else { + result = m_terrain->height(X, Z, Ceiling); + } + if (bed <= Ceiling && (false == result.has_value() || bed > *result)) { + result = bed; + } + return result; +} + +// ---- the vehicle + +void body::begin(start const &Start, vehicle_shape const &Shape, ground const &Ground, scatter const &Scatter) { + *this = body{}; + m_active = true; + m_reason = Start.reason; + m_shape = Shape; + m_scatter = Scatter; + // the body a box turning about its middle + m_yawgyration = std::max((Shape.length * Shape.length + Shape.width * Shape.width) / 12.0, 1.0); + + m_pivot = 0.5 * std::max(Shape.contact_spacing, 0.5); + auto const centre{std::max(Shape.centre_of_gravity, 0.3)}; + m_lever = centre + Shape.flexibility * std::max(0.0, centre - Shape.roll_centre); + m_tipangle = std::atan2(m_pivot, m_lever); + m_reach = std::hypot(m_pivot, m_lever); + // the body a box rolling about its middle, carried over to the wheels it tips about + m_gyration = m_reach * m_reach + (Shape.width * Shape.width + Shape.height * Shape.height) / 12.0; + + m_position = Start.position; + m_origin = Start.position; + m_front = level(Start.front); + m_line = level(Start.line, m_front); + m_speed = Start.speed; + // out of the curve, the way it travels + auto const direction{Start.speed < 0.0 ? -1.0 : 1.0}; + auto turn{Start.outward * direction * departure_angle(Start.reason, Start.speed, Start.acceleration)}; + if (Start.reason != cause::end_of_track && Start.reason != cause::collision) { + turn += Scatter.departure; + } + m_front = level(turned(m_front, world_up, turn), m_front); + m_axis = level(turned(m_front, world_up, Scatter.yaw), m_front); + + if (Start.reason == cause::overturned) { + m_guided = true; + m_outward = Start.outward != 0 ? Start.outward : 1; + m_guideacceleration = std::abs(Start.acceleration); + m_guidespeed = std::max(std::abs(Start.speed), 0.1); + } + else { + m_yawrate = Scatter.yaw_rate; + } + auto const foot{find_footing(Ground)}; + m_pitch = foot.grade; + m_grade = foot.grade; + m_cross = foot.cross; + place(); +} + +void body::step(double const Dt, double const Distance, double const Speed, ground const &Ground, std::array const &Ends) { + if (false == m_active || Dt <= 0.0) { + return; + } + // where the forces of the couplings act on the body, which turns under them through the step + for (std::size_t end = 0; end < Ends.size(); ++end) { + glm::dvec3 const arm{Ends[end].point.x - m_position.x, 0.0, Ends[end].point.z - m_position.z}; + m_ends[end].force = glm::dvec3{Ends[end].force.x, 0.0, Ends[end].force.z}; + m_ends[end].along = glm::dot(arm, m_axis); + m_ends[end].across = glm::dot(arm, left_of_heading()); + } + auto const steps{std::max(1, static_cast(std::ceil(Dt / substep - 1e-9)))}; + auto const dt{Dt / steps}; + auto const startspeed{m_speed}; + // the heading turned about within the step goes the other way along with the rest of the step + auto direction{1.0}; + for (int index = 1; index <= steps; ++index) { + auto const speed{std::lerp(startspeed, direction * Speed, static_cast(index) / steps)}; + auto const reversals{m_reversals}; + advance(dt, direction * Distance / steps, speed, Ground); + if (m_reversals != reversals) { + direction = -direction; + } + } + m_speed = direction * Speed; + place(); +} + +void body::advance(double const Dt, double const Distance, double const Speed, ground const &Ground) { + m_position += m_front * Distance + left_of_heading() * (m_lateral * Dt); + m_travelled += std::hypot(Distance, m_lateral * Dt); + m_time += Dt; + auto const foot{find_footing(Ground)}; + m_pitch = foot.grade; + // along the way it goes: of the slope along the body and across it + m_grade = foot.grade * glm::dot(m_front, m_axis) + foot.cross * glm::dot(m_front, left_of_heading()); + m_cross = foot.cross; + fall(Dt, foot.level, std::hypot(Distance, m_lateral * Dt)); + slide(Dt, foot.cross); + tip(Dt, foot.cross, Speed); + turn(Dt, Speed); + if (m_guided) { + m_guidetime += Dt; + if (m_tipping >= m_tipangle || std::abs(Speed) < 0.5 || m_guidetime > guidance_time) { + m_guided = false; + } + } +} + +body::footing body::find_footing(ground const &Ground) const { + auto const left{left_of_heading()}; + // a step up under the middle, and as much more under a support away from it as a slope of 2 in 1 rises: what is + // higher is over the vehicle, not under it (a bridge, a roof), and the ground under the slope of a bank isn't the + // ground the support stands on + constexpr double steepest{2.0}; + auto const sample = [&Ground, this](glm::dvec3 const &Point) { + auto const reach{std::hypot(Point.x - m_position.x, Point.z - m_position.z)}; + return Ground.height(Point.x, Point.z, m_position.y + step_up + steepest * reach).value_or(m_position.y); + }; + auto const ahead{m_axis * (0.5 * std::max(m_shape.base, 1.0))}; + // upright it stands on its wheels; tipping over, it comes to rest on the side of its body, which reaches out + // from the wheels it tips about as far as the body is high + auto const lean{std::sin(m_tipping)}; + auto const middle{left * (m_side * lean * 0.5 * m_shape.height)}; + auto const span{m_pivot + lean * std::max(0.0, 0.5 * m_shape.height - m_pivot)}; + auto const aside{left * span}; + auto const frontleft{sample(m_position + middle + ahead + aside)}; + auto const frontright{sample(m_position + middle + ahead - aside)}; + auto const rearleft{sample(m_position + middle - ahead + aside)}; + auto const rearright{sample(m_position + middle - ahead - aside)}; + footing result; + result.level = std::max(0.25 * (frontleft + frontright + rearleft + rearright), sample(m_position)); + // a step under one support is no slope steeper than 2 in 1 + result.grade = std::clamp((frontleft + frontright - rearleft - rearright) / (2.0 * std::max(m_shape.base, 1.0)), -steepest, steepest); + result.cross = std::clamp((frontleft + rearleft - frontright - rearright) / (4.0 * span), -steepest, steepest); + return result; +} + +void body::fall(double const Dt, double const Level, double const Travel) { + // on the ground it follows it down a slope as steep as 1:1.5; off a steeper drop it falls + constexpr double follows{1.0 / 1.5}; + if (m_grounded && m_position.y - Level <= std::max(0.02, follows * Travel)) { + m_position.y = Level; + return; + } + m_fallspeed -= gravity * Dt; + auto const height{m_position.y + m_fallspeed * Dt}; + m_grounded = (height <= Level); + if (m_grounded) { + m_position.y = Level; + m_fallspeed = 0.0; + } + else { + m_position.y = height; + } +} + +void body::slide(double const Dt, double const Cross) { + if (false == m_grounded) { + // in the air nothing holds it, nor pushes it + return; + } + auto const angle{std::atan(Cross)}; + // down the slope, to the left positive; held by the friction of its weight on the slope + m_lateral -= gravity * std::sin(angle) * Dt; + auto const held{lateral_friction * gravity * std::cos(angle) * Dt}; + if (std::abs(m_lateral) <= held) { + m_lateral = 0.0; + } + else { + m_lateral -= sign_of(m_lateral) * held; + } +} + +double body::lateral_load(double const Cross, double const Speed) const { + auto const angle{std::atan(Cross)}; + auto load{0.0}; + if (m_grounded) { + if (m_lateral != 0.0) { + // sliding across, the friction under its wheels or its side trips it the way it slides + load = sign_of(m_lateral) * lateral_friction * gravity * std::cos(angle); + } + else { + // standing on the slope, the weight pulls it down the slope, the friction holds its feet + load = -gravity * std::sin(angle); + } + // going askew, the friction across it trips it too + load += m_trip; + } + if (m_guided) { + auto const share{Speed / m_guidespeed}; + load += m_outward * m_guideacceleration * share * share; + } + return load; +} + +void body::tip(double const Dt, double const Cross, double const Speed) { + if (lying()) { + return; + } + auto const normal{gravity * std::cos(std::atan(Cross))}; + auto const load{lateral_load(Cross, Speed)}; + if (m_side == 0) { + // upright: it starts to tip once the load lifts the wheels of the other side + if (std::abs(load) * std::cos(m_tipangle) - normal * std::sin(m_tipangle) <= 0.0) { + return; + } + m_side = load > 0.0 ? 1 : -1; + } + auto const angle{m_tipping - m_tipangle}; + auto const acceleration{m_reach / m_gyration * (m_side * load * std::cos(angle) + normal * std::sin(angle))}; + m_tiprate += acceleration * Dt; + m_tipping += m_tiprate * Dt; + if (m_tipping <= 0.0) { + // back on its wheels + m_tipping = 0.0; + m_tiprate = 0.0; + m_side = 0; + } + else if (m_tipping >= half_turn) { + // on its side, where it stays + m_tipping = half_turn; + m_tiprate = 0.0; + } +} + +glm::dvec3 body::left_of_heading() const { + return left_of(m_axis); +} + +double body::friction_along() const { + return sliding_friction(m_tipping, m_guided); +} + +double body::friction_across() const { + return m_guided ? guided_friction : std::max(lateral_friction, friction_along()); +} + +double body::friction_share(bool const Front) const { + return Front ? m_scatter.friction_front : m_scatter.friction_rear; +} + +int body::biting() const { + if (m_scatter.dig_in < 0.0 || m_guided || false == m_grounded || m_time < m_scatter.dig_in || m_time >= m_scatter.dig_in + m_scatter.dig_in_time) { + return 0; + } + // the end it goes towards + auto const going{m_speed < 0.0 ? -m_front : m_front}; + return glm::dot(going, m_axis) >= 0.0 ? 1 : -1; +} + +double body::friction() const { + auto const along{glm::dot(m_front, m_axis)}; + auto const across{1.0 - along * along}; + auto result{0.5 * (friction_share(true) + friction_share(false)) * (friction_along() * along * along + friction_across() * across)}; + if (biting() != 0) { + // under half of its weight + result += 0.5 * (m_scatter.dig_in_friction - 1.0) * friction_along(); + } + return result; +} + +glm::dvec3 body::velocity() const { + return m_front * m_speed + left_of_heading() * m_lateral; +} + +void body::kick(glm::dvec3 const &Velocity, double const YawRate) { + if (false == m_active) { + return; + } + auto const moving{m_front * m_speed + glm::dvec3{Velocity.x, 0.0, Velocity.z}}; + auto const speed{glm::length(moving)}; + if (speed > 1e-6) { + m_front = moving / speed; + m_speed = speed; + if (glm::dot(m_front, m_axis) < 0.0) { + // it goes rear first + m_front = -m_front; + m_speed = -m_speed; + ++m_reversals; + } + } + else { + m_speed = 0.0; + } + m_yawrate = std::clamp(m_yawrate + YawRate, -most_yaw_rate, most_yaw_rate); +} + +void body::nudge(glm::dvec3 const &Offset) { + if (false == m_active) { + return; + } + m_position += glm::dvec3{Offset.x, 0.0, Offset.z}; + place(); +} + +double body::yaw() const { + return angle_between(m_line, m_axis); +} + +body::drag body::friction_under(double const Speed, double const Yawrate) const { + drag result; + if (false == m_grounded) { + // nothing holds it in the air + return result; + } + auto const left{left_of_heading()}; + auto const along{friction_along()}; + auto const across{friction_across()}; + // upright it stands on its bogies (the ends of its base), on its side it lies along all of its length + auto const share{std::clamp(m_tipping / half_turn, 0.0, 1.0)}; + auto const base{std::max(m_shape.base, 1.0)}; + auto const span{std::max(m_shape.length, base)}; + auto const velocity{m_front * Speed}; + auto const point = [&](double const Along, double const Across, double const Weight) { + // the friction under a point of the body: against the way it slides there, along the body and across it as each + // holds; slower than the creep, as much as it slides + auto const motion{velocity + left * (Yawrate * Along) - m_axis * (Yawrate * Across)}; + auto const speed{std::max(glm::length(motion), creep_speed)}; + auto const force{-(gravity * Weight) * (along * glm::dot(motion, m_axis) * m_axis + across * glm::dot(motion, left) * left) / speed}; + result.force += force; + // about the vertical, to the left positive + result.moment += Along * glm::dot(force, left) - Across * glm::dot(force, m_axis); + }; + if (share < 1.0) { + for (auto const end : {1.0, -1.0}) { + point(end * 0.5 * base, 0.0, (1.0 - share) * 0.5 * friction_share(end > 0.0)); + } + } + if (share > 0.0) { + for (int index = 0; index < friction_points; ++index) { + auto const along_body{span * ((index + 0.5) / friction_points - 0.5)}; + point(along_body, 0.0, share * friction_share(along_body > 0.0) / friction_points); + } + } + if (auto const end{biting()}; end != 0) { + // the leading end bites into the ballast at one of its wheels, under half of its weight; on its side, at a corner + // of its body + point(end * 0.5 * std::lerp(base, 0.5 * span, share), m_scatter.dig_in_side * std::lerp(m_pivot, 0.5 * m_shape.height, share), 0.5 * (m_scatter.dig_in_friction - 1.0)); + } + // the way it slides across, the friction trips it + result.trip = -glm::dot(result.force, left); + return result; +} + +void body::turn(double const Dt, double const Speed) { + // the forces of the couplings, per the mass + auto const left{left_of_heading()}; + auto moment{0.0}; + glm::dvec3 push{0.0}; + if (m_shape.mass > 0.0) { + for (auto const &end : m_ends) { + auto const arm{m_axis * end.along + left * end.across}; + moment += (arm.z * end.force.x - arm.x * end.force.z) / m_shape.mass; + push += end.force / m_shape.mass; + } + } + if (m_guided) { + // on its outer wheels on the rail it goes along the rail + m_yawrate = 0.0; + m_trip = 0.0; + return; + } + // the body: the couplings turn it, and the friction under it where it differs between the ends of a body going + // askew; the friction holds it against turning, never turning it back the other way + auto const driving{friction_under(Speed, 0.0).moment}; + auto rate{m_yawrate + (moment + driving) / m_yawgyration * Dt}; + auto const change{(friction_under(Speed, rate).moment - driving) / m_yawgyration * Dt}; + rate = ((rate + change) * rate <= 0.0 ? 0.0 : rate + change); + if (std::abs(Speed) < creep_speed && m_lateral == 0.0 && std::abs(rate) < 0.01 && m_grounded) { + // at a standstill it doesn't turn as long as the friction under it holds against the couplings + // on its bogies at half the base from the middle, lying along the length a quarter of it on average + auto const share{std::clamp(m_tipping / half_turn, 0.0, 1.0)}; + auto const arm{std::lerp(0.5 * std::max(m_shape.base, 1.0), 0.25 * std::max(m_shape.length, m_shape.base), share)}; + if (std::abs(moment) <= gravity * friction_across() * arm) { + rate = 0.0; + } + } + m_yawrate = std::clamp(rate, -most_yaw_rate, most_yaw_rate); + m_axis = level(turned(m_axis, world_up, m_yawrate * Dt), m_axis); + + // the way it travels: the friction of the body going askew turns it towards the body (no further), the couplings + // pushing across it turn it their way; the faster it goes, the less + auto const drag{friction_under(Speed, m_yawrate)}; + m_trip = drag.trip; + if (m_grounded && std::abs(Speed) >= turning_speed) { + auto const across{left_of(m_front)}; + auto const off{angle_between(m_front, glm::dot(m_front, m_axis) >= 0.0 ? m_axis : -m_axis)}; + auto byfriction{glm::dot(drag.force, across) * Dt / Speed}; + byfriction = (byfriction * off <= 0.0 ? 0.0 : sign_of(off) * std::min(std::abs(byfriction), std::abs(off))); + auto const bypush{glm::dot(push, across) * Dt / Speed}; + auto const turning{std::clamp(byfriction + bypush, -most_yaw_rate * Dt, most_yaw_rate * Dt)}; + m_front = level(turned(m_front, world_up, turning), m_front); + } + if (glm::dot(m_front, m_axis) < 0.0) { + // the body turned past a right angle off the way it goes: it goes rear first, the heading the other way + m_front = -m_front; + m_speed = -m_speed; + ++m_reversals; + } +} + +double body::roll() const { + // the ground rising to the left leans it to the right + return tipping() - std::atan(m_cross); +} + +double body::along() const { + return glm::dot(m_position - m_origin, m_line); +} + +double body::across() const { + return glm::dot(m_position - m_origin, left_of(m_line)); +} + +bool body::at_rest() const { + return m_active && m_grounded && std::abs(m_speed) < 0.01 && m_lateral == 0.0 && m_tiprate == 0.0 && m_yawrate == 0.0 && false == m_guided; +} + +void body::place() { + // the plane of the ground under the supports + auto const front{glm::normalize(m_axis + world_up * m_pitch)}; + auto const flatleft{glm::normalize(left_of_heading() + world_up * m_cross)}; + auto const up{glm::normalize(glm::cross(front, flatleft))}; + auto const left{glm::cross(up, front)}; + // tipped about the wheels of its side: turned about the front, the up going over to that side + auto const angle{-m_side * m_tipping}; + auto const pivot{m_position + left * (m_side * m_pivot)}; + auto origin{pivot + turned(m_position - pivot, front, angle)}; + auto const tippedleft{turned(left, front, angle)}; + auto const tippedup{turned(up, front, angle)}; + // the body doesn't go into the ground: the lowest of the edges of its box on it, from the rails to its roof + auto lowest{std::numeric_limits::max()}; + for (auto const across : {-0.5 * m_shape.width, 0.5 * m_shape.width}) { + for (auto const height : {0.0, m_shape.height}) { + lowest = std::min(lowest, glm::dot(origin + tippedleft * across + tippedup * height - m_position, up)); + } + } + if (lowest < 0.0) { + origin -= up * lowest; + } + m_pose.position = origin; + m_pose.front = front; + m_pose.left = tippedleft; + m_pose.up = tippedup; +} + +} // namespace derail_motion diff --git a/vehicle/derailmotion.h b/vehicle/derailmotion.h new file mode 100644 index 000000000..8513e7e13 --- /dev/null +++ b/vehicle/derailmotion.h @@ -0,0 +1,496 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include + +// a rail vehicle off the rails (physics.derailment new, see McZapkie/derailment.h for when it derails): from then on +// it doesn't follow the track any more, it moves on the ground by itself until the friction stops it. +// +// along: the longitudinal motion stays with the physics of the vehicle (TMoverParameters), which brakes it with the +// friction() of this one, takes the grade() under it and passes the forces of the couplings on; each step gives +// the distance travelled along the heading of the vehicle +// the heading: the way it travels; the one the vehicle had when it derailed, turned out of the curve by the sideways +// speed it left the rail with: none off the end of the track, the speed of the flange climbing over the rail head +// (or of the wheels lifting over it) otherwise. so in a curve it leaves the track to its outside, on a buckle +// towards the bulge. from then on the friction of a body sliding askew (more across it than along it) and the +// sideways part of the forces of its couplings turn it, little at speed +// the yaw: the body turns about its vertical axis by itself, apart from the way it travels: the forces of the +// couplings at its ends (the push of the buffers of two bodies at an angle to each other, off the middle of the +// buffer beam) turn it, the friction of the ground under the length of it holds it. pushed from behind, a train +// of bodies off the track folds up into a zigzag once the bends between them are past what the buffers hold +// sideways: the vehicle slides across its heading only where the ground slopes across it more than the friction +// holds, down an embankment say +// the height and the attitude: the ground under the supports of the vehicle (the ends of its wheelbase, the wheels +// of both sides) gives its height, its pitch and its roll; it doesn't sink into the ground, it falls off a step +// tipping over: about the wheels of one side, the body as a rigid one with the lean of its suspension, so it tips at +// the very lateral acceleration the wheel unloading of McZapkie/derailment.h reaches 1 at. what tips it: the +// overturning in the curve while its outer wheels still run on the rail (the curve keeps pushing it out as v^2/R, +// the excess over the limit the faster it tips), the slope of the ground across it, and the friction under it +// while it slides sideways. once over its tipping angle it falls on its side, at 90 degrees, and stays there +// +// the steps are cut to 0.01 s inside, so the result doesn't depend on the step of the simulation +namespace derail_motion { + +inline constexpr double gravity{9.81}; // [m/s2] +// the longest step of the motion [s] +inline constexpr double substep{0.01}; + +// what put the vehicle off the rails, for the way it leaves the track +enum class cause { + off_rails, // the flange climbed the rail + overturned, // the vehicle fell over out of the curve + end_of_track, // it ran off the end of the track: straight on + pulled_off, // the coupling of a vehicle off the track pulled it off sideways + collision // overriding, or pushed off the track in a collision: straight on +}; + +// ---- the friction [-] + +// of a vehicle tipping over on its outer wheels, which still roll on the outer rail +inline constexpr double guided_friction{0.1}; +// of the wheels, or of the body on its side, sliding across the heading +inline constexpr double lateral_friction{0.5}; +// the friction along the heading: upright on its wheels on the sleepers and the ballast, rising to the friction of a +// vehicle on its side (McZapkie/derailment.h) as it tips over +double sliding_friction(double Tipping, bool Guided); + +// ---- the way the vehicle leaves the track + +// how far the flange or the wheel goes sideways over the head of the rail before it drops off it [m] +inline constexpr double climb_width{0.1}; +// the largest angle the vehicle turns off the track by [rad] +inline constexpr double most_departure{0.2}; +// the angle [rad] the heading turns out of the curve by: the sideways speed sqrt(2 a w) the lateral acceleration a +// [m/s2] gives the wheels over the climb width w, against the speed [m/s]. none off the end of the track or in a +// collision +double departure_angle(cause Cause, double Speed, double Acceleration); + +// ---- the scatter: what differs from one derailed vehicle to the next + +// the ground under it and the way it bites into the ballast: each vehicle draws its own from the seed of the run and its +// name, so a run with the same seed goes the same way and one with another seed another way +struct scatter { + double departure{0.0}; // added to the angle it leaves the track at [rad], not off the end of the track nor in a collision + double yaw{0.0}; // its body turned off the way it travels when it leaves the rails [rad], to the left positive + double yaw_rate{0.0}; // [rad/s] the kick of the leading wheels dropping off the rail head + double friction_front{1.0}; // the friction under the front half of its body, of the friction of the motion + double friction_rear{1.0}; // and under the rear half + double dig_in{-1.0}; // the time after leaving the rails its leading end digs into the ballast [s], -1 never + double dig_in_time{0.0}; // for how long [s] + double dig_in_friction{1.0}; // the friction under the leading half then, of the friction of the motion + int dig_in_side{1}; // the wheel that digs in: 1 the left one of the leading end, -1 the right one +}; +// the scatter of a vehicle: departure angle +-0.01 rad, yaw +-0.02 rad, yaw rate +-0.02 rad/s, the friction under each +// half 0.85..1.15 of the friction of the motion, and in two of three vehicles a bite of the leading end 0.2..1.5 s after +// it left the rails, for 0.3..0.8 s, the friction under that half 2..4 times the friction of the motion then +scatter draw_scatter(std::uint32_t Seed); +// the seed of a vehicle: of the seed of the run and its name +std::uint32_t seed_of(std::uint32_t Run, std::string_view Name); + +// ---- the buffers and the couplings of two vehicles, one of them off the track at least + +// the height of the middle of the buffer beam above the rails [m]: UIC, 940..1065 mm +inline constexpr double buffer_height{1.0}; +// half the spacing of the buffers [m]: UIC, 1750 mm +inline constexpr double buffer_half_spacing{0.875}; +// the height of a buffer head [m]: two buffers further apart in height than that miss each other +inline constexpr double buffer_head{0.34}; +// the bend between two bodies [rad] the push of the buffers goes all onto the inner buffer at: their play, 45 mm of +// difference over the spacing +inline constexpr double buffer_lock{0.05}; +// the most a buffer takes [N]: past it, it is pressed solid and gives way, the frames push against each other at +// the middle of the beams +inline constexpr double buffer_limit{1.0e6}; + +// an end of a vehicle, where it meets the vehicle coupled to it +struct end_point { + glm::dvec3 point{0.0}; // the middle of the buffer beam, at the height of the buffers + glm::dvec3 outward{0.0, 0.0, 1.0}; // the way the end faces, level + // how far the body is rolled [rad]: the buffers of two bodies rolled apart miss each other in height + double roll{0.0}; +}; +// a force on a body [N], at the point it acts at +struct end_force { + glm::dvec3 force{0.0}; + glm::dvec3 point{0.0}; +}; +// two ends meeting, as the first sees it +struct meeting { + // apart [m], negative where the buffers press into each other: along the bisector of the bend while they touch, + // the distance between the middles of the beams once they are apart + double gap{0.0}; + // the bend: the angle [rad] the second body turns off the axis of the first, to the left of its end positive + double bend{0.0}; + glm::dvec3 push{0.0, 0.0, 1.0}; // outwards from the first, the bisector of the bend: the buffers push the other way + glm::dvec3 pull{0.0, 0.0, 1.0}; // the way the coupling draws the first: to the beam of the second + glm::dvec3 point{0.0}; // the middle of the beam of the first + // how well the buffers meet in height: 0 they miss each other (one body lower than the other, or rolled against it), to 1 + double overlap{1.0}; +}; +meeting meet(end_point const &First, end_point const &Second); +// the force on the first end of the meeting, Compression [N] pushing it (negative: the coupling pulling it): through +// the inner buffer of the bend, off the middle of the beam as far as the buffers meet and hold +end_force force_on(meeting const &Meeting, double Compression); + +// ---- the bodies of two vehicles running into each other, one of them off the track at least + +// how far the buffers and the coupling stand out of the body at each end [m]: the body box is shorter by them, so two +// ends meeting through their buffers (meet(), force_on()) don't touch as bodies until the buffers are pressed in by that +inline constexpr double buffer_length{0.6}; +// the least overlap in height [m] two bodies run into each other with: lower, one goes over the other +inline constexpr double height_overlap{0.2}; +// the bodies part after a hit with this share of the speed they met at +inline constexpr double contact_restitution{0.2}; +// the friction of the side of one body sliding along the other +inline constexpr double contact_friction{0.3}; +// the overlap left after a hit, taken out of it by moving the bodies apart: what is over the slop [m], this share of it +// a step +inline constexpr double contact_slop{0.02}; +inline constexpr double contact_correction{0.8}; + +// where a body stands on the ground: the rectangle under its box (the box of the body, the buffers left out, rolled and +// pitched as it lies, seen from above along its level axis), and the height it reaches from and to +struct footprint { + glm::dvec3 centre{0.0}; // of the rectangle, level + glm::dvec3 axis{0.0, 0.0, 1.0}; // along the body, level + double half_length{10.0}; + double half_width{1.5}; + double low{0.0}; // [m] the lowest and the highest point of the box + double high{4.0}; +}; +struct pose; +// the footprint of the body of Length (over the buffers), Width and Height (above the rails) in the Pose +footprint footprint_of(pose const &Pose, double Length, double Width, double Height); +// two bodies in each other: how deep (the least the rectangles overlap across any of their sides), the way out of the +// first into the second (level), and the point they touch at +struct contact { + double depth{0.0}; + glm::dvec3 normal{1.0, 0.0, 0.0}; + glm::dvec3 point{0.0}; +}; +std::optional collide(footprint const &First, footprint const &Second); +// a body in a contact, for the impulse: its mass, the velocity of its middle (base) and how fast it turns; on the rails +// it moves only along the track (Guided: along the Guide), not turning +struct contact_body { + double mass{0.0}; // [kg], none: it doesn't move + glm::dvec3 base{0.0}; + glm::dvec3 velocity{0.0}; + double yaw_rate{0.0}; + double gyration{30.0}; // the square of its radius of gyration about the vertical [m2] + bool guided{false}; + glm::dvec3 guide{0.0, 0.0, 1.0}; +}; +// the velocity of the point of the body [m/s] +glm::dvec3 velocity_at(contact_body const &Body, glm::dvec3 const &Point); +// the impulse [N s] on the second body of the contact (the first gets the opposite one): it stops the two closing in on +// each other at the point, parting them with the restitution, and the friction holds them sliding along each other +glm::dvec3 contact_impulse(contact const &Contact, contact_body const &First, contact_body const &Second); +// the change of the velocity [m/s] and of the yaw rate [rad/s] of the body by the impulse at the point +std::pair impulse_change(contact_body const &Body, glm::dvec3 const &Impulse, glm::dvec3 const &Point); + +// the distance [m] a vehicle slides from the speed [m/s] with the friction, on the grade (rise per metre along the +// way); none when the grade doesn't let it stop +std::optional stopping_distance(double Speed, double Friction, double Grade = 0.0); + +// the Y/Q of the leading wheel of an end of a vehicle which the coupling pulls (or pushes) at the angle [rad] to its +// axis with the force [N]: the part across, taken by the axles of that end (half of them), against the static load of +// a wheel of the vehicle of the mass [kg] +double pull_ratio(double Force, double Angle, double Mass, int Axles); + +// ---- the ground + +// where the vehicle can find the ground +class ground { +public: + virtual ~ground() = default; + // the height of the ground at (X, Z): of the highest surface there at or under Ceiling; none where there is none + virtual std::optional height(double X, double Z, double Ceiling) const = 0; +}; + +// level everywhere +class flat_ground final : public ground { +public: + explicit flat_ground(double Level) : m_level{Level} {} + std::optional height(double X, double Z, double Ceiling) const override; + +private: + double m_level; +}; + +// the triangles of the terrain of the scenery, kept in square cells for the lookup +class mesh_ground final : public ground { +public: + using triangle = std::array; + // the triangles which reach into the rectangle from Min to Max (x, z), in cells of the size [m] + mesh_ground(std::vector const &Triangles, glm::dvec2 const &Min, glm::dvec2 const &Max, double Cell = 8.0); + std::optional height(double X, double Z, double Ceiling) const override; + // whether the point is inside the rectangle the triangles were taken for + bool covers(double X, double Z) const; + // whether the rectangle from Min to Max (x, z) is inside the one the triangles were taken for + bool covers(glm::dvec2 const &Min, glm::dvec2 const &Max) const; + // the ground of a smaller area: the triangles which reach into the rectangle from Min to Max (x, z) + mesh_ground cropped(glm::dvec2 const &Min, glm::dvec2 const &Max) const; + std::size_t size() const { return m_triangles.size(); } + glm::dvec2 const &minimum() const { return m_min; } + glm::dvec2 const &maximum() const { return m_max; } + +private: + std::optional cell_of(double X, double Z) const; + + std::vector m_triangles; + std::vector> m_cells; // the triangles reaching into each cell + glm::dvec2 m_min; + glm::dvec2 m_max; + double m_cell; + std::size_t m_columns{0}; + std::size_t m_rows{0}; +}; + +// the bed of the track at the place nearest to the vehicle: the top of the ballast under the rails, level out to the +// edge of the formation, then the slope of the embankment going down +struct formation { + glm::dvec3 point{0.0}; // on the axis of the track, at the height of the rails + glm::dvec3 direction{0.0, 0.0, 1.0}; // of the axis + double depth{0.2}; // of the top of the ballast under the rails [m] + double half_width{2.0}; // from the axis to the edge of the top [m] + double slope{1.5}; // run of the slope per metre of fall: 1:1.5, of an embankment + double height(double X, double Z) const; +}; + +// the ground as the vehicle finds it: the terrain of the scenery where it has any, level with the top of the ballast +// where it has none (a scenery without terrain), and the bed of the track over it +class site final : public ground { +public: + explicit site(ground const *Terrain = nullptr, formation const &Bed = {}) : m_terrain{Terrain}, m_bed{Bed} {} + void terrain(ground const *Terrain) { m_terrain = Terrain; } + // the bed moves along the track with the vehicle + void bed(formation const &Bed) { m_bed = Bed; } + formation const &bed() const { return m_bed; } + std::optional height(double X, double Z, double Ceiling) const override; + +private: + ground const *m_terrain; + formation m_bed; +}; + +// ---- the vehicle + +// what of the vehicle the motion takes +struct vehicle_shape { + double length{20.0}; // over the buffers [m] + double width{3.0}; // of the body [m] + double height{4.0}; // of the body above the rail [m] + double centre_of_gravity{1.5}; // its height above the rail [m] + double contact_spacing{1.5}; // of the wheels of a wheelset [m] + double base{10.0}; // between the bogie pivots or the outer axles, which it rests on lengthwise [m] + // the lean of the body on the suspension, as McZapkie/derailment.h takes it: flexibility and roll centre + double flexibility{0.4}; + double roll_centre{0.5}; + // [kg] for the forces of the couplings on it; none: they don't move it + double mass{0.0}; +}; + +// how it left the rails +struct start { + glm::dvec3 position{0.0}; // of the vehicle, at the height of the rails + glm::dvec3 front{0.0, 0.0, 1.0}; // the way its front faces + glm::dvec3 line{0.0, 0.0, 1.0}; // the direction of the track there, to measure the offset across it by + double speed{0.0}; // along the front [m/s] + cause reason{cause::off_rails}; + // the outer side of the curve of the line under it: 1 to the left of its front, -1 to the right, 0 straight + int outward{0}; + double acceleration{0.0}; // the lateral acceleration of the body when it derailed, out of the curve [m/s2] +}; + +// where the body is and how it lies: the origin of its model, at the height of the rails between its wheels when +// upright, and its axes +struct pose { + glm::dvec3 position{0.0}; + glm::dvec3 front{0.0, 0.0, 1.0}; + glm::dvec3 left{1.0, 0.0, 0.0}; + glm::dvec3 up{0.0, 1.0, 0.0}; +}; + +class body { +public: + // the vehicle leaves the rails, set apart from the others by the Scatter + void begin(start const &Start, vehicle_shape const &Shape, ground const &Ground, scatter const &Scatter = {}); + // the step of Dt [s], in which the vehicle travelled Distance [m] along its heading (forwards along its front) and + // has the Speed [m/s] along it at its end; the couplings of its ends push or pull it with the Ends through the step + void step(double Dt, double Distance, double Speed, ground const &Ground, std::array const &Ends = {}); + // back on the rails, or never off them + void reset() { *this = body{}; } + + bool active() const { return m_active; } + pose const ¤t() const { return m_pose; } + // the middle of the vehicle on the ground, under it as it stands (not moved over to the side it tipped to) + glm::dvec3 const &base() const { return m_position; } + // the speed along the heading [m/s], and the velocity of the middle, level + double speed() const { return m_speed; } + glm::dvec3 velocity() const; + // the square of the radius of gyration about the vertical [m2] + double gyration() const { return m_yawgyration; } + // hit by another body: the velocity and the yaw rate change by these, the heading becomes the way it goes then + // (turned about where it goes rear first); the speed() after it is the one its vehicle goes on with + void kick(glm::dvec3 const &Velocity, double YawRate); + // moved over by the offset (level), out of another body it is in + void nudge(glm::dvec3 const &Offset); + // the friction along the heading now, of its weight: of the body sliding along itself, more the more askew it goes, + // up to the friction across it going sideways + double friction() const; + // the rise of the ground per metre along the heading, for the force of the gravity along it + double grade() const { return m_grade; } + // how far the body tipped over from its wheels [rad], to the left positive; 90 degrees: it lies on its side + double tipping() const { return m_side * m_tipping; } + // the roll of the body against the level [rad], to the left positive: the tipping and the slope across it + double roll() const; + bool lying() const { return m_tipping >= half_turn - 1e-9; } + // still on its outer wheels on the rail, tipping over out of the curve + bool guided() const { return m_guided; } + // the distance it went on the ground since it left the rails [m] + double travelled() const { return m_travelled; } + // from the place it left the rails at: along the line of the track there, and across it, to the left positive [m] + double along() const; + double across() const; + // the speed it slides with sideways, to the left of its front positive [m/s] + double sideways() const { return m_lateral; } + // at rest: not sliding, not tipping, on the ground + bool at_rest() const; + // the way it travels, level + glm::dvec3 const &heading() const { return m_front; } + // the way the front of its body faces, level + glm::dvec3 const &axis() const { return m_axis; } + // the angle [rad] its body is turned by off the line of the track where it left the rails, to the left positive + double yaw() const; + // how fast it turns [rad/s], to the left positive + double yaw_rate() const { return m_yawrate; } + // how many times the heading was turned about, the body having turned more than a right angle off the way it + // goes: the heading stays within a right angle of the front of the body, so the speed along the heading (of + // TMoverParameters, of its couplers at its ends) goes with the body; the speed changes its sign with each + int reversals() const { return m_reversals; } + cause reason() const { return m_reason; } + // the vehicle the motion was begun with + vehicle_shape const &shape() const { return m_shape; } + + static constexpr double half_turn{1.5707963267948966}; + +private: + // the ground under the supports of the vehicle + struct footing { + double level{0.0}; // under the middle, not under any support + double grade{0.0}; // rise per metre forwards + double cross{0.0}; // rise per metre to the left + }; + + void advance(double Dt, double Distance, double Speed, ground const &Ground); + footing find_footing(ground const &Ground) const; + // down to the ground at the Level, or onto it, having travelled Travel [m] over the ground in the step + void fall(double Dt, double Level, double Travel); + void slide(double Dt, double Cross); + void tip(double Dt, double Cross, double Speed); + // the lateral acceleration [m/s2] on the centre of gravity, to the left positive, in the plane of the ground + double lateral_load(double Cross, double Speed) const; + void place(); + // to the left of the body + glm::dvec3 left_of_heading() const; + // the friction under the body going along its heading at the Speed and turning at the Yawrate, per its mass: the + // force [m/s2], the moment about its middle [m2/s2] and the sideways load that trips it over [m/s2] + struct drag { + glm::dvec3 force{0.0}; + double moment{0.0}; + double trip{0.0}; + }; + drag friction_under(double Speed, double Yawrate) const; + // the friction under the front (Front) or the rear half of the body, of the friction of the motion + double friction_share(bool Front) const; + // the leading end biting into the ballast now: 1 its front, -1 its rear, 0 none + int biting() const; + // the friction along the body and across it + double friction_along() const; + double friction_across() const; + // the body turns, and the way it travels turns, through the substep + void turn(double Dt, double Speed); + + bool m_active{false}; + cause m_reason{cause::off_rails}; + vehicle_shape m_shape; + // the geometry of the tipping: half the spacing of the wheels, the height the lateral force leans the body at, + // the distance of the centre of gravity from the wheels it tips about, the angle it tips over past, and the + // square of the radius of gyration about them + double m_pivot{0.75}; + double m_lever{1.8}; + double m_reach{1.9}; + double m_tipangle{0.4}; + double m_gyration{5.0}; + + glm::dvec3 m_position{0.0}; // of the middle of the vehicle on the ground (at its base) + glm::dvec3 m_front{0.0, 0.0, 1.0}; // the heading, level + glm::dvec3 m_axis{0.0, 0.0, 1.0}; // the front of the body, level + double m_yawrate{0.0}; // [rad/s] + double m_yawgyration{30.0}; // the square of the radius of gyration of the body about its vertical axis [m2] + scatter m_scatter; + double m_time{0.0}; // since it left the rails [s] + int m_reversals{0}; + double m_trip{0.0}; // the load across of the friction of the body going askew [m/s2], the way it slides + // the forces of the couplings through the step: the force, and where it acts, along the body and across it + struct end_load { + glm::dvec3 force{0.0}; + double along{0.0}; + double across{0.0}; + }; + std::array m_ends{}; + glm::dvec3 m_origin{0.0}; // where it left the rails + glm::dvec3 m_line{0.0, 0.0, 1.0}; // the direction of the track there, level + double m_fallspeed{0.0}; // [m/s], downwards negative + // on the ground, not falling. it leaves the rails above the top of the ballast, and drops onto it + bool m_grounded{false}; + double m_lateral{0.0}; // [m/s], to the left positive + double m_grade{0.0}; // along the heading + double m_pitch{0.0}; // along the body + double m_cross{0.0}; + int m_side{0}; // the side it tips to: 1 left, -1 right, 0 upright + double m_tipping{0.0}; // [rad] + double m_tiprate{0.0}; // [rad/s] + // overturning in the curve: the lateral acceleration of the curve at the speed it derailed at, which goes with the + // square of the speed, the side out of the curve, and how long it has been tipping + bool m_guided{false}; + double m_guideacceleration{0.0}; + double m_guidespeed{0.0}; + int m_outward{0}; + double m_guidetime{0.0}; + double m_speed{0.0}; + double m_travelled{0.0}; + pose m_pose; +}; + +// the slowest a point of the body slides at [m/s]: the friction under one going slower holds it as much as it goes +inline constexpr double creep_speed{0.05}; +// the fastest the body turns about its vertical axis [rad/s] +inline constexpr double most_yaw_rate{2.0}; +// the slowest the heading is turned at by the forces across it [m/s]: slower, the vehicle stops where it goes +inline constexpr double turning_speed{0.5}; +// the points the friction under the body is taken at, along it +inline constexpr int friction_points{8}; + +// how long the curve can keep tipping over a vehicle on its outer wheels [s] +inline constexpr double guidance_time{5.0}; +// how high a step up the vehicle can climb onto, for the ground under it [m] +inline constexpr double step_up{1.0}; + +} // namespace derail_motion diff --git a/vehicle/doorwings.h b/vehicle/doorwings.h index 07286aac8..db05b03fc 100644 --- a/vehicle/doorwings.h +++ b/vehicle/doorwings.h @@ -10,6 +10,13 @@ http://mozilla.org/MPL/2.0/. #pragma once #include +#include +#include +#include +#include +#include +#include +#include #include @@ -17,6 +24,12 @@ http://mozilla.org/MPL/2.0/. // in the main model and, when the low poly interior has a submodel of the same name, in the interior as well namespace door_wings { +// the kinds of wing animation, numbered as DoorOpenMethod of the .fiz (TMoverParameters::door_data::type) +inline constexpr int shift_type{1}; +inline constexpr int rotate_type{2}; +inline constexpr int fold_type{3}; +inline constexpr int plug_type{4}; + // whether the animation with the given flags (TAnim::iFlags, the kind of animation in bits 4-7) moves a door wing inline bool is_wing(int const Flags) { return (Flags & 0xF0) == 0x10; @@ -49,4 +62,145 @@ inline fold_angles fold(float const Position) { return {Position, -Position - Position, Position}; } +// the animation of one wing given in the .mmd, in place of the one the .fiz sets for all door wings of the vehicle +// (eu07/maszyna#70). the wing still follows the door of its side, over its own range: +// animdoor: { type: range: rangeout: } +// every key is optional; a key left out keeps the value of the .fiz +struct wing_spec { + int number{0}; // of the wing, as in animdoorprefix: door1 is 1 + int type{rotate_type}; + float range{0.f}; // shift or angle of the wing when the door is fully open + float range_out{0.f}; // how far a plug wing is pushed out +}; + +// the kind of wing animation with the given name of DoorOpenMethod, in any letter case +inline std::optional type_from_name(std::string_view const Name) { + std::string name{Name}; + std::transform(name.begin(), name.end(), name.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + if (name == "shift") { + return shift_type; + } + if (name == "rotate") { + return rotate_type; + } + if (name == "fold") { + return fold_type; + } + if (name == "plug") { + return plug_type; + } + return std::nullopt; +} + +// the number written in the whole of the text, or nothing +inline std::optional number_from_text(std::string const &Text) { + if (Text.empty()) { + return std::nullopt; + } + char *end{nullptr}; + auto const value{std::strtof(Text.c_str(), &end)}; + if (end != Text.c_str() + Text.size() || false == std::isfinite(value)) { + return std::nullopt; + } + return value; +} + +// applies the keys and values of the block of an animdoor entry (the tokens between the braces) to the spec, which +// comes filled with the values of the .fiz. returns what is wrong with the block, or an empty text when nothing is; +// the keys before the fault are applied +inline std::string parse_spec(std::vector const &Tokens, wing_spec &Spec) { + for (std::size_t index = 0; index < Tokens.size(); index += 2) { + std::string key{Tokens[index]}; + std::transform(key.begin(), key.end(), key.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + if (index + 1 >= Tokens.size()) { + return "no value for \"" + key + "\""; + } + auto const &value{Tokens[index + 1]}; + if (key == "type:") { + auto const type{type_from_name(value)}; + if (false == type.has_value()) { + return "unknown door type \"" + value + "\""; + } + Spec.type = *type; + } + else if (key == "range:" || key == "rangeout:") { + auto const number{number_from_text(value)}; + if (false == number.has_value()) { + return "bad number \"" + value + "\" for \"" + key + "\""; + } + (key == "range:" ? Spec.range : Spec.range_out) = *number; + } + else { + return "unknown key \"" + key + "\""; + } + } + return {}; +} + +// whether the token is one of the keys of an animdoor block, in any letter case +inline bool is_spec_key(std::string const &Token) { + std::string key{Token}; + std::transform(key.begin(), key.end(), key.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + return key == "type:" || key == "range:" || key == "rangeout:"; +} + +// reads an animdoor entry after its key: the wing number and the block in braces, into the spec filled with the values +// of the .fiz. returns what is wrong with the entry, or an empty text when nothing is. the parser is a cParser. a block +// without its } ends at the first token that is neither a key nor the value right after one (or at endmodels): that +// token is left for the caller, so the entries after a faulty one are read as ever +template +std::string read_spec(Parser_ &Parser, wing_spec &Spec) { + Parser.getTokens(1, false); + Parser >> Spec.number; + std::string token; + Parser.getTokens(1, false); + Parser >> token; + if (token != "{") { + return "no { after the wing number"; + } + std::vector block; + auto value{false}; // the token is the value of the key before it + while (true) { + token.clear(); + Parser.getTokens(1, false); + Parser >> token; + if (token.empty()) { + return "no } after the keys"; + } + if (token == "}") { + break; + } + if (token == "endmodels" || (false == value && false == is_spec_key(token))) { + Parser.injectString(token); + return "no } after the keys, \"" + token + "\" is none of them"; + } + value = false == value; + block.emplace_back(token); + } + return parse_spec(block, Spec); +} + +// the spec given for the wing with the given number, or null when the wing animates as the .fiz says +inline wing_spec const *find(std::vector const &Specs, int const Number) { + auto const lookup{std::find_if(Specs.begin(), Specs.end(), [Number](wing_spec const &Spec) { return Spec.number == Number; })}; + return lookup != Specs.end() ? &(*lookup) : nullptr; +} + +// keeps the spec of a wing; a later entry for the same wing replaces the earlier one +inline void store(std::vector &Specs, wing_spec const &Spec) { + auto lookup{std::find_if(Specs.begin(), Specs.end(), [&Spec](wing_spec const &Stored) { return Stored.number == Spec.number; })}; + if (lookup != Specs.end()) { + *lookup = Spec; + } + else { + Specs.emplace_back(Spec); + } +} + +// the shift or angle of a wing which opens over Wingrange, while the door of its side opens over Doorrange: the wing +// is as far along its range as the door is along the door range +inline float wing_position(float const Doorposition, float const Doorrange, float const Wingrange) { + return Doorrange != 0.f ? Doorposition / Doorrange * Wingrange : 0.f; +} + } // namespace door_wings diff --git a/vehicle/drivingaid.cpp b/vehicle/drivingaid.cpp new file mode 100644 index 000000000..df8fc37a7 --- /dev/null +++ b/vehicle/drivingaid.cpp @@ -0,0 +1,79 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/drivingaid.h" + +#include "McZapkie/MOVER.h" +#include "McZapkie/hamulce.h" + +#include +#include + +namespace drivingaid { + +namespace { + +// the first throttle number: the drive demand in percent with an EIM controller, else the master controller. +// a separate ED lever off its zero shows as the negative step the cab's joint controller is at +int throttle_first(input const &Input) { + if (Input.splited && Input.dynamicbrakepos > 0.0) { + return -static_cast(std::lround(Input.dynamicbrakepos * Input.dynamicbrakeposno)); + } + if (Input.eimctrltype > 0) { + return std::max(0, static_cast(100.4 * Input.eimic_real)); + } + return Input.mainctrlpos; +} + +// the cab has a control of the local brake: its own lever, or the braking range of the joint controller +// unless that range is the separate ED lever +bool has_local_brake_control(input const &Input) { + return Input.cab.localbrake || (Input.cab.jointctrl && false == Input.splited); +} + +} // namespace + +readout compute(input const &Input) { + readout result; + result.throttle_first = throttle_first(Input); + result.throttle_second = Input.eimctrltype > 0 ? Input.mainctrlpos : Input.scndctrlpos; + + auto const edbraking{std::max(0.0, -100.0 * Input.eimic_real)}; + result.brake_first = Input.integratedbrake ? edbraking : Input.brakectrlpos; + result.local_brake = Input.localbrakepos * LocalBrakePosNo; + // without a control in the cab the local brake is left out, unless it is applied after all (the AI or a key) + result.show_local_brake = has_local_brake_control(Input) || Input.localbrakepos > 0.0; + // the integrated universal controller shows the ED demand as its brake number already + if (Input.eim && false == Input.integratedbrake) { + if (auto const percent{static_cast(std::lround(edbraking))}; percent > 0) { + result.ed_percent = percent; + } + } + return result; +} + +input from_movers(TMoverParameters const &Vehicle, TMoverParameters const &Controlling, cab_controls const &Cab) { + input result; + result.eim = Vehicle.EngineType == TEngineType::ElectricInductionMotor || Vehicle.EIMCtrlType > 0; + result.eimctrltype = Vehicle.EIMCtrlType; + result.splited = Controlling.SplitEDPneumaticBrake; + result.integratedbrake = Vehicle.UniCtrlIntegratedBrakeCtrl; + result.eimic_real = Vehicle.eimic_real; + result.dynamicbrakepos = Controlling.DynamicBrakeCtrlPos; + result.dynamicbrakeposno = Controlling.DynamicBrakeCtrlPosNo; + result.mainctrlpos = Controlling.MainCtrlPos; + result.scndctrlpos = Controlling.ScndCtrlPos; + result.brakectrlpos = Vehicle.fBrakeCtrlPos; + result.localbrakepos = Vehicle.LocalBrakePosA; + result.cab = Cab; + return result; +} + +} // namespace drivingaid diff --git a/vehicle/drivingaid.h b/vehicle/drivingaid.h new file mode 100644 index 000000000..8cec257da --- /dev/null +++ b/vehicle/drivingaid.h @@ -0,0 +1,68 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include + +class TMoverParameters; + +// what the driving aid panel shows of the controls and of the braking: the numbers of its throttle and +// brakes lines, worked out from the vehicle state (eu07/maszyna#558, eu07/maszyna#555) +namespace drivingaid { + +// the cab controls the panel needs to know of, which the cab definition (.mmd) has or lacks +struct cab_controls { + // a lever of the local (auxiliary) brake: localbrake: + bool localbrake{true}; + // a joint controller, jointctrl:, whose braking range is the local brake, or the ED lever with + // SplitEDPneumaticBrake + bool jointctrl{false}; +}; + +struct input { + // the vehicle works out the integrated drive and brake demand (eimic): an induction motor vehicle, + // or a diesel one with an EIM controller + bool eim{false}; + int eimctrltype{0}; + // the ED brake has a lever of its own (SplitEDPneumaticBrake), with dynamicbrakeposno steps + bool splited{false}; + // the universal controller brakes with the ED brake, so the brake handle number is the ED demand already + bool integratedbrake{false}; + // the demand in use, -1..1, negative braking + double eimic_real{0.0}; + double dynamicbrakepos{0.0}; // 0..1 + int dynamicbrakeposno{10}; + int mainctrlpos{0}; + int scndctrlpos{0}; + double brakectrlpos{0.0}; // the train brake handle + double localbrakepos{0.0}; // 0..1 + cab_controls cab; +}; + +struct readout { + // "Throttle: first+second" + int throttle_first{0}; + int throttle_second{0}; + // "Brakes: first+local" + double brake_first{0.0}; + double local_brake{0.0}; + bool show_local_brake{true}; + // the ED braking demand in percent, while there is some + std::optional ed_percent; +}; + +// the panel's numbers from the vehicle state +readout compute(input const &Input); + +// the state the panel reads: Vehicle is the one the driver sits in, Controlling the one whose controllers +// the driver moves (TController::Controlling()) +input from_movers(TMoverParameters const &Vehicle, TMoverParameters const &Controlling, cab_controls const &Cab); + +} // namespace drivingaid diff --git a/vehicle/fieldshunting.cpp b/vehicle/fieldshunting.cpp new file mode 100644 index 000000000..49300f50b --- /dev/null +++ b/vehicle/fieldshunting.cpp @@ -0,0 +1,27 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/fieldshunting.h" + +namespace fieldshunting { + +bool has_switch(int const Autorelaytype, bool const Fieldshuntswitch) { + return Autorelaytype == 2 && Fieldshuntswitch; +} + +control diesel_electric(int const Autorelaytype, bool const Fieldshuntswitch, bool const Autorelayflag) { + using enum control; + if (Autorelayflag) { + return automatic; + } + return has_switch(Autorelaytype, Fieldshuntswitch) ? off : manual; +} + +} // namespace fieldshunting diff --git a/vehicle/fieldshunting.h b/vehicle/fieldshunting.h new file mode 100644 index 000000000..2dec04be5 --- /dev/null +++ b/vehicle/fieldshunting.h @@ -0,0 +1,32 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +// the field shunting (ScndCtrlPos) of the diesel-electric locomotives +namespace fieldshunting { + +// who sets the field shunting +enum class control : int { + manual, // the driver, with the second controller + automatic, // the shunting relays (RelayType) + off // nobody: the shunting is switched off, the field stays full +}; + +// whether a diesel-electric has the switch that lets the relays shunt the field, as the SU45's and SP45's "załączenie +// bocznikowania" (eu07/maszyna#167): AutoRelay=Optional (Autorelaytype 2) with FieldShuntSwitch=Yes (Fieldshuntswitch) +bool has_switch(int Autorelaytype, bool Fieldshuntswitch); + +// who sets the field shunting of a diesel-electric locomotive, by its AutoRelay (Autorelaytype: 0 No, 1 Yes, 2 Optional), +// its FieldShuntSwitch (Fieldshuntswitch) and its AutoRelayFlag (Autorelayflag). with the flag set, the relays. with the +// switch of the field shunting (has_switch()) switched off, nobody. otherwise the driver, AutoRelay=Optional without +// FieldShuntSwitch included +control diesel_electric(int Autorelaytype, bool Fieldshuntswitch, bool Autorelayflag); + +} // namespace fieldshunting diff --git a/vehicle/gaugewrap.cpp b/vehicle/gaugewrap.cpp new file mode 100644 index 000000000..f16b6e857 --- /dev/null +++ b/vehicle/gaugewrap.cpp @@ -0,0 +1,48 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/gaugewrap.h" + +#include + +namespace gauge_wrap { + +namespace { + +// how far the positions in a full turn worked out from the scale may be off a whole number: the scales in the cab +// definitions are given to three decimals or so, 0.167 for a sixth gives 5.988 +constexpr double turn_tolerance{0.05}; + +} // namespace + +std::optional full_turn(float const Scale, int const Positions) { + if (Positions < 2 || Scale == 0.f) { + return std::nullopt; + } + auto const perturn{1.0 / std::abs(static_cast(Scale))}; + auto const turn{std::round(perturn)}; + if (std::abs(perturn - turn) > turn_tolerance) { + // the positions don't make a full turn: a lever, or a knob that stops at its ends + return std::nullopt; + } + auto const positions{static_cast(turn)}; + // the way on from the last position to the first one, in positions + if (auto const wayon{positions - (Positions - 1)}; wayon < 1 || 2 * wayon > positions) { + // the positions overlap in a turn, or the knob would turn on more than half a turn + return std::nullopt; + } + return positions; +} + +float turned_round(float const Value, int const Turn, bool const Forward) { + return Forward ? Value - static_cast(Turn) : Value + static_cast(Turn); +} + +} // namespace gauge_wrap diff --git a/vehicle/gaugewrap.h b/vehicle/gaugewrap.h new file mode 100644 index 000000000..126652922 --- /dev/null +++ b/vehicle/gaugewrap.h @@ -0,0 +1,29 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include + +// a multi-position rotary switch of the cab turned past its last position to the first one, or back past the first +// one to the last (a selector with Wrap=Yes, such as the light preset selector) +namespace gauge_wrap { + +// the number of positions in one full turn of a rotary switch of Positions positions that turns by Scale of a full turn +// per position, if the switch can turn on past its end the short way round: the full turn is a whole number of positions +// (within the rounding of the scale in the cab definition, e.g. 0.167 for a sixth), all the positions fit in it, and the +// way on from the last position to the first one is at most half a turn. None otherwise +std::optional full_turn(float Scale, int Positions); + +// the value of the switch at Value seen one full turn of Turn positions earlier (Forward: it turns on past its last +// position to the first one) or later (back past the first position to the last one). The knob stands the same there, +// and turning from that value to the new position turns it on the way it was turned rather than all the way back +float turned_round(float Value, int Turn, bool Forward); + +} // namespace gauge_wrap diff --git a/vehicle/linebreaker.cpp b/vehicle/linebreaker.cpp index 97eae0325..cc9b2f008 100644 --- a/vehicle/linebreaker.cpp +++ b/vehicle/linebreaker.cpp @@ -12,11 +12,11 @@ http://mozilla.org/MPL/2.0/. namespace linebreaker { -toggle pressed(int const Breakerstate, bool const Latchinglever, bool const Leveron) { - if (Breakerstate == 1) { +toggle pressed(state const Breakerstate, bool const Latchinglever, bool const Leveron) { + if (Breakerstate == state::closed) { return toggle::open; } - if (Breakerstate != 0) { + if (Breakerstate != state::open) { return toggle::none; } // the line breaker is open; a lever left on goes off first diff --git a/vehicle/linebreaker.h b/vehicle/linebreaker.h index 370e992cc..e87312dd1 100644 --- a/vehicle/linebreaker.h +++ b/vehicle/linebreaker.h @@ -12,6 +12,13 @@ http://mozilla.org/MPL/2.0/. // the line breaker (main switch, WS) controls of the cab namespace linebreaker { +// the state the cab keeps of the line breaker, besides the vehicle's own (TMoverParameters::Mains) +enum class state : int { + open, + closed, + closing // the closing control was held long enough; the line breaker closes when it's released, or right away +}; + enum class toggle : int { none, // the press does nothing close, // the control goes to its on position, and the line breaker closes if it can @@ -19,10 +26,10 @@ enum class toggle : int { }; // what a press of the line breaker toggle does. Breakerstate is the state the cab keeps of the line -// breaker (0: open, 1: closed, 2: freshly closed). Latchinglever is a single two-state switch which -// stays where it was put, Leveron that it stands in its on position. such a lever doesn't follow the -// line breaker: knocked out (by the converter overload relay, say) the breaker opens with the lever -// left on, and the lever has to go off before it can be put on again (eu07/maszyna#394) -toggle pressed(int Breakerstate, bool Latchinglever, bool Leveron); +// breaker. Latchinglever is a single two-state switch which stays where it was put, Leveron that it +// stands in its on position. such a lever doesn't follow the line breaker: knocked out (by the converter +// overload relay, say) the breaker opens with the lever left on, and the lever has to go off before it +// can be put on again (eu07/maszyna#394) +toggle pressed(state Breakerstate, bool Latchinglever, bool Leveron); } // namespace linebreaker diff --git a/vehicle/odometer.cpp b/vehicle/odometer.cpp index 8f98cb084..7495cbda2 100644 --- a/vehicle/odometer.cpp +++ b/vehicle/odometer.cpp @@ -15,13 +15,17 @@ http://mozilla.org/MPL/2.0/. #include "utilities/utilities.h" #include +#include #include #include #include +#include #include #include #include +#include #include +#include #ifdef _WIN32 #include #else @@ -62,8 +66,61 @@ std::optional parse_number(std::string const &Text) { } } +// the comment line which gives the day the states after it were last updated +constexpr std::string_view stamp_prefix{"# updated "}; + +// a whole number making up all of the text +std::optional parse_integer(std::string_view const Text) { + if (Text.empty() || Text.front() == '-') + return std::nullopt; + int value{0}; + auto const *const end{Text.data() + Text.size()}; + if (auto const [used, error] {std::from_chars(Text.data(), end, value)}; error != std::errc{} || used != end) + return std::nullopt; + return value; +} + +// day written as yyyy-mm-dd +std::optional parse_day(std::string_view const Text) { + if (Text.size() != 10 || Text[4] != '-' || Text[7] != '-') + return std::nullopt; + auto const year{parse_integer(Text.substr(0, 4))}; + auto const month{parse_integer(Text.substr(5, 2))}; + auto const dayofmonth{parse_integer(Text.substr(8, 2))}; + if (false == (year.has_value() && month.has_value() && dayofmonth.has_value())) + return std::nullopt; + std::chrono::year_month_day const date{std::chrono::year{*year}, std::chrono::month{static_cast(*month)}, + std::chrono::day{static_cast(*dayofmonth)}}; + if (false == date.ok()) + return std::nullopt; + return day{date}; +} + +std::string format_day(day const Day) { + std::chrono::year_month_day const date{Day}; + return std::format("{:04}-{:02}-{:02}", static_cast(date.year()), static_cast(date.month()), + static_cast(date.day())); +} + +// the day of a stamp line, as written, a day later than Today included. Today for a malformed one: the states after it +// are kept +day stamp_day(std::string_view const Line, day const Today) { + auto text{Line.substr(stamp_prefix.size())}; + while (false == text.empty() && (text.back() == ' ' || text.back() == '\t')) + text.remove_suffix(1); + return parse_day(text).value_or(Today); +} + } // namespace +day today() { + return std::chrono::floor(std::chrono::system_clock::now()); +} + +std::chrono::days expiry() { + return std::chrono::days{std::max(0, Global.odometer_expiry)}; +} + void reading::begin(double const Km, origin const Source) { km = Km; start = Km; @@ -89,12 +146,16 @@ bool reading::moved() const { return km != start; } -std::size_t store::read(std::istream &Input) { +std::size_t store::read(std::istream &Input, day const Today) { std::size_t count{0}; + // the states with no stamp before them, as the builds without the stamps wrote them, count as updated today + auto stamp{Today}; std::string line; while (std::getline(Input, line)) { if (false == line.empty() && line.back() == '\r') line.pop_back(); + if (line.starts_with(stamp_prefix)) + stamp = stamp_day(line, Today); if (line.empty() || line.front() == '#') continue; // the name goes last, it's the rest of the line after the separator @@ -109,7 +170,8 @@ std::size_t store::read(std::istream &Input) { auto const name{line.substr(separator + 1)}; if (false == km.has_value() || name.empty()) continue; - m_states[name] = state{*km, guessed}; + m_states[name] = state{*km, guessed, stamp}; + m_read_latest = std::max(m_read_latest.value_or(stamp), stamp); ++count; } return count; @@ -117,9 +179,23 @@ std::size_t store::read(std::istream &Input) { void store::write(std::ostream &Output) const { Output << "# odometer states of the vehicles: , ~ for one counted from a made up state\n"; + Output << "# the states after a line \"" << stamp_prefix << "\" were last updated on that day (UTC)\n"; Output << std::fixed << std::setprecision(4); - for (auto const &[name, state] : m_states) - Output << (state.guessed ? "~" : "") << state.km << ' ' << name << '\n'; + // by the day, then by the name as the map has them + std::vector::value_type const *> entries; + entries.reserve(m_states.size()); + for (auto const &entry : m_states) + entries.push_back(&entry); + std::ranges::stable_sort(entries, {}, [](auto const *Entry) { return Entry->second.updated; }); + std::optional group; + for (auto const *entry : entries) { + auto const &written{entry->second}; + if (group != written.updated) { + group = written.updated; + Output << stamp_prefix << format_day(written.updated) << '\n'; + } + Output << (written.guessed ? "~" : "") << written.km << ' ' << entry->first << '\n'; + } } std::optional store::find(std::string const &Vehicle) const { @@ -129,6 +205,13 @@ std::optional store::find(std::string const &Vehicle) const { return lookup->second.km; } +std::optional store::updated(std::string const &Vehicle) const { + auto const lookup{m_states.find(Vehicle)}; + if (lookup == m_states.end()) + return std::nullopt; + return lookup->second.updated; +} + bool store::guessed(std::string const &Vehicle) const { auto const lookup{m_states.find(Vehicle)}; return lookup != m_states.end() && lookup->second.guessed; @@ -140,10 +223,10 @@ bool store::newer(state const &Left, state const &Right) { return Left.km > Right.km; } -void store::record(std::string const &Vehicle, reading const &Odometer) { +void store::record(std::string const &Vehicle, reading const &Odometer, day const Today) { if (Vehicle.empty() || false == valid(Odometer.km)) return; - state const recorded{Odometer.km, Odometer.source == origin::guessed}; + state const recorded{Odometer.km, Odometer.source == origin::guessed, Today}; auto const lookup{m_states.find(Vehicle)}; if (lookup == m_states.end()) { if (false == Odometer.moved()) @@ -154,7 +237,10 @@ void store::record(std::string const &Vehicle, reading const &Odometer) { } if (false == newer(recorded, lookup->second)) return; + // a clock set back doesn't move the day back + auto const latest{std::max(lookup->second.updated, Today)}; lookup->second = recorded; + lookup->second.updated = latest; m_modified = true; } @@ -171,11 +257,32 @@ void record(store &States, std::string const &Vehicle, bool const Drivercab, rea void store::merge(store const &Other) { for (auto const &[name, other] : Other.m_states) { auto const [lookup, added] {m_states.try_emplace(name, other)}; - if (false == added && newer(other, lookup->second)) - lookup->second = other; + if (added) + continue; + auto &mine{lookup->second}; + auto const latest{std::max(mine.updated, other.updated)}; + if (newer(other, mine)) + mine = other; + mine.updated = latest; } } +std::size_t store::expire(day const Today, std::chrono::days const Period) { + if (Period <= std::chrono::days::zero()) + return 0; + // not from a later Today alone: a clock set forward, or the first save after a break, doesn't drop every state not + // run in this session + auto const since{std::min(Today, m_read_latest.value_or(Today))}; + return std::erase_if(m_states, [since, Period](auto const &Entry) { return since - Entry.second.updated > Period; }); +} + +bool store::holds(store const &Other) const { + return std::all_of(Other.m_states.begin(), Other.m_states.end(), [this](auto const &Entry) { + auto const lookup{m_states.find(Entry.first)}; + return lookup != m_states.end() && false == newer(Entry.second, lookup->second); + }); +} + std::optional read_legacy(std::istream &Input) { std::stringstream content; content << Input.rdbuf(); @@ -277,20 +384,46 @@ store &states() { return odometers; } -bool save(store &States, std::filesystem::path const &File) { - if (false == States.modified()) +namespace { + +// the states as the file holds them once written, the km rounded to the digits written +store as_written(store const &States, day const Today) { + std::stringstream text; + States.write(text); + store result; + result.read(text, Today); + return result; +} + +} // namespace + +bool save(store &States, std::filesystem::path const &File, day const Today, std::chrono::days const Period) { + if (false == States.modified() && false == States.unconfirmed()) return true; std::error_code error; + std::size_t expired{0}; if (File.has_parent_path()) std::filesystem::create_directories(File.parent_path(), error); // other simulations on the machine (multiplayer, parallel runs) keep their states in the same file: what they // saved since this one read it is merged in, not overwritten { + store saved; std::ifstream input{File, std::ios::binary}; - if (input.is_open()) { - store saved; - saved.read(input); - States.merge(saved); + if (input.is_open()) + saved.read(input, Today); + States.merge(saved); + // the vehicles not run for long, of this simulation and of the others alike, so the file doesn't keep every + // vehicle ever run. they're logged once the file is written without them: a save that doesn't write it leaves + // them in it (the next save that writes it drops them again), and a write that fails is tried again + expired = States.expire(Today, Period); + // another simulation that read the file before the last save of this one and put its own in place after it + // dropped the states this one wrote. when the file holds them all, the same or newer, there's nothing to write + if (false == States.modified()) { + if (saved.holds(as_written(States, Today))) { + States.confirmed(); + return true; + } + WriteLog("Odometer states saved to \"" + File.string() + "\" are missing from it, saving them again"); } } // written aside first, a crash in the middle of a write doesn't lose the states. the file aside is this process' @@ -325,6 +458,8 @@ bool save(store &States, std::filesystem::path const &File) { return false; } States.saved(); + if (expired > 0) + WriteLog(std::format("Odometer states of {} vehicles not updated for {} days dropped", expired, Period.count())); return true; } diff --git a/vehicle/odometer.h b/vehicle/odometer.h index 9708311f4..958a15f60 100644 --- a/vehicle/odometer.h +++ b/vehicle/odometer.h @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include #include #include #include @@ -23,6 +24,16 @@ http://mozilla.org/MPL/2.0/. // their own files namespace odometer { +// a calendar day, in UTC +using day = std::chrono::sys_days; +day today(); + +// a state not updated for longer than this is dropped from the store when it's saved: the vehicle wasn't run for that +// long. it's odometer.expiry in eu07.ini (global_settings::odometer_expiry), a year unless set there, 0 for never. +// a year so the vehicles of the scenarios played once a season or once a year, and of the players who take a break of a +// few months, keep their states; the file of the vehicles run within a year stays small all the same +std::chrono::days expiry(); + // the saved odometer states of the vehicles, km by vehicle name. the name is the one the scenario gives the vehicle // (the name of its node, TDynamicObject::name(), e.g. EU07-424), the only identity a vehicle has between the sessions: // the vehicles of the same name in any scenarios share one state, whatever their type, and a vehicle the scenario @@ -31,37 +42,65 @@ namespace odometer { class store { public: // reads the states written by write(). lines " ", "~ " for a state counted - // from a made up one, '#' starts a comment line, a malformed line is skipped. returns the number of states read - std::size_t read(std::istream &Input); + // from a made up one, '#' starts a comment line, a malformed line is skipped. returns the number of states read. + // the day a state was last updated is in a comment line "# updated " before it, which the builds + // without the stamps skip as any comment. a state with no stamp before it (a file of such a build) or with a + // malformed one counts as updated Today. a stamp is kept as written, also one later than Today (a clock set back + // doesn't move the days of the states back, expire() doesn't measure from them) + std::size_t read(std::istream &Input, day Today = today()); + // the states grouped by the day they were last updated, the oldest first, each group after its stamp line void write(std::ostream &Output) const; std::optional find(std::string const &Vehicle) const; // the state of the vehicle is counted from a made up one, which the cab's counter can still replace bool guessed(std::string const &Vehicle) const; + // the day the state of the vehicle was last updated + std::optional updated(std::string const &Vehicle) const; // records the state of a vehicle. one not in the store yet gets in only once it has run, so the vehicles // standing in the sceneries don't fill the file. a recorded state is replaced only by a newer one: a larger - // one, or a known one in place of a guessed one - void record(std::string const &Vehicle, reading const &Odometer); + // one, or a known one in place of a guessed one. a state recorded is updated Today, or keeps its later day: the day + // of a state never goes back + void record(std::string const &Vehicle, reading const &Odometer, day Today = today()); // takes the states of the other store (the file, as other simulations have saved it since) newer than these. // the odometers only count up, so of two states of a vehicle the larger is the newer one. they aren't added - // up: two simulations on one machine (multiplayer) count the same runs of the same vehicles + // up: two simulations on one machine (multiplayer) count the same runs of the same vehicles. a state is updated + // on the later of the days the two stores have void merge(store const &Other); + // drops the states not updated for longer than Period, 0 for none. the period is measured back from Today, or from + // the latest day of the states read() took when that's earlier: the last day the file was updated before this + // simulation read it. so a clock set forward doesn't drop the states at once (nor one set back, the days of the + // states are then later than Today), and a player back after a break keeps them in the session he comes back in; + // the states this session records, updated Today, don't count. returns the number dropped + std::size_t expire(day Today, std::chrono::days Period); + // this store holds every state of the other one, the same or a newer one + bool holds(store const &Other) const; // there are states recorded since they were last saved bool modified() const { return m_modified; } - void saved() { m_modified = false; } + // the states were written to the file. until a later save finds them there (confirmed()), they may have been lost to + // another simulation's save, which read the file before this one wrote it and put its own in place after + void saved() { + m_modified = false; + m_unconfirmed = true; + } + bool unconfirmed() const { return m_unconfirmed; } + void confirmed() { m_unconfirmed = false; } std::size_t size() const { return m_states.size(); } private: struct state { double km{0.0}; bool guessed{false}; + day updated{}; }; // the first state is newer than the second one static bool newer(state const &Left, state const &Right); std::map m_states; + // the latest day of the states read() took + std::optional m_read_latest; bool m_modified{false}; + bool m_unconfirmed{false}; }; // the vehicle is one the store keeps: one with a driver's cab, which can show its odometer on the cab's counter or a @@ -113,9 +152,12 @@ bool persistent(); store &states(); std::filesystem::path file(); // writes the store to the file when anything was recorded since, merged with what other simulations saved in the -// file meanwhile. it's written to a file of this process aside first, then put in place. returns false when the -// write failed -bool save(store &States, std::filesystem::path const &File); +// file meanwhile. it's written to a file of this process aside first, then put in place. with nothing recorded since, +// the file is read once more after a write, and written again when it lacks any of the states (another simulation's +// save put its file over this one's); otherwise left as it is. the states, those of the other simulations included, +// not updated for longer than Period (store::expire()) are dropped first; the number dropped is logged by the save that +// writes the file without them. returns false when the write failed +bool save(store &States, std::filesystem::path const &File, day Today = today(), std::chrono::days Period = expiry()); // saves the store of the simulation to its file. a test run doesn't save it bool save(); diff --git a/vehicle/pulleemode.h b/vehicle/pulleemode.h new file mode 100644 index 000000000..f01ed5768 --- /dev/null +++ b/vehicle/pulleemode.h @@ -0,0 +1,35 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include + +// the pullee mode ("jazda ciągniona", MaSzyna-EU07/maszyna#64): a vehicle prepared for being hauled dead in a train, +// TMoverParameters::PulleeModeSwitch(). a scenery asks for it with the parameter H among the ones written after the +// coupling of the vehicle, split by dots: "3.H", or with others, "3.BG.H" +// node -1 0 EU160-001 dynamic pkp/vectron_v1 1293-107 wariant_7w 0 nobody 3.H 0 enddynamic +namespace pullee_mode { + +// whether the parameters of a vehicle, the text after the first dot of its coupling entry, ask for the mode. a +// parameter is told by its first letter, as the others are (B brakes, W wheels, T temperatures, L load), in either +// case; the letters after the H are left for later +inline bool requested(std::string_view const Parameters) { + auto first{true}; // of a parameter + for (auto const character : Parameters) { + if (first && std::toupper(static_cast(character)) == 'H') { + return true; + } + first = character == '.'; + } + return false; +} + +} // namespace pullee_mode diff --git a/vehicle/signalpassing.cpp b/vehicle/signalpassing.cpp new file mode 100644 index 000000000..58d691760 --- /dev/null +++ b/vehicle/signalpassing.cpp @@ -0,0 +1,30 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/signalpassing.h" + +namespace signal_passing { + +bool seen_ahead_when_found( double const Distance, bool const Standing ) { + + return Distance >= ( Standing ? 0.0 : -moving_tolerance ); +} + +bool seen_ahead_on_update( double const Distance, bool const Seenahead ) { + + return Seenahead || Distance >= 0.0; +} + +bool passed_now( bool const Elapsedbefore, bool const Elapsed, bool const Seenahead ) { + + return Elapsed && !Elapsedbefore && Seenahead; +} + +} // namespace signal_passing diff --git a/vehicle/signalpassing.h b/vehicle/signalpassing.h new file mode 100644 index 000000000..33f2e5265 --- /dev/null +++ b/vehicle/signalpassing.h @@ -0,0 +1,38 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +// when a point of the AI's speed table (a signal above all) counts as passed by the train: the test mode's +// "signal passed at danger" and the blackbox record of passed signals (TController::CheckSignalPassed) +namespace signal_passing { + +// how far behind the head a point found by the scan of a moving train may lie and still count as one the head +// had ahead [m]. GetDistanceToEvent() finds the distance in steps of a metre from the position of the memory +// cell, so a signal just ahead of the head may come out a little behind it +inline constexpr double moving_tolerance { 5.0 }; + +// whether a point the scan finds Distance [m] ahead of the head (negative: behind it) counts as one the head had +// ahead. a moving train may be just passing it, so a point up to moving_tolerance behind counts. a standing train +// isn't passing anything: a point found behind its head was passed before (a train set or stopped past a signal), +// and counts only once an update finds it ahead. +// known gap: the distance can be off by about half a metre (GetDistanceToEvent() takes the nearest of samples a +// metre apart), so a train standing a few decimetres short of a signal may find it just behind the head, and if it +// then runs past it at stop, that isn't reported. a tolerance for a standing train wouldn't close it: the first +// update marks a point behind the head elapsed (TSpeedPos::Update()), so such a train would be reported as passing +// the signal at once, while it stands short of it. the AI stops 8-15 m short of a signal +bool seen_ahead_when_found( double Distance, bool Standing ); + +// whether the head had the point ahead, after an update finds it Distance [m] ahead of the head +bool seen_ahead_on_update( double Distance, bool Seenahead ); + +// whether an update of a point reports it as passed: it became elapsed in this update, and the head had it ahead +bool passed_now( bool Elapsedbefore, bool Elapsed, bool Seenahead ); + +} // namespace signal_passing diff --git a/vehicle/timetableservice.cpp b/vehicle/timetableservice.cpp new file mode 100644 index 000000000..913e9d2d4 --- /dev/null +++ b/vehicle/timetableservice.cpp @@ -0,0 +1,49 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "vehicle/timetableservice.h" + +#include "McZapkie/MOVER.h" + +namespace timetable { + +bool opens_doors(TMoverParameters const &Vehicle, service_flags const &Flags) { + switch (Vehicle.Doors.open_control) { + case control_t::conductor: + case control_t::driver: + return true; + case control_t::mixed: + // left to the passengers, unless the timetable has the driver open them all + return Flags.central_doors == tristate::yes; + default: + return false; + } +} + +std::optional doorstep(service_flags const &Flags) { + switch (Flags.doorstep) { + case tristate::yes: + return true; + case tristate::no: + return false; + default: + return std::nullopt; + } +} + +bool has_conductor(service_flags const &Flags) { + return Flags.conductor != tristate::no; +} + +bool makes_brake_test(service_flags const &Flags) { + return Flags.brake_test != tristate::no; +} + +} // namespace timetable diff --git a/vehicle/timetableservice.h b/vehicle/timetableservice.h new file mode 100644 index 000000000..b5c72adf7 --- /dev/null +++ b/vehicle/timetableservice.h @@ -0,0 +1,37 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include + +#include "world/timetableflags.h" + +class TMoverParameters; + +// what the AI driver does at a stop and on the way, as the service flags of the timetable ask (eu07/maszyna#95). with +// no flags each answer is the one the AI gave before the flags +namespace timetable { + +// whether the driver opens the doors of the consist from the cab at a stop, Vehicle being the one he drives: the doors +// the conductor or the driver opens, and with the central door opening also the ones of mixed control, which are +// otherwise left to the passengers +bool opens_doors(TMoverParameters const &Vehicle, service_flags const &Flags); + +// the state the driver sets the doorsteps to before he opens the doors at a stop, none when he leaves them as they are +std::optional doorstep(service_flags const &Flags); + +// whether a conductor serves the train: gives the departure signal (by radio or by voice) and keeps the first door +// open for himself until the departure +bool has_conductor(service_flags const &Flags); + +// whether the driver makes the running brake test after the departure +bool makes_brake_test(service_flags const &Flags); + +} // namespace timetable diff --git a/vehicle/universaldrag.h b/vehicle/universaldrag.h new file mode 100644 index 000000000..d25f93c57 --- /dev/null +++ b/vehicle/universaldrag.h @@ -0,0 +1,138 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include +#include + +// smooth regulation of the universal cab controls (MaSzyna-EU07/maszyna#62): a universal whose definition in the +// .mmd has "drag: " can be dragged with the mouse to any position between its ends (0 and 1), and stays +// where it is let go, like a window opened a crack or a sun blind pulled half way down. a click without dragging and +// the keys still move it to its ends, as they do any universal. universals without the key work as they always did +namespace universal_drag { + +// the way the mouse moves to take the control towards its end 1 (to open it); none: the control can't be dragged +enum class direction { none, up, down, left, right }; + +// the direction the value of the drag: key gives, nothing for a value it doesn't know +inline std::optional parse(std::string_view const Value) { + if (Value == "yes" || Value == "true" || Value == "1" || Value == "up") { + return direction::up; + } + if (Value == "down") { + return direction::down; + } + if (Value == "left") { + return direction::left; + } + if (Value == "right") { + return direction::right; + } + if (Value == "no" || Value == "false" || Value == "0" || Value == "none") { + return direction::none; + } + return std::nullopt; +} + +// a push (impulse) universal springs back when it is let go, so it can't be left anywhere in between +inline direction effective(direction const Drag, bool const Push) { + return Push ? direction::none : Drag; +} + +// the position of the control, kept between its ends +inline float clamp(double const Position) { + return static_cast(std::clamp(Position, 0.0, 1.0)); +} + +// how far the cursor moving by Dx, Dy pixels (y grows downwards, as the cursor's does) takes the control along the +// Drag direction, as a fraction of its full travel; Size is the move in pixels which takes it from one end to the other +inline double along(direction const Drag, double const Dx, double const Dy, double const Size) { + if (Size <= 0.0) { + return 0.0; + } + switch (Drag) { + case direction::up: + return -Dy / Size; + case direction::down: + return Dy / Size; + case direction::left: + return -Dx / Size; + case direction::right: + return Dx / Size; + default: + return 0.0; + } +} + +// the position the keys and a click move the control to: the end farther from the position it is set to, as for +// the two-state universals: a control open less than half way opens fully, one open half way or more closes +inline float toggled(float const Desired) { + return Desired < 0.5f ? 1.f : 0.f; +} + +// the travel of the cursor along the direction of the drag, as a fraction of the full travel of the control, under +// which letting the button go counts as a click rather than a drag +inline constexpr double click_travel{0.02}; + +// one drag of a control, from the press of the mouse button to its release +class drag { + + public: + drag(direction const Drag, float const Position) : m_direction{Drag}, m_position{clamp(Position)}, m_start{m_position} {} + + // the cursor moved to X, Y; Size is the move in pixels which takes the control from one end to the other. + // the first position of the cursor is only where the drag starts from: when the cursor gets hidden for the drag + // it can be put elsewhere. returns whether the position of the control changed + bool move(double const X, double const Y, double const Size) { + if (false == m_started) { + m_started = true; + m_x = X; + m_y = Y; + return false; + } + auto const step{along(m_direction, X - m_x, Y - m_y, Size)}; + m_x = X; + m_y = Y; + m_travel += std::abs(step); + // the position follows each move from where it is, so after the control reached its end, moving the cursor + // back takes it back at once rather than after the overshoot is undone + auto const position{clamp(m_position + step)}; + if (position == m_position) { + return false; + } + m_position = position; + return true; + } + // the position the control is dragged to + float position() const { + return m_position; + } + // the position the control was in when the drag started + float start() const { + return m_start; + } + // whether letting the button go now is a click rather than a drag: the cursor barely moved along the direction + bool is_click() const { + return m_travel < click_travel; + } + + private: + direction m_direction; + float m_position; + float m_start; + bool m_started{false}; + double m_x{0.0}; + double m_y{0.0}; + double m_travel{0.0}; // the moves of the cursor along the direction, either way, as fractions of the full travel +}; + +} // namespace universal_drag diff --git a/widgets/perfgraphs.cpp b/widgets/perfgraphs.cpp index 041a25134..83221d696 100644 --- a/widgets/perfgraphs.cpp +++ b/widgets/perfgraphs.cpp @@ -49,13 +49,13 @@ void perfgraph_panel::render_contents() { if (!stopwatch) return; - history[pos] = static_cast(static_cast(stopwatch->last().count()) / 1000.0); - const std::string label = std::to_string(history[pos]) + "ms"; + history[history_pos] = static_cast(static_cast(stopwatch->last().count()) / 1000.0); + const std::string label = std::to_string(history[history_pos]) + "ms"; - pos++; - if (pos >= history.size()) - pos = 0; + history_pos++; + if (history_pos >= history.size()) + history_pos = 0; ImGui::SliderFloat(STR_C("Range"), &max, 0.1f, 250.0f); - ImGui::PlotLines("##timer", &history[0], static_cast(history.size()), static_cast(pos), label.c_str(), 0.0f, max, ImVec2(500, 200)); + ImGui::PlotLines("##timer", &history[0], static_cast(history.size()), static_cast(history_pos), label.c_str(), 0.0f, max, ImVec2(500, 200)); } diff --git a/widgets/perfgraphs.h b/widgets/perfgraphs.h index d3ddb3c6d..961f98fcd 100644 --- a/widgets/perfgraphs.h +++ b/widgets/perfgraphs.h @@ -3,7 +3,7 @@ class perfgraph_panel : public ui_panel { std::array history = { 0 }; - size_t pos = 0; + size_t history_pos = 0; enum timers_e { gfx_total = 0, diff --git a/world/Event.cpp b/world/Event.cpp index 80697cfa2..814cd9918 100644 --- a/world/Event.cpp +++ b/world/Event.cpp @@ -29,6 +29,7 @@ http://mozilla.org/MPL/2.0/. #include "model/AnimModel.h" #include "vehicle/DynObj.h" #include "vehicle/Driver.h" +#include "vehicle/crewchange.h" #include "rendering/renderer.h" #include "utilities/Timer.h" #include "utilities/Logs.h" @@ -177,110 +178,6 @@ basic_event::event_conditions::test() const { return true; } -void -basic_event::event_conditions::deserialize( cParser &Input ) { - // przetwarzanie warunków, wspólne dla Multiple i UpdateValues - - std::string token; - while( true == Input.getTokens() - && false == (token = Input.peek()).empty() - && false == basic_event::is_keyword(token) ) { - - if( token == "trackoccupied" ) { - flags |= flags::track_busy; - } - else if( token == "trackfree" ) { - flags |= flags::track_free; - } - else if( token == "propability" || token == "probability") { //remove propability in few years after changing old scenery scripts 01.2021 - flags |= flags::probability; - Input.getTokens(); - Input >> probability; - } - else if( token == "memcompare" ) { - Input.getTokens( 1, false ); // case sensitive - if( Input.peek() != "*" ) //"*" - nie brac command pod uwage - { // zapamiętanie łańcucha do porównania - Input >> memcompare_text; - flags |= flags::text; - } - Input.getTokens(); - if( Input.peek() != "*" ) //"*" - nie brac val1 pod uwage - { - Input >> memcompare_value1; - flags |= flags::value1; - } - Input.getTokens(); - if( Input.peek() != "*" ) //"*" - nie brac val2 pod uwage - { - Input >> memcompare_value2; - flags |= flags::value2; - } - } - else if( token == "memcompareex" ) { - memcompare_pass = comparison_pass_from_string( Input.getToken() ); - Input.getTokens(); - if( Input.peek() != "*" ) //"*" - nie brac pod uwage - { // two tokens, operator followed by comparison value - std::string operatorstring; - Input >> operatorstring; - memcompare_text_operator = comparison_operator_from_string( operatorstring ); - Input.getTokens( 1, false ); // case sensitive - Input >> memcompare_text; - flags |= flags::text; - } - Input.getTokens(); - if( Input.peek() != "*" ) //"*" - nie brac pod uwage - { // two tokens, operator followed by comparison value - std::string operatorstring; - Input >> operatorstring; - memcompare_value1_operator = comparison_operator_from_string( operatorstring ); - Input.getTokens(); - Input >> memcompare_value1; - flags |= flags::value1; - } - Input.getTokens(); - if( Input.peek() != "*" ) //"*" - nie brac pod uwage - { // two tokens, operator followed by comparison value - std::string operatorstring; - Input >> operatorstring; - memcompare_value2_operator = comparison_operator_from_string( operatorstring ); - Input.getTokens(); - Input >> memcompare_value2; - flags |= flags::value2; - } - } - } -} - -// sends basic content of the class in legacy (text) format to provided stream -void -basic_event::event_conditions::export_as_text( std::ostream &Output ) const { - - if( flags != 0 ) { - Output << "condition "; - if( ( flags & flags::track_busy ) != 0 ) { - Output << "trackoccupied "; - } - if( ( flags & flags::track_free ) != 0 ) { - Output << "trackfree "; - } - if( ( flags & flags::probability ) != 0 ) { - Output - << "probability " - << probability << ' '; - } - if( ( flags & ( flags::text | flags::value1 | flags::value2 ) ) != 0 ) { - // NOTE: export doesn't preserve original memcompare condition, these are all upgraded to memcompareex format for simplicity - Output - << "memcompareex " - << ( ( flags & flags::text ) == 0 ? "*" : memcompare_text + ' ' + to_string( memcompare_text_operator ) ) << ' ' - << ( ( flags & flags::value1 ) == 0 ? "*" : std::to_string( memcompare_value1 ) + ' ' + to_string( memcompare_value1_operator ) ) << ' ' - << ( ( flags & flags::value2 ) == 0 ? "*" : std::to_string( memcompare_value2 ) + ' ' + to_string( memcompare_value2_operator ) ) << ' '; - } - } -} - basic_event::~basic_event() { m_sibling = nullptr; // nie usuwać podczepionych tutaj @@ -439,12 +336,10 @@ basic_event::input_location() const { return glm::dvec3( 0, 0, 0 ); }; -bool -basic_event::is_keyword( std::string const &Token ) { - // TODO: convert to array lookup if keyword list gets longer - return Token == "endevent" - || Token == "randomdelay" - || Token == "departuredelay"; +TMemCell const * +basic_event::input_cell() const { + + return nullptr; } @@ -676,6 +571,12 @@ getvalues_event::input_location() const { return m_input.data_cell()->location(); // współrzędne podłączonej komórki pamięci } +TMemCell const * +getvalues_event::input_cell() const { + + return m_input.data_cell(); +} + // prepares event for use @@ -716,7 +617,8 @@ putvalues_event::deserialize_( cParser &Input, scene::scratch_data &Scratchpad ) if( contains( token, '#' ) ) { token.erase( token.find( '#' ) ); // obcięcie unikatowości } - win1250_to_ascii( token ); // get rid of non-ascii chars + // NOTE: the name stays as the scenery spells it, with its polish letters; whoever matches it with the name + // a timetable has goes by timetable::stop_point_is_for(), which takes any spelling of the station m_input.command_type = TCommandType::cm_PassengerStopPoint; // nie do kolejki (dla SetVelocity też, ale jak jest do toru dowiązany) m_passive = true; @@ -781,6 +683,12 @@ putvalues_event::run_() { + to_string( m_input.data_value_1, 2 ) + "] [" + to_string( m_input.data_value_2, 2 ) + "]" ); + if( crew::is_command( m_input.data_text ) ) { + // a driver for the vehicle named in the command, or none (eu07/maszyna#510). not a command for a driver or + // a vehicle to take, and it works with nothing setting the event off too (a key, an event launcher) + crew::change( crew::parse( m_input.data_text, m_input.data_value_1, m_input.data_value_2 ), m_activator ); + return; + } if( m_activator == nullptr ) { return; } // zamiana, bo fizyka ma inaczej niż sceneria // NOTE: y & z swap, negative x @@ -2054,6 +1962,69 @@ track_event::export_as_text_( std::ostream &Output ) const { +// prepares event for use +void +buckle_event::init() { + + init_targets( simulation::Paths, "track" ); +} + +// event type string +std::string +buckle_event::type() const { + + return "trackbuckle"; +} + +// deserialize() subclass details +void +buckle_event::deserialize_( cParser &Input, scene::scratch_data &Scratchpad ) { + + Input.getTokens(); + Input >> m_buckle.amplitude; + m_buckle.amplitude = std::clamp( m_buckle.amplitude, 0.f, static_cast( 1000.0 * track_buckle::most_amplitude ) ); + Input.getTokens(); + // the length, the centre and the side, each optional + if( false == is_keyword( Input.peek() ) ) { + Input >> m_buckle.length; + if( m_buckle.length > 0.f ) { + m_buckle.length = std::clamp( m_buckle.length, static_cast( track_buckle::least_length ), static_cast( track_buckle::most_length ) ); + } + Input.getTokens(); + } + if( false == is_keyword( Input.peek() ) ) { + Input >> m_buckle.centre; + Input.getTokens(); + } + if( false == is_keyword( Input.peek() ) ) { + auto side { 0.f }; + Input >> side; + m_buckle.side = ( side > 0.f ? 1 : side < 0.f ? -1 : 0 ); + Input.getTokens(); + } +} + +// run() subclass details +void +buckle_event::run_() { + + WriteLog( "Type: TrackBuckle - [" + to_string( m_buckle.amplitude, 0 ) + " mm]" ); + for( auto &target : m_targets ) { + auto *targettrack = static_cast( std::get( target ) ); + if( targettrack == nullptr ) { continue; } + targettrack->buckle_now( m_buckle, "event " + m_name ); + } +} + +// export_as_text() subclass details +void +buckle_event::export_as_text_( std::ostream &Output ) const { + + Output << m_buckle.amplitude << ' ' << m_buckle.length << ' ' << m_buckle.centre << ' ' << m_buckle.side << ' '; +} + + + // prepares event for use void voltage_event::init() { @@ -2310,6 +2281,7 @@ make_event( cParser &Input, scene::scratch_data &Scratchpad ) { else if( type == "multiple" ) { event = new multi_event(); } else if( type == "switch" ) { event = new switch_event(); } else if( type == "trackvel" ) { event = new track_event(); } + else if( type == "trackbuckle" ) { event = new buckle_event(); } else if( type == "sound" ) { event = new sound_event(); } else if( type == "texture" ) { event = new texture_event(); } else if( type == "animation" ) { event = new animation_event(); } diff --git a/world/Event.h b/world/Event.h index f1d75689b..c86fb8275 100644 --- a/world/Event.h +++ b/world/Event.h @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "scene/scene.h" #include "utilities/Names.h" #include "world/EvLaunch.h" +#include "world/TrackBuckle.h" #include "utilities/Logs.h" #include "input/command.h" #include "utilities/comparison.h" @@ -84,6 +85,8 @@ public: virtual TCommandType input_command() const; virtual double input_value( int Index ) const; virtual glm::dvec3 input_location() const; + // the memory cell the data comes from, null if the event doesn't read one + virtual TMemCell const *input_cell() const; void group( scene::group_handle Group ); scene::group_handle group() const; std::string const &name() const { return m_name; } @@ -242,6 +245,7 @@ public: TCommandType input_command() const override; double input_value( int Index ) const override; glm::dvec3 input_location() const override; + TMemCell const *input_cell() const override; private: // methods @@ -527,6 +531,31 @@ private: +// trackbuckle [ [ []]]: the target tracks buckle in the heat as the entry +// "buckle" of a track says (see world/TrackBuckle.h), amplitude 0 straightens them +class buckle_event : public basic_event { + +public: +// methods + // prepares event for use + void init() override; + +private: +// methods + // event type string + std::string type() const override; + // deserialize() subclass details + void deserialize_( cParser &Input, scene::scratch_data &Scratchpad ) override; + // run() subclass details + void run_() override; + // export_as_text() subclass details + void export_as_text_( std::ostream &Output ) const override; +// members + track_buckle::declared m_buckle; +}; + + + class voltage_event : public basic_event { public: diff --git a/world/Road.cpp b/world/Road.cpp index 3455bf791..bbfb9d8cc 100644 --- a/world/Road.cpp +++ b/world/Road.cpp @@ -875,7 +875,7 @@ glm::dvec3 road_node::state::tangent(double const T) const road_node::road_node(scene::node_data const &Nodedata) : basic_node(Nodedata) {} // restores content of the node from provided input stream; reads up to and including the closing 'endroad' -void road_node::import(cParser &Input, glm::dvec3 const &Offset) +void road_node::import_from(cParser &Input, glm::dvec3 const &Offset) { auto const label{m_name.empty() ? std::string{"unnamed road"} : "road \"" + m_name + "\""}; @@ -956,6 +956,14 @@ void road_node::import(cParser &Input, glm::dvec3 const &Offset) m_state.surface = Input.getToken(); replace_slashes(m_state.surface); } + else if (token == "surfacetype") + { + auto const type{Input.getToken()}; + if (false == road_surface::from_name(type, m_state.surfacetype)) + { + ErrorLog("Bad road: unknown surface type \"" + type + "\" defined for " + label + ", paved is used instead"); + } + } else if (token == "texlength") { Input.getTokens(); @@ -2307,7 +2315,7 @@ std::vector junction_node::state::outline(std::vector , // kerbs , bank , // bankmaterial , weight , roundabout, +// surfacetype : what the road is made of, which sets how tight the road editor lets it be laid out; paved unless told otherwise, // lanesto : lanes the piece has at the end of its axis, where these aren't the ones it starts with class road_node : public scene::basic_node { @@ -134,7 +136,8 @@ class road_node : public scene::basic_node std::vector lanes; std::vector changes; // permissions to change the lane, one for each pair of neighbouring lanes std::array taper{1.f, 1.f}; // what the widths of the lanes are multiplied by at the start and at the end of the axis - std::string surface{"asphaltdark1"}; + std::string surface{road_surface::default_material(road_surface_type::paved)}; + road_surface_type surfacetype{road_surface_type::paved}; // what the road is made of, as far as laying it out goes float texturelength{4.f}; std::array sides; // left, right float kerbheight{0.12f}; @@ -220,7 +223,7 @@ class road_node : public scene::basic_node explicit road_node(scene::node_data const &Nodedata); // methods // restores content of the node from provided input stream; reads up to and including the closing 'endroad' - void import(cParser &Input, glm::dvec3 const &Offset); + void import_from(cParser &Input, glm::dvec3 const &Offset); state const &definition() const { return m_state; @@ -441,7 +444,7 @@ class junction_node : public scene::basic_node explicit junction_node(scene::node_data const &Nodedata); // methods // restores content of the node from provided input stream; reads up to and including the closing 'endjunction' - void import(cParser &Input, glm::dvec3 const &Offset); + void import_from(cParser &Input, glm::dvec3 const &Offset); state const &definition() const { return m_state; diff --git a/world/RoadPoint.cpp b/world/RoadPoint.cpp index 14ff57a0e..776d747e4 100644 --- a/world/RoadPoint.cpp +++ b/world/RoadPoint.cpp @@ -327,7 +327,7 @@ std::vector roadpoint_node::parse_vehicles(std::st } // restores content of the node from provided input stream; reads up to and including the closing statement -void roadpoint_node::import(cParser &Input, glm::dvec3 const &Offset) +void roadpoint_node::import_from(cParser &Input, glm::dvec3 const &Offset) { auto const type{keyword(m_state.kind)}; auto const label{type + " \"" + m_name + "\""}; @@ -1060,8 +1060,7 @@ void roadpoint_node::update_spawn(double const Deltatime) auto *vehicle{entry.vehicle}; // it comes back the way it was made: whole, at speed, with the driver told to drive on vehicle->bEnabled = true; - vehicle->MoverParameters->DamageFlag = 0; - vehicle->MoverParameters->EngDmgFlag = 0; + vehicle->MoverParameters->repair_damage(); vehicle->MoverParameters->V = entry.velocity; vehicle->place_on_track(m_lanes.front(), m_offset + 0.5 * vehicle->MoverParameters->Dim.L, false); if (vehicle->Mechanik != nullptr) diff --git a/world/RoadPoint.h b/world/RoadPoint.h index fd5fdc731..f3e1dd0e4 100644 --- a/world/RoadPoint.h +++ b/world/RoadPoint.h @@ -102,7 +102,7 @@ class roadpoint_node : public scene::basic_node explicit roadpoint_node(scene::node_data const &Nodedata); // methods // restores content of the node from provided input stream; reads up to and including the closing statement - void import(cParser &Input, glm::dvec3 const &Offset); + void import_from(cParser &Input, glm::dvec3 const &Offset); state const &definition() const { return m_state; diff --git a/world/RoadSurfaceType.h b/world/RoadSurfaceType.h new file mode 100644 index 000000000..d71215ba2 --- /dev/null +++ b/world/RoadSurfaceType.h @@ -0,0 +1,63 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include + +// what a road is made of, as far as laying it out goes. a paved road (asphalt, concrete, setts) keeps to the bends and the angles +// of a built road; a dirt road (a track between fields, through a forest) turns tighter, comes in shorter stretches +// and leaves other roads at sharper angles. +// scenery entry: surfacetype , written for a dirt road only +enum class road_surface_type +{ + paved, + dirt +}; + +namespace road_surface +{ + +// the word the scenery uses for the type +inline char const *name(road_surface_type const Type) +{ + return Type == road_surface_type::dirt ? "dirt" : "paved"; +} + +// the type going by specified word. returns: false if there's no such type, with Type left as it was +inline bool from_name(std::string_view const Name, road_surface_type &Type) +{ + if (Name == "paved") + { + Type = road_surface_type::paved; + return true; + } + if (Name == "dirt") + { + Type = road_surface_type::dirt; + return true; + } + return false; +} + +// the scenery entry of the type, followed by a space. a paved road, which all the roads made before the types are, writes nothing, +// so the sceneries are saved as they were +inline std::string entry(road_surface_type const Type) +{ + return Type == road_surface_type::paved ? std::string{} : std::string{"surfacetype "} + name(Type) + ' '; +} + +// the material the surface of a road of the type gets unless told otherwise: the default asphalt, or the field road of the game's textures +inline char const *default_material(road_surface_type const Type) +{ + return Type == road_surface_type::dirt ? "droga_polna" : "asphaltdark1"; +} + +} // namespace road_surface diff --git a/world/Segment.cpp b/world/Segment.cpp index 5da1d0ad7..6e0326c33 100644 --- a/world/Segment.cpp +++ b/world/Segment.cpp @@ -141,6 +141,10 @@ bool TSegment::Init(glm::dvec3 &NewPoint1, glm::dvec3 NewCPointOut, glm::dvec3 N // dense enough for the waves; a switch keeps its division, the blades depend on it fStep = std::min( fStep, 2.0 ); } + if( m_setting.buckled ) { + // and for the lobes of a buckle, 9 m and more + fStep = std::min( fStep, 1.0 ); + } // NOTE: optionally replace this part with the commented version, after solving geometry issues with double switches if( pOwner->eType == tt_Switch && fStep * (3.0 * Global.SplineFidelity) > fLength ) { @@ -433,16 +437,36 @@ Math3D::vector3 TSegment::GetPoint(double const fDistance) const }; */ -glm::dvec3 TSegment::stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance ) const { - auto const field { track_uneven::field( Point ) }; - glm::dvec3 result { - field.x * Amount.side * track_uneven::stray_side_per_mm, - field.y * Amount.up * track_uneven::stray_up_per_mm, - field.z * Amount.side * track_uneven::stray_side_per_mm }; - result.y -= pOwner->joint_dip( Distance ); +glm::dvec3 TSegment::stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance, glm::dvec3 const &Across ) const { + glm::dvec3 result { 0.0 }; + if( m_setting.uneven ) { + auto const field { track_uneven::field( Point ) }; + result = glm::dvec3 { + field.x * Amount.side * track_uneven::stray_side_per_mm, + field.y * Amount.up * track_uneven::stray_up_per_mm, + field.z * Amount.side * track_uneven::stray_side_per_mm }; + result.y -= pOwner->joint_dip( Distance ); + } + if( m_setting.buckled && m_pieces.empty() ) { + result += Across * track_buckle::offset( pOwner->buckle(), Distance ); + } return result; } +double TSegment::buckle_bend( double const Distance, double const Base ) const { + if( false == m_setting.buckled || false == m_pieces.empty() ) { + return 0.0; + } + return track_buckle::mean_bend( pOwner->buckle(), Distance, Base ); +} + +glm::dvec3 TSegment::across_at( double const Distance ) const { + glm::dvec3 point; + glm::dvec3 across; + plan_frame( Distance, point, across ); + return across; +} + glm::dvec3 TSegment::uneven_bend( double const Distance ) const { if( false == m_setting.uneven ) { return glm::dvec3 { 0.0 }; @@ -457,12 +481,13 @@ glm::dvec3 TSegment::uneven_bend( double const Distance ) const { if( auto const direction { FastGetDirection( t, 0.1 / fLength ) }; on != At && glm::length( direction ) > 0.0 ) { point += direction * ( ( At - on ) / glm::length( direction ) ); } - return stray( point, pOwner->uneven_at( At, m_setting.path ), At ); }; + // the buckle left out: its curvature is taken on its own, see buckle_bend() + return stray( point, pOwner->uneven_at( At, m_setting.path ), At, glm::dvec3 { 0.0 } ); }; return ( strayed( Distance + reach ) - 2.0 * strayed( Distance ) + strayed( Distance - reach ) ) / ( reach * reach ); } void TSegment::settle_vertex( gfx::basic_vertex &Vertex, glm::dvec3 const &Origin, glm::vec3 const &Position, glm::vec3 const &Parallel, double const Distance ) const { - if( false == m_setting.uneven ) { + if( false == m_setting.uneven && false == m_setting.buckled ) { return; } // the rails settling apart turn about the middle of the track, what's outside them follows the rail; the foot of the ballast stays @@ -472,9 +497,9 @@ void TSegment::settle_vertex( gfx::basic_vertex &Vertex, glm::dvec3 const &Origi if( share <= 0.0 ) { return; } - auto const amount { pOwner->uneven_at( Distance, m_setting.path ) }; + auto const amount { m_setting.uneven ? pOwner->uneven_at( Distance, m_setting.path ) : track_uneven::amounts {} }; Vertex.position.y -= static_cast( share * track_uneven::stray_up_per_mm * amount.cross * track_uneven::level( Origin + glm::dvec3 { Position }, glm::dvec3 { Parallel } ) * across / gauge ); - Vertex.position += glm::vec3 { share * stray( Origin + glm::dvec3 { Vertex.position }, amount, Distance ) }; + Vertex.position += glm::vec3 { share * stray( Origin + glm::dvec3 { Vertex.position }, amount, Distance, glm::dvec3 { Parallel } ) }; } void TSegment::RaPositionGet(double const fDistance, glm::dvec3 &position, glm::vec3 &rotation) const { @@ -505,17 +530,18 @@ void TSegment::RaPositionGet(double const fDistance, glm::dvec3 &position, glm:: rotation.y = static_cast(fStoop); // pochylenie toru prostego rotation.z = static_cast(fDirection); // kierunek toru w planie } - if( false == m_setting.uneven ) { + if( false == m_setting.uneven && false == m_setting.buckled ) { return; } - // direction and slope stay as designed: the physics takes the curve radius and the grade from them + // direction and slope stay as designed: the physics takes the curve radius and the grade from them, and the curvature of a buckle + // on its own (buckle_bend()) auto const gauge { std::max( std::abs( pOwner->fTrackWidth ), 0.1f ) }; glm::dvec3 const across { -std::cos( rotation.z ), 0.0, -std::sin( rotation.z ) }; - auto const amount { pOwner->uneven_at( fDistance, m_setting.path ) }; + auto const amount { m_setting.uneven ? pOwner->uneven_at( fDistance, m_setting.path ) : track_uneven::amounts {} }; rotation.x += static_cast( track_uneven::stray_up_per_mm * ( amount.up * track_uneven::roll( position, across, gauge ) + amount.cross * track_uneven::level( position, across ) / gauge ) ); - position += track_uneven::across_only( stray( position, amount, fDistance ), across ); + position += track_uneven::across_only( stray( position, amount, fDistance, across ), across ); }; void TSegment::plan_frame( double const Distance, glm::dvec3 &Point, glm::dvec3 &Across ) const { diff --git a/world/Segment.h b/world/Segment.h index 596d95912..88aa9adff 100644 --- a/world/Segment.h +++ b/world/Segment.h @@ -109,6 +109,7 @@ class TSegment struct setting { std::array designrolls { 0.f, 0.f }; // as entered; fRoll1 and fRoll2 can differ at a joint bool uneven { false }; // see TrackUneven.h + bool buckled { false }; // see TrackBuckle.h int path { 0 }; // which path of a switch // where the path meets the next one: the middle of their ends and their common vector across std::array>, 2> joints; @@ -145,8 +146,9 @@ class TSegment // moves a lofted vertex with the unevenness of the track void settle_vertex( gfx::basic_vertex &Vertex, glm::dvec3 const &Origin, glm::vec3 const &Position, glm::vec3 const &Parallel, double const Distance ) const; - // displacement of a point by the unevenness, at a distance along the path - glm::dvec3 stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance ) const; + // displacement of a point by the unevenness, at a distance along the path, and by the buckle of the track across it, along Across + // (none along a zero vector) + glm::dvec3 stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance, glm::dvec3 const &Across ) const; public: bool bCurve = false; @@ -201,6 +203,10 @@ public: set_uneven( bool const Uneven, int const Path = 0 ) { m_setting.uneven = Uneven; m_setting.path = Path; } + // call before Init too + void + set_buckled( bool const Buckled ) { + m_setting.buckled = Buckled; } // a point of the path and the unit vector across it in the plan, towards the right rail profile; zero for a path never made void plan_frame( double const Distance, glm::dvec3 &Point, glm::dvec3 &Across ) const; @@ -214,6 +220,13 @@ public: // second derivative of the displacement along the path; times speed squared: acceleration of an axle glm::dvec3 uneven_bend( double const Distance ) const; + // the curvature the buckle of the track adds to the path at the distance, 1/m, positive bending towards its right; averaged over Base + // around it, as a bogie or a body takes it + double + buckle_bend( double const Distance, double const Base = 0.0 ) const; + // the unit vector across the path at the distance, towards its right + glm::dvec3 + across_at( double const Distance ) const; glm::dvec3 FastGetPoint(double const t) const; inline glm::dvec3 diff --git a/world/SleeperModels.cpp b/world/SleeperModels.cpp index 0efba7425..e820fc5f6 100644 --- a/world/SleeperModels.cpp +++ b/world/SleeperModels.cpp @@ -23,8 +23,6 @@ http://mozilla.org/MPL/2.0/. #include #include -#include -#include #include #include @@ -328,44 +326,6 @@ double plain_length( TTrack const &Track ) { return 2.0 * ( 0.5 * std::abs( Track.fTrackWidth ) + rail_reach + beam_overhang ); } -namespace { - -// the model of sleepers or timbers of the file added to those found, once by its name, what goes wrong left in the error -void add_pack_model( std::filesystem::directory_entry const &Entry, std::filesystem::path const &Root, std::error_code &Error, std::vector &Models ) { - - namespace fs = std::filesystem; - if( false == Entry.is_regular_file( Error ) ) { - return; - } - auto const extension { ToLower( Entry.path().extension().string() ) }; - if( extension != ".t3d" && extension != ".e3d" ) { - return; - } - auto name { ToLower( fs::relative( Entry.path(), Root, Error ).replace_extension().generic_string() ) }; - if( Error || name.empty() ) { - return; - } - if( name.find( "podklad" ) == std::string::npos && name.find( "podrozjazd" ) == std::string::npos - && name.find( "sleeper" ) == std::string::npos && name.find( "timber" ) == std::string::npos ) { - return; - } - // a timber model has the parts it's put together from, told by their names in the file - std::ifstream file { Entry.path(), std::ios::binary }; - std::string const content { std::istreambuf_iterator( file ), std::istreambuf_iterator() }; - auto const has = [ &extension, &content ]( std::string const &Part ) { - return ( - extension == ".t3d" ? - content.find( "Name: " + Part + "\n" ) != std::string::npos || content.find( "Name: " + Part + " " ) != std::string::npos - || content.find( "Name: " + Part + "\r" ) != std::string::npos : - content.find( std::string { '\0' } + Part + '\0' ) != std::string::npos ); }; - auto const timber { has( "begin" ) && has( "main" ) && has( "end" ) }; - if( std::ranges::none_of( Models, [ &name ]( pack_model const &Model ) { return Model.name == name; } ) ) { - Models.emplace_back( std::move( name ), timber ); - } -} - -} // namespace - std::vector const &pack_models() { static std::vector models; @@ -374,20 +334,7 @@ std::vector const &pack_models() { return models; } scanned = true; - namespace fs = std::filesystem; - std::error_code error; - auto const root { fs::path { paths::models } }; - fs::recursive_directory_iterator entry { root, fs::directory_options::follow_directory_symlink | fs::directory_options::skip_permission_denied, error }; - fs::recursive_directory_iterator const end; - while( entry != end ) { - if( error ) { - break; - } - add_pack_model( *entry, root, error, models ); - entry.increment( error ); - } - std::ranges::sort( models, []( pack_model const &Left, pack_model const &Right ) { - return ( Left.timber != Right.timber ? Left.timber : Left.name < Right.name ); } ); + models = pack_models( std::filesystem::path { paths::models } ); return models; } diff --git a/world/SleeperPack.cpp b/world/SleeperPack.cpp new file mode 100644 index 000000000..b04c573bb --- /dev/null +++ b/world/SleeperPack.cpp @@ -0,0 +1,91 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" + +#include "world/TrackSleepers.h" +#include "utilities/utilities.h" + +#include +#include +#include +#include + +// the models of sleepers and timbers found among the files of a folder, by their names; apart from the models drawn, so the +// unit tests can look through a folder of their own + +namespace track_sleepers { + +namespace { + +// the model of sleepers or timbers of the file added to those found, once by its name, what goes wrong left in the error +void add_pack_model( std::filesystem::directory_entry const &Entry, std::filesystem::path const &Root, std::error_code &Error, std::vector &Models ) { + + namespace fs = std::filesystem; + if( false == Entry.is_regular_file( Error ) ) { + return; + } + // a name with a character the code page lacks throws as it's turned into the narrow names the models are loaded by, which + // couldn't open the file anyway: the file is left out, not the rest of the folder with it + std::string extension; + std::string name; + try { + extension = ToLower( Entry.path().extension().string() ); + if( extension != ".t3d" && extension != ".e3d" ) { + return; + } + name = ToLower( fs::relative( Entry.path(), Root, Error ).replace_extension().generic_string() ); + } + catch( std::exception const & ) { + return; + } + if( Error || name.empty() ) { + return; + } + if( name.find( "podklad" ) == std::string::npos && name.find( "podrozjazd" ) == std::string::npos + && name.find( "sleeper" ) == std::string::npos && name.find( "timber" ) == std::string::npos ) { + return; + } + // a timber model has the parts it's put together from, told by their names in the file + std::ifstream file { Entry.path(), std::ios::binary }; + std::string const content { std::istreambuf_iterator( file ), std::istreambuf_iterator() }; + auto const has = [ &extension, &content ]( std::string const &Part ) { + return ( + extension == ".t3d" ? + content.find( "Name: " + Part + "\n" ) != std::string::npos || content.find( "Name: " + Part + " " ) != std::string::npos + || content.find( "Name: " + Part + "\r" ) != std::string::npos : + content.find( std::string { '\0' } + Part + '\0' ) != std::string::npos ); }; + auto const timber { has( "begin" ) && has( "main" ) && has( "end" ) }; + if( std::ranges::none_of( Models, [ &name ]( pack_model const &Model ) { return Model.name == name; } ) ) { + Models.emplace_back( std::move( name ), timber ); + } +} + +} // namespace + +std::vector pack_models( std::filesystem::path const &Root ) { + + namespace fs = std::filesystem; + std::vector models; + std::error_code error; + fs::recursive_directory_iterator entry { Root, fs::directory_options::follow_directory_symlink | fs::directory_options::skip_permission_denied, error }; + fs::recursive_directory_iterator const end; + while( entry != end ) { + if( error ) { + break; + } + add_pack_model( *entry, Root, error, models ); + entry.increment( error ); + } + std::ranges::sort( models, []( pack_model const &Left, pack_model const &Right ) { + return ( Left.timber != Right.timber ? Left.timber : Left.name < Right.name ); } ); + return models; +} + +} // namespace track_sleepers diff --git a/world/Sweep.cpp b/world/Sweep.cpp index 75270d42d..aacefa142 100644 --- a/world/Sweep.cpp +++ b/world/Sweep.cpp @@ -404,7 +404,7 @@ bool sweep_node::state::operator==(state const &Other) const sweep_node::sweep_node(scene::node_data const &Nodedata) : basic_node(Nodedata) {} -void sweep_node::import(cParser &Input, glm::dvec3 const &Offset) +void sweep_node::import_from(cParser &Input, glm::dvec3 const &Offset) { m_state = state{}; m_state.model = Input.getToken(); diff --git a/world/Sweep.h b/world/Sweep.h index 2e65f5fa9..b83b7fa12 100644 --- a/world/Sweep.h +++ b/world/Sweep.h @@ -91,7 +91,7 @@ class sweep_node : public scene::basic_node explicit sweep_node(scene::node_data const &Nodedata); - void import(cParser &Input, glm::dvec3 const &Offset); + void import_from(cParser &Input, glm::dvec3 const &Offset); void define(state const &State); state const &definition() const { diff --git a/world/Track.cpp b/world/Track.cpp index 9111b731d..990ff4b0b 100644 --- a/world/Track.cpp +++ b/world/Track.cpp @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "world/Track.h" #include "world/TrackRails.h" +#include "world/TrackCheck.h" #include "simulation/simulation.h" #include "scene/scene.h" #include "utilities/Globals.h" @@ -773,6 +774,20 @@ void TTrack::Load(cParser *parser, glm::dvec3 const &pOrigin) m_uneven = track_uneven::read_attribute( values, eType == tt_Switch ); } } + else if( str == "buckle" ) { + // buckle ;;[;]: the track buckled by the heat, see TrackBuckle.h + auto const values { parser->getToken( false, "\n\r\t " ) }; + if( eType == tt_Normal && iCategoryFlag == 1 ) { + m_buckledeclared = track_buckle::read_buckle( values ); + } + } + else if( str == "cwr" ) { + // cwr ;[;]: the welded rail, for the buckling by the temperature + auto const values { parser->getToken( false, "\n\r\t " ) }; + if( eType == tt_Normal && iCategoryFlag == 1 ) { + m_cwr = track_buckle::read_cwr( values ); + } + } else if( str == "friction" ) { // memory cell holding friction value modifiers m_friction.first = parser->getToken(); @@ -835,8 +850,15 @@ void TTrack::Load(cParser *parser, glm::dvec3 const &pOrigin) // from the scenery is put back after it auto const velocity { fVelocity }; init_segments( true ); + // the buckle goes along the path made + if( Global.track_buckling != global_settings::track_buckling_mode::off && track_buckle::given( m_buckledeclared ) ) { + m_buckle = resolve_buckle( m_buckledeclared, 0 ); + if( false == is_buckled() ) { + ErrorLog( "Bad track: \"" + m_name + "\" too short for its buckle" ); + } + } // made with no unevenness, which is read with the attributes and goes onto them by making them again - if( is_uneven() ) { + if( is_uneven() || is_buckled() ) { init_segments( false ); } if( SwitchExtension ) { @@ -892,6 +914,7 @@ void TTrack::init_segments( bool const Initial ) { } else if( Segment ) { Segment->set_uneven( is_uneven() ); + Segment->set_buckled( is_buckled() ); } switch (eType) { @@ -1283,6 +1306,10 @@ bool TTrack::AddDynamicObject(TDynamicObject *Dynamic) } } } + if( Dynamics.empty() ) { + // a train comes onto the track, which can buckle under it in the heat + buckle_pass_enter( *Dynamic ); + } Dynamics.emplace_back( Dynamic ); Dynamic->MyTrack = this; // ABu: na ktorym torze jesteśmy if( Dynamic->iOverheadMask ) { @@ -1330,6 +1357,10 @@ bool TTrack::RemoveDynamicObject(TDynamicObject *Dynamic) } } } + if( result ) { + // the head of a train leaving the track the pass was drawn to buckle + buckle_pass_leave(); + } if( Global.iMultiplayer ) { // jeśli multiplayer if( true == Dynamics.empty() ) { @@ -2918,6 +2949,9 @@ TTrack::export_as_text_( std::ostream &Output ) const { Output << "railprofile " << m_profile1.first << ' '; } Output << track_uneven::write_attribute( m_uneven, eType == tt_Switch ); + if( eType == tt_Normal && iCategoryFlag == 1 ) { + Output << track_buckle::write_buckle( m_buckledeclared ) << track_buckle::write_cwr( m_cwr ); + } if( false == m_friction.first.empty() ) { Output << "friction " << m_friction.first << ' '; } @@ -4223,6 +4257,68 @@ path_table::InitTracks() { TTrack::fetch_default_profiles(); } +namespace { + +// the tightest radius of the curve of a path in the plan [m], from the circles through its design points about 5 m apart +// (without the unevenness, whose short waves would bend it): the curve the axles of a vehicle follow, whether the track +// gives the radius or only its control points. 0 for a straight one; a radius over 15 km is taken for one, as +// TDynamicObject::Update() takes it +double tightest_radius(TSegment const &Segment) { + + auto const length { Segment.GetLength() }; + if( length < 0.5 ) { + return 0.0; + } + auto const intervals { std::max( 2, static_cast( std::ceil( length / 5.0 ) ) ) }; + auto const flat = [&]( int const Index ) { + auto const point { Segment.FastGetPoint( static_cast( Index ) / intervals ) }; + return glm::dvec2 { point.x, point.z }; }; + auto tightest { 0.0 }; + for( int index = 1; index < intervals; ++index ) { + auto const a { flat( index - 1 ) }; + auto const b { flat( index ) }; + auto const c { flat( index + 1 ) }; + auto const ab { b - a }; + auto const ac { c - a }; + auto const area2 { std::abs( ab.x * ac.y - ab.y * ac.x ) }; + if( area2 < 1e-9 ) { + continue; + } + auto const radius { glm::length( ab ) * glm::length( c - b ) * glm::length( ac ) / ( 2.0 * area2 ) }; + if( radius < 15000.0 && ( tightest == 0.0 || radius < tightest ) ) { + tightest = radius; + } + } + return tightest; +} + +} // namespace + +void +path_table::CheckTracks() const { + + std::vector tracks; + for( auto *path : sequence() ) { + if( path == nullptr || ( path->iCategoryFlag & 1 ) == 0 || path->Segment == nullptr ) { + continue; + } + track_check::track track; + track.name = path->name(); + track.velocity = path->VelocityGet(); + track.plain = ( path->eType == tt_Normal ); + track.radius = track.plain ? tightest_radius( *path->Segment ) : 0.0; + float roll1 { 0.f }, roll2 { 0.f }; + path->Segment->GetRolls( roll1, roll2 ); + track.gauge = path->fTrackWidth; + auto const spacing { 1000.0 * derailment::contact_spacing( track.gauge ) }; + track.cant = { spacing * std::sin( roll1 ), spacing * std::sin( roll2 ) }; + track.damage = path->iDamageFlag; + track.uneven = path->m_uneven; + tracks.emplace_back( std::move( track ) ); + } + track_check::scan( tracks, []( std::string const &Line ) { WriteLog( Line ); } ); +} + // legacy method, sends list of occupied paths over network void path_table::TrackBusyList() const { diff --git a/world/Track.h b/world/Track.h index e679613eb..3ed6e712a 100644 --- a/world/Track.h +++ b/world/Track.h @@ -22,6 +22,7 @@ http://mozilla.org/MPL/2.0/. #include "world/RailLayout.h" #include "world/TrackSleepers.h" #include "world/TrackBlend.h" +#include "world/TrackBuckle.h" #include "world/TrackUneven.h" #include "model/material.h" #include "scene/scenenode.h" @@ -289,6 +290,8 @@ public: int iAction = 0; // czy modyfikowany eventami (specjalna obsługa przy skanowaniu) float fOverhead = -1.0; // można normalnie pobierać prąd (0 dla jazdy bezprądowej po danym odcinku, >0-z opuszczonym i ograniczeniem prędkości) track_uneven::attribute m_uneven; // plain tracks and switches + track_buckle::declared m_buckledeclared; // the buckle entered in the scenery; plain rail tracks + track_buckle::cwr m_cwr; // the welded rail, for the buckling by the temperature private: double fVelocity = -1.0; // ograniczenie prędkości // prędkość dla AI (powyżej rośnie prawdopowobieństwo wykolejenia) public: @@ -423,6 +426,20 @@ public: track_uneven::amounts uneven_at( double const Distance, int const Path = 0 ); // how much of the displacement a point of the profile at the depth takes double uneven_bed_share( double const Depth ) const; + // the buckle the track has now (see TrackBuckle.h): none with physics.trackbuckling off + track_buckle::shape const &buckle() const { + return m_buckle; } + bool is_buckled() const { + return track_buckle::active( m_buckle ); } + // buckles the track during the game as the values say, or with none straightens it, and makes its geometry again. Cause goes to the log + bool buckle_now( track_buckle::declared const &Values, std::string const &Cause ); + // the buckling of the tracks by the temperature of the rails, physics.trackbuckling auto; once a minute + static void update_buckling( double const Deltatime ); + // the radius of the path in the plan at the distance, 0 straight, and the side away from its centre: -1 left, 1 right, 0 straight + double plan_radius( double const Distance, int &Outward ) const; + // the curvature the buckle adds at the distance, averaged over Base around it, 1/m: positive bending with the curve, on a straight + // track to the right of the path + double buckle_curvature( double const Distance, double const Base ) const; // closes the gaps and steps of cant between the ends of joined paths void share_joints(); double joint_depth() const; // mm @@ -484,6 +501,21 @@ private: int stamp { -1 }; }; switch_stray m_switchstray; + track_buckle::shape m_buckle; + // the buckling by the temperature: the passes of the trains over the track, and the pass which will buckle it as its head leaves + std::uint32_t m_buckle_passes { 0 }; + bool m_buckle_armed { false }; + // the buckle of the values on this track, its place and side drawn with the seed where not given + track_buckle::shape resolve_buckle( track_buckle::declared const &Values, std::uint32_t const Seed ) const; + // the draws for this track: by its name, by where it is for one with none + std::uint64_t buckle_key() const; + // whether the temperature can buckle the track, and the rise of the rails above its neutral temperature it does it at + bool buckles_by_heat() const; + track_buckle::limits buckle_limits() const; + // a train coming onto the track and its head leaving it, for the buckling under a train + void buckle_pass_enter( TDynamicObject const &Dynamic ); + void buckle_pass_leave(); + void buckle_under_train(); switch_stray const &switch_uneven(); void settle_switch_stray(); void settle_switch_ends(); @@ -534,6 +566,9 @@ public: // legacy method, initializes tracks after deserialization from scenario file void InitTracks(); + // physics.trackcheck: logs the geometry of the rail tracks the checks of world/TrackCheck.h find suspicious + void + CheckTracks() const; // legacy method, sends list of occupied paths over network void TrackBusyList() const; diff --git a/world/TrackBuckle.cpp b/world/TrackBuckle.cpp new file mode 100644 index 000000000..c8c20fe08 --- /dev/null +++ b/world/TrackBuckle.cpp @@ -0,0 +1,245 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "world/Track.h" +#include "simulation/simulation.h" +#include "simulation/simulationenvironment.h" +#include "scene/scene.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "vehicle/DynObj.h" + +#include + +namespace { + +// how often the temperature is checked, s of the simulation +double constexpr check_interval { 60.0 }; +// the tracks the temperature can buckle, found at the first check +std::vector heat_sites; +bool heat_sites_found { false }; +double heat_clock { 0.0 }; +// the tracks to buckle under a train, done with the next update rather than amid the moves of the vehicles +std::vector heat_due; + +double rail_temperature_now() { + + return track_buckle::rail_temperature( Global.AirTemperature, simulation::Environment.sun().getAngle(), Global.Overcast ); +} + +} // namespace + +double TTrack::plan_radius( double const Distance, int &Outward ) const { + + Outward = 0; + if( Segment == nullptr || eType != tt_Normal ) { + return 0.0; + } + auto const length { Segment->GetLength() }; + auto const reach { std::min( 5.0, 0.25 * length ) }; + auto const at { std::clamp( Distance, reach, length - reach ) }; + glm::dvec3 behind, middle, ahead, across; + Segment->plan_frame( at - reach, behind, across ); + Segment->plan_frame( at + reach, ahead, across ); + Segment->plan_frame( at, middle, across ); + auto bend { ( behind + ahead - 2.0 * middle ) / ( reach * reach ) }; + bend.y = 0.0; + auto const curvature { glm::length( bend ) }; + // straighter than the curves the tracks are laid with + if( curvature < 1.0 / 20000.0 ) { + return 0.0; + } + // away from the centre, which the bend points to + Outward = ( glm::dot( bend, across ) > 0.0 ? -1 : 1 ); + return 1.0 / curvature; +} + +double TTrack::buckle_curvature( double const Distance, double const Base ) const { + + if( false == is_buckled() || false == track_buckle::within( m_buckle, Distance ) ) { + return 0.0; + } + auto const bend { track_buckle::mean_bend( m_buckle, Distance, Base ) }; + auto outward { 0 }; + plan_radius( Distance, outward ); + // the centre of the curve is away from the outer side + return outward != 0 ? -outward * bend : bend; +} + +std::uint64_t TTrack::buckle_key() const { + + if( false == m_name.empty() && m_name != "none" ) { + return track_buckle::name_hash( m_name ); + } + auto const point { location() }; + return track_buckle::name_hash( std::format( "{:.1f};{:.1f};{:.1f}", point.x, point.y, point.z ) ); +} + +track_buckle::shape TTrack::resolve_buckle( track_buckle::declared const &Values, std::uint32_t const Seed ) const { + + if( Segment == nullptr || eType != tt_Normal || iCategoryFlag != 1 ) { + return {}; + } + auto const length { Segment->GetLength() }; + auto const key { buckle_key() }; + auto const place { track_buckle::draw( key, Seed, track_buckle::place ) }; + // the side out of the curve where the buckle is + auto const centre { Values.centre >= 0.f ? static_cast( Values.centre ) : 0.5 * length }; + auto outward { 0 }; + auto const radius { plan_radius( centre, outward ) }; + return track_buckle::resolve( Values, length, outward, radius, place, track_buckle::draw( key, Seed, track_buckle::way ) ); +} + +bool TTrack::buckle_now( track_buckle::declared const &Values, std::string const &Cause ) { + + if( Global.track_buckling == global_settings::track_buckling_mode::off ) { + return false; + } + if( eType != tt_Normal || iCategoryFlag != 1 || Segment == nullptr ) { + ErrorLog( "Bad track: \"" + m_name + "\" can't buckle, it isn't a plain rail track" ); + return false; + } + auto const shape { resolve_buckle( Values, 0 ) }; + if( track_buckle::given( Values ) && false == track_buckle::active( shape ) ) { + ErrorLog( std::format( "Bad track: \"{}\" too short for a buckle {:.0f} m long", m_name, 2.0 * track_buckle::reach_share * ( Values.length > 0.f ? Values.length : track_buckle::straight_length ) ) ); + return false; + } + m_buckle = shape; + m_buckle_armed = false; + // made again with the buckle, which the rails, the sleepers and the axles on the track follow + init_segments( false ); + auto const rebuild = []( TTrack &Track ) { + auto §ion { simulation::Region->section( Track.location() ) }; + Track.rebuild_geometry( section.m_geometrycreated ? section.m_geometrybank : gfx::geometrybank_handle {} ); }; + rebuild( *this ); + for( auto *crossing : m_crossings ) { + if( crossing != nullptr && crossing != this ) { + rebuild( *crossing ); + } + } + if( is_buckled() ) { + WriteLog( std::format( + "Track \"{}\" buckled ({}): {:.0f} mm to the {} at {:.1f} m, main lobe {:.1f} m, curvature up to 1/{:.0f} m", + m_name, Cause, std::abs( 1000.0 * m_buckle.amplitude ), m_buckle.amplitude > 0.0 ? "right" : "left", m_buckle.centre, m_buckle.length, + 1.0 / track_buckle::peak_bend( m_buckle.amplitude, m_buckle.length ) ) ); + } + else { + WriteLog( "Track \"" + m_name + "\" straightened (" + Cause + ")" ); + } + return true; +} + +bool TTrack::buckles_by_heat() const { + + if( eType != tt_Normal || iCategoryFlag != 1 || Segment == nullptr || is_buckled() || false == m_crossings.empty() ) { + return false; + } + auto outward { 0 }; + auto const radius { plan_radius( 0.5 * Segment->GetLength(), outward ) }; + // continuous welded rail is laid down to a radius of 190 m (PLK ST-T1-A8) + if( radius > 0.0 && radius < 190.0 ) { + return false; + } + auto const natural { track_buckle::natural( outward != 0 && radius < track_buckle::curve_radius ) }; + if( Segment->GetLength() < 2.0 * ( track_buckle::reach_share * natural.length + track_buckle::end_margin ) ) { + return false; + } + return track_buckle::weak_spot( buckle_key(), Global.random_seed, Segment->GetLength(), m_cwr.worked ); +} + +track_buckle::limits TTrack::buckle_limits() const { + + auto outward { 0 }; + auto const radius { plan_radius( 0.5 * Segment->GetLength(), outward ) }; + return track_buckle::limits_of( m_cwr, radius, uneven_declared().side ); +} + +void TTrack::update_buckling( double const Deltatime ) { + + if( Global.track_buckling != global_settings::track_buckling_mode::automatic ) { + return; + } + if( false == heat_sites_found ) { + heat_sites_found = true; + for( auto *track : simulation::Paths.sequence() ) { + if( track != nullptr && track->buckles_by_heat() ) { + heat_sites.push_back( track ); + } + } + WriteLog( std::format( "Track buckling: {} places the heat can buckle", heat_sites.size() ) ); + // the first check right away, a scenario can start in the heat + heat_clock = check_interval; + } + for( auto *track : heat_due ) { + track->buckle_under_train(); + } + heat_due.clear(); + heat_clock += Deltatime; + if( heat_clock < check_interval ) { + return; + } + heat_clock = 0.0; + auto const rail { rail_temperature_now() }; + for( auto *track : heat_sites ) { + if( track->is_buckled() ) { + continue; + } + auto const rise { rail - track->m_cwr.neutral }; + if( track_buckle::decide( rise, track->buckle_limits(), false, 1.0 ) == track_buckle::verdict::by_itself ) { + auto outward { 0 }; + auto const radius { track->plan_radius( 0.5 * track->Segment->GetLength(), outward ) }; + auto values { track_buckle::natural( outward != 0 && radius < track_buckle::curve_radius ) }; + values.centre = static_cast( track_buckle::resolve( values, track->Segment->GetLength(), outward, radius, + track_buckle::draw( track->buckle_key(), Global.random_seed, track_buckle::place ), 0.0 ).centre ); + track->buckle_now( values, std::format( "rails at {:.0f} C, {:.0f} K above neutral, {:.0f} kN in each", rail, rise, + 0.001 * track_buckle::thermal_force( track_buckle::rail_area( track->m_profile1.first ), rise ) ) ); + } + } +} + +void TTrack::buckle_pass_enter( TDynamicObject const &Dynamic ) { + + if( Global.track_buckling != global_settings::track_buckling_mode::automatic || is_buckled() || false == heat_sites_found ) { + return; + } + if( std::ranges::find( heat_sites, this ) == heat_sites.end() ) { + return; + } + ++m_buckle_passes; + auto const *mover { Dynamic.MoverParameters }; + auto const train { mover != nullptr && track_buckle::stirs( std::abs( mover->Vel ), mover->BrakePress > 0.5 ) }; + auto const rise { rail_temperature_now() - m_cwr.neutral }; + auto const draw { track_buckle::draw( buckle_key(), Global.random_seed, track_buckle::pass, m_buckle_passes ) }; + m_buckle_armed = ( track_buckle::decide( rise, buckle_limits(), train, draw ) != track_buckle::verdict::none ); +} + +void TTrack::buckle_pass_leave() { + + if( false == m_buckle_armed ) { + return; + } + m_buckle_armed = false; + heat_due.push_back( this ); +} + +void TTrack::buckle_under_train() { + + if( is_buckled() ) { + return; + } + // under the rest of the train, which lifts the track between its bogies + auto const rail { rail_temperature_now() }; + auto outward { 0 }; + auto const radius { plan_radius( 0.5 * Segment->GetLength(), outward ) }; + auto values { track_buckle::natural( outward != 0 && radius < track_buckle::curve_radius ) }; + values.centre = static_cast( track_buckle::resolve( values, Segment->GetLength(), outward, radius, + track_buckle::draw( buckle_key(), Global.random_seed, track_buckle::place ), 0.0 ).centre ); + buckle_now( values, std::format( "under a train, rails at {:.0f} C, {:.0f} K above neutral", rail, rail - m_cwr.neutral ) ); +} diff --git a/world/TrackBuckle.h b/world/TrackBuckle.h new file mode 100644 index 000000000..25825ed99 --- /dev/null +++ b/world/TrackBuckle.h @@ -0,0 +1,440 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Lateral buckling of continuous welded rail: in the heat the rails, held from growing longer, press on the track along it with +// E*A*alpha*dT, and where the bed holds it too weakly sideways the track jumps out to the side. The track of the scenery takes it as +// a displacement across it (TSegment::stray()), drawn and followed by the axles as the unevenness of TrackUneven.h is. +// Sources: Kish, Samavedam, "Risk analysis based CWR track buckling safety evaluations" (Volpe, about 2001); FRA, "Dynamic buckling +// test analyses of a high degree CWR track"; PKP PLK ST-T1-A8 (2021); the answers of the ministry to interpellations 3875 (2026) and +// 2575 (2025). The thresholds and the shape are fitted to the numbers there, see test_track_buckle.cpp. +namespace track_buckle { + +// the shape: a main lobe and a side lobe of the other way on each side of it, as the buckled shapes of Kerr and Kish have it. A +// cosine of a period twice the main lobe under a window cos^2 over three lobes: the side lobes come to a quarter of the main one, and +// the curvature runs on smoothly all along, into the straight track at the ends too, as a bent rail has it +// straight track jumps out far at once, a curve goes out step by step and less far, to the outside of the curve (Kish, Samavedam) +inline constexpr double straight_amplitude { 0.4 }; // m +inline constexpr double straight_length { 14.0 }; // m, main lobe +inline constexpr double curve_amplitude { 0.2 }; // m +inline constexpr double curve_length { 11.0 }; // m +inline constexpr double curve_radius { 1500.0 }; // m, below which a track counts as a curve for the shape +inline constexpr double end_margin { 2.0 }; // m between the buckle and the ends of the track +inline constexpr double most_amplitude { 1.0 }; // m +inline constexpr double least_length { 4.0 }; // m +inline constexpr double most_length { 60.0 }; // m +// how far the side lobes reach from the centre, in lengths of the main lobe +inline constexpr double reach_share { 1.5 }; + +struct shape { + double amplitude { 0.0 }; // of the main lobe, m: positive to the right of the path looking from its start to its end, negative to the left + double length { 0.0 }; // of the main lobe between the points it crosses the line, m; each side lobe is as long + double centre { 0.0 }; // of the main lobe, distance from the start of the path, m +}; + +inline bool active( shape const &Shape ) { + + return Shape.amplitude != 0.0 && Shape.length > 0.0; +} + +// the wave and the window at a distance from the centre, with their derivatives +struct parts { + double wave, wave1, wave2; + double window, window1, window2; +}; + +inline parts parts_at( shape const &Shape, double const Distance ) { + + auto const from { Distance - Shape.centre }; + auto const k { glm::pi() / Shape.length }; + // cos^2(b x) = ( 1 + cos( 2 b x ) ) / 2 reaching 0 at the ends of the side lobes + auto const b { glm::pi() / ( 2.0 * reach_share * Shape.length ) }; + return { + std::cos( k * from ), -k * std::sin( k * from ), -k * k * std::cos( k * from ), + 0.5 * ( 1.0 + std::cos( 2.0 * b * from ) ), -b * std::sin( 2.0 * b * from ), -2.0 * b * b * std::cos( 2.0 * b * from ) }; +} + +inline bool within( shape const &Shape, double const Distance ) { + + return active( Shape ) && std::abs( Distance - Shape.centre ) < reach_share * Shape.length; +} + +// displacement across the path at a distance along it, m +inline double offset( shape const &Shape, double const Distance ) { + + if( false == within( Shape, Distance ) ) { + return 0.0; + } + auto const p { parts_at( Shape, Distance ) }; + return Shape.amplitude * p.wave * p.window; +} + +// its first derivative along the path +inline double slope( shape const &Shape, double const Distance ) { + + if( false == within( Shape, Distance ) ) { + return 0.0; + } + auto const p { parts_at( Shape, Distance ) }; + return Shape.amplitude * ( p.wave1 * p.window + p.wave * p.window1 ); +} + +// and the second: the curvature the buckle adds to the path, 1/m, positive bending to the right +inline double bend( shape const &Shape, double const Distance ) { + + if( false == within( Shape, Distance ) ) { + return 0.0; + } + auto const p { parts_at( Shape, Distance ) }; + return Shape.amplitude * ( p.wave2 * p.window + 2.0 * p.wave1 * p.window1 + p.wave * p.window2 ); +} + +// the mean curvature over a stretch around a distance, as a bogie over its wheelbase feels it: the difference of the slopes at its ends +// over its length +inline double mean_bend( shape const &Shape, double const Distance, double const Base ) { + + if( Base <= 0.0 ) { + return bend( Shape, Distance ); + } + return ( slope( Shape, Distance + 0.5 * Base ) - slope( Shape, Distance - 0.5 * Base ) ) / Base; +} + +// and as a body on two bogies: it goes sideways by the mean of its pivots, so its lateral acceleration is v^2 times the mean of the +// curvatures at the pivots, each over the wheelbase of the bogie (without bogies: the pivots are the axles, with no base) +inline double body_bend( shape const &Shape, double const Distance, double const Pivots, double const Base ) { + + return 0.5 * ( mean_bend( Shape, Distance - 0.5 * Pivots, Base ) + mean_bend( Shape, Distance + 0.5 * Pivots, Base ) ); +} + +// how far from the centre the buckle reaches on each side +inline double reach( shape const &Shape ) { + + return active( Shape ) ? reach_share * Shape.length : 0.0; +} + +// the largest curvature of the buckle, 1/m, in the middle of the main lobe: pi^2 a / L^2 of the wave and 2/9 of it from the window +inline double peak_bend( double const Amplitude, double const Length ) { + + return ( 1.0 + 2.0 / ( 4.0 * reach_share * reach_share ) ) * glm::pi() * glm::pi() * std::abs( Amplitude ) / ( Length * Length ); +} + +// the heat + +inline constexpr double steel_modulus { 210e9 }; // Pa +inline constexpr double steel_expansion { 1.15e-5 }; // 1/K +inline constexpr double sun_heating { 17.0 }; // K a rail in full sun is warmer than the air: 30 F (Kish, Samavedam) +inline constexpr float neutral_default { 26.f }; // C, the rail stress-free temperature PLK lays its tracks at since 2025 +inline constexpr double area_60e1 { 76.70e-4 }; // m2 +inline constexpr double area_49e1 { 62.92e-4 }; +inline constexpr double area_s42 { 54.2e-4 }; + +// the rail section by the name of the rail profile, 60E1 if it tells nothing +inline double rail_area( std::string_view const Profile ) { + + auto const has = [ Profile ]( std::string_view const Part ) { + return std::search( Profile.begin(), Profile.end(), Part.begin(), Part.end(), []( char const Left, char const Right ) { + return std::tolower( static_cast( Left ) ) == std::tolower( static_cast( Right ) ); } ) != Profile.end(); }; + if( has( "49" ) ) { + return area_49e1; + } + if( has( "s42" ) ) { + return area_s42; + } + return area_60e1; +} + +// the force along a rail held from growing longer, N, pressing for Rise above the neutral temperature +inline double thermal_force( double const Area, double const Rise ) { + + return steel_modulus * Area * steel_expansion * Rise; +} + +// the temperature of a rail, C, from the air, the height of the sun over the horizon in degrees and the clouds (0 clear, 1 overcast; +// above 1 it rains, which cools as much) +inline double rail_temperature( double const Air, double const Sun, double const Overcast ) { + + auto const sun { std::max( 0.0, std::sin( glm::radians( Sun ) ) ) }; + return Air + sun_heating * sun * ( 1.0 - std::clamp( Overcast, 0.0, 1.0 ) ); +} + +// the state of the track, from the scenery +namespace grade { +inline constexpr int good { 0 }; // concrete sleepers, full ballast shoulder, consolidated +inline constexpr int average { 1 }; +inline constexpr int weak { 2 }; // timber sleepers, ballast missing, or the bed disturbed by tamping or sleeper renewal not yet consolidated +} + +struct cwr { + float neutral { neutral_default }; // C + int grade { grade::average }; + bool worked { false }; // works on the bed lately: weak whatever the grade +}; + +// the rise above the neutral temperature at which the track buckles: from low on under a passing train, which lifts it between the +// bogies and takes away part of its hold sideways, at high and above by itself +struct limits { + double low { 0.0 }; // K + double high { 0.0 }; +}; + +inline constexpr std::array grade_limits { { { 40.0, 55.0 }, { 32.0, 45.0 }, { 22.0, 32.0 } } }; + +// for the grade of the track, lowered in a curve, which presses outwards, and by an uneven line, which gives it a start +inline limits limits_of( cwr const &Track, double const Radius, double const Side ) { + + auto const kind { Track.worked ? grade::weak : std::clamp( Track.grade, grade::good, grade::weak ) }; + auto result { grade_limits[ kind ] }; + auto less { 0.0 }; + auto const radius { std::abs( Radius ) }; + if( radius > 0.0 && radius < 300.0 ) { + less += 6.0; + } + else if( radius > 0.0 && radius < 600.0 ) { + less += 3.0; + } + if( Side > 15.0 ) { + less += 3.0; + } + result.low -= less; + result.high -= less; + return result; +} + +// the share of the passes of a train which buckle the track at the rise: none below low, all at high +inline double chance( double const Rise, limits const &Limits ) { + + if( Limits.high <= Limits.low ) { + return Rise >= Limits.high ? 1.0 : 0.0; + } + return std::clamp( ( Rise - Limits.low ) / ( Limits.high - Limits.low ), 0.0, 1.0 ); +} + +enum class verdict { + none, + under_train, + by_itself +}; + +// with Train the track has a train going over it hard enough, Draw is the draw of the pass, 0 to 1 +inline verdict decide( double const Rise, limits const &Limits, bool const Train, double const Draw ) { + + if( Rise >= Limits.high ) { + return verdict::by_itself; + } + if( Train && Rise >= Limits.low && Draw < chance( Rise, Limits ) ) { + return verdict::under_train; + } + return verdict::none; +} + +// a train stirs the track up when it goes fast or brakes on it +inline constexpr double stirring_speed { 40.0 }; // km/h +inline bool stirs( double const Speed, bool const Braking ) { + + return Speed > stirring_speed || ( Braking && Speed > 5.0 ); +} + +// draws, the same for the same track and seed + +// FNV-1a, which std::hash isn't on every compiler +inline std::uint64_t name_hash( std::string_view const Name ) { + + std::uint64_t hash { 14695981039346656037ULL }; + for( auto const character : Name ) { + hash ^= static_cast( character ); + hash *= 1099511628211ULL; + } + return hash; +} + +// the splitmix64 finalizer, so close numbers give far apart draws +inline std::uint64_t scramble( std::uint64_t Value ) { + + Value += 0x9e3779b97f4a7c15ULL; + Value = ( Value ^ ( Value >> 30 ) ) * 0xbf58476d1ce4e5b9ULL; + Value = ( Value ^ ( Value >> 27 ) ) * 0x94d049bb133111ebULL; + return Value ^ ( Value >> 31 ); +} + +// what a draw is for, so the draws for one track don't go together +enum purpose : std::uint64_t { + pass = 1, + site = 2, + place = 3, + way = 4 +}; + +// a fraction 0 to 1 +inline double draw( std::uint64_t const Name, std::uint32_t const Seed, std::uint64_t const Purpose, std::uint64_t const Number = 0 ) { + + auto const value { scramble( scramble( scramble( Name ^ Purpose ) + Seed ) + Number ) }; + // the 53 high bits + return static_cast( value >> 11 ) / 9007199254740992.0; +} + +// where the track buckles by the temperature on its own: one place in so many metres of track, and the tracks worked on lately. +// Elsewhere the bed holds far beyond the limits of the grade (Sweden: 200 buckles in the hot summer of 2018 on 14 000 km) +inline constexpr double site_spacing { 10000.0 }; // m + +inline bool weak_spot( std::uint64_t const Name, std::uint32_t const Seed, double const Length, bool const Worked ) { + + return Worked || draw( Name, Seed, site ) < Length / site_spacing; +} + +// the entries in the scenery + +// buckle ;;[;] +struct declared { + float amplitude { 0.f }; // mm + float length { -1.f }; // m, negative: by the shape of the track + float centre { -1.f }; // m, negative: drawn + int side { 0 }; +}; + +inline bool given( declared const &Values ) { + + return Values.amplitude > 0.f; +} + +// the numbers of an entry like "400;18;60", NaN where left out +template +std::array read_numbers( std::string_view const Text ) { + + std::array result; + result.fill( std::numeric_limits::quiet_NaN() ); + auto rest { Text }; + for( auto &field : result ) { + auto const end { std::min( rest.find( ';' ), rest.size() ) }; + if( auto value { 0.f }; end > 0 && std::from_chars( rest.data(), rest.data() + end, value ).ec == std::errc {} && std::isfinite( value ) ) { + field = value; + } + if( end == rest.size() ) { + break; + } + rest.remove_prefix( end + 1 ); + } + return result; +} + +inline declared read_buckle( std::string_view const Text ) { + + auto const fields { read_numbers<4>( Text ) }; + declared result; + if( std::isfinite( fields[ 0 ] ) ) { + result.amplitude = std::clamp( fields[ 0 ], 0.f, static_cast( most_amplitude * 1000.0 ) ); + } + if( std::isfinite( fields[ 1 ] ) && fields[ 1 ] > 0.f ) { + result.length = std::clamp( fields[ 1 ], static_cast( least_length ), static_cast( most_length ) ); + } + if( std::isfinite( fields[ 2 ] ) && fields[ 2 ] >= 0.f ) { + result.centre = fields[ 2 ]; + } + if( std::isfinite( fields[ 3 ] ) ) { + result.side = ( fields[ 3 ] > 0.f ? 1 : fields[ 3 ] < 0.f ? -1 : 0 ); + } + return result; +} + +inline std::string write_buckle( declared const &Values ) { + + if( false == given( Values ) ) { + return {}; + } + std::ostringstream text; + text << "buckle " << Values.amplitude << ';'; + if( Values.length > 0.f ) { + text << Values.length; + } + text << ';'; + if( Values.centre >= 0.f ) { + text << Values.centre; + } + if( Values.side != 0 ) { + text << ';' << Values.side; + } + text << ' '; + return text.str(); +} + +// cwr ;[;] +inline cwr read_cwr( std::string_view const Text ) { + + auto const fields { read_numbers<3>( Text ) }; + cwr result; + if( std::isfinite( fields[ 0 ] ) ) { + result.neutral = std::clamp( fields[ 0 ], -20.f, 60.f ); + } + if( std::isfinite( fields[ 1 ] ) ) { + result.grade = std::clamp( static_cast( std::lround( fields[ 1 ] ) ), 0, 2 ); + } + if( std::isfinite( fields[ 2 ] ) ) { + result.worked = fields[ 2 ] > 0.f; + } + return result; +} + +inline std::string write_cwr( cwr const &Values ) { + + if( Values.neutral == neutral_default && Values.grade == grade::average && false == Values.worked ) { + return {}; + } + std::ostringstream text; + text << "cwr " << Values.neutral << ';' << Values.grade; + if( Values.worked ) { + text << ";1"; + } + text << ' '; + return text.str(); +} + +// the buckle of the values on a track of the length, which curves to the side Outward (-1 left, 1 right, 0 straight), with radius +// Radius (0 straight); None for one which doesn't fit into the track. Place and Way are draws for the centre and the side not given +inline shape resolve( declared const &Values, double const Length, int const Outward, double const Radius, double const Place, double const Way ) { + + if( false == given( Values ) ) { + return {}; + } + auto const curve { Outward != 0 && Radius > 0.0 && Radius < curve_radius }; + shape result; + result.length = Values.length > 0.f ? static_cast( Values.length ) : ( curve ? curve_length : straight_length ); + auto const first { reach_share * result.length + end_margin }; + auto const last { Length - reach_share * result.length - end_margin }; + if( last < first ) { + return {}; + } + result.centre = Values.centre >= 0.f ? std::clamp( static_cast( Values.centre ), first, last ) : first + ( last - first ) * Place; + auto const side { Values.side != 0 ? Values.side : Outward != 0 ? Outward : ( Way < 0.5 ? -1 : 1 ) }; + result.amplitude = side * 0.001 * Values.amplitude; + return result; +} + +// the buckle the temperature makes on a track: as large as a curve or a straight one makes +inline declared natural( bool const Curve ) { + + declared result; + result.amplitude = static_cast( 1000.0 * ( Curve ? curve_amplitude : straight_amplitude ) ); + result.length = static_cast( Curve ? curve_length : straight_length ); + return result; +} + +} // namespace track_buckle diff --git a/world/TrackCheck.cpp b/world/TrackCheck.cpp new file mode 100644 index 000000000..c0661bf2f --- /dev/null +++ b/world/TrackCheck.cpp @@ -0,0 +1,240 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "world/TrackCheck.h" + +#include +#include +#include + +namespace track_check { + +namespace { + +constexpr double kmh{3.6}; + +reference make_reference(std::string const &Name, double const Mass, double const Length, double const AxleBase, double const BodyHeight, derailment::vehicle_class const Class) { + reference result; + result.name = Name; + result.vehicle.mass = Mass; + result.vehicle.axles = 4; + result.vehicle.length = Length; + result.vehicle.axle_base = AxleBase; + result.vehicle.centre_of_gravity = derailment::default_centre_of_gravity(BodyHeight, Class); + return result; +} + +// the cant [rad] of the given height of the outer rail [mm] +double cant_angle(double const Cant, double const Gauge) { + return std::asin(std::clamp(std::abs(Cant) / (1000.0 * derailment::contact_spacing(Gauge)), 0.0, 1.0)); +} + +void append(std::string &Text, std::string const &Part) { + if (false == Text.empty()) { + Text += "; "; + } + Text += Part; +} + +// the values of the unevenness past the range, as "side 40, cross 30" +std::string uneven_excess(track_uneven::attribute const &Uneven, settings const &Settings) { + std::string result; + auto const test = [&](char const *Name, float const Value, double const Most) { + if (Value > Most) { + if (false == result.empty()) { + result += ", "; + } + result += std::format("{} {:g}", Name, Value); + } + }; + test("value", Uneven.value, Settings.most_uneven); + test("up", Uneven.up, Settings.most_uneven); + test("side", Uneven.side, Settings.most_uneven); + test("cross", Uneven.cross, Settings.most_cross); + test("dip", Uneven.dip, Settings.most_uneven); + test("branch", Uneven.branch, Settings.most_uneven); + test("branch up", Uneven.branchup, Settings.most_uneven); + test("branch side", Uneven.branchside, Settings.most_uneven); + return result; +} + +// what the check of a track found so far +struct collector { + findings &result; + void add(kind const Kind, std::string const &Text) const { + if (std::ranges::find(result.kinds, Kind) == result.kinds.end()) { + result.kinds.push_back(Kind); + } + append(result.text, Text); + } +}; + +derailment::track_state curve_of(track const &Track) { + // with the cant both ends have at the least + auto const cant{std::min(std::abs(Track.cant[0]), std::abs(Track.cant[1]))}; + derailment::track_state result; + result.radius = Track.radius; + result.cant = cant_angle(cant, Track.gauge); + result.gauge = Track.gauge; + return result; +} + +// a speed limit over the speed a reference vehicle overturns or climbs the rail at in the curve +void check_limit(track const &Track, std::vector const &References, collector const &Found) { + auto const curve{curve_of(Track)}; + for (auto const &reference : References) { + auto const overturning{derailment::overturning_speed(curve.radius, curve.cant, reference.vehicle.centre_of_gravity, curve.gauge) * kmh}; + if (overturning > 0.0 && Track.velocity > overturning) { + Found.add(kind::overturning, std::format("speed limit {:.0f} km/h over the overturning speed of {} {:.0f} km/h", Track.velocity, reference.name, overturning)); + } + if (auto const climbing{derailment::climbing_speed(reference.vehicle, curve)}; climbing.has_value() && Track.velocity > *climbing * kmh) { + Found.add(kind::climbing, std::format("speed limit {:.0f} km/h over the flange climbing speed of {} {:.0f} km/h", Track.velocity, reference.name, *climbing * kmh)); + } + } +} + +// a curve without a speed limit: how fast it takes the reference vehicles, when that's under the unlimited velocity +void check_unlimited(track const &Track, std::vector const &References, settings const &Settings, collector const &Found) { + auto const curve{curve_of(Track)}; + auto slowest{Settings.unlimited_velocity}; + std::string what; + for (auto const &reference : References) { + auto const overturning{derailment::overturning_speed(curve.radius, curve.cant, reference.vehicle.centre_of_gravity, curve.gauge) * kmh}; + if (overturning > 0.0 && overturning < slowest) { + slowest = overturning; + what = std::format("the overturning speed of {}", reference.name); + } + if (auto const climbing{derailment::climbing_speed(reference.vehicle, curve)}; climbing.has_value() && *climbing * kmh < slowest) { + slowest = *climbing * kmh; + what = std::format("the flange climbing speed of {}", reference.name); + } + } + if (what.empty()) { + return; + } + Found.result.unlimited_speed = slowest; + Found.add(kind::unlimited_curve, std::format("no speed limit set (not a defect): the curve takes at most {:.0f} km/h, {}", slowest, what)); +} + +} // namespace + +std::vector const &default_references() { + static std::vector const references{ + make_reference("EU07", 80000.0, 15.915, 3.0, 4.348, derailment::vehicle_class::powered), + make_reference("coach", 40000.0, 24.5, 2.5, 4.05, derailment::vehicle_class::unpowered), + }; + return references; +} + +std::string_view name_of(kind const Kind) { + switch (Kind) { + case kind::overturning: + return "overturning"; + case kind::climbing: + return "flange climbing"; + case kind::cant_on_straight: + return "cant on a straight"; + case kind::cant_excess: + return "cant too high"; + case kind::tight_curve: + return "tight curve too fast"; + case kind::uneven: + return "uneven out of range"; + case kind::unlimited_curve: + return "curve without a speed limit"; + default: + return "?"; + } +} + +bool is_defect(kind const Kind) { + return Kind != kind::unlimited_curve; +} + +bool findings::defective() const { + return std::ranges::any_of(kinds, [](kind const Kind) { return is_defect(Kind); }); +} + +findings check(track const &Track, std::vector const &References, settings const &Settings) { + findings result; + collector const found{result}; + auto const curved{Track.radius > 0.0}; + auto const given{Track.velocity >= 0.0}; + + if (Track.plain) { + // a closed track (speed 0) isn't run on + if (curved && given && Track.velocity > 0.0) { + check_limit(Track, References, found); + } + if (curved && false == given) { + check_unlimited(Track, References, Settings, found); + } + // cant held over the whole of a straight track: a transition has it at one end only + if (false == curved && std::abs(Track.cant[0]) > Settings.straight_cant && std::abs(Track.cant[1]) > Settings.straight_cant && Track.cant[0] * Track.cant[1] > 0.0) { + found.add(kind::cant_on_straight, std::format("cant {:.0f} / {:.0f} mm on a straight track", Track.cant[0], Track.cant[1])); + } + if (curved && given && Track.velocity > Settings.tight_velocity && Track.radius < Settings.tight_radius) { + found.add(kind::tight_curve, std::format("radius {:.0f} m with a speed limit of {:.0f} km/h", Track.radius, Track.velocity)); + } + } + if (auto const most{std::max(std::abs(Track.cant[0]), std::abs(Track.cant[1]))}; most > Settings.most_cant) { + found.add(kind::cant_excess, std::format("cant {:.0f} mm over {:.0f} mm", most, Settings.most_cant)); + } + if (auto const excess{uneven_excess(Track.uneven, Settings)}; false == excess.empty()) { + found.add(kind::uneven, std::format("uneven {} mm out of range", excess)); + } + if (false == result.empty()) { + result.text += std::format(" (radius {:.0f} m, cant {:.0f} / {:.0f} mm, speed limit {}, damage {})", Track.radius, Track.cant[0], Track.cant[1], + given ? std::format("{:.0f} km/h", Track.velocity) : std::string{"none"}, Track.damage); + } + return result; +} + +summary scan(std::vector const &Tracks, sink const &Log, std::vector const &References, settings const &Settings) { + summary result; + for (auto const &track : Tracks) { + ++result.tracks; + if (track.damage != 0) { + ++result.damage[track.damage]; + } + auto const found{check(track, References, Settings)}; + if (found.empty()) { + continue; + } + if (found.defective()) { + ++result.suspicious; + } + if (found.unlimited_speed > 0.0) { + ++result.unlimited; + result.slowest = result.slowest > 0.0 ? std::min(result.slowest, found.unlimited_speed) : found.unlimited_speed; + } + for (auto const kind : found.kinds) { + ++result.counts[static_cast(kind)]; + } + Log(std::format("trackcheck: {}: {}", track.name.empty() ? std::string{"(none)"} : track.name, found.text)); + } + std::string counts; + for (std::size_t index = 0; index < result.counts.size(); ++index) { + if (auto const kind{static_cast(index)}; is_defect(kind)) { + append(counts, std::format("{} {}", name_of(kind), result.counts[index])); + } + } + Log(std::format("trackcheck: {} rail tracks checked, {} suspicious: {}", result.tracks, result.suspicious, counts)); + Log(std::format("trackcheck: curves without a speed limit: {} taking the reference vehicles under {:.0f} km/h (not a defect){}", result.unlimited, Settings.unlimited_velocity, + result.unlimited > 0 ? std::format(", the slowest at {:.0f} km/h", result.slowest) : std::string{})); + std::string damage; + for (auto const &[flags, count] : result.damage) { + append(damage, std::format("{} on {}", flags, count)); + } + Log(std::format("trackcheck: damage flags: {}", damage.empty() ? std::string{"none"} : damage)); + return result; +} + +} // namespace track_check diff --git a/world/TrackCheck.h b/world/TrackCheck.h new file mode 100644 index 000000000..e6e99fb2b --- /dev/null +++ b/world/TrackCheck.h @@ -0,0 +1,106 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include "McZapkie/derailment.h" +#include "world/TrackUneven.h" + +#include +#include +#include +#include +#include +#include + +// the check of the geometry of the rail tracks of a scenery (physics.trackcheck yes in eu07.ini): what the criteria of +// derailment (McZapkie/derailment.h) and the plain rules of the track find suspicious, to the log once the scenery +// loaded, so a run can tell a faulty scenery from a faulty simulation. one line for a track with all it found +// ("trackcheck: : ..."), and a summary with the count of each kind. the damage flags are only counted: sceneries +// set them for the jolts of a worn track (damage 31 on every track of line 107). a curve without a speed limit of its +// own is no defect (the drivers go by the signals and the timetable there, the tram loops of a town have none), it is +// only told how fast it takes the reference vehicles, apart from the defects. the rail tracks of trams have no category +// of their own (a tram is a vehicle of the category of the trains, on a track of theirs), so they are checked alike +namespace track_check { + +// a rail track as the check sees it +struct track { + std::string name; + double velocity{-1.0}; // the speed limit of the track [km/h], negative when it gives none + double radius{0.0}; // the tightest radius of its curve [m], 0 on a straight one + std::array cant{0.0, 0.0}; // at its ends [mm], positive raising the right rail + double gauge{1.435}; // [m] + int damage{0}; // dtrack_* flags + bool plain{true}; // a plain track, its speed and curve checked; a switch or a crossing has the paths and the + // speeds of its position, only its unevenness and its damage are + track_uneven::attribute uneven; +}; + +// a vehicle the speed limit of a curve is checked for +struct reference { + std::string name; + derailment::vehicle_state vehicle; +}; +// the default vehicles of derailment.h: an EU07 (4 axles, 80 t, 15.9 m, bogies of 3 m, the centre of gravity of its +// 4.35 m high body) and a 4-axle coach (40 t, 24.5 m, bogies of 2.5 m, 4.05 m high), alone, without a .fiz +std::vector const &default_references(); + +struct settings { + // a curve without a speed limit is told of when it takes the reference vehicles slower than this [km/h]: the top + // speed of the EU07, the trains the default vehicles make up run no faster + double unlimited_velocity{125.0}; + double most_cant{160.0}; // [mm], 150 the most of the Polish rules (Id-1), and a margin + double straight_cant{5.0}; // the cant both ends of a straight track have, past which it's cant without a curve [mm] + double tight_radius{40.0}; // a curve tighter than this [m] + double tight_velocity{40.0}; // with a speed limit over this [km/h] + double most_uneven{30.0}; // the value, up, side and dip of the unevenness [mm]: Id-14 lets the poorest track 28 mm + double most_cross{25.0}; // the cross level [mm]: 20 mm in class C of Id-14 +}; + +enum class kind { + overturning, // the speed limit is over the speed a reference vehicle overturns at + climbing, // or over the one its flange climbs the rail at + cant_on_straight, // both ends of a straight track have the same cant + cant_excess, // over the most cant + tight_curve, // a curve tighter than the tight radius with a speed limit over the tight velocity + uneven, // the unevenness out of the plausible range + unlimited_curve, // no defect: a curve without a speed limit, which takes the reference vehicles slower than the + // unlimited velocity + count_ +}; +std::string_view name_of(kind Kind); +// whether the kind is a defect of the scenery, rather than a note +bool is_defect(kind Kind); + +// what the check found on a track +struct findings { + std::vector kinds; + std::string text; // what the log line tells after the name of the track, empty when nothing + double unlimited_speed{0.0}; // the speed a curve without a speed limit takes the reference vehicles at [km/h], 0 when + // not told of + bool empty() const { return kinds.empty(); } + bool defective() const; // has a kind which is a defect +}; +findings check(track const &Track, std::vector const &References = default_references(), settings const &Settings = {}); + +struct summary { + int tracks{0}; // checked + int suspicious{0}; // with a defect + int unlimited{0}; // curves without a speed limit told of, defects or not + double slowest{0.0}; // the lowest speed one of them takes the reference vehicles at [km/h], 0 without any + std::array(kind::count_)> counts{}; + std::map damage; // the tracks of each value of the damage flags, none for 0 + int count(kind const Kind) const { return counts[static_cast(Kind)]; } +}; + +using sink = std::function; +// checks the tracks, logs a line for each one found suspicious and the summary +summary scan(std::vector const &Tracks, sink const &Log, std::vector const &References = default_references(), settings const &Settings = {}); + +} // namespace track_check diff --git a/world/TrackSleepers.h b/world/TrackSleepers.h index 117e68dcf..7fd16f5e8 100644 --- a/world/TrackSleepers.h +++ b/world/TrackSleepers.h @@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/. #include #include +#include #include #include #include @@ -158,6 +159,9 @@ struct pack_model { // the models of sleepers and timbers in the scenery data, found once in models/ by the names of their files telling sleepers // or timbers: podklad, podrozjazd, sleeper, timber. the timber ones first, then by the name std::vector const &pack_models(); +// the models of sleepers and timbers among the files under the folder given, named relative to it, in the same order; a file +// named with a character the code page lacks is left out +std::vector pack_models( std::filesystem::path const &Root ); // the beams of the track placed anew, as instances of the parts of the model; with the fastenings, or those left for later void lay( TTrack &Track, bool const Fastened = true ); // the fastenings left out laid on the beams of the track diff --git a/world/TrkFoll.cpp b/world/TrkFoll.cpp index 986f87a4f..bc8027f43 100644 --- a/world/TrkFoll.cpp +++ b/world/TrkFoll.cpp @@ -363,6 +363,27 @@ double TTrackFollower::RailPhase( double const Offset ) const { return pCurrentTrack != nullptr ? pCurrentTrack->rail_phase( fCurrentDistance + fDirection * Offset ) : -1.0; } +double TTrackFollower::BuckleCurvature( double const Base ) const { + + return pCurrentTrack != nullptr ? pCurrentTrack->buckle_curvature( fCurrentDistance, Base ) : 0.0; +} + +glm::dvec3 TTrackFollower::PathDirection( double const Reach ) const { + + if( pCurrentSegment == nullptr ) { + return glm::dvec3 { 0.0 }; + } + auto const length { pCurrentSegment->GetLength() }; + glm::dvec3 ahead; + glm::dvec3 behind; + glm::vec3 rotation; + pCurrentSegment->RaPositionGet( std::clamp( fCurrentDistance + Reach, 0.0, length ), ahead, rotation ); + pCurrentSegment->RaPositionGet( std::clamp( fCurrentDistance - Reach, 0.0, length ), behind, rotation ); + glm::dvec3 const direction { ( ahead.x - behind.x ) * fDirection, 0.0, ( ahead.z - behind.z ) * fDirection }; + auto const size { glm::length( direction ) }; + return size > 1e-6 ? direction / size : glm::dvec3 { 0.0 }; +} + bool TTrackFollower::ComputatePosition() { // ustalenie współrzędnych XYZ if (pCurrentSegment) // o ile jest tor diff --git a/world/TrkFoll.h b/world/TrkFoll.h index aaef51762..8de41a261 100644 --- a/world/TrkFoll.h +++ b/world/TrkFoll.h @@ -43,6 +43,11 @@ public: return pCurrentSegment ? pCurrentSegment->uneven_bend( fCurrentDistance ) : glm::dvec3 { 0.0 }; }; // TTrack::rail_phase of the point Offset ahead of the axle along the vehicle double RailPhase( double const Offset ) const; + // TTrack::buckle_curvature at the axle, averaged over Base around it + double BuckleCurvature( double const Base ) const; + // the level direction of the path the axle runs on, with its buckle and its uneven track, over Reach [m] behind and + // ahead of it, the way the axle goes forwards; none without a path + glm::dvec3 PathDirection( double const Reach = 1.0 ) const; bool Init(TTrack *pTrack, TDynamicObject *NewOwner, double fDir); void Reset(); void Render(float fNr); diff --git a/world/eventconditions.cpp b/world/eventconditions.cpp new file mode 100644 index 000000000..a091746e6 --- /dev/null +++ b/world/eventconditions.cpp @@ -0,0 +1,129 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +// the text of the event conditions: read from the scenery and written back by the editor. kept apart from +// Event.cpp so the unit tests can check that what is written reads back the same + +#include "stdafx.h" +#include "world/Event.h" + +bool +basic_event::is_keyword( std::string const &Token ) { + // TODO: convert to array lookup if keyword list gets longer + return Token == "endevent" + || Token == "randomdelay" + || Token == "departuredelay"; +} + +void +basic_event::event_conditions::deserialize( cParser &Input ) { + // przetwarzanie warunków, wspólne dla Multiple i UpdateValues + + std::string token; + while( true == Input.getTokens() + && false == (token = Input.peek()).empty() + && false == basic_event::is_keyword(token) ) { + + if( token == "trackoccupied" ) { + flags |= flags::track_busy; + } + else if( token == "trackfree" ) { + flags |= flags::track_free; + } + else if( token == "propability" || token == "probability") { //remove propability in few years after changing old scenery scripts 01.2021 + flags |= flags::probability; + Input.getTokens(); + Input >> probability; + } + else if( token == "memcompare" ) { + Input.getTokens( 1, false ); // case sensitive + if( Input.peek() != "*" ) //"*" - nie brac command pod uwage + { // zapamiętanie łańcucha do porównania + Input >> memcompare_text; + flags |= flags::text; + } + Input.getTokens(); + if( Input.peek() != "*" ) //"*" - nie brac val1 pod uwage + { + Input >> memcompare_value1; + flags |= flags::value1; + } + Input.getTokens(); + if( Input.peek() != "*" ) //"*" - nie brac val2 pod uwage + { + Input >> memcompare_value2; + flags |= flags::value2; + } + } + else if( token == "memcompareex" ) { + memcompare_pass = comparison_pass_from_string( Input.getToken() ); + Input.getTokens(); + if( Input.peek() != "*" ) //"*" - nie brac pod uwage + { // two tokens, operator followed by comparison value + std::string operatorstring; + Input >> operatorstring; + memcompare_text_operator = comparison_operator_from_string( operatorstring ); + Input.getTokens( 1, false ); // case sensitive + Input >> memcompare_text; + flags |= flags::text; + } + Input.getTokens(); + if( Input.peek() != "*" ) //"*" - nie brac pod uwage + { // two tokens, operator followed by comparison value + std::string operatorstring; + Input >> operatorstring; + memcompare_value1_operator = comparison_operator_from_string( operatorstring ); + Input.getTokens(); + Input >> memcompare_value1; + flags |= flags::value1; + } + Input.getTokens(); + if( Input.peek() != "*" ) //"*" - nie brac pod uwage + { // two tokens, operator followed by comparison value + std::string operatorstring; + Input >> operatorstring; + memcompare_value2_operator = comparison_operator_from_string( operatorstring ); + Input.getTokens(); + Input >> memcompare_value2; + flags |= flags::value2; + } + } + } +} + +// sends basic content of the class in legacy (text) format to provided stream +void +basic_event::event_conditions::export_as_text( std::ostream &Output ) const { + + if( flags != 0 ) { + Output << "condition "; + if( ( flags & flags::track_busy ) != 0 ) { + Output << "trackoccupied "; + } + if( ( flags & flags::track_free ) != 0 ) { + Output << "trackfree "; + } + if( ( flags & flags::probability ) != 0 ) { + Output + << "probability " + << probability << ' '; + } + if( ( flags & ( flags::text | flags::value1 | flags::value2 ) ) != 0 ) { + // NOTE: export doesn't preserve original memcompare condition, these are all upgraded to memcompareex format for simplicity + // memcompareex then for the text and both values either * or the operator followed by the compared value, + // the order deserialize() reads them in. a legacy memcompare is the same as memcompareex all with all operators == + Output + << "memcompareex " + << to_string( memcompare_pass ) << ' ' + << ( ( flags & flags::text ) == 0 ? "*" : to_string( memcompare_text_operator ) + ' ' + memcompare_text ) << ' ' + << ( ( flags & flags::value1 ) == 0 ? "*" : to_string( memcompare_value1_operator ) + ' ' + std::to_string( memcompare_value1 ) ) << ' ' + << ( ( flags & flags::value2 ) == 0 ? "*" : to_string( memcompare_value2_operator ) + ' ' + std::to_string( memcompare_value2 ) ) << ' '; + } + } +} diff --git a/world/mtable.cpp b/world/mtable.cpp index 0ac08bc20..bef0e20d8 100644 --- a/world/mtable.cpp +++ b/world/mtable.cpp @@ -9,10 +9,12 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "world/mtable.h" +#include "world/timetablestart.h" #include "utilities/Globals.h" #include "simulation/simulationtime.h" #include "utilities/dictionary.h" #include "utilities/utilities.h" +#include "world/stationnames.h" double TTrainParameters::CheckTrainLatency() const { @@ -109,6 +111,16 @@ sound_source TTrainParameters::current_stop_sound() const { return { sound_placement::engine }; } +timetable::service_flags const &TTrainParameters::stop_flags() const { + + return TimeTable[ timetable::stop_flags_entry( StationIndex, StationCount ) ].flags; +} + +timetable::service_flags const &TTrainParameters::run_flags() const { + + return TimeTable[ timetable::run_flags_entry( StationIndex, StationCount ) ].flags; +} + bool TTrainParameters::UpdateMTable( scenario_time const &Time, std::string const &NewName ) { return UpdateMTable( Time.data().wHour, Time.data().wMinute + Time.data().wSecond * 0.0167, NewName ); @@ -150,12 +162,14 @@ bool TTrainParameters::UpdateMTable(double hh, double mm, std::string_view NewNa bool Mtable::TTrainParameters::RewindTimeTable(std::string actualStationName) { - if( actualStationName.compare( 0, 19, "PassengerStopPoint:" ) == 0 ) { - actualStationName = ToLower( actualStationName.substr( 19 ) ); - } + // the text of a W4 or a plain name, spelled the way its file has it: with or without the polish letters, in any case + auto const isstoppoint { actualStationName.starts_with( timetable::stop_point_prefix ) }; for( auto i = 1; i <= StationCount; ++i ) { // przechodzimy po całej tabelce i sprawdzamy nazwy stacji (bez pierwszej) - if (ToLower(TimeTable[i].StationName) == actualStationName) { + auto const &stationname { TimeTable[i].StationName }; + if( isstoppoint ? + timetable::stop_point_is_for( actualStationName, stationname ) : + timetable::same_station( actualStationName, stationname ) ) { // nazwa stacji zgodna więc ustawiamy na poprzednią, żeby w następnym kroku poprawnie obsłużyć StationIndex = i; NextStationName = TimeTable[ i ].StationName; @@ -208,6 +222,29 @@ std::string TTrainParameters::ShowRelation() const return ""; } +std::string TTrainParameters::relation_caption() const +{ + if (Relation1 != "" && Relation2 != "") + return timetable::station_caption( RelationLabel1 ) + " - " + timetable::station_caption( RelationLabel2 ); + else + return ""; +} + +std::string TTrainParameters::station_caption( std::string const &Name ) const +{ + // the station the train makes for first, then the rest of the table + if( StationIndex >= 0 && StationIndex <= StationCount && TimeTable[ StationIndex ].StationName == Name ) { + return timetable::station_caption( TimeTable[ StationIndex ].StationLabel ); + } + for( auto i = 1; i <= StationCount; ++i ) { + if( TimeTable[ i ].StationName == Name ) { + return timetable::station_caption( TimeTable[ i ].StationLabel ); + } + } + // not a station of the timetable + return timetable::station_caption( Name ); +} + TTrainParameters::TTrainParameters(std::string const &NewTrainName) /*wstępne ustawienie parametrów rozkładu jazdy*/ { @@ -226,6 +263,8 @@ void TTrainParameters::NewName(std::string_view NewTrainName) Direction = 1; Relation1 = ""; Relation2 = ""; + RelationLabel1 = ""; + RelationLabel2 = ""; for (auto &tableline : TimeTable) { tableline = TMTableLine(); @@ -257,21 +296,16 @@ void TTrainParameters::UpdateVelocity(int /*Stationcount*/, double vActual) bool TTrainParameters::LoadTTfile(std::string const &scnpath, int iPlus, double vmax) // wczytanie pliku-tabeli z rozkładem przesuniętym o (fPlus); (vMax) nie ma znaczenia { - std::string lines; std::string s; std::ifstream fin; - bool EndTable; - double vActual; int conversionerror = 0; - EndTable = false; if (TrainName == "") { // jeśli pusty rozkład // UpdateVelocity(StationCount,vMax); //ograniczenie do prędkości startowej } else { - vActual = -1; s = scnpath + TrainName + ".txt"; replace_slashes(s); // Ra 2014-09: ustalić zasady wyznaczenia pierwotnego pliku przy przesuniętych rozkładach @@ -302,288 +336,28 @@ bool TTrainParameters::LoadTTfile(std::string const &scnpath, int iPlus, double } else { /*analiza rozkładu jazdy*/ - conversionerror = 0; - while (fin.good() && !(conversionerror != 0 || EndTable)) - { - std::getline(fin, lines); /*wczytanie linii*/ - if (contains( lines, "___________________") ) /*linia pozioma górna*/ - { - fin >> s; - if (s == "[") /*lewy pion*/ - { - fin >> s; - if (s == "Rodzaj") /*"Rodzaj i numer pociagu"*/ - do - { - fin >> s; - } while (!(s == "|") || fin.eof()); /*środkowy pion*/ - } - } - else if (lines == "") - { - fin.close(); - break; - } - fin >> s; /*nazwa pociągu*/ - // if LowerCase(s)<>ExtractFileName(TrainName) then {musi być taka sama, jak nazwa - // pliku} - // ConversionError:=-7 {błąd niezgodności} - TrainName = s; // nadanie nazwy z pliku TXT (bez ścieżki do pliku) - while (fin >> s || fin.bad()) - { - if (contains( s,"_______|") ) - { - break; - } - if (s == "Kategoria") - { - do - { - fin >> s; - } while (!(s == "|" || fin.bad())); - fin >> TrainCategory; - continue; - } - if (s == "Nazwa") - { - do - { - fin >> s; - } while (!(s == "|" || fin.bad())); - fin >> TrainLabel; - continue; - } - } // while (!(s == "Seria")); - // else - { /*czytaj naglowek*/ - while (fin >> s || !fin.bad()) - { - if (s == "[") - break; - } // while (!() || (fin.eof())); /*pierwsza linia z relacją*/ - while (fin >> s || !fin.bad()) - { - if (s != "|") - break; - } // while (!(() || fin.eof())); - if( s != "|" ) { - Relation1 = s; - win1250_to_ascii( Relation1 ); - } - else - conversionerror = -5; - while (fin >> s || !fin.bad()) - { - if (s == "Relacja") - break; - } // while ( - // !( || (fin.eof()))); /*druga linia z relacją*/ - while (fin >> s || !fin.bad()) - { - if (s == "|") - break; - } // while (!( || (fin.eof()))); - fin >> Relation2; - win1250_to_ascii( Relation2 ); - while (fin >> s || !fin.bad()) - { - if (s == "Wymagany") - break; - } // while (!(); - while (fin >> s || !fin.bad()) - { - if (s == "|" || s == "\n") - break; - } // while (!()); - fin >> s; - s = s.substr(0, s.find("%")); - BrakeRatio = atof(s.c_str()); - while (fin >> s || fin.bad()) - { - if (s == "Seria") - break; - } // while (!(s == "Seria")); - do - { - fin >> s; - } while (!(s == "|" || fin.bad())); - fin >> LocSeries; - fin >> LocLoad; // = s2rE(ReadWord(fin)); - do - { - fin >> s; - } while (!(contains( s,"[______________" ) || fin.bad())); - auto activeradiochannel{ -1 }; - while (!fin.bad() && !EndTable) - { - ++StationCount; - do - { - fin >> s; - } while (!(s == "[" || fin.bad())); - TMTableLine *record = &TimeTable[StationCount]; - { - if (s == "[") - fin >> s; - else - conversionerror = -4; - if (false == contains( s,"|") ) - { - record->km = static_cast(atof(s.c_str())); - fin >> s; - } - if (contains( s,"|_____|")) /*zmiana predkosci szlakowej*/ - UpdateVelocity(StationCount, vActual); - else - { - fin >> s; - if (false == contains(s,"|")) - vActual = atof(s.c_str()); - } - while (false == contains( s,"|")) - fin >> s; - fin >> record->StationName; - // get rid of non-ascii chars. TODO: run correct version based on locale - win1250_to_ascii( record->StationName ); - do - { - fin >> s; - } while (!(s == "1" || s == "2" || fin.bad())); - record->TrackNo = atoi(s.c_str()); - fin >> s; - if (s != "|") - { - if (contains( s, hrsd) ) - { - record->Ah = atoi( s.substr(0, s.find(hrsd)).c_str()); // godzina przyjazdu - record->Am = static_cast(atof(s.substr(s.find(hrsd) + 1, s.length()).c_str())); // minuta przyjazdu - } - else - { - record->Ah = TimeTable[StationCount - 1].Ah; // godzina z poprzedniej pozycji - record->Am = static_cast(atof(s.c_str())); // bo tylko minuty podane - } - } - do - { - fin >> s; - } while (!(s != "|" || fin.bad())); - if (s != "]") - record->tm = static_cast(atof(s.c_str())); - do - { - fin >> s; - } while (!(s == "[" || fin.bad())); - fin >> s; - if (false == contains(s,"|")) - { - /*tu s moze byc miejscem zmiany predkosci szlakowej*/ - fin >> s; - } - if (s.find("|_____|") != - std::string::npos) /*zmiana predkosci szlakowej*/ - UpdateVelocity(StationCount, vActual); - else - { - fin >> s; - if (false == contains(s,"|")) - vActual = atof(s.c_str()); - } - while (false == contains(s,"|")) - fin >> s; - // stationware. added fix for empty entry - fin >> s; - while( false == ( s == "1" - || s == "2" - || fin.bad() ) ) { - record->StationWare += s; - fin >> s; - } - // cache relevant station data - record->is_maintenance = contains(s, "pt"); - { - auto const stationware { Split( record->StationWare, ',' ) }; - for( auto const &entry : stationware ) { - if( entry.front() != 'R' ) { - continue; - } - auto const [entrytype, entrynumber]{ split_string_and_number( entry ) }; - if( entrytype == "R" - && entrynumber <= 10 ) { - auto const radiochannel { entrynumber }; - if( record->radio_channel == -1 - || radiochannel != activeradiochannel ) { - // if the station has more than one radiochannel listed, - // it generally means we should switch to the one we weren't using so far - // TODO: reverse this behaviour (keep the channel used so far) once W28 signs are included in the system - record->radio_channel = radiochannel; - } - } - } - if( record->radio_channel != -1 ) { - activeradiochannel = record->radio_channel; - } - } - record->TrackNo = atoi(s.c_str()); - fin >> s; - if (s != "|") - { - if (contains( s, hrsd) ) - { - record->Dh = atoi(s.substr(0, s.find(hrsd)).c_str()); // godzina odjazdu - record->Dm = static_cast(atof(s.substr(s.find(hrsd) + 1, s.length()).c_str())); // minuta odjazdu - } - else - { - record->Dh = TimeTable[StationCount - 1].Dh; // godzina z poprzedniej pozycji - record->Dm = static_cast(atof(s.c_str())); // bo tylko minuty podane - } - } - else - { - record->Dh = record->Ah; // odjazd o tej samej, co przyjazd (dla ostatniego też) - record->Dm = record->Am; // bo są używane do wyliczenia opóźnienia po dojechaniu - } - do - { - fin >> s; - } while (!(s != "|" || fin.bad())); - if (s != "]") - record->tm = static_cast(atof(s.c_str())); - do - { - fin >> s; - } while (!(contains( s, "[" ) || fin.bad())); - if (false == contains( s, "_|_")) - fin >> s; - if (false == contains( s, "|")) - { - /*tu s moze byc miejscem zmiany predkosci szlakowej*/ - fin >> s; - } - if (contains( s, "|_____|") ) /*zmiana predkosci szlakowej*/ - UpdateVelocity(StationCount, vActual); - else - { - fin >> s; - if (false == contains( s, "|")) - vActual = atof(s.c_str()); - } - while (false == contains( s, "|" ) ) - fin >> s; - while (false == contains(s, "]")) - fin >> s; - if (contains( s,"_|_") ) - EndTable = true; - } /*timetableline*/ - } - } - } /*while eof*/ + timetable_data data; + data.TrainName = TrainName; + conversionerror = read_timetable( fin, data ); fin.close(); + TrainName = data.TrainName; + TrainCategory = data.TrainCategory; + TrainLabel = data.TrainLabel; + Relation1 = data.Relation1; + Relation2 = data.Relation2; + RelationLabel1 = data.RelationLabel1; + RelationLabel2 = data.RelationLabel2; + BrakeRatio = data.BrakeRatio; + LocSeries = data.LocSeries; + LocLoad = data.LocLoad; + StationCount = data.StationCount; + for( auto i = 0; i <= MaxTTableSize; ++i ) { + static_cast( TimeTable[ i ] ) = data.TimeTable[ i ]; + } } } - // jeśli nazwa pierwszego zgodna z relacją - if (conversionerror == 0 && TimeTable[1].StationName == Relation1 && TimeTable[1].Ah < 0) // a nie podany czas przyjazdu + // jeśli nazwa pierwszego zgodna z relacją (bez względu na wielkość liter) + if (conversionerror == 0 && timetable::starts_at( TimeTable[1].StationName, Relation1 ) && TimeTable[1].Ah < 0) // a nie podany czas przyjazdu { // to mamy zatrzymanie na pierwszym, a nie przelot TimeTable[1].Ah = TimeTable[1].Dh; TimeTable[1].Am = TimeTable[1].Dm; diff --git a/world/mtable.h b/world/mtable.h index 841fea815..be8b2c90d 100644 --- a/world/mtable.h +++ b/world/mtable.h @@ -13,32 +13,19 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Classes.h" #include "audio/sound.h" +#include "world/timetablereader.h" namespace Mtable { -static int const MaxTTableSize = 100; // można by to robić dynamicznie static char const *const hrsd = "."; // Ra: pozycja zerowa rozkładu chyba nie ma sensu // Ra: numeracja przystanków jest 1..StationCount -struct TMTableLine +// a station of the timetable as the file gives it (TMTableEntry, world/timetablereader.h), with its name announcement +struct TMTableLine : TMTableEntry { - float km{ 0.f }; // kilometraz linii - float vmax{ -1.f }; // predkosc rozkladowa przed przystankiem - // StationName:string[32]; //nazwa stacji ('_' zamiast spacji) - // StationWare:string[32]; //typ i wyposazenie stacji, oddz. przecinkami} - std::string StationName{ "nowhere" }; // nazwa stacji ('_' zamiast spacji) - std::string StationWare; // typ i wyposazenie stacji, oddz. przecinkami} - int TrackNo{ 1 }; // ilosc torow szlakowych - int Ah{ -1 }; - float Am{ -1.f }; // godz. i min. przyjazdu, -1 gdy bez postoju - int Dh{ -1 }; - float Dm{ -1.f }; // godz. i min. odjazdu - float tm{ 0.f }; // czas jazdy do tej stacji w min. (z kolumny) - bool is_maintenance{ false }; - int radio_channel{ -1 }; sound_source name_sound{ sound_placement::engine }; }; @@ -55,10 +42,13 @@ class TTrainParameters double TTVmax; std::string Relation1; std::string Relation2; // nazwy stacji danego odcinka + // the two as the timetable spells them, with their letters (see TMTableEntry::StationLabel) + std::string RelationLabel1; + std::string RelationLabel2; double BrakeRatio; std::string LocSeries; // seria (typ) pojazdu double LocLoad; - TMTable TimeTable; + TMTable TimeTable; // TimeTable[0].flags holds the service flags of the whole train int StationCount; // ilość przystanków (0-techniczny) int StationIndex; // numer najbliższego (aktualnego) przystanku int StationStart; // numer pierwszej stacji pokazywanej na podglądzie rozkładu @@ -68,6 +58,9 @@ class TTrainParameters double CheckTrainLatency() const; /*todo: str hh:mm to int i z powrotem*/ std::string ShowRelation() const; + // the relation and the name of given station for the player: utf-8, with the letters the timetable has + std::string relation_caption() const; + std::string station_caption( std::string const &Name ) const; double WatchMTable(double DistCounter) const; std::string NextStop() const; // wpis rozkladu Offset pozycji za StationIndex (Offset>=1); poza zakresem 1..StationCount @@ -95,6 +88,10 @@ class TTrainParameters int radio_channel() const; // returns: sound file associated with current station, or -1 sound_source current_stop_sound() const; + // service flags (eu07/maszyna#95) which hold at the stop the train makes for or stands at + timetable::service_flags const &stop_flags() const; + // service flags which hold on the way, since the stop the train left last + timetable::service_flags const &run_flags() const; private: void load_sounds(); }; diff --git a/world/stationnames.cpp b/world/stationnames.cpp new file mode 100644 index 000000000..62948d7c8 --- /dev/null +++ b/world/stationnames.cpp @@ -0,0 +1,43 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "world/stationnames.h" + +#include "utilities/utilities.h" + +#include + +namespace timetable { + +std::string station_ascii(std::string Name) { + win1250_to_ascii(Name); + return Name; +} + +std::string station_key(std::string_view const Name) { + // the same steps the comparison of a W4 with the timetable always took: the marks off, then the case + auto key{ToLower(station_ascii(std::string{Name}))}; + std::ranges::replace(key, ' ', '_'); + return key; +} + +bool same_station(std::string_view const Left, std::string_view const Right) { + return station_key(Left) == station_key(Right); +} + +bool stop_point_is_for(std::string_view const Text, std::string_view const Station) { + return Text.starts_with(stop_point_prefix) && same_station(Text.substr(stop_point_prefix.size()), Station); +} + +std::string station_caption(std::string const &Name) { + return data_name_to_utf8(Name, true); +} + +} // namespace timetable diff --git a/world/stationnames.h b/world/stationnames.h new file mode 100644 index 000000000..0d171363f --- /dev/null +++ b/world/stationnames.h @@ -0,0 +1,40 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include + +// the names of the stations (MaSzyna-EU07/maszyna#94): a timetable and the W4 stop points of a scenery name a station +// each in its own file, in windows-1250, and they don't have to spell it the same way (with or without the polish +// letters, in another case). a name has three forms here: +// - as written, with its letters: what the files hold and what the player is shown (station_caption()) +// - the ascii one, the polish letters without their marks: what the timetable always kept as the name of a station, +// what the scenery events, the scripts and the file names of the announcements and destination boards go by +// (station_ascii()) +// - the key two spellings are the same station by (station_key(), same_station()) +namespace timetable { + +// what a W4 text starts with: "PassengerStopPoint:". in the scenery a "#" follows; the event cuts it as it's read, a memory cell keeps the whole of its text +inline constexpr std::string_view stop_point_prefix{"PassengerStopPoint:"}; + +// the name without the marks of the polish letters of windows-1250, the rest as written +std::string station_ascii(std::string Name); +// the key of a name: the ascii form in lower case, spaces as underscores +std::string station_key(std::string_view Name); +// whether the two names are spellings of the same station +bool same_station(std::string_view Left, std::string_view Right); +// whether the W4 text, as an event or a memory cell holds it, is for the station of given name, in any spelling of the two +bool stop_point_is_for(std::string_view Text, std::string_view Station); +// the name for the player: utf-8, with its letters, underscores as spaces +std::string station_caption(std::string const &Name); + +} // namespace timetable diff --git a/world/timetableflags.cpp b/world/timetableflags.cpp new file mode 100644 index 000000000..5c7d6ae9e --- /dev/null +++ b/world/timetableflags.cpp @@ -0,0 +1,103 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "world/timetableflags.h" + +#include "utilities/Logs.h" +#include "utilities/utilities.h" + +namespace timetable { + +namespace { + +void apply_one(tristate &Flag, tristate const Other) { + if (Other != tristate::unset) { + Flag = Other; + } +} + +tristate *flag_named(std::string_view const Key, service_flags &Flags) { + if (Key == "drzwi_centralne") { + return &Flags.central_doors; + } + if (Key == "stopien") { + return &Flags.doorstep; + } + if (Key == "kierownik") { + return &Flags.conductor; + } + if (Key == "proba_hamulca") { + return &Flags.brake_test; + } + return nullptr; +} + +} // namespace + +void service_flags::apply(service_flags const &Other) { + apply_one(central_doors, Other.central_doors); + apply_one(doorstep, Other.doorstep); + apply_one(conductor, Other.conductor); + apply_one(brake_test, Other.brake_test); +} + +bool read_flag(std::string_view const Entry, service_flags &Flags) { + auto const separator{Entry.find('=')}; + if (separator == std::string_view::npos) { + return false; + } + auto const key{ToLower(std::string{Entry.substr(0, separator)})}; + auto *flag{flag_named(key, Flags)}; + if (flag == nullptr) { + return false; + } + auto const value{ToLower(std::string{Entry.substr(separator + 1)})}; + if (value == "tak" || value == "1") { + *flag = tristate::yes; + } + else if (value == "nie" || value == "0") { + *flag = tristate::no; + } + else { + ErrorLog("Bad timetable: unknown value of " + key + " in \"" + std::string{Entry} + "\", expected tak or nie"); + } + return true; +} + +std::string extract_flags(std::string const &Ware, service_flags &Flags) { + if (false == contains(Ware, '=')) { + // no flags, the list as it was + return Ware; + } + std::string rest; + for (auto const &entry : Split(Ware, ',')) { + if (read_flag(entry, Flags)) { + continue; + } + if (contains(entry, '=')) { + ErrorLog("Bad timetable: unknown flag \"" + entry + "\" in station ware \"" + Ware + "\""); + } + if (false == rest.empty()) { + rest += ','; + } + rest += entry; + } + return rest; +} + +int stop_flags_entry(int const StationIndex, int const StationCount) { + return std::clamp(StationIndex, 0, std::max(StationCount, 0)); +} + +int run_flags_entry(int const StationIndex, int const StationCount) { + return std::clamp(StationIndex - 1, 0, std::max(StationCount, 0)); +} + +} // namespace timetable diff --git a/world/timetableflags.h b/world/timetableflags.h new file mode 100644 index 000000000..8c463d3f3 --- /dev/null +++ b/world/timetableflags.h @@ -0,0 +1,59 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include + +// the way a train is served, set by its timetable for the AI driver (eu07/maszyna#95): trams and underground trains +// open all the doors from the cab, have no doorstep, no conductor, no running brake test. each flag the timetable +// leaves out keeps the behaviour of the vehicles, as before the flags. +// +// the whole train: a row of the first box of the header +// [ Flagi AI | kierownik=nie,proba_hamulca=nie ] +// from a station on: entries of its station ware (the second line of the station, with R2, ph, @...) +// [ | | R2,ph,drzwi_centralne=tak,stopien=nie 1 12.47 | ] +// a station's entry holds from that station on, until another station changes it +namespace timetable { + +enum class tristate : std::uint8_t { + unset, // left to the vehicles, as before the flags + yes, + no +}; + +struct service_flags { + tristate central_doors{tristate::unset}; // drzwi_centralne: the driver opens all the doors, of mixed control too + tristate doorstep{tristate::unset}; // stopien: the doorsteps on (tak) or off (nie) before the doors open + tristate conductor{tristate::unset}; // kierownik: no conductor (nie), no departure signal, no door kept open for him + tristate brake_test{tristate::unset}; // proba_hamulca: no running brake test (nie) + + bool operator==(service_flags const &) const = default; + bool empty() const { return *this == service_flags{}; } + // the flags Other sets explicitly override these + void apply(service_flags const &Other); +}; + +// reads one entry, key=value (tak/nie, 1/0), into Flags. returns false for an entry which isn't a flag, so the caller +// keeps it; a flag with a value it doesn't know is reported to the log and taken as handled +bool read_flag(std::string_view Entry, service_flags &Flags); + +// reads the flags out of a station ware list (comma separated entries) into Flags. returns the list without them: the +// list as it was when it had none +std::string extract_flags(std::string const &Ware, service_flags &Flags); + +// the timetable entry whose flags hold at the stop the train makes for or stands at: the current one (StationIndex), +// within 0 (the header's flags) and the last station +int stop_flags_entry(int StationIndex, int StationCount); +// the entry whose flags hold on the way: the station the train left last, 0 (the header's flags) before the first one +int run_flags_entry(int StationIndex, int StationCount); + +} // namespace timetable diff --git a/world/timetablereader.cpp b/world/timetablereader.cpp new file mode 100644 index 000000000..331680f54 --- /dev/null +++ b/world/timetablereader.cpp @@ -0,0 +1,329 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "world/timetablereader.h" + +#include "utilities/Logs.h" +#include "utilities/utilities.h" +#include "world/stationnames.h" + +namespace Mtable { + +namespace { + +char const *const hrsd = "."; + +// the rest of the row "Flagi" of the header after its label: flag entries up to the closing bracket. returns true when +// a row with no closing bracket ran into the line under the box +bool read_header_flags(std::istream &fin, timetable_data &Data) { + std::string s; + do { + fin >> s; + } while (!(s == "|" || fin.fail())); + while (fin >> s) { + if (s.starts_with('[')) { + // the next row, or the line under the box + ErrorLog("Bad timetable: row \"Flagi\" of " + Data.TrainName + " without the closing bracket"); + return contains(s, "_______|"); + } + auto const closing{s.ends_with(']')}; + for (auto const &entry : Split(closing ? std::string_view{s}.substr(0, s.size() - 1) : std::string_view{s}, ',')) { + if (false == entry.empty() && false == timetable::read_flag(entry, Data.Flags)) { + ErrorLog("Bad timetable: unknown flag \"" + entry + "\" in row \"Flagi\" of " + Data.TrainName); + } + } + if (closing) { + break; + } + } + return false; +} + +} // namespace + +// the reader as TTrainParameters::LoadTTfile had it, but for: the row "Flagi" of the header and the flags of the +// station ware; the loops end with the end of the file, where they used to spin forever (on a truncated file, or one +// with a number where the reader expects it which isn't one). a file the old reader read gets read the same +int read_timetable(std::istream &fin, timetable_data &Data) { + std::string lines; + std::string s; + bool EndTable{false}; + double vActual{-1}; + int conversionerror{0}; + auto &TimeTable{Data.TimeTable}; + auto &StationCount{Data.StationCount}; + // the table is read from its start, whatever Data held before + StationCount = 0; + TimeTable.fill(TMTableEntry{}); + // zapisywanie prędkości maksymalnej do wcześniejszych odcinków + auto const UpdateVelocity{[&TimeTable, &StationCount](double const Velocity) { + int i = StationCount; + while (i >= 0 && TimeTable[i].vmax == -1) { + TimeTable[i].vmax = static_cast(Velocity); // prędkość dojazdu do przystanku i + --i; // ewentualnie do poprzedniego też + } + }}; + + while (fin.good() && !(conversionerror != 0 || EndTable)) { + std::getline(fin, lines); /*wczytanie linii*/ + if (contains(lines, "___________________")) /*linia pozioma górna*/ + { + fin >> s; + if (s == "[") /*lewy pion*/ + { + fin >> s; + if (s == "Rodzaj") /*"Rodzaj i numer pociagu"*/ + do { + fin >> s; + } while (!(s == "|" || fin.fail())); /*środkowy pion*/ + } + } + else if (lines == "") { + break; + } + fin >> s; /*nazwa pociągu*/ + Data.TrainName = s; // nadanie nazwy z pliku TXT (bez ścieżki do pliku) + while (fin >> s) { + if (contains(s, "_______|")) { + break; + } + if (s == "Kategoria") { + do { + fin >> s; + } while (!(s == "|" || fin.fail())); + fin >> Data.TrainCategory; + continue; + } + if (s == "Nazwa") { + do { + fin >> s; + } while (!(s == "|" || fin.fail())); + fin >> Data.TrainLabel; + continue; + } + if (s == "Flagi") { + // service flags of the whole train (eu07/maszyna#95) + if (read_header_flags(fin, Data)) { + break; + } + continue; + } + } + { /*czytaj naglowek*/ + while (fin >> s) { + if (s == "[") + break; + } /*pierwsza linia z relacją*/ + while (fin >> s) { + if (s != "|") + break; + } + if (s != "|") { + // the name is kept as written, for showing; the ascii form is what the rest of the simulator goes by + Data.RelationLabel1 = s; + Data.Relation1 = timetable::station_ascii(s); + } + else + conversionerror = -5; + while (fin >> s) { + if (s == "Relacja") + break; + } /*druga linia z relacją*/ + while (fin >> s) { + if (s == "|") + break; + } + if (fin >> Data.RelationLabel2) { + Data.Relation2 = timetable::station_ascii(Data.RelationLabel2); + } + while (fin >> s) { + if (s == "Wymagany") + break; + } + while (fin >> s) { + if (s == "|" || s == "\n") + break; + } + fin >> s; + s = s.substr(0, s.find("%")); + Data.BrakeRatio = atof(s.c_str()); + while (fin >> s) { + if (s == "Seria") + break; + } + do { + fin >> s; + } while (!(s == "|" || fin.fail())); + fin >> Data.LocSeries; + fin >> Data.LocLoad; // = s2rE(ReadWord(fin)); + do { + fin >> s; + } while (!(contains(s, "[______________") || fin.fail())); + // the header's flags hold from the start, entry 0 keeps them for the stations to inherit + TimeTable[0].flags = Data.Flags; + auto activeradiochannel{-1}; + while (!fin.fail() && !EndTable) { + // both bounds, so TimeTable[StationCount] and TimeTable[StationCount - 1] below stay in the table + if (StationCount < 0 || StationCount >= MaxTTableSize) { + conversionerror = timetable_too_long; + break; + } + ++StationCount; + do { + fin >> s; + } while (!(s == "[" || fin.fail())); + TMTableEntry *record = &TimeTable[StationCount]; + { + if (s == "[") + fin >> s; + else + conversionerror = -4; + if (false == contains(s, "|")) { + record->km = static_cast(atof(s.c_str())); + fin >> s; + } + if (contains(s, "|_____|")) /*zmiana predkosci szlakowej*/ + UpdateVelocity(vActual); + else { + fin >> s; + if (false == contains(s, "|")) + vActual = atof(s.c_str()); + } + while (false == contains(s, "|") && false == fin.fail()) + fin >> s; + // the name is kept as written, for showing; the W4 stop points, the announcement files, the scenery + // events and the scripts go by its ascii form, as they always did + if (fin >> record->StationLabel) { + record->StationName = timetable::station_ascii(record->StationLabel); + } + do { + fin >> s; + } while (!(s == "1" || s == "2" || fin.fail())); + record->TrackNo = atoi(s.c_str()); + fin >> s; + if (s != "|") { + if (contains(s, hrsd)) { + record->Ah = atoi(s.substr(0, s.find(hrsd)).c_str()); // godzina przyjazdu + record->Am = static_cast(atof(s.substr(s.find(hrsd) + 1, s.length()).c_str())); // minuta przyjazdu + } + else { + record->Ah = TimeTable[StationCount - 1].Ah; // godzina z poprzedniej pozycji + record->Am = static_cast(atof(s.c_str())); // bo tylko minuty podane + } + } + do { + fin >> s; + } while (!(s != "|" || fin.fail())); + if (s != "]") + record->tm = static_cast(atof(s.c_str())); + do { + fin >> s; + } while (!(s == "[" || fin.fail())); + fin >> s; + if (false == contains(s, "|")) { + /*tu s moze byc miejscem zmiany predkosci szlakowej*/ + fin >> s; + } + if (s.find("|_____|") != std::string::npos) /*zmiana predkosci szlakowej*/ + UpdateVelocity(vActual); + else { + fin >> s; + if (false == contains(s, "|")) + vActual = atof(s.c_str()); + } + while (false == contains(s, "|") && false == fin.fail()) + fin >> s; + // stationware. added fix for empty entry + fin >> s; + while (false == (s == "1" || s == "2" || fin.fail())) { + record->StationWare += s; + fin >> s; + } + // cache relevant station data + record->is_maintenance = contains(s, "pt"); + // service flags (eu07/maszyna#95): the ones of the station before, changed by the ones given here + record->flags = TimeTable[StationCount - 1].flags; + record->StationWare = timetable::extract_flags(record->StationWare, record->flags); + { + auto const stationware{Split(record->StationWare, ',')}; + for (auto const &entry : stationware) { + if (entry.front() != 'R') { + continue; + } + auto const [entrytype, entrynumber]{split_string_and_number(entry)}; + if (entrytype == "R" && entrynumber <= 10) { + auto const radiochannel{entrynumber}; + if (record->radio_channel == -1 || radiochannel != activeradiochannel) { + // if the station has more than one radiochannel listed, + // it generally means we should switch to the one we weren't using so far + // TODO: reverse this behaviour (keep the channel used so far) once W28 signs are included in the system + record->radio_channel = radiochannel; + } + } + } + if (record->radio_channel != -1) { + activeradiochannel = record->radio_channel; + } + } + record->TrackNo = atoi(s.c_str()); + fin >> s; + if (s != "|") { + if (contains(s, hrsd)) { + record->Dh = atoi(s.substr(0, s.find(hrsd)).c_str()); // godzina odjazdu + record->Dm = static_cast(atof(s.substr(s.find(hrsd) + 1, s.length()).c_str())); // minuta odjazdu + } + else { + record->Dh = TimeTable[StationCount - 1].Dh; // godzina z poprzedniej pozycji + record->Dm = static_cast(atof(s.c_str())); // bo tylko minuty podane + } + } + else { + record->Dh = record->Ah; // odjazd o tej samej, co przyjazd (dla ostatniego też) + record->Dm = record->Am; // bo są używane do wyliczenia opóźnienia po dojechaniu + } + do { + fin >> s; + } while (!(s != "|" || fin.fail())); + if (s != "]") + record->tm = static_cast(atof(s.c_str())); + do { + fin >> s; + } while (!(contains(s, "[") || fin.fail())); + if (false == contains(s, "_|_")) + fin >> s; + if (false == contains(s, "|")) { + /*tu s moze byc miejscem zmiany predkosci szlakowej*/ + fin >> s; + } + if (contains(s, "|_____|")) /*zmiana predkosci szlakowej*/ + UpdateVelocity(vActual); + else { + fin >> s; + if (false == contains(s, "|")) + vActual = atof(s.c_str()); + } + while (false == contains(s, "|") && false == fin.fail()) + fin >> s; + while (false == contains(s, "]") && false == fin.fail()) + fin >> s; + if (contains(s, "_|_")) + EndTable = true; + } /*timetableline*/ + } + if (false == EndTable && conversionerror == 0) { + // the old reader went on reading past the end of the file here, forever + conversionerror = timetable_truncated; + } + } + } /*while eof*/ + return conversionerror; +} + +} // namespace Mtable diff --git a/world/timetablereader.h b/world/timetablereader.h new file mode 100644 index 000000000..8c60d3361 --- /dev/null +++ b/world/timetablereader.h @@ -0,0 +1,73 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include + +#include "world/timetableflags.h" + +// the reader of the timetable files (.txt next to the scenery), without the parts of the engine the timetable +// of a running train needs (sounds, scenario time), so it can be tested on its own +namespace Mtable { + +static int const MaxTTableSize = 100; // można by to robić dynamicznie + +// one station of a timetable, as the file gives it +struct TMTableEntry { + float km{0.f}; // kilometraz linii + float vmax{-1.f}; // predkosc rozkladowa przed przystankiem + // nazwa stacji ('_' zamiast spacji), bez ogonków: the form the station is matched, looked up and handed over by + // (the W4 stop points, the announcement files, the scenery events, the scripts) + std::string StationName{"nowhere"}; + // the name as the timetable spells it, in windows-1250 with its letters: for showing (timetable::station_caption()) + std::string StationLabel{"nowhere"}; + std::string StationWare; // typ i wyposazenie stacji, oddz. przecinkami, bez flag obsługi + int TrackNo{1}; // ilosc torow szlakowych + int Ah{-1}; + float Am{-1.f}; // godz. i min. przyjazdu, -1 gdy bez postoju + int Dh{-1}; + float Dm{-1.f}; // godz. i min. odjazdu + float tm{0.f}; // czas jazdy do tej stacji w min. (z kolumny) + bool is_maintenance{false}; + int radio_channel{-1}; + // the service flags which hold from this station on: the header's, changed by this and the earlier stations. + // entry 0 holds the header's + timetable::service_flags flags; +}; + +// what a timetable file holds +struct timetable_data { + std::string TrainName; // the name the file is looked up by, then the one the file gives + std::string TrainCategory; + std::string TrainLabel; + // the first and the last station, in the two forms a station name has (see TMTableEntry) + std::string Relation1; + std::string Relation2; + std::string RelationLabel1; + std::string RelationLabel2; + double BrakeRatio{0.0}; + std::string LocSeries; + double LocLoad{0.0}; + timetable::service_flags Flags; // of the whole train, the row "Flagi" of the header + int StationCount{0}; // stations 1..StationCount, entry 0 is the technical one + std::array TimeTable; +}; + +// conversion errors of read_timetable, besides the ones it always had (-4: no station row where expected, -5: no +// first station of the relation) +int const timetable_truncated{-9}; // the file ends before the bottom line of the table (the reader used to hang) +int const timetable_too_long{-10}; // more stations than MaxTTableSize (the reader used to write past the table) + +// reads the timetable from Input into Data. returns the conversion error, 0 when read +int read_timetable(std::istream &Input, timetable_data &Data); + +} // namespace Mtable diff --git a/world/timetablestart.cpp b/world/timetablestart.cpp new file mode 100644 index 000000000..2ece9a71c --- /dev/null +++ b/world/timetablestart.cpp @@ -0,0 +1,25 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "world/timetablestart.h" + +#include +#include + +namespace timetable { + +bool starts_at(std::string_view const Firststation, std::string_view const Relationfrom) { + // the station names are plain ascii by now, the timetable loader strips the polish letters + return std::ranges::equal(Firststation, Relationfrom, [](char const Left, char const Right) { + return std::tolower(static_cast(Left)) == std::tolower(static_cast(Right)); + }); +} + +} // namespace timetable diff --git a/world/timetablestart.h b/world/timetablestart.h new file mode 100644 index 000000000..78e6f2c36 --- /dev/null +++ b/world/timetablestart.h @@ -0,0 +1,23 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include + +// the first row of a timetable +namespace timetable { + +// whether the first row of a timetable is the station the train sets off from: it names the station +// the relation starts at. such a row is a stop even with no arrival time given, the train waits there +// for its departure time. the names are compared regardless of case, as the timetables write the +// station of departure in capitals as often as not (ZAGORZ in the rows, Zagorz in the relation) +bool starts_at(std::string_view Firststation, std::string_view Relationfrom); + +} // namespace timetable